nx-kv 0.8.4 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +47 -2
  3. package/assets/kv-submit/SKILL.md +12 -4
  4. package/assets/kv-submit/references/submit-workflow.md +9 -2
  5. package/assets/kv-waittask/SKILL.md +23 -1
  6. package/assets/kv-waittask/references/kv-waittask-workflow.md +26 -4
  7. package/assets/nx-kv/SKILL.md +48 -0
  8. package/assets/nx-kv/references/todo-commands.md +52 -0
  9. package/package.json +1 -1
  10. package/src/core/attachstore.js +269 -0
  11. package/src/core/config.js +22 -0
  12. package/src/core/fileapi.js +243 -0
  13. package/src/core/kvapi.js +3 -1
  14. package/src/core/paths.js +9 -0
  15. package/src/modules/file/index.js +100 -0
  16. package/src/modules/file/service.js +214 -0
  17. package/src/modules/localtask/index.js +44 -21
  18. package/src/modules/localtask/service.js +238 -46
  19. package/src/modules/localtask/view.jsx +72 -16
  20. package/src/modules/setting/index.js +33 -0
  21. package/src/modules/setting/service.js +48 -0
  22. package/src/modules/todo/attach.js +96 -0
  23. package/src/modules/todo/editor.jsx +229 -0
  24. package/src/modules/todo/index.js +72 -0
  25. package/src/modules/todo/markdown.jsx +53 -0
  26. package/src/modules/todo/service.js +171 -10
  27. package/src/modules/todo/upload.js +107 -0
  28. package/src/modules/todo/view.jsx +83 -10
  29. package/src/runtime/api.js +6 -1
  30. package/src/runtime/registry.js +3 -1
  31. package/src/web/frontend/style.css +133 -0
  32. package/src/web/public/assets/{CliHints-D70_R4vQ.js → CliHints-CGOWc046.js} +1 -1
  33. package/src/web/public/assets/{index-CmCYxz0e.css → index-BDsJPdhM.css} +1 -1
  34. package/src/web/public/assets/{index-2OK9SG2y.js → index-BVbLNACS.js} +2 -2
  35. package/src/web/public/assets/{view-C5ictDJi.js → view-BBdEL07x.js} +1 -1
  36. package/src/web/public/assets/view-BlGIceud.js +3 -0
  37. package/src/web/public/assets/view-CwFWDigR.js +1 -0
  38. package/src/web/public/assets/{view-gzBv_kjb.js → view-DUy79STG.js} +1 -1
  39. package/src/web/public/index.html +2 -2
  40. package/src/modules/localtask/popup.js +0 -285
  41. package/src/web/public/assets/view-DxwcTgBZ.js +0 -1
  42. package/src/web/public/assets/view-l_lnGEBC.js +0 -2
@@ -0,0 +1,214 @@
1
+ // 附件模块:用户空间里的图片 / 文档等二进制原件。
2
+ //
3
+ // 后端是 dev_ctr_hello 的图床(/api/v1/files*,上传 multipart,出图 /files/:fileId)。
4
+ // 本模块只做「业务编排 + 人读渲染」,网络细节全在 core/fileapi.js,
5
+ // 本地镜像细节全在 core/attachstore.js。
6
+ //
7
+ // 与 todo 的分工:附件**内容**归这里;附件**怎么被任务引用**归 todo
8
+ // (任务正文里的 ![说明](fileId),见 modules/todo/attach.js)。
9
+ // 两边都不 import 对方 —— 需要共享的东西都在 core/。
10
+ import { readFile } from 'node:fs/promises';
11
+ import { basename, resolve } from 'node:path';
12
+ import { Readable } from 'node:stream';
13
+ import { badInput } from '../../core/errors.js';
14
+ import { loadConfig, resolveGroupId } from '../../core/config.js';
15
+ import {
16
+ accessUrlOf, contentTypeOf, deleteFile, fileInfo, fileUpload, isImageName, listFiles, openFileStream,
17
+ } from '../../core/fileapi.js';
18
+ import { localDirFor, localIndex, resolveLocal, syncAttachments } from '../../core/attachstore.js';
19
+
20
+ const fmtBytes = (n) => {
21
+ const v = Number(n) || 0;
22
+ if (v < 1024) return `${v} B`;
23
+ if (v < 1024 * 1024) return `${(v / 1024).toFixed(1)} KB`;
24
+ return `${(v / (1024 * 1024)).toFixed(2)} MB`;
25
+ };
26
+
27
+ function decodeBase64(content) {
28
+ let b64 = String(content || '');
29
+ const comma = b64.indexOf(',');
30
+ if (b64.startsWith('data:') && comma >= 0) b64 = b64.slice(comma + 1);
31
+ let buf;
32
+ try { buf = Buffer.from(b64, 'base64'); } catch { throw badInput('上传内容不是合法的 base64'); }
33
+ if (!buf.length) throw badInput('上传内容为空');
34
+ return buf;
35
+ }
36
+
37
+ // 贴进任务正文的嵌入语法。解析端在 modules/todo/attach.js——
38
+ // 那里是**唯一**的解析实现;这里只是把同一套语法生成出来给人/agent 复制。
39
+ const snippetOf = (name, fileId) => ({ image: `![${name}](${fileId})`, file: `[${name}](${fileId})` });
40
+
41
+ export async function listFilesAction({ group, limit = 100, offset = 0 } = {}) {
42
+ const cfg = await loadConfig();
43
+ // 一律先解析工作空间:显式 --group 优先,否则回落本机配置的当前值。
44
+ // 直接拿裸 group 会让「配置里是 24、这次没传 --group」变成去查后端默认组 ——
45
+ // 那正是「读任务在 A 组、同步附件在 B 组」这种不报错的错位。
46
+ const gid = await resolveGroupId(group);
47
+ const r = await listFiles({ groupId: gid, limit, offset });
48
+ const { dir, index } = await localIndex(gid, cfg.attachmentsDir);
49
+ return {
50
+ groupId: gid || 0,
51
+ total: r.total,
52
+ hasMore: r.hasMore,
53
+ localDir: dir,
54
+ files: r.items.map((f) => ({
55
+ fileId: f.fileId,
56
+ url: accessUrlOf(cfg.baseUrl, f.fileId),
57
+ size: f.size,
58
+ contentType: f.contentType,
59
+ isImage: isImageName(f.fileId, f.contentType),
60
+ accessLevel: f.accessLevel,
61
+ createdAt: f.createdAt,
62
+ localPath: index.get(f.fileId)?.path || '',
63
+ })),
64
+ };
65
+ }
66
+
67
+ export async function uploadFileAction(patch = {}) {
68
+ const { path: localPath, content, name, contentType, group, accessLevel = 'public' } = patch;
69
+ const gid = await resolveGroupId(group);
70
+ let buffer;
71
+ let fileName;
72
+
73
+ if (localPath) {
74
+ const abs = resolve(String(localPath));
75
+ try {
76
+ buffer = await readFile(abs);
77
+ } catch (e) {
78
+ throw badInput(`读不到文件: ${abs}(${e.code || e.message})`);
79
+ }
80
+ fileName = name || basename(abs);
81
+ } else if (content !== undefined && content !== null) {
82
+ if (!name) throw badInput('Web 上传需要文件名:--name <文件名>');
83
+ buffer = decodeBase64(content);
84
+ fileName = name;
85
+ } else {
86
+ throw badInput('上传需要 --path <本机文件>,或 --content <base64> --name <文件名>');
87
+ }
88
+
89
+ const meta = await fileUpload({
90
+ name: fileName,
91
+ buffer,
92
+ contentType: contentType || contentTypeOf(fileName),
93
+ groupId: gid,
94
+ accessLevel,
95
+ });
96
+ const cfg = await loadConfig();
97
+ return {
98
+ ...meta,
99
+ url: accessUrlOf(cfg.baseUrl, meta.fileId),
100
+ isImage: isImageName(fileName, meta.contentType),
101
+ localDir: localDirFor(gid, cfg.attachmentsDir),
102
+ markdown: snippetOf(fileName, meta.fileId),
103
+ };
104
+ }
105
+
106
+ export async function getFileAction(fileId, { group } = {}) {
107
+ if (!fileId) throw badInput('缺少 fileId');
108
+ const cfg = await loadConfig();
109
+ const gid = await resolveGroupId(group);
110
+ const meta = await fileInfo(fileId, gid);
111
+ const local = await resolveLocal(gid, fileId, cfg.attachmentsDir);
112
+ return {
113
+ ...meta,
114
+ url: accessUrlOf(cfg.baseUrl, meta.fileId),
115
+ isImage: isImageName(meta.fileId, meta.contentType),
116
+ localPath: local?.path || '',
117
+ localName: local?.name || '',
118
+ };
119
+ }
120
+
121
+ export async function removeFileAction(fileId, { group } = {}) {
122
+ if (!fileId) throw badInput('缺少 fileId');
123
+ const r = await deleteFile(fileId, await resolveGroupId(group));
124
+ return { status: 'ok', ...r, note: '本地已同步的副本不会自动删除;要一并清理用 nx-kv file sync --prune' };
125
+ }
126
+
127
+ /** 同步到本地 —— 这个子命令存在的唯一理由:**让 agent 读本地文件而不是读网**。 */
128
+ export async function syncFilesAction({ group, ids, dir, prune, dryRun } = {}) {
129
+ const cfg = await loadConfig();
130
+ const gid = await resolveGroupId(group);
131
+ const result = await syncAttachments({
132
+ groupId: gid,
133
+ ids: Array.isArray(ids) && ids.length ? ids : null,
134
+ dir: dir || cfg.attachmentsDir,
135
+ prune: prune === true,
136
+ dryRun: dryRun === true,
137
+ });
138
+ return { ...result, usedDir: localDirFor(gid, dir || cfg.attachmentsDir) };
139
+ }
140
+
141
+ /** HTTP 原始流:把后端的出图内容原样透给浏览器(面板里 <img src> 直接用)。 */
142
+ export async function serveContent(ctx) {
143
+ const { res } = ctx.__raw || {};
144
+ if (!res) throw badInput('内部错误:缺少响应对象');
145
+ const up = await openFileStream(ctx.fileId);
146
+ const ct = up.headers.get('content-type') || 'application/octet-stream';
147
+ res.writeHead(200, { 'content-type': ct, 'cache-control': 'no-store' });
148
+ const rs = Readable.fromWeb(up.body);
149
+ await new Promise((done, fail) => {
150
+ rs.once('error', fail);
151
+ res.once('close', done);
152
+ res.once('finish', done);
153
+ rs.pipe(res);
154
+ });
155
+ }
156
+
157
+ // ---- CLI 人读渲染 ----
158
+
159
+ export function renderFileList(d) {
160
+ const lines = [`附件 ${d.files.length} 个(共 ${d.total})· 本地目录 ${d.localDir}`];
161
+ for (const f of d.files) {
162
+ lines.push(` ${f.fileId} ${f.isImage ? '[图片]' : '[文件]'} ${fmtBytes(f.size)} ${f.contentType}`);
163
+ if (f.localPath) lines.push(` 本地: ${f.localPath}`);
164
+ }
165
+ lines.push('', '上传: nx-kv file upload --path <本机文件> 同步到本地: nx-kv file sync');
166
+ return lines.join('\n');
167
+ }
168
+
169
+ export function renderUpload(d) {
170
+ return [
171
+ `已上传 ${d.fileId}(${fmtBytes(d.size)} · ${d.contentType})`,
172
+ `地址: ${d.url}`,
173
+ `本地目录: ${d.localDir}(跑 nx-kv file sync 可落到本地)`,
174
+ `贴进任务正文(编辑时也可直接选图上传):`,
175
+ ` ${d.isImage ? d.markdown.image : d.markdown.file}`,
176
+ ].join('\n');
177
+ }
178
+
179
+ export function renderFileInfo(d) {
180
+ return [
181
+ `${d.fileId} · ${d.isImage ? '图片' : '文件'} · ${fmtBytes(d.size)} · ${d.contentType}`,
182
+ `地址: ${d.url}`,
183
+ d.localPath ? `本地: ${d.localPath}` : '本地: (未同步;nx-kv file sync 拉到本地)',
184
+ `权限: ${d.accessLevel}${d.createdAt ? ` · 上传于 ${d.createdAt}` : ''}`,
185
+ ].join('\n');
186
+ }
187
+
188
+ export function renderRemove(d) {
189
+ return `已删除附件 ${d.fileId}\n${d.note}`;
190
+ }
191
+
192
+ export function renderSync(d) {
193
+ const head = d.dryRun ? '试运行(未下载):' : '同步完成:';
194
+ const lines = [
195
+ `${head}下载 ${d.downloaded} · 跳过 ${d.skipped} · 删除 ${d.removed.length} · 目标 ${d.target}`,
196
+ `本地目录: ${d.usedDir}`,
197
+ ];
198
+ for (const f of d.files) lines.push(` ${f.path}`);
199
+ if (d.missing.length) lines.push(`后端不存在(可能已删): ${d.missing.join(', ')}`);
200
+ if (d.failures.length) {
201
+ lines.push('下载失败:');
202
+ for (const f of d.failures) lines.push(` ${f.id}: ${f.error}`);
203
+ }
204
+ if (!d.files.length) lines.push('(没有可同步的附件)');
205
+ return lines.join('\n');
206
+ }
207
+
208
+ export function renderContent(d) {
209
+ return [
210
+ `${d.fileId}`,
211
+ `地址: ${d.url}`,
212
+ d.localPath ? `本地: ${d.localPath}` : '本地: (未同步)',
213
+ ].join('\n');
214
+ }
@@ -15,6 +15,8 @@ import * as service from './service.js';
15
15
 
16
16
  const CWD = { type: 'string', hint: '工作目录(作为主题;默认当前目录)' };
17
17
  const SUMMARY = { type: 'string', required: true, hint: '当前现状(agent 当前状态,展示给用户)' };
18
+ // 任务级寻址的 key flag:全局主题没有 cwd,只能按 key 定位(__GLOBAL__)
19
+ const KEY = { type: 'string', hint: '主题 key(与 --cwd 二选一;全局任务池固定 __GLOBAL__)' };
18
20
 
19
21
  const STATUS_TAG = { pending: '待领取', consumed: '已领取' };
20
22
 
@@ -26,7 +28,7 @@ function renderOverview(d) {
26
28
  return lines.join('\n');
27
29
  }
28
30
  for (const t of d.topics) {
29
- const tag = t.waiting ? '[等待中]' : '[已结束]';
31
+ const tag = t.isGlobal ? '[全局池]' : t.waiting ? '[等待中]' : '[已结束]';
30
32
  const head = t.cwd ? `${t.name} ${t.cwd}` : t.name;
31
33
  lines.push(` ${tag} ${head} · 待领取 ${t.pending}/${t.total}`);
32
34
  if (t.summary) lines.push(` 现状: ${t.summary}`);
@@ -44,40 +46,43 @@ const renderTask = (t) =>
44
46
  .join('\n');
45
47
 
46
48
  function renderAdd(d) {
49
+ const where = d.isGlobal ? '全局任务(共享池)' : `主题「${d.name}」`;
47
50
  const head = `#${d.task.id} [${d.task.status}] ${d.task.text}`;
48
51
  return d.delivered
49
- ? `已实时回填给等待中的 agent(主题 ${d.name}): ${head}`
50
- : `已排入主题「${d.name}」队列(agent 下一次 wait 取走): ${head}`;
52
+ ? `已实时投递给等待中的 agent(${where}): ${head}`
53
+ : `已排入${where}队列(agent 下一次 wait 取走): ${head}`;
51
54
  }
52
55
 
53
- // wait 的人读输出:成功给任务,超时明确提示「本轮结束」
56
+ // wait 的人读输出:成功给任务(注明来自本地队列还是全局共享池),超时明确提示「本轮结束」
54
57
  function renderWait(r) {
55
58
  if (r.status === 'timeout') {
56
59
  const tail = r.cancelled ? '(用户在面板点了「关闭」)' : '';
57
60
  return `等待超时(${Math.round(r.timeoutMs / 1000)} 秒未回填)${tail}:主题「${r.cwd}」现状「${r.summary}」结束本轮。`;
58
61
  }
59
- const origin = r.queued ? '排队任务' : '实时回填';
62
+ const origin =
63
+ (r.source === 'global' ? '全局任务池' : '本目录队列') + (r.queued ? '排队任务' : ' · 实时回填');
60
64
  return (
61
65
  `已取得下一条任务(${origin} · 主题「${r.cwd}」现状「${r.summary}」): #${r.task.id}\n` +
62
66
  ` ${r.task.text.replace(/\n/g, '\n ')}`
63
67
  );
64
68
  }
65
69
 
66
- // cancel 的人读输出:等待中→已关闭(主题与任务保留);非等待中→无操作
70
+ // cancel 的人读输出:等待中→已关闭(主题与任务保留);非等待中→无操作;全局→不可关闭
67
71
  function renderCancel(d) {
68
72
  if (d.cancelled) return `已关闭主题「${d.name}」的等待:阻塞中的 wait 立即收尾,主题与任务保留。`;
73
+ if (d.reason === 'global_not_waitable') return '全局主题是共享任务池(不是等待源),无从关闭。';
69
74
  if (d.reason === 'not_waiting') return `主题「${d.name || d.key}」不在等待中,无需关闭。`;
70
75
  return '已关闭。';
71
76
  }
72
77
 
73
- // 批量删除的人读输出:删除清单 + 跳过清单(等待中/不存在)
78
+ // 批量删除的人读输出:删除清单 + 跳过清单(等待中/受保护/不存在)
74
79
  function renderRemoveMany(d) {
75
80
  const lines = [d.all ? `清空:删除 ${d.count} 个主题` : `已删除 ${d.count} 个主题`];
76
81
  for (const r of d.removed) lines.push(` - ${r.name}${r.cwd ? ` ${r.cwd}` : ''}`);
77
82
  if (d.skipped.length) {
78
83
  lines.push(`跳过 ${d.skipped.length} 个:`);
79
84
  for (const s of d.skipped) {
80
- const why = s.reason === 'waiting' ? '等待中' : '不存在';
85
+ const why = s.reason === 'waiting' ? '等待中' : s.reason === 'protected' ? '全局共享池' : '不存在';
81
86
  lines.push(` - [${why}] ${s.name || s.key}`);
82
87
  }
83
88
  }
@@ -108,41 +113,51 @@ export default {
108
113
  id: 'localtask.get',
109
114
  cli: ['localtask', 'get'],
110
115
  http: ['GET', '/api/localtasks/item'],
111
- summary: '查看单条任务(按 --id,定位到 --cwd 主题)',
112
- flags: { id: { type: 'number', required: true, hint: '任务编号' }, cwd: CWD },
113
- run: (ctx) => service.getTask({ id: ctx.id, cwd: ctx.cwd }),
116
+ summary: '查看单条任务(按 --id,定位到 --cwd 主题或 --key)',
117
+ flags: { id: { type: 'number', required: true, hint: '任务编号' }, cwd: CWD, key: KEY },
118
+ run: (ctx) => service.getTask({ id: ctx.id, cwd: ctx.cwd, key: ctx.key }),
114
119
  render: renderTask,
115
120
  },
116
121
  {
117
122
  id: 'localtask.add',
118
123
  cli: ['localtask', 'add'],
119
124
  http: ['POST', '/api/localtasks'],
120
- summary: '向某主题(工作目录)的队列回填一条任务(有 wait 在等则即时投递,否则排队)',
125
+ summary:
126
+ '向某主题(工作目录)的队列回填一条任务(有 wait 在等则即时投递,否则排队);--global 推到全局共享池',
121
127
  args: ['text'],
122
- flags: { cwd: CWD, summary: { type: 'string', hint: '顺带刷新该主题的当前现状(可选)' } },
123
- run: (ctx) => service.addTask({ text: ctx.text, cwd: ctx.cwd, summary: ctx.summary }),
128
+ flags: {
129
+ cwd: CWD,
130
+ summary: { type: 'string', hint: '顺带刷新该主题的当前现状(可选)' },
131
+ global: {
132
+ type: 'boolean',
133
+ hint: '推到全局主题(共享池):任何目录的 wait 在本地空时自动领取;--cwd 被忽略',
134
+ },
135
+ },
136
+ run: (ctx) =>
137
+ service.addTask({ text: ctx.text, cwd: ctx.cwd, summary: ctx.summary, global: ctx.global }),
124
138
  render: renderAdd,
125
139
  },
126
140
  {
127
141
  id: 'localtask.update',
128
142
  cli: ['localtask', 'update'],
129
143
  http: ['PATCH', '/api/localtasks/item'],
130
- summary: '编辑任务内容(按 --id,定位到 --cwd 主题)',
144
+ summary: '编辑任务内容(按 --id,定位到 --cwd 主题或 --key)',
131
145
  flags: {
132
146
  id: { type: 'number', required: true, hint: '任务编号' },
133
147
  text: { type: 'string', required: true, hint: '改成这个内容' },
134
148
  cwd: CWD,
149
+ key: KEY,
135
150
  },
136
- run: (ctx) => service.updateTask({ id: ctx.id, text: ctx.text, cwd: ctx.cwd }),
151
+ run: (ctx) => service.updateTask({ id: ctx.id, text: ctx.text, cwd: ctx.cwd, key: ctx.key }),
137
152
  render: (d) => `已更新主题「${d.name}」#${d.task.id}: ${d.task.text}`,
138
153
  },
139
154
  {
140
155
  id: 'localtask.remove',
141
156
  cli: ['localtask', 'remove'],
142
157
  http: ['DELETE', '/api/localtasks/item'],
143
- summary: '删除一条任务(按 --id,定位到 --cwd 主题)',
144
- flags: { id: { type: 'number', required: true, hint: '任务编号' }, cwd: CWD },
145
- run: (ctx) => service.removeTask({ id: ctx.id, cwd: ctx.cwd }),
158
+ summary: '删除一条任务(按 --id,定位到 --cwd 主题或 --key)',
159
+ flags: { id: { type: 'number', required: true, hint: '任务编号' }, cwd: CWD, key: KEY },
160
+ run: (ctx) => service.removeTask({ id: ctx.id, cwd: ctx.cwd, key: ctx.key }),
146
161
  render: (d) => `已删除主题「${d.name}」#${d.removed.id}: ${d.removed.text}`,
147
162
  },
148
163
 
@@ -228,9 +243,16 @@ export default {
228
243
  beforeId: { type: 'number', hint: '插到该编号之前(与 afterId 二选一)' },
229
244
  afterId: { type: 'number', hint: '插到该编号之后(与 beforeId 二选一)' },
230
245
  cwd: CWD,
246
+ key: KEY,
231
247
  },
232
248
  run: (ctx) =>
233
- service.reorderTasks({ id: ctx.id, beforeId: ctx.beforeId, afterId: ctx.afterId, cwd: ctx.cwd }),
249
+ service.reorderTasks({
250
+ id: ctx.id,
251
+ beforeId: ctx.beforeId,
252
+ afterId: ctx.afterId,
253
+ cwd: ctx.cwd,
254
+ key: ctx.key,
255
+ }),
234
256
  render: (d) => {
235
257
  const order = d.topic.tasks.filter((x) => x.status !== 'consumed').map((x) => `#${x.id}`);
236
258
  return `主题「${d.name}」待领取顺序:${order.join(' -> ') || '(无待领取)'}`;
@@ -242,7 +264,8 @@ export default {
242
264
  id: 'localtask.wait',
243
265
  cli: ['localtask', 'wait'],
244
266
  http: null,
245
- summary: '针对某主题(按 cwd 目录名识别)阻塞等待用户回填(默认 3 分钟,最大 10 分钟)',
267
+ summary:
268
+ '针对某主题(按 cwd 目录名识别)阻塞等待用户回填(默认 3 分钟,最大 10 分钟);本地空时自动领取全局共享池的任务',
246
269
  flags: {
247
270
  cwd: CWD,
248
271
  summary: SUMMARY,