@sleep2agi/commhub-server 0.9.0-preview.12 → 0.9.0-preview.121
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.
- package/README.md +130 -10
- package/bin/commhub.ts +92 -11
- package/package.json +7 -7
- package/src/ack-create-request-transport.test.ts +182 -0
- package/src/ack-create-request.test.ts +50 -7
- package/src/admin-delete-network-http.test.ts +228 -0
- package/src/admin-networks-http.test.ts +88 -0
- package/src/adoption-candidates-http.test.ts +137 -0
- package/src/adoption-candidates.ts +158 -0
- package/src/agent-access-batch.test.ts +210 -0
- package/src/agent-access.ts +487 -0
- package/src/agent-acl-groups-http.test.ts +247 -0
- package/src/agent-acl-http.test.ts +659 -0
- package/src/agent-acl-slice3-http.test.ts +267 -0
- package/src/agent-groups-perf.test.ts +223 -0
- package/src/agent-notice.ts +48 -0
- package/src/agent-team-whoami-http.test.ts +98 -0
- package/src/agent-teams-http.test.ts +323 -0
- package/src/agent-teams.ts +244 -0
- package/src/alias-filter.test.ts +72 -0
- package/src/alias-filter.ts +42 -0
- package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
- package/src/api-host-supervisors-fallback.test.ts +271 -0
- package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
- package/src/api-nodes-shape.test.ts +26 -10
- package/src/auth-password-change-cli-tokens-http.test.ts +294 -0
- package/src/auth-sessions-http.test.ts +250 -0
- package/src/auth-validate.test.ts +5 -1
- package/src/auth-weak-password-login.test.ts +176 -0
- package/src/auth.ts +598 -49
- package/src/avatar-validate.test.ts +163 -0
- package/src/avatar-validate.ts +103 -0
- package/src/binding-generation-http.test.ts +121 -0
- package/src/blocked-exit-on-reply.test.ts +122 -0
- package/src/boot-side-effect.test.ts +124 -0
- package/src/codex-config-flags.ts +77 -0
- package/src/codex-fork-contract.ts +23 -0
- package/src/codex-fork-migration.test.ts +38 -0
- package/src/commhub-bin-args.test.ts +85 -0
- package/src/config-apply-sec1.test.ts +107 -0
- package/src/config-apply-validate.test.ts +134 -1
- package/src/config-apply-validate.ts +111 -5
- package/src/create-node-blocked-gate.test.ts +356 -0
- package/src/create-node-tool-schema.test.ts +48 -0
- package/src/create-node-unicode-name.test.ts +120 -0
- package/src/create-node-validate.test.ts +193 -7
- package/src/create-node-validate.ts +217 -15
- package/src/create-node-workdir.test.ts +289 -0
- package/src/create-node.ts +77 -23
- package/src/daemon-provider-snapshots.test.ts +256 -0
- package/src/daemon-provider-snapshots.ts +226 -0
- package/src/daemon-token-owner-http.test.ts +231 -0
- package/src/dashboard-slash-routing-http.test.ts +107 -0
- package/src/db-adapter-guard.test.ts +148 -0
- package/src/db-adapter-translate.test.ts +128 -0
- package/src/db-adapter.ts +323 -87
- package/src/db-timestamp.test.ts +38 -0
- package/src/db-timestamp.ts +15 -0
- package/src/db.ts +903 -35
- package/src/delivered-without-push.test.ts +140 -0
- package/src/department-groups-http.test.ts +209 -0
- package/src/department-groups-sync-http.test.ts +328 -0
- package/src/department-groups.ts +434 -0
- package/src/department-heads-http.test.ts +330 -0
- package/src/department-heads.ts +226 -0
- package/src/departments-http.test.ts +185 -0
- package/src/departments.ts +260 -0
- package/src/desktop-message-seam.test.ts +150 -0
- package/src/desktop-message.test.ts +368 -0
- package/src/dm-file-scope-http.test.ts +178 -0
- package/src/ext-token-shared.test.ts +60 -0
- package/src/ext-validation-regression.test.ts +131 -0
- package/src/external-schedule-edits-http.test.ts +321 -0
- package/src/external-schedule-edits-timestamps.test.ts +64 -0
- package/src/external-schedule-edits.ts +327 -0
- package/src/file-download-authz-dev-open.test.ts +135 -0
- package/src/file-download-authz.test.ts +404 -0
- package/src/file-download-date-bucket.test.ts +436 -0
- package/src/file-network-scope-dev-open.test.ts +97 -0
- package/src/file-network-scope.test.ts +732 -0
- package/src/group-membership-events-http.test.ts +264 -0
- package/src/group-messages-http.test.ts +482 -0
- package/src/group-messages.ts +297 -0
- package/src/health-redaction.test.ts +642 -0
- package/src/http-gzip.test.ts +94 -0
- package/src/http-gzip.ts +112 -0
- package/src/hub-timestamp.test.ts +38 -0
- package/src/hub-timestamp.ts +27 -0
- package/src/human-dm.ts +215 -0
- package/src/inbox-count-sse.test.ts +310 -0
- package/src/inbox-count.ts +29 -0
- package/src/index.ts +15 -2356
- package/src/lifecycle-guard.ts +1 -1
- package/src/mcp-context-cost-http.test.ts +120 -0
- package/src/mcp-projects-events-http.test.ts +162 -0
- package/src/mcp-route-label-http.test.ts +120 -0
- package/src/mcp-write-network-resolution.test.ts +429 -0
- package/src/member-audit-network-id-http.test.ts +93 -0
- package/src/member-presence-http.test.ts +210 -0
- package/src/messages-ack-by-agent-http.test.ts +142 -0
- package/src/migrate-sqlite-to-pg.test.ts +47 -0
- package/src/migrate-sqlite-to-pg.ts +263 -0
- package/src/model-auth-notify-http.test.ts +181 -0
- package/src/model-auth-notify.ts +116 -0
- package/src/network-name-http.test.ts +75 -0
- package/src/network-scope.ts +276 -0
- package/src/network-token-membership-http.test.ts +139 -0
- package/src/node-alias-control.ts +12 -0
- package/src/node-attrs-validate.ts +88 -0
- package/src/node-attrs.test.ts +217 -0
- package/src/node-caller-identity-http.test.ts +714 -0
- package/src/node-create-request-status-http.test.ts +105 -0
- package/src/node-daemon-bindings.test.ts +132 -0
- package/src/node-daemon-bindings.ts +130 -0
- package/src/node-files-transport.test.ts +344 -0
- package/src/node-health-codex-login.test.ts +120 -0
- package/src/node-health-dispatch-http.test.ts +279 -0
- package/src/node-health-guard.ts +105 -0
- package/src/node-health-passthrough.test.ts +115 -0
- package/src/node-health-store.ts +101 -0
- package/src/node-id-alias.test.ts +190 -0
- package/src/node-identity-conflict-http.test.ts +269 -0
- package/src/node-identity-conflict.ts +142 -0
- package/src/node-identity-mismatch.test.ts +74 -0
- package/src/node-lifecycle-controllable.test.ts +64 -0
- package/src/node-lifecycle-controllable.ts +53 -0
- package/src/node-lifecycle-read-http.test.ts +245 -0
- package/src/node-lifecycle-read.ts +121 -0
- package/src/node-logs-transport.test.ts +263 -0
- package/src/node-permissions-http.test.ts +276 -0
- package/src/node-permissions.ts +283 -0
- package/src/node-request-retention.test.ts +281 -0
- package/src/node-request-retention.ts +120 -0
- package/src/node-skills-transport.test.ts +209 -0
- package/src/node-token-ownership.ts +36 -0
- package/src/node-token-privilege-http.test.ts +158 -0
- package/src/observer-avatar-http.test.ts +431 -0
- package/src/observer-push.test.ts +252 -0
- package/src/package-version-consistency.test.ts +25 -0
- package/src/peer-reply-atomic.test.ts +455 -0
- package/src/peer-reply-capability.test.ts +70 -0
- package/src/pg-worker.ts +87 -0
- package/src/project-dir-warn-clear-http.test.ts +132 -0
- package/src/project-viewer-can-http.test.ts +114 -0
- package/src/push.ts +429 -10
- package/src/redact-tokens.test.ts +65 -0
- package/src/redact-tokens.ts +40 -0
- package/src/rename.ts +22 -2
- package/src/reply-target-derivation.test.ts +96 -0
- package/src/report-status-handover-capabilities-http.test.ts +124 -0
- package/src/report-status-host-schema.test.ts +235 -0
- package/src/report-status-resume-id-handover.test.ts +150 -0
- package/src/require-explicit-test-db.ts +9 -0
- package/src/requirement-due-reminders-http.test.ts +620 -0
- package/src/requirement-due-reminders.ts +416 -0
- package/src/requirement-events-http.test.ts +268 -0
- package/src/requirement-events.test.ts +45 -0
- package/src/requirement-events.ts +144 -0
- package/src/requirement-notify.ts +165 -0
- package/src/requirement-participant-notify-http.test.ts +309 -0
- package/src/requirement-tag-ops-http.test.ts +266 -0
- package/src/requirement-tags.ts +89 -0
- package/src/requirements-abandoned-http.test.ts +236 -0
- package/src/requirements-comment-http.test.ts +167 -0
- package/src/requirements-completed-at-migration.test.ts +70 -0
- package/src/requirements-errors-mcp-http.test.ts +164 -0
- package/src/requirements-errors.ts +143 -0
- package/src/requirements-etag-http.test.ts +91 -0
- package/src/requirements-http.test.ts +709 -0
- package/src/requirements-last-event-http.test.ts +349 -0
- package/src/requirements-list-mcp-slim-http.test.ts +155 -0
- package/src/requirements-list-slim-http.test.ts +319 -0
- package/src/requirements-mcp.test.ts +163 -0
- package/src/requirements-migrate.ts +259 -0
- package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
- package/src/requirements-people-http.test.ts +114 -0
- package/src/requirements-people-mcp-http.test.ts +225 -0
- package/src/requirements-people.ts +127 -0
- package/src/requirements-priority-lowest.test.ts +114 -0
- package/src/requirements-search-http.test.ts +182 -0
- package/src/requirements-search.test.ts +32 -0
- package/src/requirements-search.ts +145 -0
- package/src/requirements-seq-http.test.ts +193 -0
- package/src/requirements-seq-migration.test.ts +63 -0
- package/src/requirements-start-date.test.ts +125 -0
- package/src/requirements-stats-http.test.ts +288 -0
- package/src/requirements-stats.ts +167 -0
- package/src/requirements-status-participants-http.test.ts +222 -0
- package/src/requirements-upgrade-e2e.test.ts +126 -0
- package/src/requirements-upgrade-migration.test.ts +98 -0
- package/src/requirements.ts +1806 -0
- package/src/resolve-port.test.ts +57 -0
- package/src/resolve-port.ts +44 -0
- package/src/response-charset.test.ts +130 -0
- package/src/rest-explicit-columns-http.test.ts +222 -0
- package/src/rest-identity.test.ts +129 -0
- package/src/rest-identity.ts +125 -0
- package/src/rest-projections.ts +68 -0
- package/src/rest-write-network-resolution.test.ts +133 -0
- package/src/restricted-files.ts +76 -0
- package/src/retention.ts +15 -3
- package/src/route-callers-http.test.ts +120 -0
- package/src/route-timing.test.ts +211 -0
- package/src/route-timing.ts +258 -0
- package/src/rules-file-duplicate-alias.test.ts +234 -0
- package/src/rules-file-session-target.test.ts +207 -0
- package/src/rules-file-transport.test.ts +237 -0
- package/src/runtime-label.test.ts +22 -0
- package/src/runtime-label.ts +21 -0
- package/src/runtime-readiness.ts +90 -0
- package/src/schedule-agent-mcp-http.test.ts +381 -0
- package/src/schedule-agent.ts +192 -0
- package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
- package/src/scheduled-failures-http.test.ts +233 -0
- package/src/scheduled-failures.ts +179 -0
- package/src/scheduled-offline.test.ts +131 -0
- package/src/scheduled-offline.ts +66 -0
- package/src/scheduled-reply-unread-http.test.ts +212 -0
- package/src/scheduled-run-terminal.test.ts +268 -0
- package/src/scheduled-skip-blocking-task.test.ts +120 -0
- package/src/scheduled-stuck-http.test.ts +238 -0
- package/src/scheduled-stuck.ts +153 -0
- package/src/scheduled-tasks-http.test.ts +638 -0
- package/src/scheduled-tasks.ts +766 -0
- package/src/send-dedup-request-id.test.ts +229 -0
- package/src/send-reply-agent-warning.test.ts +202 -0
- package/src/send-reply-alias-optional.test.ts +131 -0
- package/src/send-reply-attachments.test.ts +458 -0
- package/src/send_dedup.test.ts +54 -0
- package/src/send_dedup.ts +52 -6
- package/src/serve-error.test.ts +38 -0
- package/src/serve-error.ts +27 -0
- package/src/server.ts +5253 -0
- package/src/session-task-on-dispatch.ts +14 -0
- package/src/shared/codex-inventory.ts +34 -0
- package/src/shared/daemon-provider-snapshot.ts +49 -0
- package/src/shared/external-schedule-contract.ts +60 -0
- package/src/shared/node-name.test.ts +62 -0
- package/src/shared/node-name.ts +161 -0
- package/src/shared/provider-application.ts +24 -0
- package/src/shared/reserved-env-drift.test.ts +10 -0
- package/src/shared/task-content-limit-drift.test.ts +28 -0
- package/src/shared/task-content-limit.ts +25 -0
- package/src/side-thread-command-transport.test.ts +312 -0
- package/src/side-thread-command-transport.ts +318 -0
- package/src/side-thread-http-integration.test.ts +233 -0
- package/src/side-thread-http.ts +504 -0
- package/src/side-thread-production.test.ts +72 -0
- package/src/side-thread-production.ts +118 -0
- package/src/side-thread.test.ts +1067 -0
- package/src/side-thread.ts +2499 -0
- package/src/skillhub-http.test.ts +108 -0
- package/src/sqlite-close-checkpoint.test.ts +78 -0
- package/src/start-node.test.ts +264 -0
- package/src/status-alias-filter-http.test.ts +106 -0
- package/src/status-alias-resolver-http.test.ts +163 -0
- package/src/status-alias-resolver.ts +19 -0
- package/src/status-node-id-filter-http.test.ts +161 -0
- package/src/status-read-cache-http.test.ts +229 -0
- package/src/status-read-cache.ts +122 -0
- package/src/stop-delete-node.test.ts +469 -1
- package/src/task-access-http.test.ts +402 -0
- package/src/task-access.ts +420 -0
- package/src/task-auth-origin-http.test.ts +91 -0
- package/src/task-auth-origin.test.ts +24 -0
- package/src/task-auth-origin.ts +7 -0
- package/src/task-consumption.test.ts +482 -0
- package/src/task-diagnostic-http.test.ts +149 -0
- package/src/task-diagnostic.test.ts +115 -0
- package/src/task-diagnostic.ts +118 -0
- package/src/task-expiry-notice-http.test.ts +287 -0
- package/src/task-expiry-notice.ts +315 -0
- package/src/task-idempotency-mcp.test.ts +142 -0
- package/src/task-idempotency.test.ts +60 -0
- package/src/task-idempotency.ts +75 -0
- package/src/task-late-replies.ts +54 -0
- package/src/task-late-reply-http.test.ts +152 -0
- package/src/task-lifecycle-watcher.test.ts +204 -0
- package/src/task-lifecycle-watcher.ts +49 -0
- package/src/task-network-resolution-http.test.ts +141 -0
- package/src/task-orphan-http.test.ts +287 -0
- package/src/task-orphan.ts +119 -0
- package/src/task-queue-ahead-http.test.ts +309 -0
- package/src/task-queue-ahead-scale.test.ts +236 -0
- package/src/task-queue-ahead.ts +186 -0
- package/src/task-rejection-log-http.test.ts +160 -0
- package/src/task-rejection-log.ts +49 -0
- package/src/task-stale-open-http.test.ts +290 -0
- package/src/task-stale-open.ts +103 -0
- package/src/tasks-pagination-http.test.ts +141 -0
- package/src/tool-audience-http.test.ts +222 -0
- package/src/tool-audience.ts +116 -0
- package/src/tools-list-json-schema.test.ts +67 -0
- package/src/tools.ts +3598 -313
- package/src/upload-early-reject-guard.test.ts +155 -0
- package/src/uploads-http.test.ts +97 -15
- package/src/uploads.test.ts +66 -0
- package/src/uploads.ts +138 -5
- package/src/user-avatar-http.test.ts +74 -0
- package/src/user-avatar-migration.test.ts +25 -0
- package/src/user-inbox-by-agent-http.test.ts +161 -0
- package/src/user-inbox-netid-notnull.test.ts +122 -0
- package/src/user-inbox-read-http.test.ts +223 -0
- package/src/user-inbox-schema.test.ts +54 -0
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
// payload (RFC §4.6).
|
|
9
9
|
|
|
10
10
|
import { isReservedEnvKey } from "./shared/reserved-env.js";
|
|
11
|
+
import { checkNodeName } from "./shared/node-name.js";
|
|
12
|
+
import { CODEX_CONFIG_ONLY_FLAG_KEYS, validateCodexConfigFlag } from "./codex-config-flags.js";
|
|
11
13
|
|
|
12
14
|
export class ValidationError extends Error {
|
|
13
15
|
constructor(public code: string, public detail?: Record<string, unknown>) {
|
|
@@ -17,10 +19,49 @@ export class ValidationError extends Error {
|
|
|
17
19
|
}
|
|
18
20
|
|
|
19
21
|
// §4.2.2 — structural enums.
|
|
20
|
-
|
|
22
|
+
// #1298 —— daemon 远程创建允许的 runtime。2026-08-28 从 3 个放开到 7 个。
|
|
23
|
+
//
|
|
24
|
+
// 放开之前挡着的问题是「daemon 建出来的是**无人值守**的后台进程,而三个共存 runtime
|
|
25
|
+
// 的本质是人和 agent 共用一个 TUI 会话 —— 建出来给谁用?」
|
|
26
|
+
//
|
|
27
|
+
// Vincent 2026-08-28 定,理由是**兜底排错**:
|
|
28
|
+
// 「某个节点突然不动了,人可以进去看。在 daemon 还没那么靠谱的情况下,
|
|
29
|
+
// 这非常重要 —— 至少可以跟 Codex 和 Claude Code 对话。」
|
|
30
|
+
// 🔴 关键在于 **attach 是「建好之后」的动作,不是「建的时候」的前提**。
|
|
31
|
+
//
|
|
32
|
+
// 支撑读数(2026-08-28 实测舰队):`通信牛` 跑 codex-app-server(共存 runtime),
|
|
33
|
+
// **764 次成功完成任务**,当天仍在跑 —— 比两个普通 runtime 的节点(61 次 / 3 次)
|
|
34
|
+
// 都多一个量级。⇒ 任务链路不需要人坐在屏幕前。
|
|
35
|
+
//
|
|
36
|
+
// 🔴 这七个名字与 `agent-network/src/normalize-runtime.ts` 的 `RuntimeName` 一致。
|
|
37
|
+
// 那边是 CLI 侧的全集;两边分叉过一次(daemon 侧的 VALID_RUNTIMES 早就是 7 个,
|
|
38
|
+
// 只有这里还是 3 个,而记录此事的 #1298 正文写的是「三道闸都关着」——
|
|
39
|
+
// **一份快照式的盘点,只在写下的那一刻是真的**)。
|
|
40
|
+
export const RUNTIMES = [
|
|
41
|
+
"claude-agent-sdk",
|
|
42
|
+
"claude-code-cli",
|
|
43
|
+
"codex-sdk",
|
|
44
|
+
"codex-app-server",
|
|
45
|
+
"grok-build-acp",
|
|
46
|
+
"grok-build-cli",
|
|
47
|
+
"opencode-cli",
|
|
48
|
+
] as const;
|
|
21
49
|
export type Runtime = typeof RUNTIMES[number];
|
|
22
50
|
|
|
23
|
-
|
|
51
|
+
// #584 —— `copresence` 是**建节点时**的开关,不是 agent 的运行参数:为 true 时 daemon 把它写成子节点
|
|
52
|
+
// config 的 `codexCopresence: true`,之后一条 `anet node start` 就起共享 TUI(app 向导的「Codex(TUI 共存)」)。
|
|
53
|
+
// 🔴 故意放在 flags 里而不是 node_spec 顶层:老 hub 的 zod 会静默丢弃未知顶层字段、老 daemon 也静默忽略
|
|
54
|
+
// —— 那正是 #584 的形状(用户选了共存,拿到无头节点,没有任何报错)。flags 的未知键在老 hub(这份
|
|
55
|
+
// FLAG_KEYS)和老 daemon(buildAnetArgsDaemon)都**拒绝**,新 app 撞到老组件得到的是一条报错。
|
|
56
|
+
export const FLAG_KEYS = [
|
|
57
|
+
"permissionMode", "dangerouslySkipPermissions", "maxTurns", "budget", "timeout",
|
|
58
|
+
"copresence", "opencodeGeneration", "opencodeUnsafeTools",
|
|
59
|
+
"approvalPolicy", "sandboxMode", "skipGitRepoCheck", "copresenceFullAccess", "modelReasoningEffort",
|
|
60
|
+
] as const;
|
|
61
|
+
|
|
62
|
+
/** #584 —— 只有这些 runtime 认 `flags.copresence`。目前只有 codex-app-server 的共存靠 config 字段
|
|
63
|
+
* (`codexCopresence`)决定;grok-build-cli / opencode-cli 各有自己的字段,接进来之前一律拒,不静默吞。 */
|
|
64
|
+
export const COPRESENCE_FLAG_RUNTIMES = ["codex-app-server"] as const;
|
|
24
65
|
export type FlagKey = typeof FLAG_KEYS[number];
|
|
25
66
|
|
|
26
67
|
export const PERMISSION_MODES = ["default", "acceptEdits", "plan", "bypassPermissions"] as const;
|
|
@@ -31,29 +72,82 @@ export const MAX_ENV_VALUE_BYTES = 16 * 1024;
|
|
|
31
72
|
const ENV_KEY_RE = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
32
73
|
|
|
33
74
|
// §4.2.2 name + model.
|
|
34
|
-
|
|
35
|
-
|
|
75
|
+
// Board #652 — the name rule lives in ./shared/node-name.ts (byte-identical copy in
|
|
76
|
+
// agent-node/src/shared/, drift-tested). It used to be /^[a-z][a-z0-9_-]{0,63}$/ here.
|
|
77
|
+
// OpenCode 共存的模型带 provider 前缀(`opencode/mimo-v2.5-free`,agent-node parseModelRef 按第一个 `/` 切),
|
|
78
|
+
// 桌面向导 0.2.61 起就发这种形状 —— 允许**恰好一个**斜杠分隔的两段;每段仍是原字符集,且不能是纯点(`..`/`.`)。
|
|
79
|
+
const MODEL_SEGMENT = "[a-zA-Z0-9._:\\-]+";
|
|
80
|
+
const MODEL_RE = new RegExp(`^${MODEL_SEGMENT}(?:/${MODEL_SEGMENT})?$`);
|
|
81
|
+
const MODEL_DOT_ONLY_SEGMENT = /(^|\/)\.+(\/|$)/;
|
|
36
82
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
83
|
+
/** Board #652 — returns the normalized (trimmed) name the caller must store and forward. */
|
|
84
|
+
export function validateName(s: unknown): string {
|
|
85
|
+
const r = checkNodeName(s);
|
|
86
|
+
if (!r.ok) {
|
|
87
|
+
throw new ValidationError("node_name_invalid", {
|
|
88
|
+
value: typeof s === "string" ? s.slice(0, 80) : typeof s,
|
|
89
|
+
reason: r.error,
|
|
90
|
+
...(r.char !== undefined ? { char: r.char } : {}),
|
|
91
|
+
message: r.message,
|
|
92
|
+
});
|
|
40
93
|
}
|
|
94
|
+
return r.name;
|
|
41
95
|
}
|
|
42
96
|
|
|
43
97
|
export function validateRuntime(s: unknown): asserts s is Runtime {
|
|
44
98
|
if (typeof s !== "string" || !(RUNTIMES as readonly string[]).includes(s)) {
|
|
45
|
-
|
|
99
|
+
// 🔴 原来只回一个 `runtime_invalid` + 用户传进来的那个值 —— **不说允许哪些,
|
|
100
|
+
// 也不说还有没有别的路**。2026-08-28 实测:从 Dashboard 建一个
|
|
101
|
+
// `codex-app-server` 节点,用户拿到的就是
|
|
102
|
+
// {"ok":false,"error":"runtime_invalid","value":"codex-app-server"}
|
|
103
|
+
// 而目标机器的 daemon 日志里一行都没有(请求根本没到)。
|
|
104
|
+
// 用户无从知道:①哪些是允许的 ②这个名字是不是打错了 ③有没有别的办法。
|
|
105
|
+
//
|
|
106
|
+
// `allowed` 直接由 RUNTIMES 展开,不是手写的第二份清单 ——
|
|
107
|
+
// 🔴 手写一份会漂移,而漂移之后报错会**理直气壮地告诉用户一组错的名字**。
|
|
108
|
+
throw new ValidationError("runtime_invalid", {
|
|
109
|
+
value: typeof s === "string" ? s.slice(0, 80) : typeof s,
|
|
110
|
+
allowed: [...RUNTIMES],
|
|
111
|
+
// 这句提示的前提是查过的:`agent-network/src/normalize-runtime.ts` 的
|
|
112
|
+
// `RuntimeName` / `SUPPORTED_RUNTIME_NAMES` 是 7 个,包含此处不放行的那几个,
|
|
113
|
+
// 所以「在目标机器上直接建」确实是一条真实存在的路,不是安慰话。
|
|
114
|
+
hint: "daemon 远程创建目前只放行以上 runtime;其余 runtime 可以在目标机器上直接 `anet node create --runtime <name>` 创建。",
|
|
115
|
+
});
|
|
46
116
|
}
|
|
47
117
|
}
|
|
48
118
|
|
|
49
|
-
export function validateModel(s: unknown): asserts s is string {
|
|
50
|
-
if (
|
|
119
|
+
export function validateModel(s: unknown): asserts s is string | undefined | null {
|
|
120
|
+
if (s === undefined || s === null) return;
|
|
121
|
+
if (typeof s !== "string" || s.length === 0 || s.length > 100 || !MODEL_RE.test(s) || MODEL_DOT_ONLY_SEGMENT.test(s)) {
|
|
51
122
|
throw new ValidationError("model_invalid", { value: typeof s === "string" ? s.slice(0, 80) : typeof s });
|
|
52
123
|
}
|
|
53
124
|
}
|
|
54
125
|
|
|
126
|
+
/**
|
|
127
|
+
* #605 —— `flags.timeout` 的单位是**毫秒**:agent-node 就是这么读的(cli.ts currentClaudeTimeoutMs /
|
|
128
|
+
* currentCodexTimeoutMs → util/timeout.ts resolveTimeoutMs、runtime/opencode-timeout.ts,默认 300000)。
|
|
129
|
+
* 这里曾按「秒」收 1..86400:填 600 想要 10 分钟的人拿到 0.6 秒、每个任务都超时;真正的毫秒值被拒。
|
|
130
|
+
*
|
|
131
|
+
* 范围与 update_node_config(config-apply-validate.ts)/ agent-node config-apply 同一把尺子:
|
|
132
|
+
* 0(不设上限)或 TIMEOUT_MS_MIN..TIMEOUT_MS_MAX。1..999 拒绝 —— 旧客户端按秒发的小值分辨不出意图,
|
|
133
|
+
* 不偷偷乘 1000,但也不再让任何人悄悄拿到一个亚秒超时。
|
|
134
|
+
*/
|
|
135
|
+
export const TIMEOUT_MS_MIN = 1000;
|
|
136
|
+
export const TIMEOUT_MS_MAX = 3_600_000;
|
|
137
|
+
export const TIMEOUT_MS_REASON =
|
|
138
|
+
`timeout is in milliseconds: 0 (no limit) or an integer ${TIMEOUT_MS_MIN}..${TIMEOUT_MS_MAX} (e.g. 600000 = 10 min)`;
|
|
139
|
+
export function isValidTimeoutMs(v: unknown): v is number {
|
|
140
|
+
return typeof v === "number" && Number.isInteger(v) && (v === 0 || (v >= TIMEOUT_MS_MIN && v <= TIMEOUT_MS_MAX));
|
|
141
|
+
}
|
|
142
|
+
|
|
55
143
|
export function validateFlagValue(k: string, v: unknown): void {
|
|
56
144
|
switch (k) {
|
|
145
|
+
case "opencodeGeneration":
|
|
146
|
+
if (v !== "v1" && v !== "v2") throw new ValidationError("flag_value_invalid", { field: k, reason: "must be v1 or v2" });
|
|
147
|
+
return;
|
|
148
|
+
case "opencodeUnsafeTools":
|
|
149
|
+
if (typeof v !== "boolean") throw new ValidationError("flag_value_invalid", { field: k, reason: "must be boolean" });
|
|
150
|
+
return;
|
|
57
151
|
case "permissionMode":
|
|
58
152
|
if (typeof v !== "string" || !(PERMISSION_MODES as readonly string[]).includes(v)) {
|
|
59
153
|
throw new ValidationError("flag_value_invalid", { field: k, reason: "must be one of default/acceptEdits/plan/bypassPermissions" });
|
|
@@ -73,15 +167,79 @@ export function validateFlagValue(k: string, v: unknown): void {
|
|
|
73
167
|
}
|
|
74
168
|
return;
|
|
75
169
|
case "timeout":
|
|
76
|
-
if (!
|
|
77
|
-
throw new ValidationError("flag_value_invalid", { field: k, reason:
|
|
170
|
+
if (!isValidTimeoutMs(v)) {
|
|
171
|
+
throw new ValidationError("flag_value_invalid", { field: k, reason: TIMEOUT_MS_REASON });
|
|
78
172
|
}
|
|
79
173
|
return;
|
|
174
|
+
case "copresence":
|
|
175
|
+
if (typeof v !== "boolean") throw new ValidationError("flag_value_invalid", { field: k, reason: "must be boolean" });
|
|
176
|
+
return;
|
|
80
177
|
default:
|
|
178
|
+
if (CODEX_CONFIG_ONLY_FLAG_KEYS.has(k)) {
|
|
179
|
+
const fail = validateCodexConfigFlag(k, v, null);
|
|
180
|
+
if (fail) throw new ValidationError("flag_value_invalid", { field: k, reason: fail.reason });
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
81
183
|
throw new ValidationError("flag_key_unknown", { field: k });
|
|
82
184
|
}
|
|
83
185
|
}
|
|
84
186
|
|
|
187
|
+
/** #584 —— 逐键校验之外的跨字段一条:`copresence` 只对 COPRESENCE_FLAG_RUNTIMES 有意义。
|
|
188
|
+
* 在别的 runtime 上收下它而什么都不做,就是又一个「选了共存、拿到无头」。 */
|
|
189
|
+
export function validateFlagsForRuntime(runtime: string, flags: Record<string, unknown> | undefined | null): void {
|
|
190
|
+
if (!flags) return;
|
|
191
|
+
// Strict flags envelope: old Hub/daemon reject these keys rather than dropping
|
|
192
|
+
// unknown node_spec fields. Opt-in must be explicit on this create request.
|
|
193
|
+
for (const field of ["opencodeGeneration", "opencodeUnsafeTools"]) {
|
|
194
|
+
if (!Object.prototype.hasOwnProperty.call(flags, field)) continue;
|
|
195
|
+
validateFlagValue(field, flags[field]);
|
|
196
|
+
if (runtime !== "opencode-cli") throw new ValidationError("flag_not_applicable_to_runtime", { field, runtime, applicable: ["opencode-cli"] });
|
|
197
|
+
}
|
|
198
|
+
if (Object.prototype.hasOwnProperty.call(flags, "opencodeUnsafeTools") && flags.opencodeGeneration !== "v2") {
|
|
199
|
+
throw new ValidationError("opencode_unsafe_requires_v2", { reason: "opencodeUnsafeTools requires explicit opencodeGeneration=v2" });
|
|
200
|
+
}
|
|
201
|
+
if (flags.opencodeGeneration === "v2" && flags.opencodeUnsafeTools !== true) {
|
|
202
|
+
throw new ValidationError("opencode_v2_requires_unsafe_opt_in", { reason: "V2 preview enables every local tool; trusted tasks only. Explicit opencodeUnsafeTools=true required." });
|
|
203
|
+
}
|
|
204
|
+
if (Object.prototype.hasOwnProperty.call(flags, "copresence") && !(COPRESENCE_FLAG_RUNTIMES as readonly string[]).includes(runtime)) {
|
|
205
|
+
throw new ValidationError("flag_not_applicable_to_runtime", {
|
|
206
|
+
field: "copresence", runtime, applicable: [...COPRESENCE_FLAG_RUNTIMES],
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
for (const [k, v] of Object.entries(flags)) {
|
|
210
|
+
if (!CODEX_CONFIG_ONLY_FLAG_KEYS.has(k)) continue;
|
|
211
|
+
const fail = validateCodexConfigFlag(k, v, runtime);
|
|
212
|
+
if (fail) throw new ValidationError("flag_value_invalid", { field: k, reason: fail.reason });
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* V2 co-presence start requires OpenCode's own `provider/model`.
|
|
218
|
+
* Call only after the unsafe-opt-in check: a missing opt-in stays
|
|
219
|
+
* `opencode_v2_requires_unsafe_opt_in`. This API does not take an anet
|
|
220
|
+
* provider preset or a vault key (#2565 owns presets).
|
|
221
|
+
*/
|
|
222
|
+
export function validateOpenCodeV2ProviderModel(
|
|
223
|
+
runtime: string,
|
|
224
|
+
model: unknown,
|
|
225
|
+
flags: Record<string, unknown> | undefined | null,
|
|
226
|
+
): void {
|
|
227
|
+
if (runtime !== "opencode-cli" || !flags || typeof flags !== "object") return;
|
|
228
|
+
if (flags.opencodeGeneration !== "v2" || flags.opencodeUnsafeTools !== true) return;
|
|
229
|
+
const native = typeof model === "string"
|
|
230
|
+
&& model.length > 0
|
|
231
|
+
&& model.length <= 100
|
|
232
|
+
&& MODEL_RE.test(model)
|
|
233
|
+
&& !MODEL_DOT_ONLY_SEGMENT.test(model)
|
|
234
|
+
&& model.includes("/")
|
|
235
|
+
&& model.indexOf("/") === model.lastIndexOf("/");
|
|
236
|
+
if (!native) {
|
|
237
|
+
throw new ValidationError("opencode_v2_requires_provider_model", {
|
|
238
|
+
reason: "OpenCode V2 uses the installed OpenCode provider/model (exactly one slash, for example provider/model). This API does not take an anet provider preset.",
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
85
243
|
// §4.4.7 — env_refs 7-step gate. networkSecretsGet is injected so
|
|
86
244
|
// callers can supply either a real DB lookup (hub) or a fixture (tests).
|
|
87
245
|
// The 6th step also reports the resolved value size; we return the
|
|
@@ -144,7 +302,7 @@ export function validateEnvRefs(
|
|
|
144
302
|
return out;
|
|
145
303
|
}
|
|
146
304
|
|
|
147
|
-
// §4.4.7 — safe serializer for .env.
|
|
305
|
+
// §4.4.7 — safe serializer for the node secrets.env file. Dotenv-quoted with escape
|
|
148
306
|
// for backslash / double-quote / newline / carriage-return so that a
|
|
149
307
|
// value containing `\n"evil=KEY2"` cannot pollute the next line.
|
|
150
308
|
export function serializeEnvLocal(env: Record<string, string>): string {
|
|
@@ -158,6 +316,40 @@ export function serializeEnvLocal(env: Record<string, string>): string {
|
|
|
158
316
|
}).join("\n") + "\n";
|
|
159
317
|
}
|
|
160
318
|
|
|
319
|
+
// app「新建节点」工作目录 —— hub 只判**形状**(daemon 才知道那台机器的 $HOME、系统目录、
|
|
320
|
+
// 目录里住没住别的节点,那几条在 agent-node/src/runtime/child-workdir.ts)。
|
|
321
|
+
// 这里挡的是「根本不像一条路径」的输入,让它在派发前就失败,而不是占一个请求行再被 daemon 拒。
|
|
322
|
+
export const MAX_WORKDIR_LEN = 1024;
|
|
323
|
+
export function validateWorkdir(s: unknown): asserts s is string | undefined | null {
|
|
324
|
+
if (s === undefined || s === null) return;
|
|
325
|
+
if (typeof s !== "string") throw new ValidationError("workdir_invalid", { reason: "must be string" });
|
|
326
|
+
const v = s.trim();
|
|
327
|
+
if (v.length === 0 || v.length > MAX_WORKDIR_LEN) {
|
|
328
|
+
throw new ValidationError("workdir_invalid", { reason: `length 1..${MAX_WORKDIR_LEN}` });
|
|
329
|
+
}
|
|
330
|
+
if (/[\u0000-\u001f\u007f]/.test(v)) throw new ValidationError("workdir_invalid", { reason: "control character" });
|
|
331
|
+
const shapeOk = v.startsWith("/") || v === "~" || v.startsWith("~/") || /^[A-Za-z]:[\\/]/.test(v);
|
|
332
|
+
if (!shapeOk) {
|
|
333
|
+
throw new ValidationError("workdir_invalid", { reason: "must be absolute (/…, ~/…, or C:\\…)", value: v.slice(0, 80) });
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** daemon 自报的默认工作目录根(`daemon_capabilities.default_workdir_root`),消毒后返回;
|
|
338
|
+
* 没报 / 形状不对 = null。**非 null 即表示该 daemon 认 `node_spec.workdir`** ——
|
|
339
|
+
* create_node 的「老 daemon 不收 workdir」门和 /api/host-supervisors 的透出共用这一个判据。 */
|
|
340
|
+
export function daemonDefaultWorkdirRoot(configSnapshot: unknown): string | null {
|
|
341
|
+
try {
|
|
342
|
+
const snap = typeof configSnapshot === "string" ? JSON.parse(configSnapshot) : configSnapshot;
|
|
343
|
+
const v = (snap as any)?.daemon_capabilities?.default_workdir_root;
|
|
344
|
+
if (typeof v !== "string" || v.length === 0 || v.length > MAX_WORKDIR_LEN) return null;
|
|
345
|
+
if (/[\u0000-\u001f\u007f]/.test(v)) return null;
|
|
346
|
+
if (!(v.startsWith("/") || /^[A-Za-z]:[\\/]/.test(v))) return null;
|
|
347
|
+
return v;
|
|
348
|
+
} catch {
|
|
349
|
+
return null;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
161
353
|
// §4.2.5 — channels fail-closed in P1.
|
|
162
354
|
export function validateChannelsP1(channels: unknown): void {
|
|
163
355
|
if (channels === undefined || channels === null) return;
|
|
@@ -173,7 +365,7 @@ export function validateChannelsP1(channels: unknown): void {
|
|
|
173
365
|
export interface NodeSpec {
|
|
174
366
|
name: string;
|
|
175
367
|
runtime: Runtime;
|
|
176
|
-
model
|
|
368
|
+
model?: string | null;
|
|
177
369
|
flags?: Record<string, unknown>;
|
|
178
370
|
channels?: unknown;
|
|
179
371
|
}
|
|
@@ -187,20 +379,30 @@ function kebab(k: string): string {
|
|
|
187
379
|
// shell, no string concat). Each value has already passed type/enum
|
|
188
380
|
// validation, so String() coercion is safe.
|
|
189
381
|
export function buildAnetArgs(spec: NodeSpec): string[] {
|
|
382
|
+
for (const field of ["opencodeGeneration", "opencodeUnsafeTools"]) {
|
|
383
|
+
if (Object.prototype.hasOwnProperty.call(spec, field)) throw new ValidationError("flag_location_invalid", { field, reason: "use node_spec.flags" });
|
|
384
|
+
}
|
|
190
385
|
validateName(spec.name);
|
|
191
386
|
validateRuntime(spec.runtime);
|
|
192
387
|
validateModel(spec.model);
|
|
193
388
|
validateChannelsP1(spec.channels);
|
|
194
389
|
|
|
195
|
-
const args: string[] = ["node", "create", spec.name, "--runtime", spec.runtime
|
|
390
|
+
const args: string[] = ["node", "create", spec.name, "--runtime", spec.runtime];
|
|
391
|
+
if (spec.model) args.push("--model", spec.model);
|
|
196
392
|
if (spec.flags && typeof spec.flags === "object") {
|
|
197
393
|
for (const [k, v] of Object.entries(spec.flags)) {
|
|
198
394
|
if (!(FLAG_KEYS as readonly string[]).includes(k)) {
|
|
199
395
|
throw new ValidationError("flag_key_unknown", { field: k });
|
|
200
396
|
}
|
|
201
397
|
validateFlagValue(k, v);
|
|
398
|
+
// `anet node create --copresence` 是布尔开关,不吃值。
|
|
399
|
+
if (k === "copresence") { if (v === true) args.push("--copresence"); continue; }
|
|
400
|
+
if (k === "opencodeUnsafeTools") { if (v === true) args.push("--opencode-unsafe-tools"); continue; }
|
|
401
|
+
if (CODEX_CONFIG_ONLY_FLAG_KEYS.has(k)) continue;
|
|
202
402
|
args.push(`--${kebab(k)}`, String(v));
|
|
203
403
|
}
|
|
404
|
+
validateFlagsForRuntime(spec.runtime, spec.flags);
|
|
204
405
|
}
|
|
406
|
+
validateOpenCodeV2ProviderModel(spec.runtime, spec.model, spec.flags);
|
|
205
407
|
return args;
|
|
206
408
|
}
|
|
@@ -0,0 +1,289 @@
|
|
|
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("#829 V2 flags survive Hub storage and daemon pull", async () => {
|
|
111
|
+
seed({ runtimes_supported: ["opencode-cli"] });
|
|
112
|
+
const flags = { opencodeGeneration: "v2", opencodeUnsafeTools: true, timeout: 600000 };
|
|
113
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { name: "v2-child", runtime: "opencode-cli", model: "stub/model", flags } });
|
|
114
|
+
expect(r.ok).toBe(true);
|
|
115
|
+
const row = db.get<{ flags_json: string }>("SELECT flags_json FROM node_create_requests WHERE request_id = ?1", r.request_id);
|
|
116
|
+
expect(JSON.parse(row!.flags_json)).toEqual(flags);
|
|
117
|
+
const pulled = await call(tools(DAEMON_TOK).get_create_request, { request_id: r.request_id });
|
|
118
|
+
expect(pulled.ok).toBe(true);
|
|
119
|
+
expect(pulled.node_spec.flags).toEqual(flags);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test("#829 V2 without native provider/model rejected before request or child token mint", async () => {
|
|
123
|
+
seed({ runtimes_supported: ["opencode-cli"] });
|
|
124
|
+
const tokenCount = () => db.get<{ n: number }>("SELECT COUNT(*) AS n FROM api_tokens WHERE network_id = ?1", NET)!.n;
|
|
125
|
+
const before = tokenCount();
|
|
126
|
+
const flags = { opencodeGeneration: "v2", opencodeUnsafeTools: true };
|
|
127
|
+
const missing = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { name: "v2-child", runtime: "opencode-cli", flags } });
|
|
128
|
+
expect(missing.error).toBe("opencode_v2_requires_provider_model");
|
|
129
|
+
const bare = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { name: "v2-child", runtime: "opencode-cli", model: "opencode", flags } });
|
|
130
|
+
expect(bare.error).toBe("opencode_v2_requires_provider_model");
|
|
131
|
+
expect(rowCount()).toBe(0);
|
|
132
|
+
expect(tokenCount()).toBe(before);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test("#829 missing opt-in rejected before request or child token mint", async () => {
|
|
136
|
+
seed({ runtimes_supported: ["opencode-cli"] });
|
|
137
|
+
const tokenCount = () => db.get<{ n: number }>("SELECT COUNT(*) AS n FROM api_tokens WHERE network_id = ?1", NET)!.n;
|
|
138
|
+
const before = tokenCount();
|
|
139
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { name: "v2-child", runtime: "opencode-cli", flags: { opencodeGeneration: "v2" } } });
|
|
140
|
+
expect(r.error).toBe("opencode_v2_requires_unsafe_opt_in");
|
|
141
|
+
expect(rowCount()).toBe(0);
|
|
142
|
+
expect(tokenCount()).toBe(before);
|
|
143
|
+
});
|
|
144
|
+
test("🔴 old daemon (no default_workdir_root) + workdir → workdir_not_supported_by_daemon, NO row", async () => {
|
|
145
|
+
seed({});
|
|
146
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { ...baseSpec, workdir: `${ROOT}/wd-child` } });
|
|
147
|
+
expect(r.ok).toBe(false);
|
|
148
|
+
expect(r.error).toBe("workdir_not_supported_by_daemon");
|
|
149
|
+
expect(rowCount()).toBe(0);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test("old daemon WITHOUT workdir still dispatches (no regression for existing callers)", async () => {
|
|
153
|
+
seed({});
|
|
154
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec });
|
|
155
|
+
expect(r.ok).toBe(true);
|
|
156
|
+
const row = db.get<{ workdir: string | null }>("SELECT workdir FROM node_create_requests WHERE request_id = ?1", r.request_id);
|
|
157
|
+
expect(row?.workdir).toBeNull();
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test("bad shape rejected before dispatch → workdir_invalid, NO row", async () => {
|
|
161
|
+
seed({ default_workdir_root: ROOT });
|
|
162
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { ...baseSpec, workdir: "relative/dir" } });
|
|
163
|
+
expect(r.error).toBe("workdir_invalid");
|
|
164
|
+
expect(rowCount()).toBe(0);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
test("new daemon + workdir → row stores it and get_create_request hands it to the daemon", async () => {
|
|
168
|
+
seed({ default_workdir_root: ROOT });
|
|
169
|
+
const wd = `${ROOT}/wd-child`;
|
|
170
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { ...baseSpec, workdir: wd } });
|
|
171
|
+
expect(r.ok).toBe(true);
|
|
172
|
+
const row = db.get<{ workdir: string | null }>("SELECT workdir FROM node_create_requests WHERE request_id = ?1", r.request_id);
|
|
173
|
+
expect(row?.workdir).toBe(wd);
|
|
174
|
+
const g = await call(tools(DAEMON_TOK).get_create_request, { request_id: r.request_id });
|
|
175
|
+
expect(g.ok).toBe(true);
|
|
176
|
+
expect(g.node_spec.workdir).toBe(wd);
|
|
177
|
+
expect(g.node_spec.name).toBe(baseSpec.name);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
test("workdir is trimmed before storage", async () => {
|
|
181
|
+
seed({ default_workdir_root: ROOT });
|
|
182
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { ...baseSpec, workdir: ` ~/wd-child ` } });
|
|
183
|
+
expect(r.ok).toBe(true);
|
|
184
|
+
const row = db.get<{ workdir: string | null }>("SELECT workdir FROM node_create_requests WHERE request_id = ?1", r.request_id);
|
|
185
|
+
expect(row?.workdir).toBe("~/wd-child");
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
test("new daemon WITHOUT workdir → get_create_request node_spec has NO workdir key (daemon keeps legacy layout)", async () => {
|
|
189
|
+
seed({ default_workdir_root: ROOT });
|
|
190
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec });
|
|
191
|
+
expect(r.ok).toBe(true);
|
|
192
|
+
const g = await call(tools(DAEMON_TOK).get_create_request, { request_id: r.request_id });
|
|
193
|
+
expect(g.ok).toBe(true);
|
|
194
|
+
expect("workdir" in g.node_spec).toBe(false);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
test("audit detail records the requested workdir", async () => {
|
|
198
|
+
seed({ default_workdir_root: ROOT });
|
|
199
|
+
const wd = `${ROOT}/wd-child`;
|
|
200
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { ...baseSpec, workdir: wd } });
|
|
201
|
+
const a = db.get<{ detail: string }>(
|
|
202
|
+
"SELECT detail FROM audit_log WHERE target_id = ?1 AND action = 'create_node_dispatch_attempted'", r.request_id,
|
|
203
|
+
);
|
|
204
|
+
expect(JSON.parse(a?.detail || "{}").workdir).toBe(wd);
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
test("list_host_supervisors (MCP) surfaces default_workdir_root for admin", async () => {
|
|
208
|
+
seed({ default_workdir_root: ROOT });
|
|
209
|
+
const r = await call(tools().list_host_supervisors, {});
|
|
210
|
+
const d = (r as any).daemons.find((x: any) => x.daemon_node_id === DAEMON_ID);
|
|
211
|
+
expect(d.default_workdir_root).toBe(ROOT);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
test("list_host_supervisors (MCP) omits the key for an old daemon", async () => {
|
|
215
|
+
seed({});
|
|
216
|
+
const r = await call(tools().list_host_supervisors, {});
|
|
217
|
+
const d = (r as any).daemons.find((x: any) => x.daemon_node_id === DAEMON_ID);
|
|
218
|
+
expect(d).toBeDefined();
|
|
219
|
+
expect("default_workdir_root" in d).toBe(false);
|
|
220
|
+
});
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
// ── REST /api/host-supervisors: admin sees the root, member does not ──────────
|
|
224
|
+
let BASE = "";
|
|
225
|
+
let server: any = null;
|
|
226
|
+
let ownerTok = "", memberTok = "", restNet = "", ownerId = "";
|
|
227
|
+
describe("/api/host-supervisors — default_workdir_root visibility", () => {
|
|
228
|
+
beforeAll(async () => {
|
|
229
|
+
process.env.HOST = "127.0.0.1";
|
|
230
|
+
const sfx = `${Date.now()}_${Math.floor(Math.random() * 1000)}`;
|
|
231
|
+
const pw = "BootstrapPw123Aa!";
|
|
232
|
+
const s = register(`wd_seed_${sfx}`, pw, undefined, "seed");
|
|
233
|
+
if (!s.ok) throw new Error("seed failed");
|
|
234
|
+
db.run("UPDATE users SET role = 'admin' WHERE username = ?1", [`wd_seed_${sfx}`]);
|
|
235
|
+
const o = register(`wd_owner_${sfx}`, pw, undefined, "seed");
|
|
236
|
+
if (!o.ok || !o.token) throw new Error("owner register failed");
|
|
237
|
+
ownerTok = o.token; restNet = o.network_id ?? "";
|
|
238
|
+
ownerId = login(`wd_owner_${sfx}`, pw).user!.user_id;
|
|
239
|
+
const m = register(`wd_member_${sfx}`, pw, undefined, "seed");
|
|
240
|
+
if (!m.ok || !m.token) throw new Error("member register failed");
|
|
241
|
+
memberTok = m.token;
|
|
242
|
+
const memberId = login(`wd_member_${sfx}`, pw).user!.user_id;
|
|
243
|
+
// 多用户 Agent 权限:新成员默认只看授权 Agent;本测试测的是「完全信任的成员」旧语义,显式 agent_access=all。
|
|
244
|
+
const add = addNetworkMember(restNet, memberId, "member", undefined, { agentAccess: "all" });
|
|
245
|
+
if (!add.ok) throw new Error("add member failed: " + add.error);
|
|
246
|
+
const { bootServer } = await import("./server.js");
|
|
247
|
+
server = bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
248
|
+
BASE = `http://127.0.0.1:${server.port}`;
|
|
249
|
+
for (const [alias, caps] of [["wd-new", { default_workdir_root: ROOT }], ["wd-old", {}]] as const) {
|
|
250
|
+
db.run(
|
|
251
|
+
`INSERT OR REPLACE INTO nodes (node_id, node_name, alias, runtime, model, config_path, channels, server, hostname, network_id, config_revision, config_snapshot)
|
|
252
|
+
VALUES (?1, ?2, ?2, 'claude-agent-sdk', 'm', '/tmp/cfg.json', '[]', 'h', 'h', ?3, 0, ?4)`,
|
|
253
|
+
[`wd_n_${alias}`, alias, restNet, JSON.stringify({ role: "host_supervisor", daemon_capabilities: caps })],
|
|
254
|
+
);
|
|
255
|
+
db.run(
|
|
256
|
+
`INSERT OR REPLACE INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope) VALUES (?1, ?2, ?3, ?4, ?5, 'network')`,
|
|
257
|
+
[`wd_t_${alias}`, `hash_wd_${alias}`, ownerId, restNet, `node:${alias}`],
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
afterAll(() => {
|
|
262
|
+
try { server?.stop?.(true); } catch {}
|
|
263
|
+
try { db.run("DELETE FROM nodes WHERE network_id = ?1", [restNet]); } catch {}
|
|
264
|
+
try { db.run("DELETE FROM api_tokens WHERE network_id = ?1 AND name LIKE 'node:%'", [restNet]); } catch {}
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
async function list(tok: string): Promise<any[]> {
|
|
268
|
+
const res = await fetch(`${BASE}/api/host-supervisors?network_id=${encodeURIComponent(restNet)}`, { headers: { Authorization: `Bearer ${tok}` } });
|
|
269
|
+
const b = await res.json();
|
|
270
|
+
if (!b.ok) throw new Error("list failed: " + JSON.stringify(b));
|
|
271
|
+
return b.daemons;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
test("owner sees default_workdir_root on the new daemon", async () => {
|
|
275
|
+
const d = (await list(ownerTok)).find(x => x.alias === "wd-new");
|
|
276
|
+
expect(d?.default_workdir_root).toBe(ROOT);
|
|
277
|
+
});
|
|
278
|
+
test("old daemon row has NO default_workdir_root key (app hides the row)", async () => {
|
|
279
|
+
const d = (await list(ownerTok)).find(x => x.alias === "wd-old");
|
|
280
|
+
expect(d).toBeDefined();
|
|
281
|
+
expect("default_workdir_root" in d).toBe(false);
|
|
282
|
+
});
|
|
283
|
+
test("🔴 member does NOT see the host's home path", async () => {
|
|
284
|
+
const rows = await list(memberTok);
|
|
285
|
+
const d = rows.find(x => x.alias === "wd-new");
|
|
286
|
+
expect(d).toBeDefined();
|
|
287
|
+
expect("default_workdir_root" in d).toBe(false);
|
|
288
|
+
});
|
|
289
|
+
});
|