@sleep2agi/commhub-server 0.9.0-preview.274 → 0.9.0-preview.276

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 (51) hide show
  1. package/build-info.json +2 -2
  2. package/package.json +1 -1
  3. package/src/agent-access-batch.test.ts +7 -2
  4. package/src/agent-acl-slice3-http.test.ts +4 -1
  5. package/src/agent-groups-perf.test.ts +6 -1
  6. package/src/anet-variant-real-daemon-http.test.ts +184 -0
  7. package/src/build-commit-report-http.test.ts +90 -0
  8. package/src/config-apply-sec1.test.ts +37 -0
  9. package/src/config-apply-validate.ts +7 -3
  10. package/src/contracts/session-project-create.ts +14 -0
  11. package/src/contracts/session-source-delivery.ts +16 -0
  12. package/src/contracts/session-source-directory.ts +54 -0
  13. package/src/contracts/session-source-evidence.ts +72 -0
  14. package/src/contracts/session-source-execution.ts +24 -0
  15. package/src/contracts/session-source-transport.ts +18 -0
  16. package/src/create-node-tool-schema.test.ts +10 -0
  17. package/src/db.ts +35 -0
  18. package/src/node-permissions.ts +1 -1
  19. package/src/node-session-control-http.test.ts +90 -2
  20. package/src/node-session-control.ts +89 -31
  21. package/src/opencode-v2-catalog.test.ts +14 -0
  22. package/src/opencode-v2-catalog.ts +1 -0
  23. package/src/package-self-contained.test.ts +32 -0
  24. package/src/report-status-host-schema.test.ts +37 -0
  25. package/src/rules-file-transport.test.ts +9 -0
  26. package/src/server.ts +47 -4
  27. package/src/session-fork-store.test.ts +43 -0
  28. package/src/session-fork-store.ts +51 -0
  29. package/src/session-project-attach-migration.test.ts +22 -0
  30. package/src/session-project-attach-native.test.ts +121 -0
  31. package/src/session-project-create-http.test.ts +407 -0
  32. package/src/session-project-create-native.test.ts +290 -0
  33. package/src/session-project-create.ts +159 -0
  34. package/src/session-source-admission-store.ts +58 -0
  35. package/src/session-source-create.test.ts +155 -0
  36. package/src/session-source-create.ts +97 -0
  37. package/src/session-source-delivery.ts +109 -0
  38. package/src/session-source-directory-http.test.ts +192 -0
  39. package/src/session-source-evidence.test.ts +890 -0
  40. package/src/session-source-evidence.ts +191 -0
  41. package/src/session-source-execution.ts +87 -0
  42. package/src/session-source-grant.test.ts +117 -0
  43. package/src/session-source-grant.ts +78 -0
  44. package/src/session-source-issuer.test.ts +247 -0
  45. package/src/session-source-issuer.ts +158 -0
  46. package/src/session-source-transport.ts +368 -0
  47. package/src/task-not-found-error-domain.test.ts +4 -1
  48. package/src/token-usage-http.test.ts +10 -0
  49. package/src/tool-audience-http.test.ts +18 -0
  50. package/src/tool-audience.ts +1 -1
  51. package/src/tools.ts +154 -51
@@ -0,0 +1,368 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { db } from "./db";
3
+ import { resolveToken } from "./auth";
4
+ import { isHumanCredential, readSessionControlCredential, resolveSessionControlNodeCaller, readSessionControlBody } from "./node-session-control";
5
+ import { createSessionSourceIssuer } from "./session-source-issuer";
6
+ import { createSessionSourceEvidenceQueue } from "./session-source-evidence";
7
+ import { createSessionSourceExecutionQueue } from "./session-source-execution";
8
+ import { createSessionSourceDeliveryQueue } from "./session-source-delivery";
9
+ import { checkNodeName } from "./shared/node-name";
10
+ import { SOURCE_DELIVERY_CAPABILITY } from "./contracts/session-source-delivery";
11
+ import { secretTransportVerdict } from "./env-transport-policy";
12
+ import { SOURCE_DIRECTORY_CAPABILITY as DIR_CAP, isDirectoryRequestId, isDirectoryServerId, isSourceDirectorySnapshot,
13
+ type SourceDirectoryTask, type SourceDirectorySnapshot } from "./contracts/session-source-directory";
14
+ import { PROJECT_CREATE_CAPABILITY, SESSION_ATTACH_CAPABILITY } from "./contracts/session-project-create";
15
+ import { createSessionProjectTransport } from "./session-project-create";
16
+ import { SOURCE_FORK_ROOT as ROOT, SOURCE_FORK_CAPABILITY as CAP, isSourceForkRequestId,
17
+ type SourceForkTask, type SourceForkStatus, type SourceForkReceipt } from "./contracts/session-source-transport";
18
+
19
+ type Row = { request_id: string; user_id: string; requester_token_id: string; network_id: string; intent_id: string;
20
+ source_node_id: string; daemon_node_id: string; daemon_token_id: string; daemon_instance_id: string; session_id: string;
21
+ child_name: string; state: SourceForkStatus; expires_at: number; evidence_id: string; execution_id: string | null;
22
+ delivery_id: string | null; child_node_id: string | null; child_session_id: string | null };
23
+ const keys = (o: Record<string, unknown>, allowed: string[]) => Object.keys(o).every(k => allowed.includes(k));
24
+ const id = (v: unknown): v is string => typeof v === "string" && /^[A-Za-z0-9_-]{1,200}$/.test(v);
25
+ const terminal = (r: Row) => ["registration_confirmed", "refused", "unknown_rotation_required"].includes(r.state);
26
+ const ok = (value: object) => Response.json({ ok: true, ...value }, { headers: { "cache-control": "no-store" } });
27
+
28
+ /** Why a fork create was refused after the caller's source permissions were verified. */
29
+ export type SourceForkFailureReason = "daemon_offline" | "daemon_not_capable" | "hub_busy" | "evidence_unavailable" | "intent_reused";
30
+
31
+ /** Separate REST semantics within the existing session-control HTTP surface.
32
+ * Secret bodies are never persisted. Original human Request lives ONLY in this
33
+ * bounded in-memory orchestration until terminal/expiry, like pendingEnvBlobs;
34
+ * no plaintext requester bearer is journaled or reconstructed after restart. */
35
+
36
+ export function createSessionSourceTransport(options: { enabled?: boolean; directoryEnabled?: boolean; projectEnabled?: boolean; attachEnabled?: boolean } = {}) {
37
+ const enabled = options.enabled === true;
38
+ const issuer = createSessionSourceIssuer(), evidence = createSessionSourceEvidenceQueue({ enabled });
39
+ const execution = createSessionSourceExecutionQueue(evidence, { enabled });
40
+ const delivery = createSessionSourceDeliveryQueue(execution, { enabled });
41
+ const daemons = new Map<string, { token: string; instance: string; expires: number; retired: Set<string>; projectCreate?: boolean; sessionAttach?: boolean }>();
42
+ type DirectoryRow = { task: SourceDirectoryTask; token: string; user: string; daemonToken: string; instance: string;
43
+ status: "pending" | "claimed" | "ready" | "failed"; snapshot?: SourceDirectorySnapshot; parent?: string };
44
+ const directories = new Map<string, DirectoryRow>();
45
+ const directoryPermissions = (r: DirectoryRow) => issuer.directoryPermissions(r.token, r.user, { network_id: r.task.network_id,
46
+ source_node_id: r.task.source_node_id, daemon_node_id: r.task.daemon_node_id, mode: "attach_existing" });
47
+ const directoryCapable = (nodeId: string, network: string) => {
48
+ try {
49
+ const n = db.get<{ config_snapshot: string }>("SELECT config_snapshot FROM nodes WHERE node_id=?1 AND network_id=?2", nodeId, network);
50
+ const s = JSON.parse(n?.config_snapshot ?? "{}");
51
+ const channel = db.get<{ env_transport: string }>("SELECT env_transport FROM sessions WHERE node_id=?1 AND network_id=?2 ORDER BY last_seen_at DESC LIMIT 1", nodeId, network);
52
+ return s.role === "host_supervisor" && s.daemon_capabilities?.source_directory_read === DIR_CAP
53
+ && secretTransportVerdict(channel?.env_transport ?? null, { ANET_SECRET_TRANSPORT_GATE: "enforce", ANET_SECRET_TRANSPORT_GATE_STRICT: "1" }) === null;
54
+ } catch { return false; }
55
+ };
56
+ const directoryCurrent = (r: DirectoryRow, projectSelection = false): boolean => {
57
+ const t = r.task, d = daemons.get(`directory:${t.network_id}:${t.daemon_node_id}`), n = resolveSessionControlNodeCaller(r.daemonToken);
58
+ return Date.now() < (projectSelection ? r.snapshot?.selection_expires_at ?? t.expires_at : t.expires_at) && !!d && d.token === r.daemonToken && d.instance === r.instance && d.expires > Date.now()
59
+ && n?.node_id === t.daemon_node_id && n.network_id === t.network_id && directoryCapable(t.daemon_node_id, t.network_id)
60
+ && directoryPermissions(r) && (!r.parent || (!!directories.get(r.parent) && directoryCurrent(directories.get(r.parent)!, projectSelection)));
61
+ };
62
+ const directoryView = (r: DirectoryRow) => ({ ...r.task, status: r.status, ...(r.snapshot ? { snapshot: r.snapshot } : {}),
63
+ ...(r.status === "failed" ? { error: "directory_read_failed" } : {}) });
64
+ const attachEnabled = options.directoryEnabled === true && process.env.COMMHUB_SESSION_ATTACH_PREVIEW === "1";
65
+ const projectTransport = createSessionProjectTransport({ enabled: options.projectEnabled === true && options.directoryEnabled === true,
66
+ attachEnabled,
67
+ select(s, token, user) {
68
+ const r = directories.get(s.selection_scope);
69
+ if (!r || r.status !== "ready" || r.token !== token || r.user !== user || !r.task.server_id || !directoryCurrent(r, true)
70
+ || typeof r.snapshot?.selection_expires_at !== "number" || r.snapshot.snapshot_id !== s.snapshot_id) return null;
71
+ const attach = "session_id" in s;
72
+ const parent = attach ? r.snapshot.sessions.find(v => v.session_id === s.session_id)?.project_id : s.project_id;
73
+ if (!parent || !r.snapshot.projects.some(p => p.project_id === parent)) return null;
74
+ return { network_id: r.task.network_id, source_node_id: r.task.source_node_id, daemon_node_id: r.task.daemon_node_id,
75
+ daemon_token_id: r.daemonToken, daemon_instance_id: r.instance, selected_project_id: parent,
76
+ operation_kind: attach ? "attach_existing_session" : "project_new_session" };
77
+ },
78
+ permissions: r => issuer.directoryPermissions(r.requester_token_id, r.user_id, { network_id: r.network_id,
79
+ source_node_id: r.source_node_id, daemon_node_id: r.daemon_node_id, mode: "attach_existing" }),
80
+ current(r) {
81
+ const d = daemons.get(`directory:${r.network_id}:${r.daemon_node_id}`), n = resolveSessionControlNodeCaller(r.daemon_token_id);
82
+ try {
83
+ const s = JSON.parse(db.get<{ config_snapshot: string }>("SELECT config_snapshot FROM nodes WHERE node_id=?1 AND network_id=?2", r.daemon_node_id, r.network_id)?.config_snapshot ?? "{}");
84
+ const canNew = options.projectEnabled === true && d?.projectCreate === true && s.daemon_capabilities?.project_new_session === PROJECT_CREATE_CAPABILITY;
85
+ const canAttach = attachEnabled && d?.sessionAttach === true && s.daemon_capabilities?.session_attach === SESSION_ATTACH_CAPABILITY;
86
+ const operationAllowed = r.operation_kind === "attach_existing_session" ? canAttach : r.source_node_id ? canNew : canNew || canAttach;
87
+ return !!d && operationAllowed && d.token === r.daemon_token_id && d.instance === r.daemon_instance_id && d.expires > Date.now()
88
+ && n?.node_id === r.daemon_node_id && n.network_id === r.network_id && directoryCapable(r.daemon_node_id, r.network_id)
89
+ ;
90
+ } catch { return false; }
91
+ } });
92
+ const active = new Map<string, { human: Request; release?: () => void; timer: ReturnType<typeof setTimeout> }>();
93
+ const row = (requestId: string) => db.get<Row>("SELECT * FROM session_source_transports WHERE request_id=?1", requestId);
94
+ const selection = (r: Row) => ({ network_id: r.network_id, source_node_id: r.source_node_id,
95
+ daemon_node_id: r.daemon_node_id, mode: "fork_independent" as const });
96
+ const permissions = (r: Row) => "permissions_verified" in issuer.inspectStoredRequester(r.requester_token_id, r.user_id, selection(r));
97
+ const capable = (nodeId: string, network: string) => {
98
+ try {
99
+ const n = db.get<{ config_snapshot: string }>("SELECT config_snapshot FROM nodes WHERE node_id=?1 AND network_id=?2", nodeId, network);
100
+ const s = JSON.parse(n?.config_snapshot ?? "{}");
101
+ const channel = db.get<{ env_transport: string }>("SELECT env_transport FROM sessions WHERE node_id=?1 AND network_id=?2 ORDER BY last_seen_at DESC LIMIT 1", nodeId, network);
102
+ return s.role === "host_supervisor" && s.daemon_capabilities?.source_node_delivery === SOURCE_DELIVERY_CAPABILITY
103
+ && s.daemon_capabilities?.source_fork_transport === CAP && secretTransportVerdict(channel?.env_transport ?? null,
104
+ { ANET_SECRET_TRANSPORT_GATE: "enforce", ANET_SECRET_TRANSPORT_GATE_STRICT: "1" }) === null;
105
+ } catch { return false; }
106
+ };
107
+ const current = (r: Row) => {
108
+ const d = daemons.get(`${r.network_id}:${r.daemon_node_id}`), n = resolveSessionControlNodeCaller(r.daemon_token_id);
109
+ return Date.now() < r.expires_at && !!d && d.token === r.daemon_token_id && d.instance === r.daemon_instance_id && d.expires > Date.now()
110
+ && n?.node_id === r.daemon_node_id && n.network_id === r.network_id && capable(r.daemon_node_id, r.network_id) && permissions(r);
111
+ };
112
+ const forget = (r: Row) => { const a = active.get(r.request_id); if (a) { clearTimeout(a.timer); active.delete(r.request_id); a.release?.(); } };
113
+ const settle = (r: Row, state: "refused" | "unknown_rotation_required" | "registration_confirmed") => {
114
+ const a = active.get(r.request_id);
115
+ if (state === "unknown_rotation_required" && r.delivery_id) delivery.abandon(r.delivery_id);
116
+ if (state === "unknown_rotation_required" && r.delivery_id && a) {
117
+ const d = delivery.recover(a.human, r.delivery_id);
118
+ if (d) db.run("UPDATE session_source_transports SET child_node_id=?1,child_session_id=?2 WHERE request_id=?3", [d.child_node_id, d.session_id, r.request_id]);
119
+ }
120
+ db.run("UPDATE session_source_transports SET state=?1 WHERE request_id=?2 AND state NOT IN ('registration_confirmed','refused','unknown_rotation_required')", [state, r.request_id]);
121
+ forget(r);
122
+ };
123
+ const refresh = (r: Row) => {
124
+ if (!terminal(r) && (!active.has(r.request_id) || Date.now() >= r.expires_at || !current(r))) settle(r, "unknown_rotation_required");
125
+ return row(r.request_id)!;
126
+ };
127
+ const view = (r: Row): Omit<SourceForkReceipt, "ok"> => ({ request_id: r.request_id, intent_id: r.intent_id, network_id: r.network_id,
128
+ source_node_id: r.source_node_id, daemon_node_id: r.daemon_node_id, session_id: r.session_id, mode: "fork_independent",
129
+ child_name: r.child_name, status: r.state, expires_at: r.expires_at,
130
+ ...(r.child_node_id ? { child_node_id: r.child_node_id } : {}), ...(r.child_session_id ? { child_session_id: r.child_session_id } : {}),
131
+ native_acceptance: "not_verified", dispatch_scope: "gated_preview" });
132
+ const envelope = (r: Row) => ({ request_id: r.request_id, intent_id: r.intent_id, network_id: r.network_id,
133
+ source_node_id: r.source_node_id, daemon_node_id: r.daemon_node_id });
134
+ function startAdmission(r: Row) {
135
+ const a = active.get(r.request_id)!;
136
+ void evidence.admit(a.human, r.evidence_id, r.intent_id, r.child_name, async () => {
137
+ db.run("UPDATE session_source_transports SET state='recheck_pending' WHERE request_id=?1 AND state='evidence_claimed'", [r.request_id]);
138
+ await new Promise<void>(resolve => { a.release = resolve; });
139
+ if (active.get(r.request_id) !== a || !current(r)) throw Error("source_fork_changed");
140
+ }).then(receipt => {
141
+ const now = row(r.request_id)!;
142
+ if (terminal(now) || !current(now)) return;
143
+ const executionId = execution.queue(a.human, receipt.request_id);
144
+ if (!executionId) { settle(now, "refused"); return; }
145
+ db.run("UPDATE session_source_transports SET execution_id=?1,state='execute_pending' WHERE request_id=?2", [executionId, r.request_id]);
146
+ }).catch(() => { const now = row(r.request_id); if (now) settle(now, "refused"); });
147
+ }
148
+ return async function handle(req: Request, url: URL): Promise<Response | null> {
149
+ const projectResponse = await projectTransport(req, url); if (projectResponse) return projectResponse;
150
+ if (url.pathname !== ROOT && !url.pathname.startsWith(`${ROOT}/`)) return null;
151
+ const directoryPath = url.pathname === `${ROOT}/directory` || url.pathname.startsWith(`${ROOT}/directory/`);
152
+ // `reason` is additive diagnostics for the UI (it used to show a bare "conflict" for every 409).
153
+ // Only attached after the caller's permissions on the source are verified — see the fork create path.
154
+ const fail = (status = 409, reason?: SourceForkFailureReason) => Response.json({ ok: false, error: directoryPath ? "source_directory_unavailable" : "source_fork_unavailable",
155
+ ...(reason ? { reason } : {}) }, { status, headers: { "cache-control": "no-store" } });
156
+ if (directoryPath ? options.directoryEnabled !== true : !enabled) return fail(404);
157
+ try {
158
+ const auth = resolveToken(req.headers.get("authorization")?.match(/^Bearer (\S+)$/)?.[1] ?? "");
159
+ if (!auth?.tokenId) return fail(401);
160
+ const credential = readSessionControlCredential(auth.tokenId);
161
+ const suffix = url.pathname.slice((directoryPath ? `${ROOT}/directory` : ROOT).length);
162
+ if (directoryPath) {
163
+ // Read-only, bounded process-memory queue using the same pin/instance
164
+ // transport as source execution. Restart/expiry discards read scopes;
165
+ // no mutation recovery journal or evidence/admission machine is involved.
166
+ for (const [key, r] of directories) if (Date.now() >= (r.snapshot?.selection_expires_at ?? r.task.expires_at)) directories.delete(key);
167
+ if (req.method === "GET") {
168
+ const r = directories.get(suffix.slice(1));
169
+ if (!isHumanCredential(credential) || !isDirectoryRequestId(suffix.slice(1)) || !r
170
+ || [...url.searchParams.keys()].some(k => k !== "network_id") || url.searchParams.getAll("network_id").length !== 1
171
+ || url.searchParams.get("network_id") !== r.task.network_id || auth.tokenId !== r.token || auth.user.user_id !== r.user
172
+ || !directoryCurrent(r)) return fail(403);
173
+ return ok(directoryView(r));
174
+ }
175
+ if (req.method !== "POST" || url.search) return fail(400);
176
+ const b = await readSessionControlBody(req, 65536); if (!b) return fail(400);
177
+ if (!suffix) {
178
+ if (!isHumanCredential(credential) || !keys(b, ["network_id", "source_node_id", "daemon_node_id", "server_id", "selection_scope"])
179
+ || !id(b.network_id) || !id(b.source_node_id) || !id(b.daemon_node_id)
180
+ || (b.server_id !== undefined && (!isDirectoryServerId(b.server_id) || !isDirectoryRequestId(b.selection_scope)))
181
+ || (b.server_id === undefined && b.selection_scope !== undefined)) return fail(400);
182
+ const d = daemons.get(`directory:${b.network_id}:${b.daemon_node_id}`);
183
+ const task: SourceDirectoryTask = { request_id: `srcdir_${randomUUID()}`, network_id: b.network_id as string,
184
+ source_node_id: b.source_node_id as string, daemon_node_id: b.daemon_node_id as string,
185
+ expires_at: Date.now() + 30000, ...(b.server_id ? { server_id: b.server_id as string } : {}) };
186
+ const r: DirectoryRow = { task, token: auth.tokenId, user: auth.user.user_id, daemonToken: d?.token ?? "", instance: d?.instance ?? "", status: "pending" };
187
+ if (!directoryCurrent(r)) return fail(403);
188
+ if (b.server_id) {
189
+ const parent = directories.get(b.selection_scope as string);
190
+ if (!parent || parent.parent || parent.status !== "ready" || !directoryCurrent(parent) || parent.token !== r.token || parent.user !== r.user
191
+ || parent.task.network_id !== task.network_id || parent.task.source_node_id !== task.source_node_id || parent.task.daemon_node_id !== task.daemon_node_id
192
+ || parent.instance !== r.instance || !parent.snapshot?.servers.some(s => s.server_id === b.server_id)) return fail(403);
193
+ r.parent = parent.task.request_id; task.expires_at = Math.min(task.expires_at, parent.task.expires_at);
194
+ }
195
+ if (directories.size >= 100) return fail();
196
+ directories.set(task.request_id, r); return ok(directoryView(r));
197
+ }
198
+ const n = resolveSessionControlNodeCaller(auth.tokenId), expected: any = b.expected;
199
+ if (!n || !expected || Object.keys(expected).length !== 2 || expected.node_id !== n.node_id || expected.network_id !== n.network_id
200
+ || b.capability !== DIR_CAP || !directoryCapable(n.node_id, n.network_id)) return fail(403);
201
+ const key = `directory:${n.network_id}:${n.node_id}`;
202
+ if (suffix === "/daemon") {
203
+ if (!keys(b, ["expected", "capability", "instance_id", "project_create_capability", "session_attach_capability"]) || typeof b.instance_id !== "string" || !/^[a-f0-9-]{36}$/.test(b.instance_id)
204
+ || (b.project_create_capability !== undefined && b.project_create_capability !== PROJECT_CREATE_CAPABILITY)
205
+ || (b.session_attach_capability !== undefined && b.session_attach_capability !== SESSION_ATTACH_CAPABILITY)) return fail(400);
206
+ const previous = daemons.get(key), retired = previous?.retired ?? new Set<string>();
207
+ if ((!previous && daemons.size >= 128) || retired.has(b.instance_id) || (previous?.instance === b.instance_id && previous.token !== auth.tokenId)) return fail();
208
+ if (previous && (previous.instance !== b.instance_id || previous.token !== auth.tokenId)) {
209
+ if (retired.size >= 64) return fail(); retired.add(previous.instance);
210
+ for (const [id, r] of directories) if (r.task.daemon_node_id === n.node_id && r.task.network_id === n.network_id) directories.delete(id);
211
+ }
212
+ daemons.set(key, { token: auth.tokenId, instance: b.instance_id, expires: Date.now() + 30000, retired,
213
+ projectCreate: options.projectEnabled === true && b.project_create_capability === PROJECT_CREATE_CAPABILITY,
214
+ sessionAttach: attachEnabled && b.session_attach_capability === SESSION_ATTACH_CAPABILITY }); return ok({ capability: DIR_CAP, expected });
215
+ }
216
+ const d = daemons.get(key);
217
+ if (!d || d.token !== auth.tokenId || d.instance !== b.instance_id || d.expires <= Date.now()) return fail(403);
218
+ if (suffix === "/pull") {
219
+ if (!keys(b, ["expected", "capability", "instance_id"])) return fail(400);
220
+ for (const r of directories.values()) if (r.status === "pending" && r.daemonToken === auth.tokenId && r.instance === d.instance && directoryCurrent(r)) {
221
+ r.status = "claimed"; return ok({ task: r.task });
222
+ }
223
+ return ok({ task: null });
224
+ }
225
+ if (suffix === "/ack") {
226
+ if (!keys(b, ["expected", "capability", "instance_id", "request_id", "result"]) || !isDirectoryRequestId(b.request_id)) return fail(400);
227
+ const r = directories.get(b.request_id as string);
228
+ if (!r || r.status !== "claimed" || r.daemonToken !== auth.tokenId || r.instance !== d.instance || !directoryCurrent(r)) return fail(403);
229
+ const result: any = b.result;
230
+ if (result && Object.keys(result).length === 1 && result.error === "directory_read_failed") r.status = "failed";
231
+ else if (isSourceDirectorySnapshot(result, r.task.expires_at)
232
+ && (!r.task.server_id ? !result.projects.length && !result.sessions.length : result.servers.some(s => s.server_id === r.task.server_id)
233
+ && result.projects.every(p => p.server_id === r.task.server_id))) { r.status = "ready"; r.snapshot = result; }
234
+ else return fail(400);
235
+ return ok({ acknowledged: true });
236
+ }
237
+ return fail(404);
238
+ }
239
+ if (req.method === "GET") {
240
+ if (!isHumanCredential(credential) || !/^\/srcf_[a-f0-9-]{36}$/.test(suffix)
241
+ || [...url.searchParams.keys()].some(k => k !== "network_id")) return fail(403);
242
+ const r = row(suffix.slice(1));
243
+ if (!r || url.searchParams.get("network_id") !== r.network_id || auth.tokenId !== r.requester_token_id
244
+ || auth.user.user_id !== r.user_id || !permissions(r)) return fail(403);
245
+ const now = refresh(r);
246
+ // Unknown recovery may record known IDs/revoke an unconfirmed credential,
247
+ // never dispatch, mint or repeat a session mutation.
248
+ if (now.state === "unknown_rotation_required") {
249
+ const e = now.execution_id && execution.recover(req, now.execution_id);
250
+ if (e && e.status === "session_ready") now.child_session_id = e.session_id!;
251
+ const d = now.delivery_id && delivery.recover(req, now.delivery_id);
252
+ if (d) { now.child_node_id = d.child_node_id; now.child_session_id = d.session_id; }
253
+ }
254
+ return ok(view(now));
255
+ }
256
+ if (req.method !== "POST" || url.search) return fail(400);
257
+ const b = await readSessionControlBody(req, 32768); if (!b) return fail(400);
258
+ if (suffix === "") {
259
+ if (db.dialect !== "sqlite" || db.atomicTransactions !== true || db.transactionalFeaturesRefusal !== null) return fail();
260
+ if (!isHumanCredential(credential) || !keys(b, ["network_id", "source_node_id", "session_id", "mode", "child_name", "intent_id"])
261
+ || !id(b.network_id) || !id(b.source_node_id) || !id(b.intent_id) || typeof b.session_id !== "string"
262
+ || !/^ses_[A-Za-z0-9]{1,190}$/.test(b.session_id) || b.mode !== "fork_independent") return fail(400);
263
+ const name = checkNodeName(b.child_name); if (!name.ok || name.name !== b.child_name) return fail(400);
264
+ // Infer management from existing authoritative create/adoption journals.
265
+ const owners = db.all<{ daemon_node_id: string }>(`SELECT daemon_node_id FROM node_create_requests WHERE child_node_id=?1
266
+ AND network_id=?2 AND status='succeeded' AND source_ref IS NULL UNION SELECT daemon_node_id FROM node_daemon_bindings
267
+ WHERE node_id=?1 AND network_id=?2 AND status='active'
268
+ UNION SELECT daemon_node_id FROM session_project_creates
269
+ WHERE child_node_id=?1 AND network_id=?2 AND state='registration_confirmed'`, b.source_node_id, b.network_id);
270
+ if (owners.length !== 1) return fail();
271
+ const s = { network_id: b.network_id, source_node_id: b.source_node_id, daemon_node_id: owners[0].daemon_node_id, mode: "fork_independent" as const };
272
+ if (!("permissions_verified" in issuer.inspect(req, s))) return fail(403);
273
+ const existing = db.get<Row>("SELECT * FROM session_source_transports WHERE user_id=?1 AND network_id=?2 AND intent_id=?3", auth.user.user_id, b.network_id, b.intent_id);
274
+ if (existing) {
275
+ if (existing.requester_token_id !== auth.tokenId || existing.source_node_id !== b.source_node_id || existing.session_id !== b.session_id
276
+ || existing.child_name !== b.child_name || existing.daemon_node_id !== s.daemon_node_id) return fail(409, "intent_reused");
277
+ return ok(view(refresh(existing))); // idempotent receipt, not a new workflow
278
+ }
279
+ const d = daemons.get(`${s.network_id}:${s.daemon_node_id}`);
280
+ if (!d || d.expires <= Date.now()) return fail(409, "daemon_offline");
281
+ if (!capable(s.daemon_node_id, s.network_id)) return fail(409, "daemon_not_capable");
282
+ if (active.size >= 128) return fail(409, "hub_busy");
283
+ const q = evidence.queue(req, s, b.session_id); if (!q) return fail(409, "evidence_unavailable");
284
+ const requestId = `srcf_${randomUUID()}`, expires = Date.now() + 75_000;
285
+ db.run(`INSERT INTO session_source_transports (request_id,user_id,requester_token_id,network_id,intent_id,source_node_id,
286
+ daemon_node_id,daemon_token_id,daemon_instance_id,session_id,child_name,state,expires_at,evidence_id)
287
+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,'evidence_pending',?12,?13)`,
288
+ [requestId, auth.user.user_id, auth.tokenId, s.network_id, b.intent_id, s.source_node_id, s.daemon_node_id,
289
+ d.token, d.instance, b.session_id, name.name, expires, q.request_id]);
290
+ const timer = setTimeout(() => { const r = row(requestId); if (r && !terminal(r)) settle(r, "unknown_rotation_required"); }, 75_000);
291
+ timer.unref?.(); active.set(requestId, { human: req, timer }); return ok(view(row(requestId)!));
292
+ }
293
+ if (suffix === "/child-register") {
294
+ if (!keys(b, ["request_id", "intent_id", "network_id", "source_node_id", "daemon_node_id", "delivery_id"]) || !isSourceForkRequestId(b.request_id)) return fail(400);
295
+ const r = row(b.request_id);
296
+ if (!r || r.state !== "deliver_claimed" || !current(r) || !active.has(r.request_id)
297
+ || !Object.entries(envelope(r)).every(([k, v]) => b[k] === v) || r.delivery_id !== b.delivery_id
298
+ || !delivery.confirmRegistration(req, r.delivery_id!)) return fail(403);
299
+ const child = db.get<{ child_node_id: string }>("SELECT child_node_id FROM session_source_node_deliveries WHERE delivery_id=?1", r.delivery_id!);
300
+ db.run("UPDATE session_source_transports SET child_node_id=?1 WHERE request_id=?2", [child!.child_node_id, r.request_id]);
301
+ settle(r, "registration_confirmed"); return ok({ request_id: r.request_id, delivery_id: r.delivery_id, status: "registration_confirmed" });
302
+ }
303
+ const n = resolveSessionControlNodeCaller(auth.tokenId);
304
+ const expected: any = b.expected;
305
+ if (!n || !expected || Object.keys(expected).length !== 2 || expected.node_id !== n.node_id || expected.network_id !== n.network_id
306
+ || b.capability !== CAP || !capable(n.node_id, n.network_id)) return fail(403);
307
+ const daemonKey = `${n.network_id}:${n.node_id}`;
308
+ if (suffix === "/daemon") {
309
+ if (!keys(b, ["expected", "capability", "instance_id"]) || typeof b.instance_id !== "string" || !/^[a-f0-9-]{36}$/.test(b.instance_id)) return fail(400);
310
+ if (!daemons.has(daemonKey) && daemons.size >= 128) return fail();
311
+ const previous = daemons.get(daemonKey), retired = previous?.retired ?? new Set<string>();
312
+ if (retired.has(b.instance_id)) return fail();
313
+ if (previous?.instance === b.instance_id && previous.token !== auth.tokenId) return fail();
314
+ if (previous && (previous.instance !== b.instance_id || previous.token !== auth.tokenId)) {
315
+ if (retired.size >= 64) return fail();
316
+ retired.add(previous.instance);
317
+ for (const r of db.all<Row>("SELECT * FROM session_source_transports WHERE daemon_node_id=?1 AND network_id=?2 AND state NOT IN ('registration_confirmed','refused','unknown_rotation_required')", n.node_id, n.network_id)) {
318
+ settle(r, "unknown_rotation_required");
319
+ }
320
+ }
321
+ daemons.set(daemonKey, { token: auth.tokenId, instance: b.instance_id, expires: Date.now() + 75_000, retired }); return ok({ capability: CAP, expected });
322
+ }
323
+ if (suffix === "/pull") {
324
+ if (!keys(b, ["expected", "capability", "instance_id"]) || daemons.get(daemonKey)?.instance !== b.instance_id) return fail(403);
325
+ const rows = db.all<Row>("SELECT * FROM session_source_transports WHERE daemon_node_id=?1 AND network_id=?2 AND daemon_token_id=?3 AND state NOT IN ('registration_confirmed','refused','unknown_rotation_required') ORDER BY rowid", n.node_id, n.network_id, auth.tokenId);
326
+ for (const original of rows) {
327
+ const r = refresh(original); if (terminal(r)) continue;
328
+ let task: SourceForkTask | null = null;
329
+ if (r.state === "evidence_pending") { const t = evidence.take(req, r.evidence_id); if (t) task = { ...envelope(r), phase: "evidence", task: t }; }
330
+ if (r.state === "recheck_pending") { const t = evidence.takeRecheck(req, r.evidence_id); if (t) task = { ...envelope(r), phase: "recheck", task: t }; }
331
+ if (r.state === "execute_pending") { const t = execution.take(req, r.execution_id!); if (t) task = { ...envelope(r), phase: "execute", task: t }; }
332
+ if (r.state === "deliver_pending") { const t = delivery.take(req, r.delivery_id!, SOURCE_DELIVERY_CAPABILITY); if (t) task = { ...envelope(r), phase: "deliver", task: t }; }
333
+ if (task) { db.run("UPDATE session_source_transports SET state=?1 WHERE request_id=?2", [`${task.phase}_claimed`, r.request_id]); return ok({ task }); }
334
+ if (r.state.endsWith("_pending")) settle(r, "unknown_rotation_required");
335
+ }
336
+ return ok({ task: null });
337
+ }
338
+ if (suffix === "/ack") {
339
+ if (!keys(b, ["expected", "capability", "instance_id", "request_id", "intent_id", "network_id", "source_node_id", "daemon_node_id", "phase", "result"])
340
+ || !isSourceForkRequestId(b.request_id)) return fail(400);
341
+ const r = row(b.request_id);
342
+ if (!r || !Object.entries(envelope(r)).every(([k, v]) => b[k] === v) || r.daemon_token_id !== auth.tokenId
343
+ || r.daemon_instance_id !== b.instance_id || !current(r)) return fail(403);
344
+ if (r.state === "registration_confirmed" && b.phase === "deliver") return ok({ acknowledged: true });
345
+ if (r.state !== `${b.phase}_claimed` || !active.has(r.request_id)) return fail();
346
+ const result: any = b.result;
347
+ if (result && Object.keys(result).length === 1 && result.transport_failure === "unknown_rotation_required") {
348
+ settle(r, "unknown_rotation_required"); return ok({ acknowledged: true });
349
+ }
350
+ if (b.phase === "evidence") { if (result?.request?.request_id !== r.evidence_id || !evidence.ack(req, result)) return fail(400); startAdmission(r); }
351
+ else if (b.phase === "recheck") { if (result?.request?.evidence?.request?.request_id !== r.evidence_id || !evidence.ackRecheck(req, result)) return fail(400); active.get(r.request_id)?.release?.(); }
352
+ else if (b.phase === "execute") {
353
+ if (result?.execution_id !== r.execution_id || !execution.ack(req, b.result)) return fail(400);
354
+ const a = active.get(r.request_id)!, recovered = execution.recover(a.human, r.execution_id!);
355
+ if (recovered?.status !== "session_ready") { settle(r, recovered?.status === "refused" ? "refused" : "unknown_rotation_required"); }
356
+ else {
357
+ const deliveryId = delivery.queue(a.human, r.execution_id!);
358
+ if (!deliveryId) settle(r, "unknown_rotation_required");
359
+ else db.run("UPDATE session_source_transports SET state='deliver_pending',delivery_id=?1,child_session_id=?2 WHERE request_id=?3", [deliveryId, recovered.session_id!, r.request_id]);
360
+ }
361
+ } else if (b.phase === "deliver") { settle(r, "unknown_rotation_required"); }
362
+ else return fail(400);
363
+ return ok({ acknowledged: true });
364
+ }
365
+ return fail(404);
366
+ } catch { return fail(); }
367
+ };
368
+ }
@@ -63,8 +63,11 @@ describe("#3325 运行时键集(list_tasks 成功路径)", () => {
63
63
  // 🔴 我第一次写的是四个键(count/ok/stats/tasks)—— 真实调用给出 **五个**:
64
64
  // `next_cursor` 也在里面。这就是这一格存在的理由:静态读代码得到的键集是
65
65
  // 「我以为它返回什么」,而运行时对照得到的是「它实际返回什么」。
66
+ // 🔴 2026-11-06 第三次被真实调用纠正(#3119 since_last 水位):多了 `server_time`。
67
+ // 它不是"顺手加的一个字段":调用方要靠它做下一次增量(`since_last` / `created_since`
68
+ // 都拿它当入参),所以"键集变了"在这里等于"契约变了",值得红一次。
66
69
  expect(Object.keys(r).sort()).toEqual([
67
- "count", "next_cursor", "ok", "stats", "tasks",
70
+ "count", "next_cursor", "ok", "server_time", "stats", "tasks",
68
71
  ].sort());
69
72
  // 空库时这几格的具体形态也钉住(**第二次被真实调用纠正**:我写「stats 是对象」,
70
73
  // 实测它是**数组** —— 源码里 stats 来自 `GROUP BY status` 的 db.all(...),本来就是行数组)。
@@ -116,6 +116,16 @@ describe("#3952 /api/token-usage", () => {
116
116
  expect(nodes.every((n: any) => n.node_id !== "n_tu_x")).toBe(true);
117
117
  });
118
118
 
119
+ test("不传 network_id:唯一所属网络时自动回退(与 /api/providers 同口径)", async () => {
120
+ // 上一版这里 400 network_required,而同一页的 /api/providers 会给 200 ——
121
+ // 同一台 hub 上相邻两个端点对同一个用户给不同答案,客户端被迫多写分支。
122
+ const r = await get(`${TOKEN_USAGE}?since_hours=24`, ownerToken);
123
+ expect(r.status).toBe(200);
124
+ expect(r.body.network_id).toBe(ownerNet);
125
+ // 镜像:既然回退了,就必须回退到**自己的**网络,而不是任意一个
126
+ expect(r.body.network_id).not.toBe(strangerNet);
127
+ });
128
+
119
129
  test("节点令牌看不到(user_token_required,不是 404 也不是空表)", async () => {
120
130
  const r = await get(`${TOKEN_USAGE}?network_id=${ownerNet}`, nodeToken);
121
131
  expect(r.status).toBe(403);
@@ -44,6 +44,7 @@ const OVERRIDES: Record<string, Record<string, unknown>> = {
44
44
  upsert_network_secret: { key: "PROBE_KEY" },
45
45
  update_provider: { provider_id: "prov_probe" },
46
46
  schedule_batch_interval: { schedule_ids: ["sched_probe"], every_seconds: 60 },
47
+ select_opencode_session_model: { session_id: "ses_probe", model: { providerID: "stub", id: "model" } },
47
48
  };
48
49
  function fill(schema: any, key: string, ctx: Record<string, unknown>): unknown {
49
50
  if (!schema) return "probe";
@@ -119,6 +120,23 @@ describe("every tool is classified", () => {
119
120
  });
120
121
  });
121
122
 
123
+ test("create_node source_ref fails MCP validation without minting or enqueueing", async () => {
124
+ const count = (table: string) => db.get<{ n: number }>(`SELECT COUNT(*) AS n FROM ${table}`)!.n;
125
+ const before = [count("node_create_requests"), count("api_tokens")];
126
+ const base = { daemon_node_id: "daemon_source_fixture", network_id: NET,
127
+ node_spec: { name: "source-fixture", runtime: "opencode-cli" } };
128
+ for (const source_ref of ["src_fixture", null, "", {}]) {
129
+ for (const args of [{ ...base, source_ref }, { ...base, node_spec: { ...base.node_spec, source_ref } }]) {
130
+ const { json } = await rpc(T.owner, "tools/call", { name: "create_node", arguments: args });
131
+ const text = String(json.result?.content?.[0]?.text ?? "");
132
+ expect(json.error?.code === -32602 || /^MCP error -32602/.test(text)).toBe(true);
133
+ }
134
+ }
135
+ expect([count("node_create_requests"), count("api_tokens")]).toEqual(before);
136
+ const ordinary = await rpc(T.owner, "tools/call", { name: "create_node", arguments: base });
137
+ expect(JSON.parse(ordinary.json.result.content[0].text).error).toBe("daemon_not_found");
138
+ });
139
+
122
140
  describe("compat replay: nothing callable today disappears from the list", () => {
123
141
  const cases: Array<[string, string, string | null]> = [
124
142
  ["node (normal, log)", "node_normal", null], ["node (readonly)", "node_readonly", null], ["node (restricted)", "node_restricted", null],
@@ -44,7 +44,7 @@ export const TOOL_AUDIENCE: Readonly<Record<string, ToolAudience>> = {
44
44
  get_opencode_catalog_request: "protocol", ack_opencode_catalog: "protocol",
45
45
  // ── 人:节点令牌一律 user_token_required(项目管理)/ node_token_cannot_browse_files / node_token_cannot_read_logs ──
46
46
  projects_create: "user", projects_update: "user", requirement_tags: "both",
47
- read_opencode_catalog: "user", get_opencode_catalog: "user",
47
+ read_opencode_catalog: "user", get_opencode_catalog: "user", select_opencode_session_model: "user",
48
48
  list_node_files: "user", read_node_file: "user", tail_node_logs: "user",
49
49
  // ── 两边都能调 ──
50
50
  submit_skill: "both", list_skills: "both", get_skill: "both", review_skill: "both",