@sleep2agi/commhub-server 0.9.0-preview.7 → 0.9.0-preview.71

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 (170) hide show
  1. package/README.md +130 -10
  2. package/bin/commhub.ts +10 -2
  3. package/package.json +5 -5
  4. package/src/ack-create-request-transport.test.ts +159 -0
  5. package/src/ack-create-request.test.ts +331 -0
  6. package/src/admin-delete-network-http.test.ts +177 -0
  7. package/src/admin-networks-http.test.ts +88 -0
  8. package/src/agent-access.ts +461 -0
  9. package/src/agent-acl-groups-http.test.ts +247 -0
  10. package/src/agent-acl-http.test.ts +510 -0
  11. package/src/agent-acl-slice3-http.test.ts +267 -0
  12. package/src/agent-groups-perf.test.ts +167 -0
  13. package/src/alias-filter.test.ts +72 -0
  14. package/src/alias-filter.ts +32 -0
  15. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  16. package/src/api-host-supervisors-fallback.test.ts +271 -0
  17. package/src/api-nodes-shape.test.ts +26 -10
  18. package/src/auth-sessions-http.test.ts +250 -0
  19. package/src/auth-validate.test.ts +5 -1
  20. package/src/auth.ts +423 -29
  21. package/src/avatar-validate.test.ts +163 -0
  22. package/src/avatar-validate.ts +103 -0
  23. package/src/blocked-exit-on-reply.test.ts +122 -0
  24. package/src/boot-side-effect.test.ts +124 -0
  25. package/src/config-apply-sec1.test.ts +107 -0
  26. package/src/config-apply-validate.test.ts +92 -0
  27. package/src/config-apply-validate.ts +81 -3
  28. package/src/create-node-blocked-gate.test.ts +356 -0
  29. package/src/create-node-tool-schema.test.ts +39 -0
  30. package/src/create-node-validate.test.ts +89 -1
  31. package/src/create-node-validate.ts +89 -7
  32. package/src/create-node-workdir.test.ts +255 -0
  33. package/src/create-node.ts +51 -1
  34. package/src/dashboard-slash-routing-http.test.ts +107 -0
  35. package/src/db-adapter-guard.test.ts +85 -0
  36. package/src/db-adapter-translate.test.ts +112 -0
  37. package/src/db-adapter.ts +246 -83
  38. package/src/db-timestamp.test.ts +38 -0
  39. package/src/db-timestamp.ts +15 -0
  40. package/src/db.ts +799 -33
  41. package/src/delivered-without-push.test.ts +140 -0
  42. package/src/desktop-message-seam.test.ts +150 -0
  43. package/src/desktop-message.test.ts +368 -0
  44. package/src/ext-token-shared.test.ts +60 -0
  45. package/src/ext-validation-regression.test.ts +131 -0
  46. package/src/external-schedule-edits-http.test.ts +321 -0
  47. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  48. package/src/external-schedule-edits.ts +327 -0
  49. package/src/file-download-authz-dev-open.test.ts +135 -0
  50. package/src/file-download-authz.test.ts +404 -0
  51. package/src/file-download-date-bucket.test.ts +436 -0
  52. package/src/file-network-scope-dev-open.test.ts +97 -0
  53. package/src/file-network-scope.test.ts +732 -0
  54. package/src/health-redaction.test.ts +642 -0
  55. package/src/http-gzip.test.ts +73 -0
  56. package/src/http-gzip.ts +60 -0
  57. package/src/hub-timestamp.test.ts +38 -0
  58. package/src/hub-timestamp.ts +27 -0
  59. package/src/human-dm.ts +149 -0
  60. package/src/inbox-count-sse.test.ts +310 -0
  61. package/src/inbox-count.ts +29 -0
  62. package/src/index.ts +15 -2331
  63. package/src/lifecycle-guard.ts +50 -0
  64. package/src/mcp-write-network-resolution.test.ts +429 -0
  65. package/src/messages-ack-by-agent-http.test.ts +142 -0
  66. package/src/network-name-http.test.ts +75 -0
  67. package/src/network-scope.ts +224 -0
  68. package/src/node-attrs-validate.ts +88 -0
  69. package/src/node-attrs.test.ts +217 -0
  70. package/src/node-create-request-status-http.test.ts +92 -0
  71. package/src/node-files-transport.test.ts +344 -0
  72. package/src/node-id-alias.test.ts +188 -0
  73. package/src/node-lifecycle-controllable.test.ts +64 -0
  74. package/src/node-lifecycle-controllable.ts +51 -0
  75. package/src/node-logs-transport.test.ts +263 -0
  76. package/src/node-request-retention.test.ts +281 -0
  77. package/src/node-request-retention.ts +120 -0
  78. package/src/node-skills-transport.test.ts +209 -0
  79. package/src/node-token-privilege-http.test.ts +149 -0
  80. package/src/observer-avatar-http.test.ts +429 -0
  81. package/src/observer-push.test.ts +252 -0
  82. package/src/package-version-consistency.test.ts +25 -0
  83. package/src/peer-reply-atomic.test.ts +455 -0
  84. package/src/peer-reply-capability.test.ts +70 -0
  85. package/src/pg-worker.ts +87 -0
  86. package/src/push.ts +204 -7
  87. package/src/redact-tokens.test.ts +65 -0
  88. package/src/redact-tokens.ts +40 -0
  89. package/src/rename.ts +7 -2
  90. package/src/reply-target-derivation.test.ts +96 -0
  91. package/src/report-status-host-schema.test.ts +211 -0
  92. package/src/report-status-resume-id-handover.test.ts +150 -0
  93. package/src/require-explicit-test-db.ts +9 -0
  94. package/src/requirement-tags.ts +16 -0
  95. package/src/requirements-etag-http.test.ts +91 -0
  96. package/src/requirements-http.test.ts +708 -0
  97. package/src/requirements-mcp.test.ts +142 -0
  98. package/src/requirements-migrate.ts +83 -0
  99. package/src/requirements-priority-lowest.test.ts +114 -0
  100. package/src/requirements-start-date.test.ts +125 -0
  101. package/src/requirements-upgrade-e2e.test.ts +126 -0
  102. package/src/requirements-upgrade-migration.test.ts +85 -0
  103. package/src/requirements.ts +899 -0
  104. package/src/resolve-port.test.ts +57 -0
  105. package/src/resolve-port.ts +44 -0
  106. package/src/response-charset.test.ts +130 -0
  107. package/src/rest-explicit-columns-http.test.ts +216 -0
  108. package/src/rest-identity.test.ts +129 -0
  109. package/src/rest-identity.ts +100 -0
  110. package/src/rest-projections.ts +68 -0
  111. package/src/rest-write-network-resolution.test.ts +133 -0
  112. package/src/restricted-files.ts +73 -0
  113. package/src/retention.ts +10 -1
  114. package/src/rules-file-duplicate-alias.test.ts +234 -0
  115. package/src/rules-file-session-target.test.ts +207 -0
  116. package/src/rules-file-transport.test.ts +237 -0
  117. package/src/runtime-label.test.ts +22 -0
  118. package/src/runtime-label.ts +21 -0
  119. package/src/scheduled-doorbell-nodeless-session.test.ts +130 -0
  120. package/src/scheduled-run-terminal.test.ts +268 -0
  121. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  122. package/src/scheduled-tasks-http.test.ts +625 -0
  123. package/src/scheduled-tasks.ts +597 -0
  124. package/src/send-dedup-request-id.test.ts +229 -0
  125. package/src/send-reply-agent-warning.test.ts +202 -0
  126. package/src/send-reply-alias-optional.test.ts +131 -0
  127. package/src/send-reply-attachments.test.ts +458 -0
  128. package/src/send_dedup.test.ts +54 -0
  129. package/src/send_dedup.ts +52 -6
  130. package/src/serve-error.test.ts +38 -0
  131. package/src/serve-error.ts +27 -0
  132. package/src/server.ts +4385 -0
  133. package/src/shared/external-schedule-contract.ts +60 -0
  134. package/src/side-thread-command-transport.test.ts +302 -0
  135. package/src/side-thread-command-transport.ts +318 -0
  136. package/src/side-thread-http-integration.test.ts +233 -0
  137. package/src/side-thread-http.ts +504 -0
  138. package/src/side-thread-production.test.ts +72 -0
  139. package/src/side-thread-production.ts +118 -0
  140. package/src/side-thread.test.ts +1067 -0
  141. package/src/side-thread.ts +2495 -0
  142. package/src/skillhub-http.test.ts +92 -0
  143. package/src/start-node.test.ts +109 -0
  144. package/src/status-alias-filter-http.test.ts +106 -0
  145. package/src/stop-delete-node.test.ts +1164 -0
  146. package/src/task-auth-origin-http.test.ts +91 -0
  147. package/src/task-auth-origin.test.ts +24 -0
  148. package/src/task-auth-origin.ts +7 -0
  149. package/src/task-consumption.test.ts +482 -0
  150. package/src/task-diagnostic-http.test.ts +149 -0
  151. package/src/task-diagnostic.test.ts +115 -0
  152. package/src/task-diagnostic.ts +118 -0
  153. package/src/task-idempotency-mcp.test.ts +142 -0
  154. package/src/task-idempotency.test.ts +60 -0
  155. package/src/task-idempotency.ts +75 -0
  156. package/src/task-lifecycle-watcher.test.ts +204 -0
  157. package/src/task-lifecycle-watcher.ts +49 -0
  158. package/src/task-network-resolution-http.test.ts +141 -0
  159. package/src/tasks-pagination-http.test.ts +141 -0
  160. package/src/tools-list-json-schema.test.ts +66 -0
  161. package/src/tools.ts +3446 -257
  162. package/src/update-provider.test.ts +65 -0
  163. package/src/upload-early-reject-guard.test.ts +155 -0
  164. package/src/uploads-http.test.ts +97 -15
  165. package/src/uploads.test.ts +66 -0
  166. package/src/uploads.ts +130 -5
  167. package/src/user-inbox-by-agent-http.test.ts +161 -0
  168. package/src/user-inbox-netid-notnull.test.ts +122 -0
  169. package/src/user-inbox-read-http.test.ts +223 -0
  170. package/src/user-inbox-schema.test.ts +54 -0
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import {
3
3
  ValidationError,
4
- validateName, validateRuntime, validateModel, validateFlagValue,
4
+ validateName, validateRuntime, validateModel, validateFlagValue, RUNTIMES,
5
5
  validateEnvRefs, validateChannelsP1, serializeEnvLocal, buildAnetArgs,
6
6
  MAX_ENV_KEYS_PER_NODE,
7
7
  } from "./create-node-validate.js";
@@ -35,6 +35,15 @@ describe("validateRuntime / validateModel (§4.2.2)", () => {
35
35
  expect(() => validateModel("gpt-4o")).not.toThrow();
36
36
  expect(() => validateModel("bad model")).toThrow(ValidationError);
37
37
  expect(() => validateModel("x;rm")).toThrow(ValidationError);
38
+ // provider/model(OpenCode 共存;桌面向导 0.2.61 起发这种形状,Vincent 2026-09-08 撞到 model_invalid)
39
+ expect(() => validateModel("opencode/mimo-v2.5-free")).not.toThrow();
40
+ expect(() => validateModel("anthropic/claude-sonnet-4")).not.toThrow();
41
+ expect(() => validateModel("a/b/c")).toThrow(ValidationError); // 只许一个斜杠
42
+ expect(() => validateModel("/model")).toThrow(ValidationError); // 不能以斜杠开头
43
+ expect(() => validateModel("provider/")).toThrow(ValidationError); // 不能以斜杠结尾
44
+ expect(() => validateModel("../x")).toThrow(ValidationError); // 纯点段(路径穿越形状)
45
+ expect(() => validateModel("x/.")).toThrow(ValidationError);
46
+ expect(() => validateModel("open code/m")).toThrow(ValidationError);
38
47
  expect(() => validateModel("")).toThrow(ValidationError);
39
48
  });
40
49
  });
@@ -169,6 +178,16 @@ describe("buildAnetArgs (§4.2.2 F2 — fully validated argv)", () => {
169
178
  expect(args).toContain("--permission-mode");
170
179
  expect(args[args.indexOf("--permission-mode") + 1]).toBe("plan");
171
180
  });
181
+ test("omitted model is allowed and does not emit --model", () => {
182
+ const args = buildAnetArgs({
183
+ name: "x", runtime: "codex-sdk",
184
+ flags: { permissionMode: "plan" },
185
+ });
186
+ expect(args).toEqual(["node", "create", "x", "--runtime", "codex-sdk", "--permission-mode", "plan"]);
187
+ });
188
+ test("empty model is still rejected", () => {
189
+ expect(() => buildAnetArgs({ name: "x", runtime: "codex-sdk", model: "" })).toThrow(ValidationError);
190
+ });
172
191
  test("rejects bad name with shell metachar", () => {
173
192
  expect(() => buildAnetArgs({ name: ";rm -rf /", runtime: "claude-agent-sdk", model: "x" })).toThrow(ValidationError);
174
193
  });
@@ -185,3 +204,72 @@ describe("buildAnetArgs (§4.2.2 F2 — fully validated argv)", () => {
185
204
  } as any)).toThrow(ValidationError);
186
205
  });
187
206
  });
207
+
208
+ // ─── runtime_invalid 要说清「允许哪些」和「还有什么路」 ────────────────
209
+ //
210
+ // 2026-08-28 实测:从 Dashboard 建一个 codex-app-server 节点,用户拿到的是
211
+ // {"ok":false,"error":"runtime_invalid","value":"codex-app-server"}
212
+ // 而目标机器的 daemon 日志里一行都没有 —— 请求被 hub 拦在最前面,
213
+ // 用户无从知道①哪些允许②是不是打错了③有没有别的办法。
214
+ // 🔴 2026-08-28:这一节原本拿 `codex-app-server` / `opencode-cli` 当"非法 runtime"的例子。
215
+ // #1298 把 hub 的 RUNTIMES 从 3 个放开到 7 个之后,那两个变成了合法值,这两条测试因此红了 ——
216
+ // **测试正确地抓到了行为变更**。修法是换例子,不是削弱断言:
217
+ // 意图仍然是「非法 runtime 要给可操作的报错」,只是例子换成永远不会合法的字符串。
218
+ describe("validateRuntime — 报错要可操作", () => {
219
+ function thrown(v: unknown): any {
220
+ try { validateRuntime(v); } catch (e: any) { return e; }
221
+ throw new Error("expected validateRuntime to throw");
222
+ }
223
+
224
+ test("非法 runtime 的报错带上允许集合", () => {
225
+ const e = thrown("definitely-not-a-runtime");
226
+ expect(e.code).toBe("runtime_invalid");
227
+ expect(Array.isArray(e.detail?.allowed)).toBe(true);
228
+ // 🔴 断言它等于 RUNTIMES 本身,而不是等于一份手抄的清单 ——
229
+ // 手抄的那份会漂,漂了之后报错会理直气壮地告诉用户一组错的名字。
230
+ expect(e.detail.allowed).toEqual([...RUNTIMES]);
231
+ });
232
+
233
+ test("报错带上一条出路提示", () => {
234
+ const e = thrown("another-bogus-runtime");
235
+ expect(typeof e.detail?.hint).toBe("string");
236
+ expect(e.detail.hint.length).toBeGreaterThan(10);
237
+ // 提示必须点名那条真实存在的路,否则它只是安慰话
238
+ expect(e.detail.hint).toContain("anet node create");
239
+ });
240
+
241
+ test("仍然回报用户传进来的那个值(便于识别是不是打错了)", () => {
242
+ const e = thrown("codex-app-servr"); // 故意少一个 e
243
+ expect(e.detail.value).toBe("codex-app-servr");
244
+ });
245
+
246
+ test("🔴 合法 runtime 一个都不能被这次改动误伤", () => {
247
+ for (const r of RUNTIMES) {
248
+ expect(() => validateRuntime(r)).not.toThrow();
249
+ }
250
+ // 正控:非字符串必须仍然被拒 —— 否则上面那条循环全过也说明不了什么
251
+ expect(() => validateRuntime(123 as any)).toThrow();
252
+ expect(() => validateRuntime(undefined as any)).toThrow();
253
+ });
254
+ });
255
+
256
+ // #1298 —— daemon 远程创建放开到 7 个 runtime(Vincent 2026-08-28 定,
257
+ // 理由是兜底排错:节点不动了,人要能进去跟 Codex / Claude Code 对话)。
258
+ describe("#1298 RUNTIMES —— 七个都放行,且与 CLI 侧一致", () => {
259
+ test("三个共存 runtime 不再被拒", () => {
260
+ for (const r of ["codex-app-server", "grok-build-cli", "opencode-cli"]) {
261
+ expect(() => validateRuntime(r)).not.toThrow();
262
+ }
263
+ });
264
+ test("原有四个仍然放行(放开不该顺手改坏别的)", () => {
265
+ for (const r of ["claude-agent-sdk", "claude-code-cli", "codex-sdk", "grok-build-acp"]) {
266
+ expect(() => validateRuntime(r)).not.toThrow();
267
+ }
268
+ });
269
+ test("🔴 恰好七个 —— 多一个少一个都要有人解释", () => {
270
+ expect(RUNTIMES.length).toBe(7);
271
+ // 正控:不在名单里的仍然被拒,证明上面不是"什么都放行"
272
+ expect(() => validateRuntime("definitely-not-a-runtime")).toThrow();
273
+ expect(() => validateRuntime("")).toThrow();
274
+ });
275
+ });
@@ -17,7 +17,33 @@ export class ValidationError extends Error {
17
17
  }
18
18
 
19
19
  // §4.2.2 — structural enums.
20
- export const RUNTIMES = ["claude-agent-sdk", "codex-sdk", "grok-build-acp"] as const;
20
+ // #1298 —— daemon 远程创建允许的 runtime。2026-08-28 从 3 个放开到 7 个。
21
+ //
22
+ // 放开之前挡着的问题是「daemon 建出来的是**无人值守**的后台进程,而三个共存 runtime
23
+ // 的本质是人和 agent 共用一个 TUI 会话 —— 建出来给谁用?」
24
+ //
25
+ // Vincent 2026-08-28 定,理由是**兜底排错**:
26
+ // 「某个节点突然不动了,人可以进去看。在 daemon 还没那么靠谱的情况下,
27
+ // 这非常重要 —— 至少可以跟 Codex 和 Claude Code 对话。」
28
+ // 🔴 关键在于 **attach 是「建好之后」的动作,不是「建的时候」的前提**。
29
+ //
30
+ // 支撑读数(2026-08-28 实测舰队):`通信牛` 跑 codex-app-server(共存 runtime),
31
+ // **764 次成功完成任务**,当天仍在跑 —— 比两个普通 runtime 的节点(61 次 / 3 次)
32
+ // 都多一个量级。⇒ 任务链路不需要人坐在屏幕前。
33
+ //
34
+ // 🔴 这七个名字与 `agent-network/src/normalize-runtime.ts` 的 `RuntimeName` 一致。
35
+ // 那边是 CLI 侧的全集;两边分叉过一次(daemon 侧的 VALID_RUNTIMES 早就是 7 个,
36
+ // 只有这里还是 3 个,而记录此事的 #1298 正文写的是「三道闸都关着」——
37
+ // **一份快照式的盘点,只在写下的那一刻是真的**)。
38
+ export const RUNTIMES = [
39
+ "claude-agent-sdk",
40
+ "claude-code-cli",
41
+ "codex-sdk",
42
+ "codex-app-server",
43
+ "grok-build-acp",
44
+ "grok-build-cli",
45
+ "opencode-cli",
46
+ ] as const;
21
47
  export type Runtime = typeof RUNTIMES[number];
22
48
 
23
49
  export const FLAG_KEYS = ["permissionMode", "dangerouslySkipPermissions", "maxTurns", "budget", "timeout"] as const;
@@ -32,7 +58,11 @@ const ENV_KEY_RE = /^[A-Z][A-Z0-9_]{0,63}$/;
32
58
 
33
59
  // §4.2.2 name + model.
34
60
  const NAME_RE = /^[a-z][a-z0-9_-]{0,63}$/;
35
- const MODEL_RE = /^[a-zA-Z0-9._:\-]+$/;
61
+ // OpenCode 共存的模型带 provider 前缀(`opencode/mimo-v2.5-free`,agent-node parseModelRef 按第一个 `/` 切),
62
+ // 桌面向导 0.2.61 起就发这种形状 —— 允许**恰好一个**斜杠分隔的两段;每段仍是原字符集,且不能是纯点(`..`/`.`)。
63
+ const MODEL_SEGMENT = "[a-zA-Z0-9._:\\-]+";
64
+ const MODEL_RE = new RegExp(`^${MODEL_SEGMENT}(?:/${MODEL_SEGMENT})?$`);
65
+ const MODEL_DOT_ONLY_SEGMENT = /(^|\/)\.+(\/|$)/;
36
66
 
37
67
  export function validateName(s: unknown): asserts s is string {
38
68
  if (typeof s !== "string" || !NAME_RE.test(s)) {
@@ -42,12 +72,29 @@ export function validateName(s: unknown): asserts s is string {
42
72
 
43
73
  export function validateRuntime(s: unknown): asserts s is Runtime {
44
74
  if (typeof s !== "string" || !(RUNTIMES as readonly string[]).includes(s)) {
45
- throw new ValidationError("runtime_invalid", { value: typeof s === "string" ? s.slice(0, 80) : typeof s });
75
+ // 🔴 原来只回一个 `runtime_invalid` + 用户传进来的那个值 —— **不说允许哪些,
76
+ // 也不说还有没有别的路**。2026-08-28 实测:从 Dashboard 建一个
77
+ // `codex-app-server` 节点,用户拿到的就是
78
+ // {"ok":false,"error":"runtime_invalid","value":"codex-app-server"}
79
+ // 而目标机器的 daemon 日志里一行都没有(请求根本没到)。
80
+ // 用户无从知道:①哪些是允许的 ②这个名字是不是打错了 ③有没有别的办法。
81
+ //
82
+ // `allowed` 直接由 RUNTIMES 展开,不是手写的第二份清单 ——
83
+ // 🔴 手写一份会漂移,而漂移之后报错会**理直气壮地告诉用户一组错的名字**。
84
+ throw new ValidationError("runtime_invalid", {
85
+ value: typeof s === "string" ? s.slice(0, 80) : typeof s,
86
+ allowed: [...RUNTIMES],
87
+ // 这句提示的前提是查过的:`agent-network/src/normalize-runtime.ts` 的
88
+ // `RuntimeName` / `SUPPORTED_RUNTIME_NAMES` 是 7 个,包含此处不放行的那几个,
89
+ // 所以「在目标机器上直接建」确实是一条真实存在的路,不是安慰话。
90
+ hint: "daemon 远程创建目前只放行以上 runtime;其余 runtime 可以在目标机器上直接 `anet node create --runtime <name>` 创建。",
91
+ });
46
92
  }
47
93
  }
48
94
 
49
- export function validateModel(s: unknown): asserts s is string {
50
- if (typeof s !== "string" || s.length === 0 || s.length > 100 || !MODEL_RE.test(s)) {
95
+ export function validateModel(s: unknown): asserts s is string | undefined | null {
96
+ if (s === undefined || s === null) return;
97
+ if (typeof s !== "string" || s.length === 0 || s.length > 100 || !MODEL_RE.test(s) || MODEL_DOT_ONLY_SEGMENT.test(s)) {
51
98
  throw new ValidationError("model_invalid", { value: typeof s === "string" ? s.slice(0, 80) : typeof s });
52
99
  }
53
100
  }
@@ -158,6 +205,40 @@ export function serializeEnvLocal(env: Record<string, string>): string {
158
205
  }).join("\n") + "\n";
159
206
  }
160
207
 
208
+ // app「新建节点」工作目录 —— hub 只判**形状**(daemon 才知道那台机器的 $HOME、系统目录、
209
+ // 目录里住没住别的节点,那几条在 agent-node/src/runtime/child-workdir.ts)。
210
+ // 这里挡的是「根本不像一条路径」的输入,让它在派发前就失败,而不是占一个请求行再被 daemon 拒。
211
+ export const MAX_WORKDIR_LEN = 1024;
212
+ export function validateWorkdir(s: unknown): asserts s is string | undefined | null {
213
+ if (s === undefined || s === null) return;
214
+ if (typeof s !== "string") throw new ValidationError("workdir_invalid", { reason: "must be string" });
215
+ const v = s.trim();
216
+ if (v.length === 0 || v.length > MAX_WORKDIR_LEN) {
217
+ throw new ValidationError("workdir_invalid", { reason: `length 1..${MAX_WORKDIR_LEN}` });
218
+ }
219
+ if (/[\u0000-\u001f\u007f]/.test(v)) throw new ValidationError("workdir_invalid", { reason: "control character" });
220
+ const shapeOk = v.startsWith("/") || v === "~" || v.startsWith("~/") || /^[A-Za-z]:[\\/]/.test(v);
221
+ if (!shapeOk) {
222
+ throw new ValidationError("workdir_invalid", { reason: "must be absolute (/…, ~/…, or C:\\…)", value: v.slice(0, 80) });
223
+ }
224
+ }
225
+
226
+ /** daemon 自报的默认工作目录根(`daemon_capabilities.default_workdir_root`),消毒后返回;
227
+ * 没报 / 形状不对 = null。**非 null 即表示该 daemon 认 `node_spec.workdir`** ——
228
+ * create_node 的「老 daemon 不收 workdir」门和 /api/host-supervisors 的透出共用这一个判据。 */
229
+ export function daemonDefaultWorkdirRoot(configSnapshot: unknown): string | null {
230
+ try {
231
+ const snap = typeof configSnapshot === "string" ? JSON.parse(configSnapshot) : configSnapshot;
232
+ const v = (snap as any)?.daemon_capabilities?.default_workdir_root;
233
+ if (typeof v !== "string" || v.length === 0 || v.length > MAX_WORKDIR_LEN) return null;
234
+ if (/[\u0000-\u001f\u007f]/.test(v)) return null;
235
+ if (!(v.startsWith("/") || /^[A-Za-z]:[\\/]/.test(v))) return null;
236
+ return v;
237
+ } catch {
238
+ return null;
239
+ }
240
+ }
241
+
161
242
  // §4.2.5 — channels fail-closed in P1.
162
243
  export function validateChannelsP1(channels: unknown): void {
163
244
  if (channels === undefined || channels === null) return;
@@ -173,7 +254,7 @@ export function validateChannelsP1(channels: unknown): void {
173
254
  export interface NodeSpec {
174
255
  name: string;
175
256
  runtime: Runtime;
176
- model: string;
257
+ model?: string | null;
177
258
  flags?: Record<string, unknown>;
178
259
  channels?: unknown;
179
260
  }
@@ -192,7 +273,8 @@ export function buildAnetArgs(spec: NodeSpec): string[] {
192
273
  validateModel(spec.model);
193
274
  validateChannelsP1(spec.channels);
194
275
 
195
- const args: string[] = ["node", "create", spec.name, "--runtime", spec.runtime, "--model", spec.model];
276
+ const args: string[] = ["node", "create", spec.name, "--runtime", spec.runtime];
277
+ if (spec.model) args.push("--model", spec.model);
196
278
  if (spec.flags && typeof spec.flags === "object") {
197
279
  for (const [k, v] of Object.entries(spec.flags)) {
198
280
  if (!(FLAG_KEYS as readonly string[]).includes(k)) {
@@ -0,0 +1,255 @@
1
+ import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
2
+ import "./require-explicit-test-db.js";
3
+ import { db } from "./db.js";
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { registerTools } from "./tools.js";
6
+ import { daemonDefaultWorkdirRoot, validateWorkdir, ValidationError } from "./create-node-validate.js";
7
+ import { addNetworkMember, login, register } from "./auth.js";
8
+
9
+ // app「新建节点」工作目录 —— hub 这一层管三件事:
10
+ // ① node_spec.workdir 的**形状**(绝对 / ~/… / C:\…),派发前就拒
11
+ // ② daemon 没自报 default_workdir_root(= 老 daemon,会静默忽略 workdir)⇒ 拒,不派
12
+ // ③ 请求行存下 workdir,get_create_request 原样交给 daemon;不带就**不出现**这个键
13
+ // 以及 /api/host-supervisors 只给 admin/owner 透出默认根(它是那台机器的家目录路径)。
14
+
15
+ const NET = "net_workdir_gate";
16
+ const USER_ID = "u_workdir_admin";
17
+ const DAEMON_ID = "node_workdir_daemon";
18
+ const DAEMON_ALIAS = "workdir-daemon";
19
+ const DAEMON_TOK = "tok_workdir_daemon";
20
+ const ROOT = "/home/user";
21
+
22
+ interface ToolHandler { (args: any, extra?: any): Promise<{ content: Array<{ type: "text"; text: string }> }>; }
23
+ interface Reply { ok?: boolean; error?: string; request_id?: string; node_spec?: any; [k: string]: unknown; }
24
+
25
+ function cleanup() {
26
+ for (const t of ["node_create_requests", "audit_log", "nodes", "sessions", "api_tokens", "network_members"]) {
27
+ try { db.run(`DELETE FROM ${t} WHERE network_id = ?1`, [NET]); } catch {}
28
+ }
29
+ try { db.run("DELETE FROM networks WHERE network_id = ?1", [NET]); } catch {}
30
+ try { db.run("DELETE FROM users WHERE user_id = ?1", [USER_ID]); } catch {}
31
+ }
32
+ beforeEach(cleanup);
33
+ afterAll(cleanup);
34
+
35
+ function seed(caps: Record<string, unknown>) {
36
+ db.run(`INSERT INTO users (user_id, username, password_hash, role, created_at) VALUES (?1, ?1, 'x', 'user', datetime('now'))`, [USER_ID]);
37
+ db.run(`INSERT OR REPLACE INTO networks (network_id, network_name, owner_id, created_at) VALUES (?1, ?1, ?2, datetime('now'))`, [NET, USER_ID]);
38
+ db.run(`INSERT INTO network_members (user_id, network_id, role, joined_at) VALUES (?1, ?2, 'admin', datetime('now'))`, [USER_ID, NET]);
39
+ db.run(
40
+ `INSERT INTO nodes (node_id, node_name, alias, network_id, config_snapshot, hostname, created_at, updated_at, lifecycle_state)
41
+ VALUES (?1, ?2, ?2, ?3, ?4, 'host-x', datetime('now'), datetime('now'), 'active')`,
42
+ [DAEMON_ID, DAEMON_ALIAS, NET, JSON.stringify({ role: "host_supervisor", daemon_capabilities: { runtimes_supported: ["claude-agent-sdk"], ...caps } })],
43
+ );
44
+ db.run(
45
+ `INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash, expires_at, revoked_at)
46
+ VALUES (?1, ?2, ?3, 'network', ?4, ?5, NULL, NULL)`,
47
+ [DAEMON_TOK, USER_ID, NET, `node:${DAEMON_ALIAS}`, `hash_${DAEMON_TOK}`],
48
+ );
49
+ }
50
+
51
+ function tools(callerTokenId: string | null = null): Record<string, ToolHandler> {
52
+ const server = new McpServer({ name: "test", version: "0" }) as any;
53
+ const out: Record<string, ToolHandler> = {};
54
+ const origTool = server.tool.bind(server);
55
+ server.tool = (name: string, d: string, schema: any, handler: ToolHandler) => { out[name] = handler; return origTool(name, d, schema, handler); };
56
+ const origRegisterTool = server.registerTool?.bind(server);
57
+ if (origRegisterTool) {
58
+ server.registerTool = (name: string, cfg: any, handler: ToolHandler) => { out[name] = handler; return origRegisterTool(name, cfg, handler); };
59
+ }
60
+ registerTools(server, undefined, NET, USER_ID, null, true, callerTokenId);
61
+ return out;
62
+ }
63
+
64
+ async function call(h: ToolHandler, args: any): Promise<Reply> {
65
+ return JSON.parse((await h(args)).content[0].text) as Reply;
66
+ }
67
+
68
+ const baseSpec = { name: "wd-child", runtime: "claude-agent-sdk", model: "claude-sonnet-4-5", flags: {} };
69
+
70
+ function rowCount(): number {
71
+ return db.get<{ n: number }>("SELECT COUNT(*) AS n FROM node_create_requests WHERE daemon_node_id = ?1", DAEMON_ID)?.n ?? -1;
72
+ }
73
+
74
+ describe("validateWorkdir — shape only", () => {
75
+ const ok = ["/home/user/proj", "/srv/x", "~", "~/proj", "C:\\Users\\alice\\proj", "D:/work", " /padded "];
76
+ for (const v of ok) test(`accepts ${JSON.stringify(v)}`, () => { expect(() => validateWorkdir(v)).not.toThrow(); });
77
+ test("accepts undefined / null (field omitted)", () => {
78
+ expect(() => validateWorkdir(undefined)).not.toThrow();
79
+ expect(() => validateWorkdir(null)).not.toThrow();
80
+ });
81
+ const bad: unknown[] = ["", " ", "proj", "./proj", "../x", "~alice/x", "C:proj", "/a\nb", "/a\u0000b", "x".repeat(10) + "/", "/" + "a".repeat(1024), 42, {}];
82
+ for (const v of bad) {
83
+ test(`rejects ${JSON.stringify(v)?.slice(0, 40)}`, () => {
84
+ let code = "";
85
+ try { validateWorkdir(v); } catch (e) { code = (e as ValidationError).code; }
86
+ expect(code).toBe("workdir_invalid");
87
+ });
88
+ }
89
+ });
90
+
91
+ describe("daemonDefaultWorkdirRoot — sanitize the self-report", () => {
92
+ const snap = (v: unknown) => JSON.stringify({ daemon_capabilities: { default_workdir_root: v } });
93
+ test("absolute posix root passes through", () => { expect(daemonDefaultWorkdirRoot(snap(ROOT))).toBe(ROOT); });
94
+ test("windows root passes through", () => { expect(daemonDefaultWorkdirRoot(snap("C:\\Users\\alice"))).toBe("C:\\Users\\alice"); });
95
+ test("object snapshot (not string) also accepted", () => {
96
+ expect(daemonDefaultWorkdirRoot({ daemon_capabilities: { default_workdir_root: ROOT } })).toBe(ROOT);
97
+ });
98
+ for (const v of [undefined, null, "", "relative", "~/x", 7, "/a\nb", "/" + "a".repeat(1100)]) {
99
+ test(`not reported / malformed ${JSON.stringify(v)?.slice(0, 30)} → null`, () => {
100
+ expect(daemonDefaultWorkdirRoot(snap(v))).toBeNull();
101
+ });
102
+ }
103
+ test("null / garbage snapshot → null", () => {
104
+ expect(daemonDefaultWorkdirRoot(null)).toBeNull();
105
+ expect(daemonDefaultWorkdirRoot("{not json")).toBeNull();
106
+ });
107
+ });
108
+
109
+ describe("create_node + workdir", () => {
110
+ test("🔴 old daemon (no default_workdir_root) + workdir → workdir_not_supported_by_daemon, NO row", async () => {
111
+ seed({});
112
+ const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { ...baseSpec, workdir: `${ROOT}/wd-child` } });
113
+ expect(r.ok).toBe(false);
114
+ expect(r.error).toBe("workdir_not_supported_by_daemon");
115
+ expect(rowCount()).toBe(0);
116
+ });
117
+
118
+ test("old daemon WITHOUT workdir still dispatches (no regression for existing callers)", async () => {
119
+ seed({});
120
+ const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec });
121
+ expect(r.ok).toBe(true);
122
+ const row = db.get<{ workdir: string | null }>("SELECT workdir FROM node_create_requests WHERE request_id = ?1", r.request_id);
123
+ expect(row?.workdir).toBeNull();
124
+ });
125
+
126
+ test("bad shape rejected before dispatch → workdir_invalid, NO row", async () => {
127
+ seed({ default_workdir_root: ROOT });
128
+ const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { ...baseSpec, workdir: "relative/dir" } });
129
+ expect(r.error).toBe("workdir_invalid");
130
+ expect(rowCount()).toBe(0);
131
+ });
132
+
133
+ test("new daemon + workdir → row stores it and get_create_request hands it to the daemon", async () => {
134
+ seed({ default_workdir_root: ROOT });
135
+ const wd = `${ROOT}/wd-child`;
136
+ const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { ...baseSpec, workdir: wd } });
137
+ expect(r.ok).toBe(true);
138
+ const row = db.get<{ workdir: string | null }>("SELECT workdir FROM node_create_requests WHERE request_id = ?1", r.request_id);
139
+ expect(row?.workdir).toBe(wd);
140
+ const g = await call(tools(DAEMON_TOK).get_create_request, { request_id: r.request_id });
141
+ expect(g.ok).toBe(true);
142
+ expect(g.node_spec.workdir).toBe(wd);
143
+ expect(g.node_spec.name).toBe(baseSpec.name);
144
+ });
145
+
146
+ test("workdir is trimmed before storage", async () => {
147
+ seed({ default_workdir_root: ROOT });
148
+ const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { ...baseSpec, workdir: ` ~/wd-child ` } });
149
+ expect(r.ok).toBe(true);
150
+ const row = db.get<{ workdir: string | null }>("SELECT workdir FROM node_create_requests WHERE request_id = ?1", r.request_id);
151
+ expect(row?.workdir).toBe("~/wd-child");
152
+ });
153
+
154
+ test("new daemon WITHOUT workdir → get_create_request node_spec has NO workdir key (daemon keeps legacy layout)", async () => {
155
+ seed({ default_workdir_root: ROOT });
156
+ const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec });
157
+ expect(r.ok).toBe(true);
158
+ const g = await call(tools(DAEMON_TOK).get_create_request, { request_id: r.request_id });
159
+ expect(g.ok).toBe(true);
160
+ expect("workdir" in g.node_spec).toBe(false);
161
+ });
162
+
163
+ test("audit detail records the requested workdir", async () => {
164
+ seed({ default_workdir_root: ROOT });
165
+ const wd = `${ROOT}/wd-child`;
166
+ const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { ...baseSpec, workdir: wd } });
167
+ const a = db.get<{ detail: string }>(
168
+ "SELECT detail FROM audit_log WHERE target_id = ?1 AND action = 'create_node_dispatch_attempted'", r.request_id,
169
+ );
170
+ expect(JSON.parse(a?.detail || "{}").workdir).toBe(wd);
171
+ });
172
+
173
+ test("list_host_supervisors (MCP) surfaces default_workdir_root for admin", async () => {
174
+ seed({ default_workdir_root: ROOT });
175
+ const r = await call(tools().list_host_supervisors, {});
176
+ const d = (r as any).daemons.find((x: any) => x.daemon_node_id === DAEMON_ID);
177
+ expect(d.default_workdir_root).toBe(ROOT);
178
+ });
179
+
180
+ test("list_host_supervisors (MCP) omits the key for an old daemon", async () => {
181
+ seed({});
182
+ const r = await call(tools().list_host_supervisors, {});
183
+ const d = (r as any).daemons.find((x: any) => x.daemon_node_id === DAEMON_ID);
184
+ expect(d).toBeDefined();
185
+ expect("default_workdir_root" in d).toBe(false);
186
+ });
187
+ });
188
+
189
+ // ── REST /api/host-supervisors: admin sees the root, member does not ──────────
190
+ let BASE = "";
191
+ let server: any = null;
192
+ let ownerTok = "", memberTok = "", restNet = "", ownerId = "";
193
+ describe("/api/host-supervisors — default_workdir_root visibility", () => {
194
+ beforeAll(async () => {
195
+ process.env.HOST = "127.0.0.1";
196
+ const sfx = `${Date.now()}_${Math.floor(Math.random() * 1000)}`;
197
+ const pw = "BootstrapPw123Aa!";
198
+ const s = register(`wd_seed_${sfx}`, pw, undefined, "seed");
199
+ if (!s.ok) throw new Error("seed failed");
200
+ db.run("UPDATE users SET role = 'admin' WHERE username = ?1", [`wd_seed_${sfx}`]);
201
+ const o = register(`wd_owner_${sfx}`, pw, undefined, "seed");
202
+ if (!o.ok || !o.token) throw new Error("owner register failed");
203
+ ownerTok = o.token; restNet = o.network_id ?? "";
204
+ ownerId = login(`wd_owner_${sfx}`, pw).user!.user_id;
205
+ const m = register(`wd_member_${sfx}`, pw, undefined, "seed");
206
+ if (!m.ok || !m.token) throw new Error("member register failed");
207
+ memberTok = m.token;
208
+ const memberId = login(`wd_member_${sfx}`, pw).user!.user_id;
209
+ // 多用户 Agent 权限:新成员默认只看授权 Agent;本测试测的是「完全信任的成员」旧语义,显式 agent_access=all。
210
+ const add = addNetworkMember(restNet, memberId, "member", undefined, { agentAccess: "all" });
211
+ if (!add.ok) throw new Error("add member failed: " + add.error);
212
+ const { bootServer } = await import("./server.js");
213
+ server = bootServer({ port: 0, hostname: "127.0.0.1" });
214
+ BASE = `http://127.0.0.1:${server.port}`;
215
+ for (const [alias, caps] of [["wd-new", { default_workdir_root: ROOT }], ["wd-old", {}]] as const) {
216
+ db.run(
217
+ `INSERT OR REPLACE INTO nodes (node_id, node_name, alias, runtime, model, config_path, channels, server, hostname, network_id, config_revision, config_snapshot)
218
+ VALUES (?1, ?2, ?2, 'claude-agent-sdk', 'm', '/tmp/cfg.json', '[]', 'h', 'h', ?3, 0, ?4)`,
219
+ [`wd_n_${alias}`, alias, restNet, JSON.stringify({ role: "host_supervisor", daemon_capabilities: caps })],
220
+ );
221
+ db.run(
222
+ `INSERT OR REPLACE INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope) VALUES (?1, ?2, ?3, ?4, ?5, 'network')`,
223
+ [`wd_t_${alias}`, `hash_wd_${alias}`, ownerId, restNet, `node:${alias}`],
224
+ );
225
+ }
226
+ });
227
+ afterAll(() => {
228
+ try { server?.stop?.(true); } catch {}
229
+ try { db.run("DELETE FROM nodes WHERE network_id = ?1", [restNet]); } catch {}
230
+ try { db.run("DELETE FROM api_tokens WHERE network_id = ?1 AND name LIKE 'node:%'", [restNet]); } catch {}
231
+ });
232
+
233
+ async function list(tok: string): Promise<any[]> {
234
+ const res = await fetch(`${BASE}/api/host-supervisors?network_id=${encodeURIComponent(restNet)}`, { headers: { Authorization: `Bearer ${tok}` } });
235
+ const b = await res.json();
236
+ if (!b.ok) throw new Error("list failed: " + JSON.stringify(b));
237
+ return b.daemons;
238
+ }
239
+
240
+ test("owner sees default_workdir_root on the new daemon", async () => {
241
+ const d = (await list(ownerTok)).find(x => x.alias === "wd-new");
242
+ expect(d?.default_workdir_root).toBe(ROOT);
243
+ });
244
+ test("old daemon row has NO default_workdir_root key (app hides the row)", async () => {
245
+ const d = (await list(ownerTok)).find(x => x.alias === "wd-old");
246
+ expect(d).toBeDefined();
247
+ expect("default_workdir_root" in d).toBe(false);
248
+ });
249
+ test("🔴 member does NOT see the host's home path", async () => {
250
+ const rows = await list(memberTok);
251
+ const d = rows.find(x => x.alias === "wd-new");
252
+ expect(d).toBeDefined();
253
+ expect("default_workdir_root" in d).toBe(false);
254
+ });
255
+ });
@@ -272,8 +272,58 @@ export function resolveCallerDaemonTokenBound(opts: {
272
272
  // RFC-026 §4.5 — append a row to audit_log for every create_node
273
273
  // lifecycle event. Best-effort: never throw out (calling tool should
274
274
  // continue even if audit insert fails for any reason).
275
+ /** RFC-027 §4.5 D8 — tx-aware variant. Identical SQL to auditCreateNode
276
+ * but RE-THROWS on failure so a BEGIN..COMMIT around lifecycle UPDATE +
277
+ * audit INSERT can ROLLBACK if the audit row would have been lost.
278
+ * Required for the "no audit-but state changed" window that §4.5 / D8
279
+ * explicitly closes (PR1 SF-2 review catch — auditCreateNode's
280
+ * swallow-and-warn defeats atomicity).
281
+ *
282
+ * Callers in a non-transaction context should keep using auditCreateNode
283
+ * (best-effort, never throws). */
284
+ export function auditCreateNodeStrict(input: {
285
+ action: Parameters<typeof auditCreateNode>[0]["action"];
286
+ user_id?: string | null;
287
+ username?: string | null;
288
+ network_id?: string | null;
289
+ target_id?: string | null;
290
+ detail: Record<string, unknown>;
291
+ }): void {
292
+ db.run(
293
+ `INSERT INTO audit_log (user_id, username, action, target_type, target_id, detail, network_id)
294
+ VALUES (?1, ?2, ?3, 'node_create_request', ?4, ?5, ?6)`,
295
+ [
296
+ input.user_id || null,
297
+ input.username || null,
298
+ input.action,
299
+ input.target_id || null,
300
+ JSON.stringify(input.detail),
301
+ input.network_id || null,
302
+ ],
303
+ );
304
+ }
305
+
275
306
  export function auditCreateNode(input: {
276
- action: "create_node_dispatched" | "create_node_rejected" | "create_node_succeeded" | "create_node_sweeper_revoked";
307
+ action:
308
+ | "create_node_dispatched"
309
+ | "create_node_dispatch_attempted"
310
+ | "create_node_rejected"
311
+ | "create_node_succeeded"
312
+ | "create_node_sweeper_revoked"
313
+ | "daemon_capability_lied" // RFC-026 §9.3 D2 — daemon declared runtime support, child died before serving
314
+ // RFC-027 §4.5 — stop/delete lifecycle audit action enum extension.
315
+ // Re-using auditCreateNode is fine: the action column carries the
316
+ // discriminator; target_type stays 'node_create_request' which is a
317
+ // misnomer for stop/delete rows but updating the schema would force a
318
+ // wider migration (see P1.1 issue).
319
+ | "stop_node_dispatched"
320
+ | "stop_node_completed"
321
+ | "start_node_dispatched"
322
+ | "start_node_completed"
323
+ | "delete_node_dispatched"
324
+ | "delete_node_completed"
325
+ | "forced_stop_with_in_flight"
326
+ | "backup_purged";
277
327
  user_id?: string | null;
278
328
  username?: string | null;
279
329
  network_id?: string | null;