@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
package/build-info.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "commit": "a10fa363e362c705a212eb1ad883fdc72dc4499c",
3
+ "commit": "2e5797704099ae555f5a95995b51a959e3b5d7d6",
4
4
  "dirty": false,
5
- "built_at": "2026-11-05T17:33:11.706Z",
5
+ "built_at": "2026-11-09T05:42:24.093Z",
6
6
  "source": "git"
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.274",
3
+ "version": "0.9.0-preview.276",
4
4
  "description": "CommHub Server — AI Agent communication hub with MCP protocol, multi-network isolation, user auth, and MCP tools (17 collaboration-core + node/provider ops tools; authoritative list: docs-site/docs/api/mcp-tools.md).",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -186,8 +186,13 @@ describe("visibleAgents batched = reference, on randomized fixtures", () => {
186
186
  db.get = (...a: any[]) => { calls.get++; return get(...a); };
187
187
  try { visibleAgents(user, net); } finally { db.all = all; db.get = get; }
188
188
  // direct grants + group grants + ceil(nodes / chunk) alias reads
189
- expect(calls.all + calls.get).toBeLessThanOrEqual(2 + Math.ceil(grants / CHUNK));
190
- expect(calls.all + calls.get).toBeLessThanOrEqual(3);
189
+ // 2026-11-06 —— 上限 +1:#3432(部门维度授权)在 visibleAgents 里多了一条
190
+ // **与节点数无关**的查询(network_departments + nodes.department_id)。
191
+ // 这条测试的意图是「固定次数,不是 per-grant」——多加一个常量查询仍是固定次数,
192
+ // 但数字必须跟着改,且要改在**两处**(本文件 + agent-groups-perf.test.ts),
193
+ // 否则另一处会以「预算超了」的措辞红,看起来像实现回归。
194
+ expect(calls.all + calls.get).toBeLessThanOrEqual(3 + Math.ceil(grants / CHUNK));
195
+ expect(calls.all + calls.get).toBeLessThanOrEqual(4);
191
196
  }, 60_000);
192
197
 
193
198
  test("more granted nodes than one chunk: same output across the chunk boundary", () => {
@@ -378,7 +378,10 @@ describe("update_node_config 响应键集(exact key set)", () => {
378
378
  const r = await tool(adminToken, "list_tasks", { network_id: NET });
379
379
  // ⚠️ 我从源码里读到的形状(capability / next_terminal_seq)与实际返回不同 ——
380
380
  // 这一条断言当场纠正了我:**读码得到的形状必须由一次真实调用确认**。
381
- expect(Object.keys(r).sort()).toEqual(["count", "next_cursor", "ok", "stats", "tasks"]);
381
+ // 🔴 2026-11-06(#3119 since_last 水位)—— 多了 `server_time`:它是下一次增量的入参,
382
+ // 所以这里「键集变了」等于「契约变了」,不是措辞变化。同一改动会同时打到
383
+ // task-not-found-error-domain.test.ts 的那一格(两处都钉了键集,本来就该一起改)。
384
+ expect(Object.keys(r).sort()).toEqual(["count", "next_cursor", "ok", "server_time", "stats", "tasks"]);
382
385
  expect(Array.isArray(r.tasks)).toBe(true);
383
386
  expect(r.count).toBe(r.tasks.length); // 计数与数组同源
384
387
  });
@@ -181,7 +181,12 @@ describe("Agent 分组:性能守卫(50 组 × 300 节点)", () => {
181
181
  (db as any).get = (...a: any[]) => { queries++; return (get as any)(...a); };
182
182
  try { visibleAgents(who.id, NET); } finally { (db as any).all = all; (db as any).get = get; }
183
183
  console.log(`[perf] visibleAgents queries (${who === bob ? "direct-300" : "groups-50x6"}): ${queries}`);
184
- expect(queries).toBeLessThanOrEqual(3);
184
+ // 2026-11-06 —— 预算 3 → 4:#3432(部门维度授权)在 visibleAgents 里**多了一条**
185
+ // 与节点数无关的查询(network_departments + nodes.department_id)。
186
+ // 这条测试的意图是「固定次数,不是 per-grant」,多加一个**常量**查询仍然是固定次数;
187
+ // 但数字必须跟着改,否则它会把一条正确的实现判成回归 —— 而更糟的读法是
188
+ // 「预算被悄悄抬高」:所以基准写在这里,谁再加一档谁改这一行。
189
+ expect(queries).toBeLessThanOrEqual(4);
185
190
  }
186
191
  });
187
192
 
@@ -0,0 +1,184 @@
1
+ // Isolated real Hub + real agent-node CLI startup probe, no direct handler calls.
2
+ import { expect, test } from "bun:test";
3
+ import { spawn } from "node:child_process";
4
+ import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { register, createNetworkTokenForNode } from "./auth.js";
8
+ import { db } from "./db.js";
9
+
10
+ test("real daemon reaches owned TEST-ONLY runtime readiness", async () => {
11
+ const root = mkdtempSync(join(tmpdir(), "anet-4099-daemon-"));
12
+ const stamp = Date.now(), alias = `variant-daemon-${stamp}`, nodeId = `node_variant_${stamp}`;
13
+ const user = register(`variant_owner_${stamp}`, "Fixture4099Only!x");
14
+ const network = user.network_id!;
15
+ const minted = createNetworkTokenForNode(user.user!.user_id, network, alias, nodeId);
16
+ expect(minted.ok).toBe(true);
17
+ const hubModule: any = await import("./server.js");
18
+ const hub = hubModule.bootServer({ port: 0, hostname: "127.0.0.1" });
19
+ const url = `http://127.0.0.1:${hub.port}`;
20
+ let holdAck = false, ackWaiting = false;
21
+ const pullWire: string[] = [];
22
+ let releaseAck!: () => void, sawAck!: () => void, sawHeartbeat!: () => void;
23
+ const ackHeld = new Promise<void>(r => { sawAck = r; });
24
+ const ackGate = new Promise<void>(r => { releaseAck = r; });
25
+ const heartbeatAfterAck = new Promise<void>(r => { sawHeartbeat = r; });
26
+ const proxy = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) {
27
+ const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.arrayBuffer();
28
+ let name = "";
29
+ if (body) { try { name = JSON.parse(new TextDecoder().decode(body))?.params?.name ?? ""; } catch {} }
30
+ if (holdAck && name === "ack_config_update") { ackWaiting = true; sawAck(); await ackGate; }
31
+ const target = new URL(req.url); target.host = `127.0.0.1:${hub.port}`;
32
+ const response = await fetch(target, { method: req.method, headers: req.headers, body, signal: req.signal });
33
+ if (name === "get_config_update") pullWire.push(await response.clone().text());
34
+ if (ackWaiting && name === "report_status") sawHeartbeat();
35
+ return response;
36
+ } });
37
+ const daemonUrl = `http://127.0.0.1:${proxy.port}`;
38
+ const configPath = join(root, "config.json");
39
+ writeFileSync(configPath, JSON.stringify({ alias, node_id: nodeId, network_id: network, hub: daemonUrl,
40
+ runtime: "opencode-cli", opencodeGeneration: "v2", opencodeMode: "copresence", model: "fixture/model", flags: { opencodeUnsafeTools: true } }), { mode: 0o600 });
41
+ let providerSignal!: () => void;
42
+ const providerReached = new Promise<void>(resolve => { providerSignal = resolve; });
43
+ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() {
44
+ providerSignal();
45
+ return new Response(new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode(": held\n\n")); } }), { headers: { "content-type": "text/event-stream" } });
46
+ } });
47
+ const config = { providers: { fixture: { name: "fixture", package: "@opencode/ai/providers/openai-compatible",
48
+ settings: { baseURL: `http://127.0.0.1:${provider.port}/v1`, apiKey: "synthetic" },
49
+ models: { model: { name: "model", limit: { context: 128000, output: 16000 }, variants: [{ id: "high" }, { id: "low" }] } },
50
+ } } };
51
+ mkdirSync(join(root, ".config", "opencode"), { recursive: true, mode: 0o700 });
52
+ writeFileSync(join(root, ".config", "opencode", "opencode.json"), JSON.stringify(config), { mode: 0o600 });
53
+ const daemon = spawn("/tool/bun", ["/out/cli.js", "--config", configPath], { cwd: root, env: {
54
+ PATH: process.env.PATH, HOME: root, TMPDIR: root, XDG_CACHE_HOME: join(root, "cache"), XDG_DATA_HOME: join(root, "data"),
55
+ XDG_CONFIG_HOME: join(root, "config"), XDG_STATE_HOME: join(root, "state"), COMMHUB_TOKEN: minted.token!,
56
+ ANET_OPENCODE_BIN: "/tmp/opencode/anet-4099-test-only-29040e2/cli/cli-linux-x64/bin/opencode", ANET_OPENCODE_SAFE_BASE: "/safe", ANET_VARIANT_TEST_ONLY: "1", ANET_STATUS_HEARTBEAT_MS: "3000", ANET_STATUS_HEARTBEAT_JITTER_MS: "0",
57
+ }, stdio: ["ignore", "pipe", "pipe"] });
58
+ let output = "";
59
+ let nativePid: number | undefined;
60
+ try {
61
+ const outcome = await new Promise<string>(resolve => {
62
+ const timeout = setTimeout(() => resolve("timeout"), 20000);
63
+ const onOutput = (chunk: Buffer) => {
64
+ output += chunk.toString();
65
+ if (/SSE connected/.test(output)) { clearTimeout(timeout); resolve("ready"); }
66
+ };
67
+ daemon.stdout.on("data", onOutput); daemon.stderr.on("data", onOutput);
68
+ daemon.once("exit", (code, signal) => { clearTimeout(timeout); resolve(`exit ${code} ${signal ?? ""}`); });
69
+ });
70
+ console.log("daemon pid", daemon.pid, "startup", outcome, "log", output.replace(/(?:ntok|utok)_[A-Za-z0-9_-]+/g, "[synthetic-token]"));
71
+ expect(outcome).toBe("ready");
72
+ const rpc = async (name: string, args: any) => {
73
+ const response = await fetch(`${url}/mcp`, { method: "POST", headers: { authorization: `Bearer ${user.token}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) });
74
+ const raw = await response.text(), line = raw.split("\n").find(x => x.startsWith("data: "));
75
+ const envelope = JSON.parse(line ? line.slice(6) : raw);
76
+ return JSON.parse(envelope.result.content[0].text);
77
+ };
78
+ const getConfig = async () => (await fetch(`${url}/api/nodes/${nodeId}/config?network_id=${network}`, { headers: { authorization: `Bearer ${user.token}` } })).json() as Promise<any>;
79
+ const until = async (label: string, check: () => Promise<any>) => {
80
+ const deadline = Date.now() + 18000;
81
+ while (Date.now() < deadline) { const value = await check(); if (value) return value; await new Promise(r => setTimeout(r, 250)); }
82
+ throw Error(`timed out waiting for ${label}`);
83
+ };
84
+ const ready = await until("daemon fresh catalog capability", async () => { const cfg = await getConfig(); return cfg.opencode_variant_config_capable === true && cfg; });
85
+ console.log("daemon capability/readback", JSON.stringify(ready));
86
+ const { readOpenCodeV2CatalogEndpoint } = await import("../../agent-node/src/runtime/opencode-v2-catalog-endpoint.js");
87
+ const endpoint = readOpenCodeV2CatalogEndpoint(root)!;
88
+ expect(endpoint).toBeTruthy();
89
+ const native = async (path: string, method = "GET", body?: unknown) => fetch(`${endpoint.url}${path}`, { method, headers: { authorization: endpoint.authorization, "x-opencode-directory": endpoint.directory, "content-type": "application/json" }, ...(body ? { body: JSON.stringify(body) } : {}) });
90
+ const info = await (await native("/api/info")).json() as any;
91
+ nativePid = info.pid;
92
+ const launch = await Bun.file(join(root, "opencode-attach.sh")).text();
93
+ const sessionId = /--session '([^']+)'/.exec(launch)?.[1];
94
+ expect(sessionId).toBeTruthy();
95
+ console.log("runtime identity", JSON.stringify({ daemonPid: daemon.pid, nativePid: info.pid, version: info.version, sessionId }));
96
+ expect(info.version).toBe("2.0.22-anet-test.29040e2");
97
+ holdAck = true;
98
+ const queued = await rpc("update_node_config", { node_id: nodeId, base_revision: ready.config_revision, patch: { modelVariant: "high" } });
99
+ expect(queued.ok).toBe(true);
100
+ await Promise.race([ackHeld, new Promise<never>((_, reject) => setTimeout(() => reject(Error("daemon ack not intercepted")), 18000))]);
101
+ await Promise.race([heartbeatAfterAck, new Promise<never>((_, reject) => setTimeout(() => reject(Error("heartbeat did not follow held ack")), 18000))]);
102
+ const heartbeatPending = await getConfig();
103
+ expect(heartbeatPending.last_update).toMatchObject({ update_id: queued.update_id, status: "pending" });
104
+ expect(heartbeatPending.modelVariant).toBe("high");
105
+ expect((await (await native(`/api/session/${sessionId}`)).json() as any).data.model.variant).toBe("high");
106
+ console.log("real heartbeat while ack held", JSON.stringify({ update: queued.update_id, status: "pending", actualVariant: "high" }));
107
+ holdAck = false; releaseAck();
108
+ const done = await until("real daemon high ack", async () => { const cfg = await getConfig();
109
+ if (cfg.last_update?.update_id === queued.update_id && ["rejected", "timeout"].includes(cfg.last_update.status)) throw Error(`high terminal ${JSON.stringify(cfg.last_update)}`);
110
+ return cfg.last_update?.update_id === queued.update_id && cfg.last_update?.status === "applied" && cfg.modelVariant === "high" && cfg; });
111
+ const actual = await (await native(`/api/session/${sessionId}`)).json() as any;
112
+ expect(actual.data.model).toMatchObject({ providerID: "fixture", id: "model", variant: "high" });
113
+ console.log("real SSE high applied", JSON.stringify({ update: queued.update_id, config: done, model: actual.data.model }));
114
+ expect(output).toContain("SSE config_update");
115
+ const waitTerminal = async (id: string) => until(`update ${id}`, async () => { const cfg = await getConfig(); return cfg.last_update?.update_id === id && cfg.last_update.terminal && cfg; });
116
+ const omitted = await rpc("update_node_config", { node_id: nodeId, base_revision: done.config_revision, patch: { model: "fixture/model" } });
117
+ expect(omitted.ok).toBe(true);
118
+ const preserved = await waitTerminal(omitted.update_id);
119
+ expect(preserved.last_update.status).toBe("applied");
120
+ const storedPatch = JSON.parse(db.get<any>("SELECT patch_json FROM node_config_updates WHERE update_id = ?1", omitted.update_id).patch_json);
121
+ expect(storedPatch._anet_variant_ack_required).toBe(true);
122
+ const omittedWire = pullWire.find(w => w.includes(omitted.update_id));
123
+ expect(omittedWire).toBeDefined();
124
+ expect(omittedWire).not.toContain("_anet_variant_ack_required");
125
+ expect((await (await native(`/api/session/${sessionId}`)).json() as any).data.model.variant).toBe("high");
126
+ const invalid = await rpc("update_node_config", { node_id: nodeId, base_revision: preserved.config_revision, patch: { modelVariant: "nonexistent" } });
127
+ expect(invalid.ok).toBe(true);
128
+ const invalidResult = await waitTerminal(invalid.update_id);
129
+ expect(invalidResult.last_update.status).toBe("rejected");
130
+ expect((await (await native(`/api/session/${sessionId}`)).json() as any).data.model.variant).toBe("high");
131
+ let cleared = invalidResult;
132
+ for (let attempt = 0; attempt < 5; attempt++) {
133
+ const clear = await rpc("update_node_config", { node_id: nodeId, base_revision: cleared.config_revision, patch: { modelVariant: null } });
134
+ expect(clear.ok).toBe(true);
135
+ cleared = await waitTerminal(clear.update_id);
136
+ if (cleared.last_update.error !== "variant_concurrent") break;
137
+ await new Promise(r => setTimeout(r, 1000));
138
+ }
139
+ expect(cleared.last_update.status).toBe("applied");
140
+ await until("clear heartbeat readback", async () => { const cfg = await getConfig(); return cfg.modelVariant === null && cfg; });
141
+ const again = await rpc("update_node_config", { node_id: nodeId, base_revision: cleared.config_revision, patch: { modelVariant: "high" } });
142
+ expect(again.ok).toBe(true);
143
+ const restored = await waitTerminal(again.update_id);
144
+ expect(restored.last_update.status).toBe("applied");
145
+ console.log("omitted invalid clear restore", JSON.stringify({ omitted: preserved.last_update, invalid: invalidResult.last_update, clear: cleared.last_update, restore: restored.last_update }));
146
+ const prompt = await native(`/api/session/${sessionId}/prompt`, "POST", { text: "synthetic local test" });
147
+ expect(prompt.status).toBe(200);
148
+ await Promise.race([providerReached, new Promise<never>((_, reject) => setTimeout(() => reject(Error("synthetic provider not reached")), 10000))]);
149
+ const busy = await rpc("update_node_config", { node_id: nodeId, base_revision: restored.config_revision, patch: { modelVariant: "low" } });
150
+ expect(busy.ok).toBe(true);
151
+ const rejected = await until("real daemon busy ack", async () => { const cfg = await getConfig(); return cfg.last_update?.update_id === busy.update_id && cfg.last_update?.status === "rejected" && cfg; });
152
+ const after = await (await native(`/api/session/${sessionId}`)).json() as any;
153
+ expect(after.data.model).toMatchObject({ providerID: "fixture", id: "model", variant: "high" });
154
+ expect((await (await native("/api/info")).json() as any).pid).toBe(info.pid);
155
+ expect(daemon.exitCode).toBeNull();
156
+ console.log("real SSE busy rejected", JSON.stringify({ update: busy.update_id, config: rejected, model: after.data.model, nativePid: info.pid, daemonPid: daemon.pid }));
157
+ } catch (error) {
158
+ try { console.log("diagnostic hub config", JSON.stringify(await (await fetch(`${url}/api/nodes/${nodeId}/config?network_id=${network}`, { headers: { authorization: `Bearer ${user.token}` } })).json())); } catch {}
159
+ const { readOpenCodeV2CatalogEndpoint } = await import("../../agent-node/src/runtime/opencode-v2-catalog-endpoint.js");
160
+ const endpoint = readOpenCodeV2CatalogEndpoint(root);
161
+ if (endpoint) {
162
+ try {
163
+ const r = await fetch(`${endpoint.url}/api/model`, { headers: { authorization: endpoint.authorization, "x-opencode-directory": endpoint.directory } });
164
+ const body = await r.json() as any;
165
+ console.log("diagnostic catalog", JSON.stringify({ status: r.status, location: body.location, fixture: body.data?.filter((m: any) => m.providerID === "fixture").map((m: any) => ({ id: m.id, variants: m.variants?.map((v: any) => v.id) })) }));
166
+ } catch (diagnostic) { console.log("diagnostic catalog failed", String(diagnostic)); }
167
+ }
168
+ console.log("daemon tail", output.slice(-12000).replace(/(?:ntok|utok)_[A-Za-z0-9_-]+/g, "[synthetic-token]"));
169
+ throw error;
170
+ } finally {
171
+ const exited = daemon.exitCode !== null || daemon.signalCode !== null ? Promise.resolve() : new Promise<void>(resolve => daemon.once("exit", () => resolve()));
172
+ daemon.kill("SIGTERM");
173
+ await Promise.race([exited, new Promise<never>((_, reject) => setTimeout(() => reject(Error("owned daemon did not exit")), 10000))]);
174
+ if (nativePid) {
175
+ const pid = nativePid;
176
+ const inactive = () => { try { return readFileSync(`/proc/${pid}/stat`, "utf8").split(") ")[1]?.startsWith("Z ") === true; } catch { return true; } };
177
+ const deadline = Date.now() + 10000;
178
+ while (!inactive() && Date.now() < deadline) await new Promise(r => setTimeout(r, 100));
179
+ expect(inactive()).toBe(true);
180
+ console.log("owned lifecycle end", JSON.stringify({ daemonPid: daemon.pid, nativePid: pid, daemonExitCode: daemon.exitCode, daemonSignal: daemon.signalCode, nativeInactive: inactive() }));
181
+ }
182
+ releaseAck(); proxy.stop(true); provider.stop(true); hub.stop(true);
183
+ }
184
+ }, 120000);
@@ -20,6 +20,7 @@ let hub: any = null;
20
20
  let USER = "";
21
21
  let NET = "";
22
22
  let ntok = "";
23
+ let utok = "";
23
24
  let ALIAS = "";
24
25
  const PW = "BuildCommitPassw0rd!x";
25
26
  const COMMIT = "0123456789abcdef0123456789abcdef01234567"; // 40 hex,固定值便于断言
@@ -50,6 +51,7 @@ beforeAll(async () => {
50
51
  USER = `bc_user_${STAMP}`;
51
52
  ALIAS = `bc-node-${STAMP}`;
52
53
  const reg = register(USER, PW);
54
+ utok = reg.token!;
53
55
  NET = reg.network_id!;
54
56
  const minted = createNetworkTokenForNode(reg.user!.user_id, NET, ALIAS, `node_bc_${STAMP}`);
55
57
  expect(minted.ok).toBe(true);
@@ -126,3 +128,91 @@ describe("#3144 opencode_catalog_seen_at 的三段链路(真 HTTP)", () => {
126
128
  expect(row.opencode_catalog_seen_at).not.toBe("");
127
129
  });
128
130
  });
131
+
132
+ test("variant capability survives authenticated report_status schema and storage", async () => {
133
+ expect((await report({ config_snapshot: { opencode_variant_config_capable: true, model_effective: "fixture/model", modelVariant: "high" } })).ok).toBe(true);
134
+ const row = db.get<{ config_snapshot: string }>("SELECT config_snapshot FROM nodes WHERE node_id = ?1", `node_bc_${STAMP}`);
135
+ expect(JSON.parse(row!.config_snapshot).opencode_variant_config_capable).toBe(true);
136
+ expect(JSON.parse(row!.config_snapshot)).toMatchObject({ model_effective: "fixture/model", modelVariant: "high" });
137
+ const configResponse = await fetch(`${BASE}/api/nodes/node_bc_${STAMP}/config?network_id=${NET}`, { headers: auth(ntok) });
138
+ expect(configResponse.status).toBe(200);
139
+ expect(await configResponse.json()).toMatchObject({ model_effective: "fixture/model", modelVariant: "high", opencode_variant_config_capable: true });
140
+ expect((await report({ config_snapshot: { opencode_variant_config_capable: "true" } })).ok).toBe(true);
141
+ const bad = db.get<{ config_snapshot: string }>("SELECT config_snapshot FROM nodes WHERE node_id = ?1", `node_bc_${STAMP}`);
142
+ expect(JSON.parse(bad!.config_snapshot).opencode_variant_config_capable).toBeUndefined();
143
+ });
144
+
145
+ test("variant-capable model update persists private ack policy across lost capability", async () => {
146
+ const nodeId = `node_bc_${STAMP}`;
147
+ expect((await report({ config_snapshot: { model: "fixture/model", opencode_variant_config_capable: true, flags: { opencodeGeneration: "v2", opencodeMode: "copresence" } } })).ok).toBe(true);
148
+ db.run("UPDATE nodes SET runtime = ?1 WHERE node_id = ?2", ["opencode", nodeId]);
149
+ const queued = await rpc("update_node_config", { node_id: nodeId, base_revision: 0, patch: { model: "fixture/model" } }, utok);
150
+ expect(queued.ok).toBe(true);
151
+ expect(JSON.parse(db.get<any>("SELECT patch_json FROM node_config_updates WHERE update_id = ?1", queued.update_id).patch_json)._anet_variant_ack_required).toBe(true);
152
+ const pulled = await rpc("get_config_update", {});
153
+ expect(pulled.update.patch._anet_variant_ack_required).toBeUndefined();
154
+ expect((await report({ config_snapshot: { model: "fixture/model", flags: {} } })).ok).toBe(true);
155
+ expect(db.get<any>("SELECT status FROM node_config_updates WHERE update_id = ?1", queued.update_id).status).toBe("pending");
156
+ expect((await rpc("ack_config_update", { update_id: queued.update_id, status: "rejected", error: "test_complete" })).ok).toBe(true);
157
+ });
158
+
159
+ test("TEST-ONLY real Hub HTTP and owned runtime variant via explicit node dispatch", async () => {
160
+ const { openVettedOpenCodeCopresence } = await import("../../agent-node/src/runtime/opencode-copresence/runtime.js");
161
+ const { OPENCODE_V2_BACKEND } = await import("../../agent-node/src/runtime/opencode-backend.js");
162
+ const { applyVariantConfig } = await import("../../agent-node/src/runtime/opencode-copresence/variant-config-apply.js");
163
+ const { readOpenCodeV2CatalogEndpoint } = await import("../../agent-node/src/runtime/opencode-v2-catalog-endpoint.js");
164
+ const root = mkdtempSync(join(tmpdir(), "anet-hub-variant-"));
165
+ const config = { model: "fixture/model", enabled_providers: ["fixture"], provider: { fixture: {
166
+ name: "fixture", npm: "@ai-sdk/openai-compatible", options: { baseURL: "http://127.0.0.1:1/v1", apiKey: "synthetic" },
167
+ models: { model: { name: "model", limit: { context: 128000, output: 16000 }, variants: { high: {}, low: {} } } },
168
+ } } };
169
+ const noTmux = () => { throw Error("unexpected tmux"); };
170
+ const session = await openVettedOpenCodeCopresence({ backend: OPENCODE_V2_BACKEND, binary: "/tool/opencode", cwd: root, workDir: root,
171
+ env: { PATH: process.env.PATH, HOME: root, XDG_CONFIG_HOME: join(root, "config"), XDG_DATA_HOME: join(root, "data"), XDG_CACHE_HOME: join(root, "cache"), XDG_STATE_HOME: join(root, "state"), ANET_VARIANT_TEST_ONLY: "1", OPENCODE_CONFIG_CONTENT: JSON.stringify(config) },
172
+ model: "fixture/model", startupTimeoutMs: 20000, tmuxRunner: noTmux, tmuxRespawn: noTmux });
173
+ try {
174
+ expect(session.variantConfigCapable).toBe(true);
175
+ const endpoint = readOpenCodeV2CatalogEndpoint(root)!;
176
+ let ready = false;
177
+ for (let i = 0; i < 60 && !ready; i++) {
178
+ const r = await fetch(`${endpoint.url}/api/model`, { headers: { authorization: endpoint.authorization, "x-opencode-directory": endpoint.directory } });
179
+ const body = await r.json() as any;
180
+ ready = body.location?.directory === root && body.data?.some((row: any) => row.providerID === "fixture" && row.id === "model" && row.variants?.some((v: any) => v.id === "high"));
181
+ }
182
+ expect(ready).toBe(true);
183
+ expect(await session.variantConfigReadback!()).toMatchObject({ providerID: "fixture", id: "model" });
184
+ expect((await report({ config_snapshot: { opencode_variant_config_capable: true, model: "fixture/model" } })).ok).toBe(true);
185
+ const nodeId = `node_bc_${STAMP}`;
186
+ const queued = await rpc("update_node_config", { node_id: nodeId, base_revision: 0, patch: { modelVariant: "high" } }, utok);
187
+ expect(queued.ok).toBe(true);
188
+ const pulled = await rpc("get_config_update", {});
189
+ expect(pulled.update).toMatchObject({ update_id: queued.update_id, patch: { modelVariant: "high" }, apply_mode: "hot" });
190
+ const applied = await applyVariantConfig(session, pulled.update.patch);
191
+ expect(applied).toMatchObject({ status: "applied", model: { providerID: "fixture", id: "model", variant: "high" } });
192
+ // A matching heartbeat must not finalize the pending write.
193
+ const observed = await session.variantConfigReadback!();
194
+ expect(observed).toMatchObject({ providerID: "fixture", id: "model", variant: "high" });
195
+ expect((await report({ config_snapshot: { opencode_variant_config_capable: true, model_effective: `${observed!.providerID}/${observed!.id}`, modelVariant: observed!.variant } })).ok).toBe(true);
196
+ expect(db.get<any>("SELECT status FROM node_config_updates WHERE update_id = ?1", queued.update_id)?.status).toBe("pending");
197
+ expect((await rpc("ack_config_update", { update_id: queued.update_id, status: "applied", new_revision: 1 })).ok).toBe(true);
198
+ const read = await fetch(`${BASE}/api/nodes/${nodeId}/config?network_id=${NET}`, { headers: auth(utok) });
199
+ expect(await read.json()).toMatchObject({ model_effective: "fixture/model", modelVariant: "high", last_update: { status: "applied" } });
200
+ const invalid = await rpc("update_node_config", { node_id: nodeId, base_revision: 1, patch: { modelVariant: "not-listed" } }, utok);
201
+ expect(invalid.ok).toBe(true);
202
+ const invalidPull = await rpc("get_config_update", {});
203
+ expect(await applyVariantConfig(session, invalidPull.update.patch)).toEqual({ status: "rejected", reason: "catalog" });
204
+ expect(await session.selectedSessionModel!(session.sessionId)).toMatchObject({ variant: "high" });
205
+ expect((await rpc("ack_config_update", { update_id: invalid.update_id, status: "rejected", error: "variant_catalog" })).ok).toBe(true);
206
+ const clear = await rpc("update_node_config", { node_id: nodeId, base_revision: 1, patch: { modelVariant: null } }, utok);
207
+ expect(clear.ok).toBe(true);
208
+ const clearPull = await rpc("get_config_update", {});
209
+ expect(clearPull.update.patch).toMatchObject({ modelVariant: null });
210
+ expect(await applyVariantConfig(session, clearPull.update.patch)).toMatchObject({ status: "applied", model: { providerID: "fixture", id: "model", variant: "default" } });
211
+ expect((await rpc("ack_config_update", { update_id: clear.update_id, status: "applied", new_revision: 2 })).ok).toBe(true);
212
+ const actual = await session.variantConfigReadback!();
213
+ expect(actual).toMatchObject({ providerID: "fixture", id: "model", variant: "default" });
214
+ expect((await report({ config_snapshot: { opencode_variant_config_capable: true, model_effective: `${actual!.providerID}/${actual!.id}`, modelVariant: actual!.variant === "default" ? null : actual!.variant } })).ok).toBe(true);
215
+ const clearRead = await fetch(`${BASE}/api/nodes/${nodeId}/config?network_id=${NET}`, { headers: auth(utok) });
216
+ expect(await clearRead.json()).toMatchObject({ model_effective: "fixture/model", modelVariant: null, last_update: { status: "applied" } });
217
+ } finally { await session.close(); }
218
+ }, 40000);
@@ -47,6 +47,15 @@ beforeEach(() => {
47
47
  db.run("DELETE FROM nodes");
48
48
  });
49
49
 
50
+ test("variant updates cannot be finalized by a configured-model heartbeat", () => {
51
+ for (const variant of [null, "high"]) {
52
+ const node = insertNode({ alias: `variant-${variant}`, network_id: "netA" });
53
+ const update = insertUpdate({ node_id: node, network_id: "netA", patch: { model: "p/m", modelVariant: variant, flags: {} } });
54
+ expect(finalizePendingMatchingUpdates(node, { model: "p/m", flags: {} }).finalizedCount).toBe(0);
55
+ expect(db.get<{ status: string }>("SELECT status FROM node_config_updates WHERE update_id = ?1", update)?.status).toBe("pending");
56
+ }
57
+ });
58
+
50
59
  describe("SEC-1 — resolveTargetNode-equivalent SELECT respects network_id", () => {
51
60
  // This is the exact query update_node_config / restart_node run
52
61
  // to fetch the target node + check network match. Pinning the SQL
@@ -740,6 +749,34 @@ describe("finalizePendingMatchingUpdates — #260 P5 channels content-match", ()
740
749
  return id;
741
750
  }
742
751
 
752
+ test("variant-capable hot model-only update cannot finish from matching old heartbeat", () => {
753
+ const nid = insertNode({ alias: "n-variant-model-race", network_id: "netA" });
754
+ const uid = insertPendingUpdate({ node_id: nid, network_id: "netA", patch: { model: "fixture/model" }, apply_mode: "hot" });
755
+ const snapshot = { model: "fixture/model", modelVariant: "high", opencode_variant_config_capable: true, flags: {} };
756
+ expect(finalizePendingMatchingUpdates(nid, snapshot).finalizedCount).toBe(0);
757
+ expect(db.get<any>("SELECT status FROM node_config_updates WHERE update_id = ?1", uid).status).toBe("pending");
758
+ });
759
+
760
+ test("ordinary hot model update without variant capability retains content-match", () => {
761
+ const nid = insertNode({ alias: "n-ordinary-model", network_id: "netA" });
762
+ const uid = insertPendingUpdate({ node_id: nid, network_id: "netA", patch: { model: "fixture/model" }, apply_mode: "hot" });
763
+ expect(finalizePendingMatchingUpdates(nid, { model: "fixture/model", flags: {} }).finalizedIds).toContain(uid);
764
+ });
765
+
766
+ test("variant heartbeat match cannot finalize before explicit ack", () => {
767
+ const nid = insertNode({ alias: "n-variant-explicit-ack", network_id: "netA" });
768
+ const uid = insertPendingUpdate({ node_id: nid, network_id: "netA", patch: { modelVariant: "high" }, apply_mode: "hot" });
769
+ expect(finalizePendingMatchingUpdates(nid, { model: "fixture/model", modelVariant: "high", opencode_variant_config_capable: true }).finalizedCount).toBe(0);
770
+ expect(db.get<any>("SELECT status FROM node_config_updates WHERE update_id = ?1", uid).status).toBe("pending");
771
+ });
772
+
773
+ test("ack-required model operation stays pending when later capability readback is missing", () => {
774
+ const nid = insertNode({ alias: "n-variant-capability-lost", network_id: "netA" });
775
+ const uid = insertPendingUpdate({ node_id: nid, network_id: "netA", patch: { model: "fixture/model", _anet_variant_ack_required: true }, apply_mode: "hot" });
776
+ expect(finalizePendingMatchingUpdates(nid, { model: "fixture/model", flags: {} }).finalizedCount).toBe(0);
777
+ expect(db.get<any>("SELECT status FROM node_config_updates WHERE update_id = ?1", uid).status).toBe("pending");
778
+ });
779
+
743
780
  test("channels-only patch: snapshot BEFORE apply (first boot) must NOT finalize", () => {
744
781
  const nid = insertNode({ alias: "n-chan-1", network_id: "netA" });
745
782
  const uid = insertPendingUpdate({
@@ -160,6 +160,12 @@ export function isAllowedToChangeFlag(
160
160
  */
161
161
  const OPENCODE_RUNTIME_LABELS = new Set<string>(["opencode-sdk", "opencode-cli", "opencode"]);
162
162
 
163
+ /** Reported runtime family + explicit mode only; never local ownership proof. */
164
+ export function isOpenCodeV2CopresenceRuntime(runtime: string | null | undefined,
165
+ generation: "v1" | "v2" | null, mode: string | null): boolean {
166
+ return !!runtime && OPENCODE_RUNTIME_LABELS.has(runtime) && generation === "v2" && mode === "copresence";
167
+ }
168
+
163
169
  /**
164
170
  * Read the OpenCode knobs the hub persists in `nodes.config_snapshot`.
165
171
  * Both are reported by agent-node (see buildConfigSnapshot in
@@ -220,9 +226,7 @@ export function isHotModelSwitchSupported(
220
226
  if (model === undefined) return false;
221
227
  if (Object.keys(flags).length !== 0) return false;
222
228
  if (channels !== undefined) return false;
223
- if (!runtime || !OPENCODE_RUNTIME_LABELS.has(runtime)) return false;
224
- if (opencodeGeneration !== "v2") return false;
225
- return opencodeMode === "copresence";
229
+ return isOpenCodeV2CopresenceRuntime(runtime, opencodeGeneration, opencodeMode);
226
230
  }
227
231
 
228
232
  /**
@@ -0,0 +1,14 @@
1
+ export const PROJECT_CREATE_CAPABILITY = "project-new-session-v1-opencode-2.0.22";
2
+ export const PROJECT_CREATE_ROOT = "/api/node-session-control/source/project-create";
3
+ export const SESSION_ATTACH_CAPABILITY = "existing-session-attach-v1-opencode-2.0.22";
4
+ export type SessionAttachSelection = { selection_scope: string; snapshot_id: string; session_id: string; child_name: string; intent_id: string };
5
+ export type ProjectOperation = "project_new_session" | "attach_existing_session";
6
+ export type ProjectCreateSelection = { selection_scope: string; snapshot_id: string; project_id: string; child_name: string; intent_id: string };
7
+ export type ProjectCreateTask = ProjectCreateSelection & { request_id: string; network_id: string; source_node_id: string;
8
+ daemon_node_id: string; accepted_at: number; expires_at: number; operation_kind?: ProjectOperation; selected_session_id?: string | null };
9
+ export type ProjectCreateDelivery = ProjectCreateTask & { session_id: string; child_node_id: string; child_token: string; credential_expires_at: number };
10
+ export type ProjectCreateStatus = "create_pending" | "create_claimed" | "delivery_pending" | "delivery_claimed" | "registration_confirmed" | "unknown_rotation_required";
11
+ export type ProjectCreateReceipt = { ok: true; request_id: string; network_id: string; daemon_node_id: string; intent_id: string; child_name: string;
12
+ status: ProjectCreateStatus; accepted_at: number; expires_at: number; operation_kind: ProjectOperation; session_creation: "confirmed" | "not_started" | "unknown" | "not_performed";
13
+ child_node_id?: string; registration_is_health: false; native_acceptance: "not_verified" };
14
+ export const isProjectCreateId = (v: unknown): v is string => typeof v === "string" && /^prjc_[a-f0-9-]{36}$/.test(v);
@@ -0,0 +1,16 @@
1
+ import { isSourceExecutionTask, type SourceExecutionTask } from "./session-source-execution";
2
+ export const SOURCE_DELIVERY_CAPABILITY = "source-node-delivery-v1-opencode-2.0.22";
3
+ export type SourceNodeDelivery = {
4
+ delivery_id: string; execution: SourceExecutionTask; session_id: string;
5
+ child_node_id: string; child_name: string; child_token: string; expires_at: number;
6
+ };
7
+ export function isSourceNodeDelivery(v: any): v is SourceNodeDelivery {
8
+ return !!v && typeof v === "object" && Object.keys(v).length === 7
9
+ && typeof v.delivery_id === "string" && /^srcd_[a-f0-9-]{36}$/.test(v.delivery_id)
10
+ && isSourceExecutionTask(v.execution) && typeof v.session_id === "string" && /^ses_[A-Za-z0-9]+$/.test(v.session_id)
11
+ && typeof v.child_node_id === "string" && v.child_node_id === `node_${v.delivery_id}`
12
+ && typeof v.child_name === "string" && v.child_name.length > 0 && v.child_name.length <= 256
13
+ && typeof v.child_token === "string" && /^ntok_[A-Za-z0-9_-]+$/.test(v.child_token)
14
+ && Number.isSafeInteger(v.expires_at) && v.expires_at > 0
15
+ && (v.execution.evidence.request.mode === "attach_existing" ? v.session_id === v.execution.evidence.request.session_id : v.session_id !== v.execution.evidence.request.session_id);
16
+ }
@@ -0,0 +1,54 @@
1
+ export const SOURCE_DIRECTORY_CAPABILITY = "source-directory-read-v1-opencode-2.0.22";
2
+ export type SourceDirectorySelection = { network_id: string; source_node_id: string; daemon_node_id: string };
3
+ export type SourceDirectoryRequest = SourceDirectorySelection & ({ server_id?: never; selection_scope?: never }
4
+ | { server_id: string; selection_scope: string });
5
+ export type SourceDirectoryReceipt = SourceDirectoryTask & { ok: true; status: "pending" | "claimed" | "ready" | "failed";
6
+ snapshot?: SourceDirectorySnapshot; error?: "directory_read_failed" };
7
+ export type SourceDirectoryTask = { request_id: string; network_id: string; source_node_id: string; daemon_node_id: string;
8
+ server_id?: string; expires_at: number };
9
+ export type SourceDirectorySnapshot = { snapshot_id: string; expires_at: number; selection_expires_at?: number; lease_kind: "process_local";
10
+ servers: { server_id: string; title: string }[];
11
+ projects: { project_id: string; server_id: string; title: string }[];
12
+ sessions: { session_id: string; project_id: string; title: string; activity: "running" | "unknown"; binding: "unknown"; attach_authorized: false }[];
13
+ completeness: "authorized_scope_only" };
14
+ const id = (v: unknown, prefix: string) => typeof v === "string" && new RegExp(`^${prefix}_[a-f0-9-]{36}$`).test(v);
15
+ export const isDirectoryRequestId = (v: unknown) => id(v, "srcdir");
16
+ export const isDirectoryServerId = (v: unknown) => id(v, "osrv");
17
+ export function directoryTitle(v: unknown, fallback: "Project" | "Session" | "Server"): string {
18
+ if (typeof v !== "string" || !v.trim() || v.length > 120
19
+ || /[\x00-\x1f\x7f/\\:]|(?:ntok_|atok_|sk-|Bearer|password|token|gh[pousr]_|github_pat_|xox[baprs]-|AKIA|AIza|ya29\.|glpat-)|\b[A-Za-z0-9_=-]{28,}\b/i.test(v)) return fallback;
20
+ return v;
21
+ }
22
+ // Exact key-set comparison as arrays, never a joined string: a key name that
23
+ // contained the separator could otherwise hide an extra key (keyset-join gate).
24
+ const keysAreExactly = (v: unknown, expected: readonly string[]): boolean => {
25
+ const keys = Object.keys(v as Record<string, unknown>).sort();
26
+ return keys.length === expected.length && keys.every((k, i) => k === expected[i]);
27
+ };
28
+ const SNAPSHOT_KEYS = ["completeness", "expires_at", "lease_kind", "projects", "servers", "sessions", "snapshot_id"] as const;
29
+ const SNAPSHOT_KEYS_WITH_SELECTION = ["completeness", "expires_at", "lease_kind", "projects", "selection_expires_at", "servers", "sessions", "snapshot_id"] as const;
30
+ export function isSourceDirectorySnapshot(v: any, expires: number): v is SourceDirectorySnapshot {
31
+ if (!v || !(keysAreExactly(v, SNAPSHOT_KEYS) || keysAreExactly(v, SNAPSHOT_KEYS_WITH_SELECTION))
32
+ || !id(v.snapshot_id, "snap") || v.expires_at !== expires || v.lease_kind !== "process_local" || v.completeness !== "authorized_scope_only"
33
+ || (v.selection_expires_at !== undefined && v.selection_expires_at !== expires + 600000)
34
+ || !Array.isArray(v.servers) || v.servers.length > 16 || !Array.isArray(v.projects) || v.projects.length > 16
35
+ || !Array.isArray(v.sessions) || v.sessions.length > 100) return false;
36
+ const servers = new Set<string>(), projects = new Set<string>(), sessions = new Set<string>();
37
+ for (const s of v.servers) {
38
+ if (!s || !keysAreExactly(s, ["server_id", "title"]) || !isDirectoryServerId(s.server_id) || servers.has(s.server_id)
39
+ || directoryTitle(s.title, "Server") !== s.title) return false;
40
+ servers.add(s.server_id);
41
+ }
42
+ for (const p of v.projects) {
43
+ if (!p || !keysAreExactly(p, ["project_id", "server_id", "title"]) || !id(p.project_id, "oprj") || projects.has(p.project_id)
44
+ || !servers.has(p.server_id) || directoryTitle(p.title, "Project") !== p.title) return false;
45
+ projects.add(p.project_id);
46
+ }
47
+ for (const s of v.sessions) {
48
+ if (!s || !keysAreExactly(s, ["activity", "attach_authorized", "binding", "project_id", "session_id", "title"]) || !id(s.session_id, "oses") || sessions.has(s.session_id)
49
+ || !projects.has(s.project_id) || directoryTitle(s.title, "Session") !== s.title || !["running", "unknown"].includes(s.activity)
50
+ || s.binding !== "unknown" || s.attach_authorized !== false) return false;
51
+ sessions.add(s.session_id);
52
+ }
53
+ return true;
54
+ }
@@ -0,0 +1,72 @@
1
+ // Read-only wire contract. No URL/auth/path input and no create-node directive.
2
+ export type SourceReadChallenge = {
3
+ request_id: string; challenge: string; network_id: string; daemon_node_id: string;
4
+ source_node_id: string; alias: string; session_id: string; expires_at: number;
5
+ user_id: string; requester_token_id: string; mode: "attach_existing" | "fork_independent";
6
+ };
7
+ export type SourceReadEvidence = {
8
+ request: SourceReadChallenge;
9
+ kind: "process_local_lease"; lease_id: string; api_version: "2.0.22" | "2.0.22-anet-test.29040e2";
10
+ canonical_directory: string; directory: { dev: string; ino: string; uid: number };
11
+ // OS observation, not caller strings or a binary-version attestation.
12
+ server: { pid: number; start_ticks: string; listen_inode: string };
13
+ };
14
+ const object = (v: unknown): v is Record<string, any> => !!v && typeof v === "object" && !Array.isArray(v);
15
+ const keys = (v: Record<string, any>, names: string[]) => Object.keys(v).length === names.length && names.every(k => k in v);
16
+ const id = (v: unknown) => typeof v === "string" && /^[A-Za-z0-9_-]{1,200}$/.test(v);
17
+ const decimal = (v: unknown) => typeof v === "string" && /^\d{1,30}$/.test(v);
18
+ export function isSourceReadChallenge(v: unknown): v is SourceReadChallenge {
19
+ return object(v) && keys(v, ["request_id", "challenge", "network_id", "daemon_node_id", "source_node_id", "alias", "session_id", "expires_at", "user_id", "requester_token_id", "mode"])
20
+ && typeof v.request_id === "string" && /^srcq_[A-Za-z0-9_-]{1,100}$/.test(v.request_id)
21
+ && typeof v.challenge === "string" && /^[A-Za-z0-9_-]{43}$/.test(v.challenge)
22
+ && [v.network_id, v.daemon_node_id, v.source_node_id, v.user_id, v.requester_token_id].every(id)
23
+ && (v.mode === "attach_existing" || v.mode === "fork_independent")
24
+ && typeof v.alias === "string" && v.alias.length > 0 && v.alias.length <= 256 && !/[\x00-\x1f\x7f/\\]/.test(v.alias)
25
+ && typeof v.session_id === "string" && /^ses_[A-Za-z0-9]{1,190}$/.test(v.session_id)
26
+ && Number.isSafeInteger(v.expires_at) && v.expires_at > 0;
27
+ }
28
+ export function isSourceReadEvidence(v: unknown): v is SourceReadEvidence {
29
+ return object(v) && keys(v, ["request", "kind", "lease_id", "api_version", "canonical_directory", "directory", "server"])
30
+ && isSourceReadChallenge(v.request) && v.kind === "process_local_lease" && ["2.0.22", "2.0.22-anet-test.29040e2"].includes(v.api_version)
31
+ && typeof v.lease_id === "string" && /^srcl_[A-Za-z0-9_-]{36}$/.test(v.lease_id)
32
+ && typeof v.canonical_directory === "string" && v.canonical_directory.startsWith("/")
33
+ && v.canonical_directory.length <= 4096 && !/[\x00-\x1f\x7f]/.test(v.canonical_directory)
34
+ && object(v.directory) && keys(v.directory, ["dev", "ino", "uid"]) && decimal(v.directory.dev) && decimal(v.directory.ino)
35
+ && Number.isSafeInteger(v.directory.uid) && v.directory.uid >= 0
36
+ && object(v.server) && keys(v.server, ["pid", "start_ticks", "listen_inode"])
37
+ && Number.isSafeInteger(v.server.pid) && v.server.pid > 1 && decimal(v.server.start_ticks) && decimal(v.server.listen_inode);
38
+ }
39
+ export function sameSourceChallenge(a: SourceReadChallenge, b: SourceReadChallenge): boolean {
40
+ return (Object.keys(a) as (keyof SourceReadChallenge)[]).every(k => a[k] === b[k]);
41
+ }
42
+
43
+ export type SourceLeaseRecheck = {
44
+ request_id: string; challenge: string; evidence: SourceReadEvidence;
45
+ intent_id: string; child_name: string; expires_at: number;
46
+ };
47
+ export type SourceLeaseConfirmation = {
48
+ request: SourceLeaseRecheck; outcome: "lease_current";
49
+ execution: "daemon_recheck_in_execution_context_required";
50
+ };
51
+ export function isSourceLeaseRecheck(v: unknown): v is SourceLeaseRecheck {
52
+ return object(v) && keys(v, ["request_id", "challenge", "evidence", "intent_id", "child_name", "expires_at"])
53
+ && typeof v.request_id === "string" && /^srcr_[A-Za-z0-9_-]{36}$/.test(v.request_id)
54
+ && typeof v.challenge === "string" && /^[A-Za-z0-9_-]{43}$/.test(v.challenge)
55
+ && isSourceReadEvidence(v.evidence) && id(v.intent_id)
56
+ && typeof v.child_name === "string" && v.child_name.length > 0 && v.child_name.length <= 256
57
+ && Number.isSafeInteger(v.expires_at) && v.expires_at > 0 && v.expires_at <= v.evidence.request.expires_at;
58
+ }
59
+ export function sameSourceEvidence(a: SourceReadEvidence, b: SourceReadEvidence): boolean {
60
+ return sameSourceChallenge(a.request, b.request) && a.kind === b.kind && a.lease_id === b.lease_id && a.api_version === b.api_version
61
+ && a.canonical_directory === b.canonical_directory && a.directory.dev === b.directory.dev && a.directory.ino === b.directory.ino
62
+ && a.directory.uid === b.directory.uid && a.server.pid === b.server.pid && a.server.start_ticks === b.server.start_ticks
63
+ && a.server.listen_inode === b.server.listen_inode;
64
+ }
65
+ export function sameSourceRecheck(a: SourceLeaseRecheck, b: SourceLeaseRecheck): boolean {
66
+ return a.request_id === b.request_id && a.challenge === b.challenge && a.intent_id === b.intent_id
67
+ && a.child_name === b.child_name && a.expires_at === b.expires_at && sameSourceEvidence(a.evidence, b.evidence);
68
+ }
69
+ export function isSourceLeaseConfirmation(v: unknown): v is SourceLeaseConfirmation {
70
+ return object(v) && keys(v, ["request", "outcome", "execution"]) && isSourceLeaseRecheck(v.request)
71
+ && v.outcome === "lease_current" && v.execution === "daemon_recheck_in_execution_context_required";
72
+ }