nx-kv 0.8.5 → 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 (33) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +47 -2
  3. package/assets/nx-kv/SKILL.md +48 -0
  4. package/assets/nx-kv/references/todo-commands.md +52 -0
  5. package/package.json +1 -1
  6. package/src/core/attachstore.js +269 -0
  7. package/src/core/config.js +22 -0
  8. package/src/core/fileapi.js +243 -0
  9. package/src/core/kvapi.js +3 -1
  10. package/src/core/paths.js +9 -0
  11. package/src/modules/file/index.js +100 -0
  12. package/src/modules/file/service.js +214 -0
  13. package/src/modules/setting/index.js +33 -0
  14. package/src/modules/setting/service.js +48 -0
  15. package/src/modules/todo/attach.js +96 -0
  16. package/src/modules/todo/editor.jsx +229 -0
  17. package/src/modules/todo/index.js +72 -0
  18. package/src/modules/todo/markdown.jsx +53 -0
  19. package/src/modules/todo/service.js +171 -10
  20. package/src/modules/todo/upload.js +107 -0
  21. package/src/modules/todo/view.jsx +83 -10
  22. package/src/runtime/api.js +6 -1
  23. package/src/runtime/registry.js +3 -1
  24. package/src/web/frontend/style.css +133 -0
  25. package/src/web/public/assets/{CliHints-ZTpac1yV.js → CliHints-CGOWc046.js} +1 -1
  26. package/src/web/public/assets/{index-CmCYxz0e.css → index-BDsJPdhM.css} +1 -1
  27. package/src/web/public/assets/{index-gJ1xxwt4.js → index-BVbLNACS.js} +2 -2
  28. package/src/web/public/assets/{view-Cq4GElgD.js → view-BBdEL07x.js} +1 -1
  29. package/src/web/public/assets/view-BlGIceud.js +3 -0
  30. package/src/web/public/assets/{view-mzUKgI5p.js → view-CwFWDigR.js} +1 -1
  31. package/src/web/public/assets/{view-CYSIt3hy.js → view-DUy79STG.js} +1 -1
  32. package/src/web/public/index.html +2 -2
  33. package/src/web/public/assets/view-C9k3lhCV.js +0 -2
@@ -0,0 +1,243 @@
1
+ // 后端文件(图床)客户端 —— 对接 dev_ctr_hello 的 /api/v1/files* 与 /files/:fileId。
2
+ //
3
+ // 与 kvapi.js 共用同一套信封判定:**HTTP 恒为 200,成败看 body 里的 `code`**(0 = 成功),
4
+ // 所以这里复用 kvapi 导出的 call(),不另写一份解析。
5
+ //
6
+ // 上传走 multipart(后端 r.GetUploadFile("file")),其余走 JSON。
7
+ //
8
+ // fileId 是后端生成的不透明串:16 字节随机 → 32 位 hex;原文件名带扩展名时
9
+ // 后端会在 id 后再接 `.<ext>`(service/file/file.go 的 newFileId + "." + newExt),
10
+ // 所以 id 偶尔带后缀。判定「像不像 fileId」一律走 attach.js 的 looksLikeFileId。
11
+ import { badInput, external, notFound } from './errors.js';
12
+ import { loadConfig, normalizeGroupId } from './config.js';
13
+ import { call } from './kvapi.js';
14
+
15
+ const TIMEOUT_MS = 60000;
16
+
17
+ // 扩展名 → Content-Type。上传时按文件名猜:一律 octet-stream 会让浏览器
18
+ // 拿到 application/octet-stream 而不内联渲染,图片就「预览不出来」了。
19
+ const MIME = {
20
+ '.png': 'image/png',
21
+ '.jpg': 'image/jpeg',
22
+ '.jpeg': 'image/jpeg',
23
+ '.webp': 'image/webp',
24
+ '.gif': 'image/gif',
25
+ '.bmp': 'image/bmp',
26
+ '.avif': 'image/avif',
27
+ '.svg': 'image/svg+xml',
28
+ '.ico': 'image/x-icon',
29
+ '.pdf': 'application/pdf',
30
+ '.doc': 'application/msword',
31
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
32
+ '.xls': 'application/vnd.ms-excel',
33
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
34
+ '.ppt': 'application/vnd.ms-powerpoint',
35
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
36
+ '.txt': 'text/plain; charset=utf-8',
37
+ '.md': 'text/markdown; charset=utf-8',
38
+ '.csv': 'text/csv; charset=utf-8',
39
+ '.json': 'application/json; charset=utf-8',
40
+ '.zip': 'application/zip',
41
+ };
42
+
43
+ const IMAGE_EXT = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.avif', '.svg', '.ico']);
44
+
45
+ const extOf = (name) => {
46
+ const m = /(\.[A-Za-z0-9]{1,8})$/.exec(String(name || ''));
47
+ return m ? m[1].toLowerCase() : '';
48
+ };
49
+
50
+ export function contentTypeOf(name, fallback = 'application/octet-stream') {
51
+ return MIME[extOf(name)] || fallback;
52
+ }
53
+
54
+ export function isImageName(name, contentType = '') {
55
+ const e = extOf(name);
56
+ if (e) return IMAGE_EXT.has(e);
57
+ return /^image\//i.test(String(contentType));
58
+ }
59
+
60
+ export function normalizeFileMeta(d = {}) {
61
+ return {
62
+ fileId: String(d.fileId ?? ''),
63
+ url: String(d.url ?? ''),
64
+ accessLevel: String(d.accessLevel ?? ''),
65
+ size: Number(d.size) || 0,
66
+ contentType: String(d.contentType ?? ''),
67
+ groupId: Number(d.groupId) || 0,
68
+ groupName: String(d.groupName ?? ''),
69
+ sha256: String(d.sha256 ?? ''),
70
+ md5: String(d.md5 ?? ''),
71
+ tags: Array.isArray(d.tags) ? d.tags.map(String) : [],
72
+ createdAt: String(d.createdAt ?? ''),
73
+ expireAt: String(d.expireAt ?? ''),
74
+ };
75
+ }
76
+
77
+ const gidQuery = (groupId) => {
78
+ const n = normalizeGroupId(groupId);
79
+ return n === undefined ? '' : `?groupId=${n}`;
80
+ };
81
+
82
+ /** 出图地址:一律**自己拼**,不用后端回的 url。
83
+ * 后端 url 按请求 Host 推断(可能被反代写成内网地址),自己拼才跟 baseUrl 一致,
84
+ * 也才在假后端 / 换域名时都可预期。 */
85
+ export function accessUrlOf(baseUrl, fileId) {
86
+ return String(baseUrl || '').replace(/\/$/, '') + '/files/' + encodeURIComponent(fileId);
87
+ }
88
+
89
+ export async function fileAccessUrl(fileId) {
90
+ const cfg = await loadConfig();
91
+ // fileId 可能带扩展名(xxx.docx);encodeURIComponent 不会编码 `.`,安全
92
+ return accessUrlOf(cfg.baseUrl, fileId);
93
+ }
94
+
95
+ // ---- 上传(multipart)----
96
+
97
+ async function parseEnvelope(res, ctxLabel) {
98
+ let envelope;
99
+ try {
100
+ envelope = JSON.parse(await res.text());
101
+ } catch {
102
+ throw external(`后端返回了非 JSON(HTTP ${res.status}): ${ctxLabel}`);
103
+ }
104
+ const code = envelope.code ?? res.status;
105
+ if (code !== 0) {
106
+ if (code === 401) throw badInput('未登录或登录已过期(执行 nx-kv auth login <email>)');
107
+ throw external(`后端 code=${code}: ${envelope.message || '(无消息)'}`, { code, path: ctxLabel });
108
+ }
109
+ return envelope.data ?? null;
110
+ }
111
+
112
+ /**
113
+ * 上传一个文件到当前用户空间(group)。
114
+ * buffer 是完整字节:CLI 从本机文件读、面板从 base64 解 —— 两条路共用这一处。
115
+ */
116
+ export async function fileUpload({
117
+ name,
118
+ buffer,
119
+ contentType,
120
+ groupId,
121
+ accessLevel = 'public',
122
+ tags = [],
123
+ key = '',
124
+ expireSeconds = 0,
125
+ } = {}) {
126
+ if (!name) throw badInput('上传必须带文件名');
127
+ if (!buffer || !buffer.length) throw badInput('上传内容为空');
128
+
129
+ const cfg = await loadConfig();
130
+ const url = cfg.baseUrl.replace(/\/$/, '') + '/api/v1/files';
131
+ const ct = contentType || contentTypeOf(name);
132
+
133
+ const form = new FormData();
134
+ form.append('file', new Blob([buffer], { type: ct }), String(name));
135
+ form.append('accessLevel', String(accessLevel));
136
+ const gid = normalizeGroupId(groupId);
137
+ if (gid !== undefined) form.append('groupId', String(gid));
138
+ if (expireSeconds) form.append('expireSeconds', String(expireSeconds));
139
+ if (key) form.append('key', String(key));
140
+ for (const t of tags) form.append('tags', String(t));
141
+
142
+ const ctrl = new AbortController();
143
+ const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS);
144
+ let res;
145
+ try {
146
+ // ⚠️ 不能自己设 content-type:multipart 的 boundary 由 FormData 生成,
147
+ // 手写一个会丢掉 boundary,后端解析直接失败。
148
+ res = await fetch(url, {
149
+ method: 'POST',
150
+ headers: cfg.token ? { authorization: `Bearer ${cfg.token}` } : {},
151
+ body: form,
152
+ signal: ctrl.signal,
153
+ });
154
+ } catch (e) {
155
+ if (e && e.name === 'AbortError') throw external(`上传超时(${TIMEOUT_MS}ms): ${name}`);
156
+ throw external(`无法连接后端 ${cfg.baseUrl}: ${e.message}`);
157
+ } finally {
158
+ clearTimeout(timer);
159
+ }
160
+
161
+ const data = await parseEnvelope(res, 'POST /api/v1/files');
162
+ if (!data || !data.fileId) throw external('上传成功但后端未返回 fileId');
163
+ return normalizeFileMeta(data);
164
+ }
165
+
166
+ // ---- 列表 / 元数据 / 删除(JSON)----
167
+
168
+ export async function listFiles({ groupId, limit = 100, offset = 0 } = {}) {
169
+ const n = normalizeGroupId(groupId);
170
+ const q = `?limit=${Number(limit) || 100}&offset=${Number(offset) || 0}` + (n === undefined ? '' : `&groupId=${n}`);
171
+ const data = await call({ method: 'GET', path: '/api/v1/files' + q });
172
+ return {
173
+ total: Number(data?.total) || 0,
174
+ hasMore: data?.hasMore === true,
175
+ items: (data?.items ?? []).map(normalizeFileMeta),
176
+ };
177
+ }
178
+
179
+ /** 一次拉全(分页直到 total 或页数上限),供同步用。
180
+ * 上限存在的意义:列表接口异常返回 hasMore=true 时不会把 CLI 卡死。 */
181
+ export async function listAllFiles({ groupId, pageSize = 200, maxPages = 50 } = {}) {
182
+ const out = [];
183
+ let total = 0;
184
+ for (let page = 0; page < maxPages; page++) {
185
+ const r = await listFiles({ groupId, limit: pageSize, offset: page * pageSize });
186
+ out.push(...r.items);
187
+ total = r.total;
188
+ if (!r.items.length || out.length >= total) break;
189
+ }
190
+ return { total, items: out };
191
+ }
192
+
193
+ export async function fileInfo(fileId, groupId) {
194
+ if (!fileId) throw badInput('缺少 fileId');
195
+ const data = await call({
196
+ method: 'GET',
197
+ path: `/api/v1/files/${encodeURIComponent(fileId)}/info` + gidQuery(groupId),
198
+ allowMissing: true,
199
+ });
200
+ if (!data) throw notFound(`附件不存在: ${fileId}(可能已被删除或不在当前工作空间)`);
201
+ return normalizeFileMeta(data);
202
+ }
203
+
204
+ export async function deleteFile(fileId, groupId) {
205
+ if (!fileId) throw badInput('缺少 fileId');
206
+ await call({
207
+ method: 'DELETE',
208
+ path: `/api/v1/files/${encodeURIComponent(fileId)}` + gidQuery(groupId),
209
+ });
210
+ return { fileId, deleted: true };
211
+ }
212
+
213
+ /**
214
+ * 取文件本体:返回未解析的 fetch Response(调用方 pipe / arrayBuffer)。
215
+ * 走的是**无鉴权的出图路由** /files/:fileId —— 与 <img src> 同一条路,
216
+ * 所以「浏览器能预览」与「CLI 能下载」在权限上永远一致。
217
+ */
218
+ export async function openFileStream(fileId) {
219
+ if (!fileId) throw badInput('缺少 fileId');
220
+ const cfg = await loadConfig();
221
+ const url = await fileAccessUrl(fileId);
222
+ const ctrl = new AbortController();
223
+ const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS);
224
+ let res;
225
+ try {
226
+ res = await fetch(url, {
227
+ headers: cfg.token ? { authorization: `Bearer ${cfg.token}` } : {},
228
+ signal: ctrl.signal,
229
+ });
230
+ } catch (e) {
231
+ if (e && e.name === 'AbortError') throw external(`下载超时(${TIMEOUT_MS}ms): ${fileId}`);
232
+ throw external(`无法连接后端 ${cfg.baseUrl}: ${e.message}`);
233
+ } finally {
234
+ clearTimeout(timer);
235
+ }
236
+ if (!res.ok) throw notFound(`附件下载失败(HTTP ${res.status}): ${fileId}`);
237
+ return res;
238
+ }
239
+
240
+ export async function downloadFile(fileId) {
241
+ const res = await openFileStream(fileId);
242
+ return Buffer.from(await res.arrayBuffer());
243
+ }
package/src/core/kvapi.js CHANGED
@@ -16,7 +16,9 @@ import { loadConfig, normalizeGroupId } from './config.js';
16
16
 
17
17
  const TIMEOUT_MS = 20000;
18
18
 
19
- async function call({ method, path, body, token, baseUrl, allowMissing = false }) {
19
+ // 信封感知的通用调用器。**导出**是为了让 fileapi.js 复用同一套
20
+ // 「HTTP 恒 200、成败看 code」的判定——两处各写一遍迟早分叉。
21
+ export async function call({ method, path, body, token, baseUrl, allowMissing = false }) {
20
22
  const cfg = baseUrl ? { baseUrl, token } : await loadConfig();
21
23
  const url = cfg.baseUrl.replace(/\/$/, '') + path;
22
24
 
package/src/core/paths.js CHANGED
@@ -8,11 +8,20 @@ export const APP_DIR = join(homedir(), '.nx-kv');
8
8
  export const STORE_PATH = join(APP_DIR, 'store.json');
9
9
  export const DEFAULT_PORT = 7877;
10
10
 
11
+ // 附件的本地镜像根目录。**刻意放在 nx-kv 的用户目录下**(~/.nx-kv/attachments/):
12
+ // agent 读附件只认本地路径,放在项目目录里会随 cwd 漂移,还会被 git 捡走。
13
+ export const ATTACHMENTS_DIR = join(APP_DIR, 'attachments');
14
+
11
15
  // 允许测试与多实例覆盖存储位置:NX_KV_STORE 环境变量优先
12
16
  export function storePathFromEnv() {
13
17
  return process.env.NX_KV_STORE || STORE_PATH;
14
18
  }
15
19
 
20
+ // 允许测试与多实例覆盖附件目录:NX_KV_ATTACHMENTS 环境变量优先
21
+ export function attachmentsRootFromEnv() {
22
+ return process.env.NX_KV_ATTACHMENTS || ATTACHMENTS_DIR;
23
+ }
24
+
16
25
  // 名称安全校验:拒绝路径穿越(保留中文等合法命名,与 fileops.go 语义一致)。
17
26
  //
18
27
  // 用于「这个字符串会被用作**目录名**」的场景:skill 名、内置包名、适配器 id。
@@ -0,0 +1,100 @@
1
+ // 附件模块(= 后端图床的用户空间视图)。
2
+ //
3
+ // 不声明 `resource`:这里的「集合」是后端图床的投影,`upload/sync` 是它的动作,
4
+ // 硬凑 get/update/remove 五动词只会得到语义别扭的命令。
5
+ // 命令与路由仍然一一对应,所以「面板上能做的,CLI 都能做」依旧成立。
6
+ import * as service from './service.js';
7
+
8
+ // 所有动作都接受 --group 覆盖当前工作空间;默认取本机配置里的当前值
9
+ const GROUP = { type: 'number', hint: '工作空间 id(默认取当前)' };
10
+
11
+ export default {
12
+ id: 'file',
13
+ title: '附件',
14
+ order: 40,
15
+ // 没有独立面板:附件在「清单」页里被引用与预览,单独开一个 tab
16
+ // 会得到第二个「附件列表」,反而不知道以哪个为准。
17
+ view: null,
18
+
19
+ actions: [
20
+ {
21
+ id: 'file.list',
22
+ cli: ['file', 'list'],
23
+ http: ['GET', '/api/file'],
24
+ summary: '列出当前用户空间的附件(含本地已同步路径)',
25
+ flags: {
26
+ group: GROUP,
27
+ limit: { type: 'number', default: 100 },
28
+ offset: { type: 'number', default: 0 },
29
+ },
30
+ run: (ctx) => service.listFilesAction(ctx),
31
+ render: (d) => service.renderFileList(d),
32
+ },
33
+ {
34
+ id: 'file.upload',
35
+ cli: ['file', 'upload'],
36
+ http: ['POST', '/api/file'],
37
+ summary: '上传附件到当前用户空间(--path 本机文件;面板走 --content base64 --name 文件名)',
38
+ flags: {
39
+ path: { type: 'string', hint: '本机文件路径' },
40
+ content: { type: 'string', hint: 'base64 内容(面板上传用,可为 data URL)' },
41
+ name: { type: 'string', hint: '文件名(content 上传时必填)' },
42
+ contentType: { type: 'string', hint: '覆盖 Content-Type(默认按扩展名猜)' },
43
+ accessLevel: { type: 'string', enum: ['public', 'private', 'protected'], default: 'public', hint: '出图权限;public 才能被 <img> 直接预览' },
44
+ group: GROUP,
45
+ },
46
+ run: (ctx) => service.uploadFileAction(ctx),
47
+ render: (d) => service.renderUpload(d),
48
+ },
49
+ {
50
+ id: 'file.get',
51
+ cli: ['file', 'get'],
52
+ http: ['GET', '/api/file/item'],
53
+ summary: '查单个附件的元数据与本地路径',
54
+ args: ['fileId'],
55
+ flags: { group: GROUP },
56
+ run: (ctx) => service.getFileAction(ctx.fileId, { group: ctx.group }),
57
+ render: (d) => service.renderFileInfo(d),
58
+ },
59
+ {
60
+ id: 'file.remove',
61
+ cli: ['file', 'remove'],
62
+ http: ['DELETE', '/api/file/item'],
63
+ summary: '删除附件(后端软删;本地副本要清用 file sync --prune)',
64
+ args: ['fileId'],
65
+ flags: { group: GROUP },
66
+ run: (ctx) => service.removeFileAction(ctx.fileId, { group: ctx.group }),
67
+ render: (d) => service.renderRemove(d),
68
+ },
69
+ {
70
+ id: 'file.content',
71
+ // HTTP 侧直接透传文件本体(面板里 <img src="/api/file/content/<id>"> 预览);
72
+ // CLI 侧只打印地址与本地路径 —— 终端吐二进制没有意义。
73
+ cli: ['file', 'content'],
74
+ http: ['GET', '/api/file/content/:fileId'],
75
+ stream: true,
76
+ summary: '取附件本体:面板内联预览;CLI 打印出图地址与本地路径',
77
+ args: ['fileId'],
78
+ flags: { group: GROUP },
79
+ run: (ctx) => (ctx.__raw
80
+ ? service.serveContent(ctx)
81
+ : service.getFileAction(ctx.fileId, { group: ctx.group })),
82
+ render: (d) => service.renderContent(d),
83
+ },
84
+ {
85
+ id: 'file.sync',
86
+ cli: ['file', 'sync'],
87
+ http: ['POST', '/api/file/sync'],
88
+ summary: '把附件同步到本机(默认全部;--ids 只同步指定附件)——为了不再依赖网络读附件',
89
+ flags: {
90
+ ids: { type: 'array', hint: '只同步这些 fileId(逗号分隔)' },
91
+ dir: { type: 'string', hint: '本地目录(默认 ~/.nx-kv/attachments/<工作空间>/)' },
92
+ prune: { type: 'boolean', hint: '删掉本地已不在后端的文件(仅全量同步时生效)' },
93
+ dryRun: { type: 'boolean', hint: '只列出将下载什么,不落盘' },
94
+ group: GROUP,
95
+ },
96
+ run: (ctx) => service.syncFilesAction(ctx),
97
+ render: (d) => service.renderSync(d),
98
+ },
99
+ ],
100
+ };
@@ -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
+ }
@@ -0,0 +1,33 @@
1
+ import * as service from './service.js';
2
+
3
+ export default {
4
+ id: 'setting',
5
+ title: '设置',
6
+ order: 5,
7
+ // 没有独立面板:开关就放在「清单」页里(附件是清单的一部分),
8
+ // 单独一个 tab 反而让「在哪改」变成一次多余的翻找。
9
+ view: null,
10
+
11
+ actions: [
12
+ {
13
+ id: 'setting.get',
14
+ cli: ['setting', 'get'],
15
+ http: ['GET', '/api/setting'],
16
+ summary: '读本机设置(附件是否读取时自动下载、附件目录)',
17
+ run: () => service.getSettings(),
18
+ render: (d) => service.renderSettings(d),
19
+ },
20
+ {
21
+ id: 'setting.set',
22
+ cli: ['setting', 'set'],
23
+ http: ['POST', '/api/setting'],
24
+ summary: '改本机设置(只改传入项)',
25
+ flags: {
26
+ autoSyncAttachments: { type: 'boolean', hint: '读任务时自动把附件下载到本地' },
27
+ attachmentsDir: { type: 'string', hint: '附件本地目录(空 = ~/.nx-kv/attachments/<工作空间>/)' },
28
+ },
29
+ run: (ctx) => service.setSettings(ctx),
30
+ render: (d) => service.renderSettings(d),
31
+ },
32
+ ],
33
+ };
@@ -0,0 +1,48 @@
1
+ // 设置模块:本机行为的开关。
2
+ //
3
+ // 为什么单独成模块而不是塞进 system:设置是**用户会主动改的东西**,
4
+ // 需要 CLI 与面板两端都能读写(`nx-kv setting set` / 清单页的开关),
5
+ // 而 system 是只读聚合器(bootstrap / health / routes),不承担写操作。
6
+ //
7
+ // 落在 ~/.nx-kv/config.json:与登录态同一个文件(都是「怎么用这个工具」而非业务数据)。
8
+ import { loadConfig, saveConfig } from '../../core/config.js';
9
+ import { attachmentsRootFromEnv } from '../../core/paths.js';
10
+ import { localDirFor } from '../../core/attachstore.js';
11
+ import { badInput } from '../../core/errors.js';
12
+
13
+ const toBool = (v) => v === true || String(v) === 'true';
14
+
15
+ export async function getSettings() {
16
+ const cfg = await loadConfig();
17
+ return {
18
+ autoSyncAttachments: cfg.autoSyncAttachments,
19
+ attachmentsDir: cfg.attachmentsDir,
20
+ // 派生信息:面板要把「附件会落到哪」直接显示出来,省得用户去猜默认值
21
+ attachmentsRoot: attachmentsRootFromEnv(),
22
+ resolvedDir: localDirFor(cfg.groupId, cfg.attachmentsDir),
23
+ groupId: cfg.groupId,
24
+ baseUrl: cfg.baseUrl,
25
+ };
26
+ }
27
+
28
+ export async function setSettings(patch = {}) {
29
+ const body = {};
30
+ if (patch.autoSyncAttachments !== undefined) body.autoSyncAttachments = toBool(patch.autoSyncAttachments);
31
+ if (patch.attachmentsDir !== undefined) body.attachmentsDir = String(patch.attachmentsDir || '').trim();
32
+ if (!Object.keys(body).length) {
33
+ throw badInput('没有要改的设置:--autoSyncAttachments <true|false> / --attachmentsDir <目录>');
34
+ }
35
+ await saveConfig({ ...(await loadConfig()), ...body });
36
+ return getSettings();
37
+ }
38
+
39
+ export function renderSettings(d) {
40
+ return [
41
+ `附件读取时自动下载: ${d.autoSyncAttachments ? '开' : '关'}`,
42
+ `附件默认目录: ${d.resolvedDir}`,
43
+ d.attachmentsDir ? `(由设置覆盖;默认根目录 ${d.attachmentsRoot})` : '',
44
+ `当前工作空间: ${d.groupId || '默认组'}`,
45
+ ]
46
+ .filter(Boolean)
47
+ .join('\n');
48
+ }