nx-kv 0.45.1 → 0.47.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 (70) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +11 -5
  3. package/assets/kv-get/SKILL.md +1 -1
  4. package/assets/kv-get/references/timegoal-workflow.md +7 -7
  5. package/assets/kv-get/references/timegoal.md +6 -6
  6. package/bin/{cli.mjs → kv.mjs} +13 -2
  7. package/package.json +23 -11
  8. package/src/core/{command-table.js → command-table.ts} +16 -5
  9. package/src/core/{config.js → config.ts} +46 -27
  10. package/src/core/db/quiet.js +4 -0
  11. package/src/core/{errors.js → errors.ts} +35 -18
  12. package/src/core/{open.js → open.ts} +3 -3
  13. package/src/core/{paths.js → paths.ts} +18 -9
  14. package/src/core/{serve-port.js → serve-port.ts} +43 -17
  15. package/src/index.js +11 -9
  16. package/src/index.ts +10 -0
  17. package/src/modules/localtask/action-lifecycle.js +3 -6
  18. package/src/modules/localtask/repo/goals.js +5 -6
  19. package/src/modules/localtask/task-lifecycle.js +2 -2
  20. package/src/modules/system/actions/_manifest.generated.ts +23 -0
  21. package/src/modules/system/actions/bootstrap.ts +74 -0
  22. package/src/modules/system/actions/health.ts +57 -0
  23. package/src/modules/system/actions/routes.ts +26 -0
  24. package/src/modules/system/index.ts +29 -0
  25. package/src/modules/system/{routes.js → routes.ts} +22 -26
  26. package/src/modules/system/schemas.ts +29 -0
  27. package/src/modules/tasktool/index.js +4 -7
  28. package/src/modules/tasktool/panel-escort.js +1 -1
  29. package/src/modules/tasktool/plugins/goal-template.js +2 -2
  30. package/src/modules/tasktool/plugins/taskgoal-store.js +1 -1
  31. package/src/modules/tasktool/plugins/timegoal-cwd-store.js +8 -11
  32. package/src/modules/tasktool/plugins/timegoal-task-store.js +9 -12
  33. package/src/runtime/action-base.ts +14 -0
  34. package/src/runtime/action-decorator.ts +176 -0
  35. package/src/runtime/api.ts +146 -0
  36. package/src/runtime/{cli.js → cli.ts} +241 -161
  37. package/src/runtime/codegen.ts +243 -0
  38. package/src/runtime/container.ts +53 -0
  39. package/src/runtime/{cors.js → cors.ts} +35 -28
  40. package/src/runtime/help.ts +77 -0
  41. package/src/runtime/registry.ts +139 -0
  42. package/src/runtime/{server.js → server.ts} +65 -24
  43. package/src/runtime/{spec.js → spec.ts} +122 -31
  44. package/src/runtime/types/module.ts +43 -0
  45. package/src/runtime/zod-bridge.ts +198 -0
  46. package/src/shared/prompt-blocks.js +1 -1
  47. package/src/web/frontend/api/cli-tree.json +49 -0
  48. package/src/web/frontend/api/client.generated.ts +39 -0
  49. package/src/web/public/assets/{Introduction-EHroxF1H.js → Introduction-BI8Ohz1l.js} +1 -1
  50. package/src/web/public/assets/{bar-BvS_Jfi4.js → bar-Jfji2mz3.js} +1 -1
  51. package/src/web/public/assets/{cloud-DlWk0wnP.js → cloud-cFewR3CF.js} +1 -1
  52. package/src/web/public/assets/{composer-panel-D3w-CjhN.js → composer-panel-CcK0D4Gd.js} +1 -1
  53. package/src/web/public/assets/{deleted-panel-BMJEEBWD.js → deleted-panel-oN8YlGvq.js} +1 -1
  54. package/src/web/public/assets/{dir-BtjHgH4Q.js → dir-BuAtw08k.js} +1 -1
  55. package/src/web/public/assets/{group-Bxq8JamU.js → group-FRUv4mQ6.js} +1 -1
  56. package/src/web/public/assets/{index-ChlZPTea.js → index-CyF6nNWE.js} +2 -2
  57. package/src/web/public/assets/{md-history-CBqcR086.js → md-history-DErcpXhC.js} +1 -1
  58. package/src/web/public/assets/{overview-BP5sB1WX.js → overview-DZHcrz4u.js} +1 -1
  59. package/src/web/public/assets/{refs-Dt7DQIOo.js → refs-BXIwmL5W.js} +1 -1
  60. package/src/web/public/assets/{repos-Zl1_SfPX.js → repos-DYugJZpl.js} +1 -1
  61. package/src/web/public/assets/{route-crumb-PqhQSVWL.js → route-crumb-C3Ce0rzR.js} +1 -1
  62. package/src/web/public/assets/{settings-CXWFvvvv.js → settings-Bpazt87u.js} +2 -2
  63. package/src/web/public/assets/{status-tag-BK-45ld2.js → status-tag-CHCpOgMP.js} +1 -1
  64. package/src/web/public/assets/{task-COFIPegR.js → task-G58spmPC.js} +1 -1
  65. package/src/web/public/assets/{templates-CIxgTTt-.js → templates-Dr0CunY8.js} +1 -1
  66. package/src/web/public/assets/{tool-bar-TIqYxsQl.js → tool-bar-BSIlsHln.js} +1 -1
  67. package/src/web/public/index.html +1 -1
  68. package/src/modules/system/index.js +0 -96
  69. package/src/runtime/api.js +0 -101
  70. package/src/runtime/registry.js +0 -89
@@ -0,0 +1,29 @@
1
+ // system 模块的 zod 契约:每个 action 一对入参 schema。
2
+ //
3
+ // 这份文件是「半自动化」的关键证据:它同时被三处消费——
4
+ // 1. 服务端:@action 装饰器引用它做入参校验(CLI 与 HTTP 共用同一份)
5
+ // 2. codegen:生成前端 apiclient 的入参类型(import type,零运行时进浏览器包)
6
+ // 3. 未来:前端表单校验可按需 import 同一份 schema(zod 本身浏览器安全)
7
+ //
8
+ // 命名约定(codegen 靠它自动拼 import 名):<camelCase(actionId)>Input,
9
+ // 如 system.bootstrap → systemBootstrapInput。约定破了 codegen 会生成指向
10
+ // 不存在符号的代码,tests/unit/api-client.test.mjs 的新鲜度对账会当场红。
11
+ //
12
+ // 已知边界(模板 spike 结论,别踩):
13
+ // - z.coerce 不能用('false'→true、''→0)——归一化在 runtime/zod-bridge.ts 做;
14
+ // - handler 入参类型手写 z.output(解析后形状);前端 client 入参是 z.input。
15
+ import { z } from 'zod';
16
+
17
+ // ---- system.bootstrap ----
18
+ export const systemBootstrapInput = z.object({});
19
+
20
+ // ---- system.health ----
21
+ export const systemHealthInput = z.object({});
22
+
23
+ // ---- system.routes ----
24
+ export const systemRoutesInput = z.object({
25
+ // 模块 id 过滤(正查)
26
+ module: z.string().optional(),
27
+ // `METHOD /api/path`(反查,:param 视为通配)
28
+ http: z.string().optional(),
29
+ });
@@ -73,7 +73,6 @@ function renderCheck(d) {
73
73
  ` 状态:${status}`,
74
74
  ` 截止:${d.deadline}(now=${d.now})`,
75
75
  ` 现状:${d.summary}`,
76
- ` 完成度 / 下一步:${d.progress}`,
77
76
  ` 日志:本目录已记录 ${d.logCount} 次检查(${d.checkedAt})`,
78
77
  ` 本轮提示词(${d.promptRendered ? '实时渲染' : 'store 原文'}):`,
79
78
  prompt,
@@ -183,18 +182,17 @@ export default {
183
182
  cli: ['timegoal', 'check'],
184
183
  http: ['GET', '/api/timegoals/check'],
185
184
  summary:
186
- '时间运算 + 原文回显 prompt + 写入一次状态日志;每次必须提供当前现状 --summary 与完成度/下一步 --progress',
185
+ '时间运算 + 原文回显 prompt + 写入一次状态日志;每次必须提供当前现状 --summary',
187
186
  flags: {
188
187
  cwd: { type: 'string', hint: '工作目录(与 --task 二选一)' },
189
188
  task: { type: 'string', hint: '任务级 goal key(task:<topicKey>:<taskId>;带时长任务领取时自带)' },
190
189
  summary: { type: 'string', required: true, hint: '当前现状(每次 check 记录到日志,≤2000 字)' },
191
- progress: { type: 'string', required: true, hint: '完成度/本轮成果/下一步(写入日志,≤2000 字)' },
192
190
  },
193
191
  run: (ctx) => {
194
192
  if (!ctx.cwd && !ctx.task) throw badInput('请给 --cwd <工作目录> 或 --task <任务goal key>');
195
193
  return ctx.task
196
- ? service.checkGoalByKey(ctx.task, { summary: ctx.summary, progress: ctx.progress })
197
- : service.checkTimegoal({ cwd: ctx.cwd, summary: ctx.summary, progress: ctx.progress });
194
+ ? service.checkGoalByKey(ctx.task, { summary: ctx.summary })
195
+ : service.checkTimegoal({ cwd: ctx.cwd, summary: ctx.summary });
198
196
  },
199
197
  render: renderCheck,
200
198
  },
@@ -219,7 +217,7 @@ export default {
219
217
  id: 'timegoal.log',
220
218
  cli: ['timegoal', 'log'],
221
219
  http: ['GET', '/api/timegoals/log'],
222
- summary: '查看本目录 timegoal 的检查日志(每轮 check 的现状 + 完成度)',
220
+ summary: '查看本目录 timegoal 的检查日志(每轮 check 的现状)',
223
221
  flags: { cwd: CWD },
224
222
  run: (ctx) => service.getTimegoalLog({ cwd: ctx.cwd }),
225
223
  render: (d) => {
@@ -232,7 +230,6 @@ export default {
232
230
  for (const e of d.entries) {
233
231
  lines.push(` ${e.checkedAt} ${e.reached ? '已到点' : `剩 ${fmtDur(e.remainingSec)}`}`);
234
232
  lines.push(` 现状:${e.summary}`);
235
- lines.push(` 下一步:${e.progress}`);
236
233
  }
237
234
  return lines.join('\n');
238
235
  },
@@ -29,7 +29,7 @@ export function deepLinkUrl(key, port) {
29
29
 
30
30
  // 本仓库/已安装包的 CLI 入口(src/modules/tasktool/ 上三级到包根)。
31
31
  function binCliPath() {
32
- return fileURLToPath(new URL('../../../bin/cli.mjs', import.meta.url));
32
+ return fileURLToPath(new URL('../../../bin/kv.mjs', import.meta.url));
33
33
  }
34
34
 
35
35
  // 确保常驻主面板可用:已在运行直接复用;否则后台 detached 拉起一个独立
@@ -15,12 +15,12 @@
15
15
  // {{goal.startedAt}} {{goal.deadline}} {{goal.remainingHuman}} {{goal.remainingSec}}
16
16
  // {{goal.elapsedHuman}} {{goal.elapsedSec}} {{goal.overtimeSec}} {{goal.reached}}
17
17
  // {{goal.extra}}
18
- // {{check.summary}} {{check.progress}} {{check.at}} {{check.count}}(仅 check 渲染时)
18
+ // {{check.summary}} {{check.at}} {{check.count}}(仅 check 渲染时)
19
19
  import { formatDuration, renderInstruction } from '../../../core/instruction-template.js';
20
20
 
21
21
  export const TASK_GOAL_PROMPT_TEMPLATE = [
22
22
  '本任务带时间目标(领取即计时,持续 {{goal.durationHuman}})。',
23
- '- 每轮推进先执行:nx-kv timegoal check --task {{goal.goalKey}} --summary "<本轮现状>" --progress "<进展/下一步>"',
23
+ '- 每轮推进先执行:nx-kv timegoal check --task {{goal.goalKey}} --summary "<本轮现状>"',
24
24
  '- 时间未到不得标记完成——应派出 sub agent 重新提出新的需求,再继续推进。',
25
25
  '- check 返回 reached:true 后才允许:nx-kv localtask done --id {{task.id}} --summary "<完成总结>"',
26
26
  '{{#if goal.extra}}',
@@ -9,7 +9,7 @@
9
9
  // → 任务记录带 timegoal 声明 { duration, prompt }(时长人类写法,领取时才解析)
10
10
  // 2. 领取:交付时刻(buildTaskDelivery)调 ensureTaskGoal → **领取即起表**
11
11
  // (起点 = consumedAt),并把 check 指令作为 goal.prompt 固化
12
- // 3. 推进:agent 每轮 `timegoal check --task <goalKey> --summary --progress`
12
+ // 3. 推进:agent 每轮 `timegoal check --task <goalKey> --summary`
13
13
  // 4. 完成:`localtask done --id ...` —— **未到时间拒绝标记完成**,提示派
14
14
  // sub agent 重新提出新的需求;到点自动记录最终 check
15
15
  //
@@ -229,7 +229,7 @@ export async function showTimegoal({ cwd: rawCwd } = {}) {
229
229
  * check 的共同实现(队列级):写一条流水 + 组装返回。
230
230
  * 日志先成功落库,再返回——「这轮 check 发生过」有据可查。
231
231
  */
232
- function applyCwdCheck(conn, blob, key, name, cwd, summary, progress) {
232
+ function applyCwdCheck(conn, blob, key, name, cwd, summary) {
233
233
  const at = nowMs();
234
234
  if (!blob) {
235
235
  return {
@@ -240,7 +240,6 @@ function applyCwdCheck(conn, blob, key, name, cwd, summary, progress) {
240
240
  overtimeSec: 0,
241
241
  prompt: '',
242
242
  summary,
243
- progress,
244
243
  key,
245
244
  name,
246
245
  cwd,
@@ -262,7 +261,6 @@ function applyCwdCheck(conn, blob, key, name, cwd, summary, progress) {
262
261
  overtimeSec: result.overtimeSec,
263
262
  reached: result.reached,
264
263
  summary,
265
- progress,
266
264
  });
267
265
  blob.totalChecks = (Number(blob.totalChecks) || blob.checks.length - 1) + 1;
268
266
  writeCwdGoal(conn, blob, at);
@@ -271,7 +269,6 @@ function applyCwdCheck(conn, blob, key, name, cwd, summary, progress) {
271
269
  ...result,
272
270
  prompt: goal.prompt, // 永远原文回显,绝不拼接/裁剪
273
271
  summary,
274
- progress,
275
272
  checkedAt: stampOf(at),
276
273
  startedAt: goal.startedAt,
277
274
  deadline: goal.deadline,
@@ -288,18 +285,17 @@ function applyCwdCheck(conn, blob, key, name, cwd, summary, progress) {
288
285
 
289
286
  /**
290
287
  * 时间运算 + 回显原 prompt,并追加一条状态日志。
291
- * - 每次有效 check 都要求调用方提供 `summary`(当前现状)与 `progress`
292
- * (完成度/下一步),空值、缺值、超长都拒绝,保证日志有用且可比较。
288
+ * - 每次有效 check 都要求调用方提供 `summary`(当前现状),空值、缺值、超长都
289
+ * 拒绝,保证日志有用且可比较。
293
290
  * - 有 goal:日志先成功落库,再返回 reached/time/prompt 和本次日志记录。
294
- * - 无 goal:仍需要提交 summary/progress,但不写日志(没有目标就不该有 goal 日志)。
291
+ * - 无 goal:仍需要提交 summary,但不写日志(没有目标就不该有 goal 日志)。
295
292
  * `prompt` 永远从库原文回显 —— 不让 agent 在长对话里漂移。
296
293
  */
297
- export async function checkTimegoal({ cwd: rawCwd, summary: rawSummary, progress: rawProgress } = {}) {
294
+ export async function checkTimegoal({ cwd: rawCwd, summary: rawSummary } = {}) {
298
295
  if (rawCwd === undefined || rawCwd === null || !String(rawCwd).trim()) {
299
296
  throw badInput('需要 --cwd "<工作目录>"');
300
297
  }
301
298
  const summary = normalizeLogField(rawSummary, 'summary', 2000);
302
- const progress = normalizeLogField(rawProgress, 'progress', 2000);
303
299
  const { key, name, cwd } = normalizeCwd(rawCwd);
304
300
  // ⚠️ check 是**写路径**(每轮都要写一条流水),"自动失效"(超过保留期 → 整条删掉)
305
301
  // 在这里顺便落库。读路径(show / list / 面板的 /api/timegoals/all)刻意不写:
@@ -307,12 +303,12 @@ export async function checkTimegoal({ cwd: rawCwd, summary: rawSummary, progress
307
303
  recycleAllCwdGoals({ persist: true });
308
304
  return withCwdGoalDb((conn) => {
309
305
  const blob = readCwdGoal(conn, key);
310
- return applyCwdCheck(conn, blob, key, name, cwd, summary, progress);
306
+ return applyCwdCheck(conn, blob, key, name, cwd, summary);
311
307
  });
312
308
  }
313
309
 
314
310
  /**
315
- * 读本目录 timegoal 的检查日志(每次 check 追加一条:现状 + 完成度)。
311
+ * 读本目录 timegoal 的检查日志(每次 check 追加一条:当轮现状)。
316
312
  * 这是 timegoal 的"历史"——回看每轮干了什么、剩多少时间。
317
313
  */
318
314
  export async function getTimegoalLog({ cwd: rawCwd } = {}) {
@@ -334,6 +330,7 @@ export async function getTimegoalLog({ cwd: rawCwd } = {}) {
334
330
  overtimeSec: Number(e.overtimeSec) || 0,
335
331
  reached: !!e.reached,
336
332
  summary: String(e.summary || ''),
333
+ // 历史 blob 可能带 progress 字段——参数已废不再写入,历史行原样透出
337
334
  progress: String(e.progress || ''),
338
335
  })),
339
336
  key,
@@ -4,7 +4,7 @@
4
4
  // 见 localtask/repo/goals.js)。任务级 goal 与**单条任务**一对一;
5
5
  // 起点 = **领取时刻**(localtask 领取路径调 startTaskGoal 时传入 consumedAt)。
6
6
  //
7
- // goal_checks 行的 progress 与 summary 合存在同一列(JSON 编码,见 goals.js)。
7
+ // goal_checks 行的 summary 存当轮总结(纯文本;旧库 JSON 编码在读取侧兼容,见 goals.js)。
8
8
  import { badInput } from '../../../core/errors.js';
9
9
  import { tx } from '../../../core/db/index.js';
10
10
  import { db as ltDb } from '../../localtask/repo/open.js';
@@ -151,11 +151,10 @@ export async function showGoalByKey(rawKey) {
151
151
  }
152
152
 
153
153
  /** 任务维度的最终 check(完成动作自动记录一条日志——「结束必须 check」的记录器语义)。 */
154
- export async function checkGoalByKey(rawKey, { summary: rawSummary, progress: rawProgress } = {}) {
154
+ export async function checkGoalByKey(rawKey, { summary: rawSummary } = {}) {
155
155
  const key = String(rawKey || '').trim();
156
156
  if (!key) throw badInput('请给 --cwd <工作目录> 或 --task <任务goal key>');
157
157
  const summary = normalizeLogField(rawSummary, 'summary', 2000);
158
- const progress = normalizeLogField(rawProgress, 'progress', 2000);
159
158
  const parsed = parseTaskGoalKey(key);
160
159
  if (!parsed) throw badInput('goal key 不合法(应为 task:<topicKey>:<seq>): ' + key);
161
160
  return tx(
@@ -170,21 +169,20 @@ export async function checkGoalByKey(rawKey, { summary: rawSummary, progress: ra
170
169
  overtimeSec: 0,
171
170
  prompt: '',
172
171
  summary,
173
- progress,
174
172
  key,
175
173
  name: key,
176
174
  cwd: '',
177
175
  now: stampNow(new Date(nowMs())),
178
176
  };
179
177
  }
180
- return applyGoalCheck(conn, row, parsed, summary, progress);
178
+ return applyGoalCheck(conn, row, parsed, summary);
181
179
  },
182
180
  { db: ltDb(), mode: 'IMMEDIATE' }
183
181
  );
184
182
  }
185
183
 
186
184
  /** 任务级 check 的共同实现:写一条 goal_checks 流水 + 组装返回。 */
187
- function applyGoalCheck(conn, row, parsed, summary, progress) {
185
+ function applyGoalCheck(conn, row, parsed, summary) {
188
186
  const at = nowMs();
189
187
  const goal = goalRowToGoal(row);
190
188
  const result = evalTimegoal(goal, at);
@@ -202,7 +200,6 @@ function applyGoalCheck(conn, row, parsed, summary, progress) {
202
200
  overtimeSec: result.overtimeSec,
203
201
  reached: result.reached,
204
202
  summary,
205
- progress,
206
203
  });
207
204
  const totalChecks = goalsRepo.countChecks(Number(row.id), conn);
208
205
  // 每轮 check 同源渲染(任务 #87):读任务**当下**的原文与附加要求,
@@ -232,7 +229,7 @@ function applyGoalCheck(conn, row, parsed, summary, progress) {
232
229
  startedAt: row.started_at,
233
230
  deadline: row.deadline,
234
231
  nowMs: at,
235
- check: { summary, progress, at: checkedAt, count: totalChecks },
232
+ check: { summary, at: checkedAt, count: totalChecks },
236
233
  });
237
234
  const promptTemplate = String(row.prompt || '');
238
235
  return {
@@ -242,7 +239,6 @@ function applyGoalCheck(conn, row, parsed, summary, progress) {
242
239
  task: { id: taskSeq, text: String((taskRow && taskRow.body) || '') },
243
240
  goal: ctx.goal,
244
241
  summary,
245
- progress,
246
242
  checkedAt,
247
243
  startedAt: goal.startedAt,
248
244
  deadline: goal.deadline,
@@ -257,15 +253,14 @@ function applyGoalCheck(conn, row, parsed, summary, progress) {
257
253
  };
258
254
  }
259
255
 
260
- export async function recordTaskCheck({ topicKey, taskId: seq, summary, progress } = {}) {
256
+ export async function recordTaskCheck({ topicKey, taskId: seq, summary } = {}) {
261
257
  const sum = normalizeLogField(summary, 'summary', 2000);
262
- const prog = normalizeLogField(progress, 'progress', 2000);
263
258
  if (!topicKey || seq === undefined || seq === null) return { recorded: false, reason: 'no_goal' };
264
259
  return tx(
265
260
  (conn) => {
266
261
  const row = goalsRepo.getGoalRowByTaskKey(topicKey, seq, conn);
267
262
  if (!row) return { recorded: false, reason: 'no_goal' };
268
- const payload = applyGoalCheck(conn, row, { topicKey: String(topicKey), seq: Number(seq) }, sum, prog);
263
+ const payload = applyGoalCheck(conn, row, { topicKey: String(topicKey), seq: Number(seq) }, sum);
269
264
  return { recorded: true, reached: payload.reached, checkedAt: payload.checkedAt };
270
265
  },
271
266
  { db: ltDb(), mode: 'IMMEDIATE' }
@@ -303,6 +298,8 @@ export async function getTaskGoalLog({ topicKey, taskId: seq } = {}) {
303
298
  let progress = '';
304
299
  try {
305
300
  const v = JSON.parse(String(c.summary || '{}'));
301
+ // 旧库的 summary 列存过 JSON `{summary, progress}` 编码——progress 参数
302
+ // 已废(不再写入),但历史行原样读出,web check 标签仍可显示
306
303
  if (v && typeof v === 'object') {
307
304
  summary = String(v.summary || '');
308
305
  progress = String(v.progress || '');
@@ -0,0 +1,14 @@
1
+ // action 的抽象基类:所有 action 类继承它,依赖经容器拿(IoC)。
2
+ //
3
+ // 为什么要基类而不是各自构造函数直接收依赖:
4
+ // - 容器 create 的签名统一为 `new (deps: Container) => T`——基类把这条约定固定下来,
5
+ // gen-actions 收清单时也只需认这一个形状;
6
+ // - 「我需要什么」写在**用点**(`this.deps.get('config')`),而不是构造函数的参数表
7
+ // ——新增依赖不必改调用方;
8
+ // - action 类只负责「声明 + 实现」,装配(模块编排、依赖注入、注册表收集)
9
+ // 都在基类与容器这一层。
10
+ import type { Container } from './container.js';
11
+
12
+ export abstract class ActionBase {
13
+ constructor(protected readonly deps: Container) {}
14
+ }
@@ -0,0 +1,176 @@
1
+ // action 装饰器:在 ModuleBase 子类的方法上声明 action(zod schema 即契约)。
2
+ //
3
+ // 单一通道:全部新业务 action 都走这里——声明(@action 元数据)与实现同文件,
4
+ // 契约常量放同域 schemas.ts;模块的 actions 字段由 zodActionsOf(instance) 收集。
5
+ // 迁移期 legacy plain-object action(flags 表契约)并存,Registry / CliApp /
6
+ // ApiRouter 对两通道无感;全部模块迁移后 legacy 删除。
7
+ //
8
+ // 三条实测结论(模板 spike 逼出来的,改前先读):
9
+ //
10
+ // (a) 元数据挂在**方法函数**上(WeakMap),不碰 `context.metadata`。
11
+ // tsx(esbuild)会给 context.metadata 传对象,但 `Symbol.metadata` 在 Node 22 里
12
+ // 是 undefined——tsc 编译后交给原生 Node 时 context.metadata 就是 undefined,
13
+ // 元数据会静默丢失。挂函数上与运行时无关,最稳。
14
+ //
15
+ // (b) 装饰器**不改方法签名**(TC39 要求返回类型与原方法兼容),handler 的入参类型
16
+ // 只能手写 `z.output<typeof schema>`。z.input(调用方形状,.default 字段可选)
17
+ // 与 z.output(解析后形状,.default 字段必填)别混:handler 拿的是 z.output。
18
+ //
19
+ // (c) 出参没有 schema——**实现即契约**:apiclient 的返回类型从 action 类的方法签名
20
+ // 直接推断(codegen type-only 引类),同一信息只声明一次。
21
+ import { describeInput, type FieldDesc } from './zod-bridge.js';
22
+ import type { ZodType } from 'zod';
23
+
24
+ /** 装饰式 action 绑定到实例后的公共形状(registry.actions 的元素类型之一)。 */
25
+ export interface BoundAction {
26
+ id: string;
27
+ module: string;
28
+ cli: readonly string[];
29
+ http?: readonly [string, string] | null;
30
+ summary?: string;
31
+ // meta 形参刻意与 legacy 的 run(ctx, { transport }) 同形(宽松 string 而非字面量联合):
32
+ // Registry / CliApp / ApiRouter 把两通道 action 装进同一个数组,run 必须可互相赋值。
33
+ run: (input: unknown, meta?: { transport?: string }) => unknown;
34
+ [k: string]: unknown;
35
+ }
36
+
37
+ export interface ActionMeta {
38
+ /** 全局唯一 id,编成 `模块.动作`(如 `system.bootstrap`) */
39
+ id: string;
40
+ /** CLI 命令路径的各段(如 ['bootstrap']) */
41
+ cli: readonly string[];
42
+ /** HTTP 路由:[METHOD, PATTERN]。纯 CLI 命令**显式写 null**(与 legacy 一致,测试断言两态) */
43
+ http?: readonly [string, string] | null;
44
+ /** 一句话说明,进 help 与面板 */
45
+ summary?: string;
46
+ /** 位置参数字段名(按声明顺序消费 argv) */
47
+ args?: readonly string[];
48
+ /** 尾部收参:剩余全部位置参数收进这个字段(z.array(z.string())) */
49
+ restArg?: string;
50
+ /** 输入 schema:CLI 与 HTTP 共用的真相源(运行时校验 + 归一化的依据)。 */
51
+ input: ZodType;
52
+ /** CLI 人读渲染(面板不用——面板拿 data 走 JSON)。 */
53
+ render?: (result: unknown, ctx?: unknown) => string | Promise<string>;
54
+ /** SSE 类动作:true 时 HTTP 侧把 req/res 透传给 run,action 自己接管响应 */
55
+ stream?: boolean;
56
+ }
57
+
58
+ /** 装饰器元数据表:方法函数 → 声明。WeakMap 不阻止方法被 GC。 */
59
+ const META = new WeakMap<object, ActionMeta>();
60
+
61
+ /**
62
+ * 标注一个 action 方法。用法:
63
+ *
64
+ * ```ts
65
+ * export class SystemModule extends ModuleBase {
66
+ * @action({ id: 'system.bootstrap', cli: ['bootstrap'], http: ['GET', '/api/bootstrap'],
67
+ * summary: '…', input: systemBootstrapInput })
68
+ * bootstrap(ctx: z.output<typeof systemBootstrapInput>) { return this.svc.bootstrap(); }
69
+ * }
70
+ * ```
71
+ */
72
+ export function action(meta: ActionMeta) {
73
+ return function <F extends (...args: never[]) => unknown>(value: F, context: { kind: string }): F {
74
+ if (context.kind !== 'method') {
75
+ throw new Error(`@action 只能标注方法(收到 kind=${context.kind})`);
76
+ }
77
+ META.set(value as unknown as object, meta);
78
+ return value;
79
+ };
80
+ }
81
+
82
+ /** 取某个方法上的 action 声明;没标注过返回 undefined */
83
+ export function metaOf(method: unknown): ActionMeta | undefined {
84
+ if (typeof method !== 'function') return undefined;
85
+ return META.get(method as object);
86
+ }
87
+
88
+ /**
89
+ * 装饰式 action 绑定到实例后的形状:在 BoundAction 之上多带 zod 契约。
90
+ * CliApp 与 ApiRouter 据此走 zod 解析通道;channel: 'zod' 是双通道判别的标记。
91
+ */
92
+ export interface ZodBoundAction extends BoundAction {
93
+ id: string;
94
+ cli: readonly string[];
95
+ /** 纯 CLI 命令显式为 null(与 legacy 的两态约定一致) */
96
+ http: readonly [string, string] | null;
97
+ summary?: string;
98
+ /** 位置参数字段名(describeInput 的排序依据) */
99
+ args?: readonly string[];
100
+ /** 尾部收参字段名(剩余位置参数全收进来) */
101
+ restArg?: string;
102
+ /** 逐字段说明(收集时用 describeInput 算好一次,CLI/HTTP/usage/codegen 共用) */
103
+ fields: FieldDesc[];
104
+ input: ZodType;
105
+ render?: (result: unknown, ctx?: unknown) => string | Promise<string>;
106
+ stream?: boolean;
107
+ channel: 'zod';
108
+ /** 绑定的 action 类名(codegen 按它从清单 type-only 引类);tsc 编译后类名不变形(无压缩)。 */
109
+ className: string;
110
+ /** 类上的方法名(= 装饰的属性名)。 */
111
+ method: string;
112
+ }
113
+
114
+ /** 路由模式里的 :param 列表 */
115
+ export function routeParams(pattern: string): string[] {
116
+ return [...pattern.matchAll(/:([\w-]+)/g)].map((m) => m[1]!);
117
+ }
118
+
119
+ /**
120
+ * 收集一个实例(ModuleBase 子类)里被 @action 标注的方法,绑定成 actions 数组。
121
+ *
122
+ * handler 以**实例**为 this 调用——装饰式的卖点就是「声明与实现写在一起、
123
+ * 类可以持有状态」(依赖经构造注入,handler 调 this.deps.get(...))。
124
+ * 收集时用 getOwnPropertyDescriptor 取值而不是 proto[name]——
125
+ * 后者会执行 getter,只为了看一眼它有没有被装饰器标过。
126
+ *
127
+ * 装载期自检:路由 :param 未在 args 里声明 → 当场报错(单通道下这是该一致性
128
+ * 的唯一防线——类型层无法校验运行期才拼出来的元数据)。
129
+ */
130
+ export function zodActionsOf(instance: object): ZodBoundAction[] {
131
+ const proto = Object.getPrototypeOf(instance);
132
+ const moduleId = String((instance as { id?: unknown }).id ?? '');
133
+ const out: ZodBoundAction[] = [];
134
+ for (const name of Object.getOwnPropertyNames(proto)) {
135
+ if (name === 'constructor') continue;
136
+ const descriptor = Object.getOwnPropertyDescriptor(proto, name);
137
+ const method = descriptor?.value;
138
+ if (typeof method !== 'function') continue;
139
+ const meta = metaOf(method);
140
+ if (!meta) continue;
141
+
142
+ const args = meta.args ?? [];
143
+ if (meta.http) {
144
+ const declared = new Set([...args, ...(meta.restArg ? [meta.restArg] : [])]);
145
+ for (const p of routeParams(meta.http[1])) {
146
+ if (!declared.has(p)) {
147
+ throw new Error(
148
+ `action ${meta.id} 的路由 ${meta.http[1]} 含 :${p},但 args 里没声明同名位置参数` +
149
+ '(运行时会是 undefined)',
150
+ );
151
+ }
152
+ }
153
+ }
154
+
155
+ const fields = describeInput(meta.input, args);
156
+ const bound = method as (this: typeof instance, input: unknown, meta?: { transport?: string }) => unknown;
157
+ out.push({
158
+ id: meta.id,
159
+ cli: meta.cli,
160
+ http: meta.http ?? null,
161
+ summary: meta.summary,
162
+ args,
163
+ restArg: meta.restArg,
164
+ fields,
165
+ input: meta.input,
166
+ render: meta.render,
167
+ stream: meta.stream,
168
+ channel: 'zod',
169
+ module: moduleId,
170
+ className: instance.constructor.name,
171
+ method: name,
172
+ run: (input: unknown, meta?: { transport?: string }) => bound.call(instance, input, meta),
173
+ });
174
+ }
175
+ return out;
176
+ }
@@ -0,0 +1,146 @@
1
+ // HTTP 路由层:路由表由 action.http 编译而来,与 CLI 同源。
2
+ //
3
+ // 这里没有手写路由 —— 每条路由都来自某个模块的 action 声明,
4
+ // 所以「面板上有按钮、CLI 里没命令」在结构上不可能发生。
5
+ // ApiRouter 在构造期把注册表的 actions 编译成排好序的路由表,
6
+ // handle() 是 server 的 /api/* 入口——一次编译,常驻复用。
7
+ //
8
+ // **迁移期双通道**:zod action 走 fields + normalizeCliValue + parseZodInput;
9
+ // legacy action 走 applySpec(flags 表契约)。路由匹配 / stream 透传 / 错误信封
10
+ // 两通道完全一致。
11
+ import type { IncomingMessage, ServerResponse } from 'node:http';
12
+ import { compileRoute, applySpec, usageOf, type AnyAction } from './spec.js';
13
+ import { normalizeCliValue, parseZodInput } from './zod-bridge.js';
14
+ import type { ZodBoundAction } from './action-decorator.js';
15
+ import { toErrorPayload, httpStatusOf } from '../core/errors.js';
16
+
17
+ interface RouteEntry {
18
+ action: AnyAction;
19
+ method: string;
20
+ keys: string[];
21
+ regex: RegExp;
22
+ }
23
+
24
+ // 逐段比较两条模式,决定谁该先匹配:**字面量段优先于参数段**,段数多的优先。
25
+ //
26
+ // 为什么要排序而不是按声明顺序:`GET /api/repos/status` 与 `GET /api/repos/:id`
27
+ // 都能匹配 `/api/repos/status`,谁先声明谁赢。一旦有人调整 actions 顺序,
28
+ // 前者就会被后者抢走——这种 bug 只在运行时、且只在特定路径上出现,极难排查。
29
+ // 排序后,声明顺序不再影响匹配结果。
30
+ function routeSpecificity([, pattern]: readonly [string, string]): string[] {
31
+ return pattern.split('/').filter(Boolean);
32
+ }
33
+
34
+ function compareRoutes(a: RouteEntry, b: RouteEntry): number {
35
+ const pa = routeSpecificity(a.action.http!);
36
+ const pb = routeSpecificity(b.action.http!);
37
+ for (let i = 0; i < Math.min(pa.length, pb.length); i++) {
38
+ const litA = !pa[i]!.startsWith(':');
39
+ const litB = !pb[i]!.startsWith(':');
40
+ if (litA !== litB) return litA ? -1 : 1; // 字面量在前
41
+ }
42
+ return pb.length - pa.length; // 更长的(更具体)在前
43
+ }
44
+
45
+ export function sendJson(res: ServerResponse, status: number, obj: unknown): void {
46
+ res.writeHead(status, {
47
+ 'content-type': 'application/json; charset=utf-8',
48
+ 'cache-control': 'no-store',
49
+ });
50
+ res.end(JSON.stringify(obj));
51
+ }
52
+
53
+ // 请求体上限。定得比较宽是因为**附件上传走 base64 JSON**(面板选图 → data URL →
54
+ // 这里),base64 有 ~33% 膨胀,10MB 的图片会变成 ~13MB 的 JSON。
55
+ // 仍然有上限:本机单用户工具,但没有上限就等于「一个请求能吃掉全部内存」。
56
+ const MAX_BODY_BYTES = 24 * 1024 * 1024;
57
+
58
+ async function readBody(req: IncomingMessage): Promise<Record<string, unknown>> {
59
+ const chunks: Buffer[] = [];
60
+ let size = 0;
61
+ for await (const c of req) {
62
+ size += (c as Buffer).length;
63
+ if (size > MAX_BODY_BYTES) throw new Error(`请求体过大(上限 ${MAX_BODY_BYTES / 1024 / 1024}MB)`);
64
+ chunks.push(c as Buffer);
65
+ }
66
+ if (!chunks.length) return {};
67
+ return JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record<string, unknown>;
68
+ }
69
+
70
+ export class ApiRouter {
71
+ private readonly routes: RouteEntry[];
72
+
73
+ constructor(actions: readonly AnyAction[]) {
74
+ this.routes = actions
75
+ .filter((a) => a.http)
76
+ .map((action) => {
77
+ const compiled = compileRoute(action as { http: readonly [string, string] });
78
+ return { action, method: compiled.method, keys: compiled.keys, regex: compiled.regex };
79
+ })
80
+ .sort(compareRoutes);
81
+ }
82
+
83
+ /** server 的 /api/* 入口:逐条尝试路由表,命中即执行并回 JSON。 */
84
+ async handle(req: IncomingMessage, res: ServerResponse, url: URL): Promise<void> {
85
+ const method = (req.method || 'GET').toUpperCase();
86
+
87
+ for (const route of this.routes) {
88
+ if (route.method !== method) continue;
89
+ const m = route.regex.exec(url.pathname);
90
+ if (!m) continue;
91
+
92
+ try {
93
+ const action = route.action;
94
+ // 这里不再按 Origin 拒绝写请求(任务 #57)。
95
+ // 原先那道校验比对 Origin 主机名是不是 127.0.0.1——但浏览器对 POST 一律带
96
+ // Origin(哪怕同源),于是走内网穿透从手机访问时 Origin 是隧道域名,
97
+ // 自己面板的同源写请求被判成跨站 → 403,任务提交不了。
98
+ // 跨域改由标准 CORS 头处理(预检 + allow-origin),见 runtime/cors.ts。
99
+
100
+ const raw: Record<string, unknown> = {};
101
+ route.keys.forEach((k, i) => {
102
+ raw[k] = decodeURIComponent(m[i + 1]!);
103
+ });
104
+ if (method === 'GET' || method === 'HEAD') {
105
+ for (const [k, v] of url.searchParams) raw[k] = v;
106
+ } else {
107
+ Object.assign(raw, await readBody(req).catch(() => ({})));
108
+ }
109
+
110
+ // 双通道分叉点:zod 走 fields 归一化 + zod 校验;legacy 走 applySpec。
111
+ const input = action.channel === 'zod'
112
+ ? parseZodChannelInput(action as ZodBoundAction, raw)
113
+ : applySpec(action, raw);
114
+
115
+ // stream 模式:把 req/res/url 透传给 run,让 action 自己接管响应(SSE 等)
116
+ if (action.stream) {
117
+ await action.run!({ ...input, __raw: { req, res, url } }, { transport: 'http' });
118
+ return;
119
+ }
120
+ const data = await action.run!(input, { transport: 'http' });
121
+ sendJson(res, 200, { ok: true, data });
122
+ } catch (err) {
123
+ // 错误码 → HTTP 状态只在这一处映射(core/errors.ts 提供表)
124
+ const p = toErrorPayload(err);
125
+ const payload: Record<string, unknown> = { ok: false, error: p.message, code: p.code };
126
+ if (p.details !== undefined) payload.details = p.details;
127
+ sendJson(res, httpStatusOf(p.code), payload);
128
+ }
129
+ return;
130
+ }
131
+
132
+ sendJson(res, 404, { ok: false, error: '接口不存在: ' + method + ' ' + url.pathname });
133
+ }
134
+ }
135
+
136
+ /** zod 通道的 HTTP 输入解析:路由参数 / query / body 统一过 normalizeCliValue 再校验。 */
137
+ function parseZodChannelInput(cmd: ZodBoundAction, raw: Record<string, unknown>): Record<string, unknown> {
138
+ const fields = cmd.fields;
139
+ const usage = usageOf(cmd);
140
+ const out: Record<string, unknown> = { ...raw };
141
+ for (const [k, v] of Object.entries(raw)) {
142
+ const f = fields.find((x) => x.name === k);
143
+ if (f) out[k] = normalizeCliValue(f, v);
144
+ }
145
+ return parseZodInput(cmd.input, out, usage) as Record<string, unknown>;
146
+ }