@sleep2agi/commhub-server 0.9.0-preview.275 → 0.9.0-preview.277
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/build-info.json +2 -2
- package/package.json +1 -1
- package/src/anet-variant-real-daemon-http.test.ts +184 -0
- package/src/build-commit-report-http.test.ts +90 -0
- package/src/config-apply-sec1.test.ts +37 -0
- package/src/config-apply-validate.ts +7 -3
- package/src/contracts/session-project-create.ts +14 -0
- package/src/contracts/session-source-delivery.ts +16 -0
- package/src/contracts/session-source-directory.ts +54 -0
- package/src/contracts/session-source-evidence.ts +72 -0
- package/src/contracts/session-source-execution.ts +24 -0
- package/src/contracts/session-source-transport.ts +18 -0
- package/src/create-node-tool-schema.test.ts +10 -0
- package/src/db.ts +35 -0
- package/src/node-permissions.ts +1 -1
- package/src/node-session-control-http.test.ts +90 -2
- package/src/node-session-control.ts +89 -31
- package/src/opencode-v2-catalog.test.ts +14 -0
- package/src/opencode-v2-catalog.ts +1 -0
- package/src/package-self-contained.test.ts +32 -0
- package/src/report-status-host-schema.test.ts +37 -0
- package/src/rules-file-transport.test.ts +9 -0
- package/src/server.ts +33 -3
- package/src/session-fork-store.test.ts +43 -0
- package/src/session-fork-store.ts +51 -0
- package/src/session-project-attach-migration.test.ts +22 -0
- package/src/session-project-attach-native.test.ts +121 -0
- package/src/session-project-create-http.test.ts +407 -0
- package/src/session-project-create-native.test.ts +290 -0
- package/src/session-project-create.ts +159 -0
- package/src/session-source-admission-store.ts +58 -0
- package/src/session-source-create.test.ts +155 -0
- package/src/session-source-create.ts +97 -0
- package/src/session-source-delivery.ts +109 -0
- package/src/session-source-directory-http.test.ts +192 -0
- package/src/session-source-evidence.test.ts +898 -0
- package/src/session-source-evidence.ts +191 -0
- package/src/session-source-execution.ts +87 -0
- package/src/session-source-grant.test.ts +117 -0
- package/src/session-source-grant.ts +78 -0
- package/src/session-source-issuer.test.ts +247 -0
- package/src/session-source-issuer.ts +158 -0
- package/src/session-source-transport.ts +375 -0
- package/src/tool-audience-http.test.ts +18 -0
- package/src/tool-audience.ts +1 -1
- package/src/tools.ts +154 -51
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
// Opt-in Docker-only acceptance against the SHA-verified real TEST-ONLY ELF.
|
|
2
|
+
// No native protocol mock/fake executable or external provider/npm. Fork fixture
|
|
3
|
+
// may use a deterministic loopback OpenAI-compatible provider via REAL prompt.
|
|
4
|
+
import { test, expect } from "bun:test";
|
|
5
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, symlinkSync, existsSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { randomUUID } from "node:crypto";
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import { SOURCE_DIRECTORY_CAPABILITY as DIR } from "../../contracts/session-source-directory";
|
|
10
|
+
import { PROJECT_CREATE_ROOT as P, PROJECT_CREATE_CAPABILITY as CAP } from "../../contracts/session-project-create";
|
|
11
|
+
import { createSessionSourceTransportWorker } from "../../agent-node/src/runtime/session-source-transport";
|
|
12
|
+
import { createSessionControlPin } from "../../agent-node/src/runtime/session-control-bridge";
|
|
13
|
+
import { SOURCE_FORK_ROOT as F, SOURCE_FORK_CAPABILITY as FCAP } from "../../contracts/session-source-transport";
|
|
14
|
+
import { SOURCE_DELIVERY_CAPABILITY } from "../../contracts/session-source-delivery";
|
|
15
|
+
|
|
16
|
+
const forkMode = process.env.TEST4150_NATIVE_FORK === "1";
|
|
17
|
+
test.skipIf(!process.env.TEST4150_NATIVE_BINARY)(forkMode ? "real patched ELF managed live-source fork, attach refusal and negative-only cleanup" : "real patched 2.0.22 ELF: directory -> project-new -> actual CLI exact child -> native SSE and real Hub registration", async () => {
|
|
18
|
+
const root = mkdtempSync("/work/native-project-"), home = join(root, "home"), project = join(root, "project"), daemonDir = join(root, "daemon");
|
|
19
|
+
for (const d of [home, project, daemonDir, join(home, ".anet"), join(daemonDir, ".anet"), join(project, ".anet"), join(project, ".anet", "nodes")]) mkdirSync(d, { mode: 0o700 });
|
|
20
|
+
process.env.COMMHUB_DB = join(root, "hub.db"); process.env.COMMHUB_SOURCE_DIRECTORY_PREVIEW = "1"; process.env.COMMHUB_PROJECT_NEW_SESSION_PREVIEW = "1";
|
|
21
|
+
if (forkMode) process.env.COMMHUB_SOURCE_FORK_PREVIEW = "1";
|
|
22
|
+
const binary = process.env.TEST4150_NATIVE_BINARY!, identity = process.env.TEST4150_NATIVE_IDENTITY!;
|
|
23
|
+
let providerCalls = 0, nativePosts: string[] = [], newBodies: any[] = [], sse = 0, sseBytes = 0;
|
|
24
|
+
const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) {
|
|
25
|
+
providerCalls++;
|
|
26
|
+
if (!forkMode || providerCalls > 4) return new Response("local_provider_refused", { status: 503 });
|
|
27
|
+
const knownRoute = new URL(request.url).pathname === "/v1/chat/completions";
|
|
28
|
+
console.log("LOCAL_PROVIDER_REQUEST", JSON.stringify({ knownRoute, methodPost: request.method === "POST", call: providerCalls }));
|
|
29
|
+
if (!knownRoute || request.method !== "POST") return new Response("local_provider_route_refused", { status: 404 });
|
|
30
|
+
const body = await request.json() as any;
|
|
31
|
+
const base = { id: "chatcmpl-offline-fixture", created: 1, model: "test-model" };
|
|
32
|
+
const usage = { prompt_tokens: 8, completion_tokens: 4, total_tokens: 12 };
|
|
33
|
+
if (!body.stream) return Response.json({ ...base, object: "chat.completion", choices: [{ index: 0,
|
|
34
|
+
message: { role: "assistant", content: "OFFLINE_FIXTURE_COMPLETE" }, finish_reason: "stop" }], usage });
|
|
35
|
+
const chunks = [
|
|
36
|
+
{ ...base, object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "OFFLINE_FIXTURE_COMPLETE" }, finish_reason: null }] },
|
|
37
|
+
{ ...base, object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage },
|
|
38
|
+
];
|
|
39
|
+
return new Response(chunks.map(c => `data: ${JSON.stringify(c)}\n\n`).join("") + "data: [DONE]\n\n", {
|
|
40
|
+
headers: { "content-type": "text/event-stream", "cache-control": "no-cache" } });
|
|
41
|
+
} });
|
|
42
|
+
const config = { model: "test-provider/test-model", enabled_providers: ["test-provider"], provider: { "test-provider": {
|
|
43
|
+
name: "test-provider", npm: "@ai-sdk/openai-compatible", options: { baseURL: `http://127.0.0.1:${provider.port}/v1`, apiKey: "synthetic-only" },
|
|
44
|
+
models: { "test-model": { name: "test-model", limit: { context: 128000, output: 16000 } } } } } };
|
|
45
|
+
const configEnv = { OPENCODE_SERVER_PASSWORD: "native-sandbox-only", OPENCODE_CONFIG_CONTENT: JSON.stringify(config) };
|
|
46
|
+
// Reserve an ephemeral port, then start the actual native serve command.
|
|
47
|
+
const reservation = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("") }); const nativePort = reservation.port; reservation.stop(true);
|
|
48
|
+
const native = spawn(binary, ["serve", "--hostname", "127.0.0.1", "--port", String(nativePort)], { cwd: project,
|
|
49
|
+
env: { ...process.env, ...configEnv, HOME: home }, stdio: ["ignore", "pipe", "pipe"] });
|
|
50
|
+
const stopNative = async () => { if (native.exitCode !== null || native.signalCode !== null) return; native.kill("SIGTERM");
|
|
51
|
+
await new Promise<void>(resolve => { const timer = setTimeout(() => { native.kill("SIGKILL"); resolve(); }, 1500); native.once("exit", () => { clearTimeout(timer); resolve(); }); }); };
|
|
52
|
+
let worker: ReturnType<typeof createSessionSourceTransportWorker> | undefined, hub: any, proxy: ReturnType<typeof Bun.serve> | undefined;
|
|
53
|
+
let db: any; let stage = "native-start";
|
|
54
|
+
const realFetch = globalThis.fetch;
|
|
55
|
+
let forkWorker: ReturnType<typeof createSessionSourceTransportWorker> | undefined;
|
|
56
|
+
const eventAbort = new AbortController(); let eventPump: Promise<void> | undefined;
|
|
57
|
+
const events: any[] = [];
|
|
58
|
+
const eventSubscribers = new Set<(event: any) => void>();
|
|
59
|
+
const forkResponses: Array<{ status: number; code: string }> = [];
|
|
60
|
+
try {
|
|
61
|
+
await new Promise<void>((resolve, reject) => {
|
|
62
|
+
let log = ""; const timer = setTimeout(() => reject(Error("native_start_timeout")), 20000);
|
|
63
|
+
const output = (b: Buffer) => { log = (log + b.toString()).slice(-32768); if (log.includes(`http://127.0.0.1:${nativePort}`)) { clearTimeout(timer); resolve(); } };
|
|
64
|
+
native.stdout!.on("data", output); native.stderr!.on("data", output);
|
|
65
|
+
native.once("exit", () => { clearTimeout(timer); reject(Error("native_exited_before_ready")); });
|
|
66
|
+
});
|
|
67
|
+
// Transparent, streaming HTTP observation only. NEVER fabricate/rewrite API
|
|
68
|
+
// status/body/version. Actual native pid is visible and remains independently
|
|
69
|
+
// checked by the launcher. Proxy records methods/paths, never credentials.
|
|
70
|
+
proxy = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(r) {
|
|
71
|
+
const u = new URL(r.url), method = r.method, body = method === "GET" || method === "HEAD" ? undefined : await r.text();
|
|
72
|
+
if (method === "POST") { nativePosts.push(u.pathname); if (u.pathname === "/api/session") newBodies.push(JSON.parse(body!)); }
|
|
73
|
+
const upstream = await fetch(`http://127.0.0.1:${nativePort}${u.pathname}${u.search}`, { method, headers: r.headers, body, redirect: "manual", signal: r.signal, decompress: false });
|
|
74
|
+
if (upstream.headers.get("content-type")?.includes("text/event-stream")) {
|
|
75
|
+
sse++; const stream = upstream.body!.pipeThrough(new TransformStream({ transform(chunk, controller) { sseBytes += chunk.length; controller.enqueue(chunk); } }));
|
|
76
|
+
return new Response(stream, { status: upstream.status, headers: upstream.headers });
|
|
77
|
+
}
|
|
78
|
+
if (["/api/session", "/api/session/active"].includes(u.pathname) && method === "GET") console.log("NATIVE_READ_SHAPE", u.pathname, await upstream.clone().text());
|
|
79
|
+
return new Response(upstream.body, { status: upstream.status, headers: upstream.headers });
|
|
80
|
+
} });
|
|
81
|
+
const nativeOrigin = `http://127.0.0.1:${nativePort}`;
|
|
82
|
+
const url = forkMode ? nativeOrigin : `http://127.0.0.1:${proxy.port}`, auth = `Basic ${Buffer.from("opencode:native-sandbox-only").toString("base64")}`;
|
|
83
|
+
if (forkMode) globalThis.fetch = (async (input: any, init: any) => {
|
|
84
|
+
const u = new URL(typeof input === "string" || input instanceof URL ? String(input) : input.url), method = init?.method ?? "GET";
|
|
85
|
+
if (u.origin === nativeOrigin && method === "POST") { nativePosts.push(u.pathname); if (u.pathname === "/api/session") newBodies.push(JSON.parse(init.body)); }
|
|
86
|
+
const r = await realFetch(input, init);
|
|
87
|
+
if (method === "POST" && u.pathname === `${F}/child-register`) console.log("NATIVE_FORK_REGISTER_HTTP", r.status);
|
|
88
|
+
if (u.origin === nativeOrigin && method === "POST" && u.pathname.endsWith("/fork")) {
|
|
89
|
+
let code = r.ok ? "success" : "unclassified";
|
|
90
|
+
if (!r.ok) {
|
|
91
|
+
const allowed = new Set(["InvalidRequestError", "SessionNotFoundError", "MessageNotFoundError", "ForkEmptyError", "Session.ForkEmptyError"]);
|
|
92
|
+
try { const b = await r.clone().json() as any; for (const value of [b?._tag, b?.code, b?.error?._tag, b?.error?.code]) if (allowed.has(value)) code = value; } catch {}
|
|
93
|
+
}
|
|
94
|
+
forkResponses.push({ status: r.status, code }); console.log("NATIVE_FORK_HTTP", JSON.stringify({ status: r.status, code }));
|
|
95
|
+
}
|
|
96
|
+
if (u.origin === nativeOrigin && r.headers.get("content-type")?.includes("text/event-stream")) sse++;
|
|
97
|
+
return r;
|
|
98
|
+
}) as typeof fetch;
|
|
99
|
+
const get = async (path: string) => { const r = await fetch(url + path, { headers: { authorization: auth, "x-opencode-directory": project }, signal: AbortSignal.timeout(10000) });
|
|
100
|
+
expect(r.status).toBe(200); return r.json() as any; };
|
|
101
|
+
stage = "native-info-project";
|
|
102
|
+
const info = await get("/api/info"); expect(info.version).toBe(identity); expect(info.pid).toBe(native.pid);
|
|
103
|
+
const unauth = await fetch(url + "/api/info"); expect(unauth.status).toBe(401);
|
|
104
|
+
const defaultModel = await get("/api/model/default"); console.log("NATIVE_DEFAULT", JSON.stringify(defaultModel));
|
|
105
|
+
const projects = await get("/api/project"); console.log("NATIVE_PROJECTS", JSON.stringify(projects));
|
|
106
|
+
const providers = await get("/api/provider"); console.log("NATIVE_PROVIDER_STATE", JSON.stringify(providers.data?.map((p: any) => ({ id: p.id, activation: p.activation }))));
|
|
107
|
+
const models = await get("/api/model"); console.log("NATIVE_MODEL_STATE", JSON.stringify(models.data?.map((m: any) => ({ id: m.id, providerID: m.providerID }))));
|
|
108
|
+
const configs = await get("/api/config"); console.log("NATIVE_CONFIG_STATE", JSON.stringify(configs.map((c: any) => ({ type: c.type, model: c.info?.model, keys: Object.keys(c.info ?? {}) }))));
|
|
109
|
+
expect(projects.some((p: any) => p.canonical === project)).toBe(true);
|
|
110
|
+
({ db } = await import("./db")); const { register, createNetworkTokenForNode } = await import("./auth");
|
|
111
|
+
register("native_bootstrap", "Synthetic-Native-4150!"); const human = register("native_owner", "Synthetic-Native-4150!"); const net = human.network_id;
|
|
112
|
+
const daemon = createNetworkTokenForNode(human.user.user_id, net, "native-daemon", "native_daemon");
|
|
113
|
+
createNetworkTokenForNode(human.user.user_id, net, "native-source", "native_source");
|
|
114
|
+
db.run("UPDATE nodes SET runtime='opencode-cli',config_snapshot=?1 WHERE node_id='native_source'", [JSON.stringify({ flags: { opencodeGeneration: "v2", opencodeMode: "copresence" } })]);
|
|
115
|
+
db.run("UPDATE nodes SET config_snapshot=?1 WHERE node_id='native_daemon'", [JSON.stringify({ role: "host_supervisor", daemon_capabilities: { source_directory_read: DIR, project_new_session: CAP, source_fork_transport: FCAP, source_node_delivery: SOURCE_DELIVERY_CAPABILITY } })]);
|
|
116
|
+
db.run("INSERT INTO sessions (resume_id,alias,node_id,network_id,env_transport,last_seen_at) VALUES ('native_daemon','native-daemon','native_daemon',?1,'loopback',datetime('now'))", [net]);
|
|
117
|
+
const serverId = `osrv_${randomUUID()}`;
|
|
118
|
+
writeFileSync(join(home, ".anet", "password"), "native-sandbox-only", { mode: 0o600 });
|
|
119
|
+
writeFileSync(join(home, ".anet", "opencode-shared-server.json"), JSON.stringify({ url, passwordFile: join(home, ".anet", "password") }), { mode: 0o600 });
|
|
120
|
+
writeFileSync(join(daemonDir, ".anet", "opencode-directory-authorities.json"), JSON.stringify({ version: 1, grants: [{ server_id: serverId, network_id: net,
|
|
121
|
+
source_node_id: "native_source", directories: [project], allow_new_session: true, opencode_unsafe_tools: true }] }), { mode: 0o600 });
|
|
122
|
+
const { bootServer } = await import("./server"); hub = bootServer({ port: 0, hostname: "127.0.0.1" }); const hubUrl = `http://127.0.0.1:${hub.port}`;
|
|
123
|
+
const pkg = join(root, "node_modules", "@sleep2agi", "agent-node"); mkdirSync(pkg, { recursive: true });
|
|
124
|
+
writeFileSync(join(pkg, "package.json"), readFileSync(join(import.meta.dir, "../../agent-node/package.json")));
|
|
125
|
+
for (const dep of ["@anthropic-ai", "@openai", "node-pty"]) symlinkSync(join(import.meta.dir, "../../agent-node/node_modules", dep), join(root, "node_modules", dep));
|
|
126
|
+
const built = await Bun.build({ entrypoints: [join(import.meta.dir, "../../agent-node/src/cli.ts")], outdir: join(pkg, "dist"), target: "bun",
|
|
127
|
+
external: ["@anthropic-ai/claude-agent-sdk", "@openai/codex-sdk", "node-pty"] }); expect(built.success).toBe(true);
|
|
128
|
+
mkdirSync(join(root, "bin")); symlinkSync(binary, join(root, "bin", "opencode")); mkdirSync(join(root, "safe"), { mode: 0o700 });
|
|
129
|
+
const nativeLaunch = { command: process.execPath, argsPrefix: [join(import.meta.dir, "../../agent-network/bin/cli.ts")], timeoutMs: 15000,
|
|
130
|
+
env: { ...process.env, ...configEnv, HOME: home, PATH: `${join(root, "bin")}:/usr/local/bin:/usr/bin:/bin`, ANET_AGENT_NODE_BIN: join(pkg, "dist", "cli.js"), ANET_OPENCODE_SAFE_BASE: join(root, "safe"),
|
|
131
|
+
TEST4150_NATIVE_ORIGIN: nativeOrigin, TEST4150_NATIVE_AUDIT: join(root, "child-native-audit.jsonl") } };
|
|
132
|
+
worker = createSessionSourceTransportWorker({ hubUrl, home, daemonWorkDir: daemonDir, directoryEnabled: true, projectEnabled: true, forkEnabled: false,
|
|
133
|
+
nativeLaunch,
|
|
134
|
+
pin: createSessionControlPin({ hubUrl, token: daemon.token, nodeId: "native_daemon", networkId: net, epoch: 0, currentEpoch: () => 0,
|
|
135
|
+
currentToken: () => daemon.token, signal: new AbortController().signal }) });
|
|
136
|
+
const api = async (path: string, body?: any) => { const r = await fetch(hubUrl + path, { method: body ? "POST" : "GET", headers: { authorization: `Bearer ${human.token}`, "content-type": "application/json" },
|
|
137
|
+
...(body ? { body: JSON.stringify(body) } : {}) }); const result = await r.json() as any; expect(r.status).toBe(200); return result; };
|
|
138
|
+
const D = "/api/node-session-control/source/directory", selection = { network_id: net, source_node_id: "native_source", daemon_node_id: "native_daemon" };
|
|
139
|
+
stage = "directory"; await worker.tick(); const list = await api(D, selection); await worker.tick();
|
|
140
|
+
const first = await api(`${D}/${list.request_id}?network_id=${net}`); expect(first.status).toBe("ready");
|
|
141
|
+
const q = await api(D, { ...selection, selection_scope: first.request_id, server_id: serverId }); await worker.tick();
|
|
142
|
+
const snapshot = await api(`${D}/${q.request_id}?network_id=${net}`); console.log("NATIVE_DIRECTORY_STATUS", snapshot.status);
|
|
143
|
+
expect(snapshot.status).toBe("ready"); expect(snapshot.snapshot.projects).toHaveLength(1); expect(snapshot.snapshot.sessions).toHaveLength(0);
|
|
144
|
+
// The idle child currently polls native state and subscribes to HUB SSE,
|
|
145
|
+
// not native SSE. Test the real native event transport independently; never
|
|
146
|
+
// pretend this observer is a child's event subscription or task execution.
|
|
147
|
+
stage = "native-event-subscribe";
|
|
148
|
+
const stream = await fetch(url + "/api/event", { headers: { authorization: auth }, signal: eventAbort.signal });
|
|
149
|
+
expect(stream.status).toBe(200); expect(stream.headers.get("content-type")).toContain("text/event-stream");
|
|
150
|
+
let connected!: () => void;
|
|
151
|
+
const firstEvent = new Promise<void>(resolve => { connected = resolve; });
|
|
152
|
+
eventPump = (async () => {
|
|
153
|
+
let buffer = ""; const decoder = new TextDecoder(), reader = stream.body!.getReader();
|
|
154
|
+
try { for (;;) { const part = await reader.read(); if (part.done) break; if (forkMode) sseBytes += part.value.length; buffer += decoder.decode(part.value, { stream: true }).replaceAll("\r\n", "\n");
|
|
155
|
+
for (;;) { const boundary = buffer.indexOf("\n\n"); if (boundary < 0) break;
|
|
156
|
+
const frame = buffer.slice(0, boundary); buffer = buffer.slice(boundary + 2);
|
|
157
|
+
const data = frame.split("\n").filter(l => l.startsWith("data:")).map(l => l.slice(5).trimStart()).join("\n");
|
|
158
|
+
if (data) { const event = JSON.parse(data); events.push(event); for (const fn of eventSubscribers) fn(event); if (event.type === "server.connected") connected(); }
|
|
159
|
+
}
|
|
160
|
+
} } catch (e) { if (!eventAbort.signal.aborted) throw e; } finally { await reader.cancel().catch(() => {}); }
|
|
161
|
+
})();
|
|
162
|
+
await Promise.race([firstEvent, new Promise((_, reject) => { const t = setTimeout(() => reject(Error("native_event_connect_timeout")), 5000); t.unref(); })]);
|
|
163
|
+
const intent = { selection_scope: q.request_id, snapshot_id: snapshot.snapshot.snapshot_id, project_id: snapshot.snapshot.projects[0].project_id, child_name: "native-child", intent_id: "native-first" };
|
|
164
|
+
stage = "project-new"; const receipt = await api(P, intent); await worker.tick();
|
|
165
|
+
const result = await api(`${P}/${receipt.request_id}?network_id=${net}`); console.log("NATIVE_RECEIPT", JSON.stringify(result));
|
|
166
|
+
expect(result.status).toBe("registration_confirmed"); expect(result.registration_is_health).toBe(false);
|
|
167
|
+
expect(nativePosts).toEqual(["/api/session"]); expect(newBodies).toEqual([{ location: { directory: project } }]);
|
|
168
|
+
const row = db.get("SELECT * FROM session_project_creates WHERE request_id=?1", receipt.request_id);
|
|
169
|
+
const session = await get(`/api/session/${row.session_id}`); expect(session.data.id).toBe(row.session_id); expect(session.data.location.directory).toBe(project);
|
|
170
|
+
const messages = await get(`/api/session/${row.session_id}/context`); console.log("NATIVE_EMPTY_MESSAGES", JSON.stringify(messages));
|
|
171
|
+
expect(messages.data ?? messages).toEqual([]);
|
|
172
|
+
const childDir = join(project, ".anet", "nodes", "native-child"), profile = JSON.parse(readFileSync(join(childDir, "config.json"), "utf8"));
|
|
173
|
+
console.log("NATIVE_CHILD_MODEL", profile.model);
|
|
174
|
+
expect(profile.model).toBe("test-provider/test-model");
|
|
175
|
+
expect(profile.sessionId).toBe(row.session_id);
|
|
176
|
+
const health = JSON.parse(readFileSync(join(childDir, "source-resume-health.json"), "utf8")); expect(health.session_id).toBe(row.session_id);
|
|
177
|
+
expect(existsSync(join(childDir, "source-resume-runtime-claim.json"))).toBe(true);
|
|
178
|
+
expect(db.get("SELECT session_id FROM sessions WHERE node_id=?1 ORDER BY last_seen_at DESC LIMIT 1", row.child_node_id).session_id).toBe(row.session_id);
|
|
179
|
+
expect(sse).toBeGreaterThan(0); expect(sseBytes).toBeGreaterThan(0); expect(providerCalls).toBe(0);
|
|
180
|
+
console.log("NATIVE_EVENT_TYPES", events.map(e => e.type));
|
|
181
|
+
const createdEvent = events.find(e => e.type === "session.created");
|
|
182
|
+
expect(createdEvent).toBeDefined();
|
|
183
|
+
expect(createdEvent.data.sessionID).toBe(row.session_id);
|
|
184
|
+
expect((await api(P, intent)).request_id).toBe(receipt.request_id); await worker.tick(); expect(nativePosts).toEqual(["/api/session"]);
|
|
185
|
+
// Exercise real nonempty pagination and the native null final cursor too.
|
|
186
|
+
const refresh = await api(D, { ...selection, selection_scope: first.request_id, server_id: serverId }); await worker.tick();
|
|
187
|
+
const after = await api(`${D}/${refresh.request_id}?network_id=${net}`);
|
|
188
|
+
expect(after.status).toBe("ready"); expect(after.snapshot.sessions).toHaveLength(1);
|
|
189
|
+
expect(after.snapshot.sessions[0].activity).toBe("unknown"); expect(after.snapshot.sessions[0].binding).toBe("unknown");
|
|
190
|
+
expect(after.snapshot.sessions[0].attach_authorized).toBe(false);
|
|
191
|
+
if (forkMode) {
|
|
192
|
+
stage = "managed-source-fork";
|
|
193
|
+
const sourceHealth = readFileSync(join(childDir, "opencode-launch-health.json"), "utf8");
|
|
194
|
+
stage = "local-provider-fixture";
|
|
195
|
+
const terminal = new Promise<void>((resolve, reject) => {
|
|
196
|
+
const timer = setTimeout(() => { eventSubscribers.delete(onEvent); reject(Error("native_fixture_terminal_timeout")); }, 15000);
|
|
197
|
+
const onEvent = (e: any) => {
|
|
198
|
+
if (e.data?.sessionID !== row.session_id) return;
|
|
199
|
+
if (e.type === "session.execution.succeeded") { clearTimeout(timer); eventSubscribers.delete(onEvent); resolve(); }
|
|
200
|
+
if (e.type === "session.execution.failed" || e.type === "session.execution.interrupted") {
|
|
201
|
+
clearTimeout(timer); eventSubscribers.delete(onEvent); reject(Error("native_fixture_execution_failed"));
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
eventSubscribers.add(onEvent);
|
|
205
|
+
});
|
|
206
|
+
terminal.catch(() => {});
|
|
207
|
+
const fixture = await fetch(`${url}/api/session/${row.session_id}/prompt`, { method: "POST", headers: {
|
|
208
|
+
authorization: auth, "content-type": "application/json", "x-opencode-directory": project },
|
|
209
|
+
body: JSON.stringify({ text: "Reply OFFLINE_FIXTURE_COMPLETE, no tools.", metadata: { testOnly: true }, resume: true }), signal: AbortSignal.timeout(15000) });
|
|
210
|
+
console.log("NATIVE_PROMPT_FIXTURE", fixture.status); expect(fixture.ok).toBe(true); await fixture.body?.cancel();
|
|
211
|
+
const drain = await fetch(`${url}/api/experimental/session/${row.session_id}/wait`, { method: "POST",
|
|
212
|
+
headers: { authorization: auth, "x-opencode-directory": project }, signal: AbortSignal.timeout(15000) });
|
|
213
|
+
console.log("NATIVE_FIXTURE_DRAIN", drain.status); expect(drain.ok).toBe(true); await drain.body?.cancel();
|
|
214
|
+
await terminal;
|
|
215
|
+
const sourceContext = await get(`/api/session/${row.session_id}/context`);
|
|
216
|
+
const sourceInfo = await get(`/api/session/${row.session_id}`);
|
|
217
|
+
expect(sourceContext.data.length).toBeGreaterThan(0);
|
|
218
|
+
expect(sourceContext.data.some((m: any) => /^msg_[A-Za-z0-9]+$/.test(m.id))).toBe(true);
|
|
219
|
+
expect(JSON.stringify(sourceContext.data)).toContain("OFFLINE_FIXTURE_COMPLETE");
|
|
220
|
+
expect(providerCalls).toBeGreaterThan(0);
|
|
221
|
+
expect((await get("/api/session/active")).data).not.toHaveProperty(row.session_id);
|
|
222
|
+
console.log("NATIVE_SOURCE_FIXTURE", JSON.stringify({ projectedMessages: sourceContext.data.length, boundaryVerified: true, terminalObserved: true, providerCalls }));
|
|
223
|
+
stage = "managed-source-fork";
|
|
224
|
+
forkWorker = createSessionSourceTransportWorker({ hubUrl, home, daemonWorkDir: daemonDir, forkEnabled: true, nativeLaunch,
|
|
225
|
+
pin: createSessionControlPin({ hubUrl, token: daemon.token, nodeId: "native_daemon", networkId: net, epoch: 0, currentEpoch: () => 0,
|
|
226
|
+
currentToken: () => daemon.token, signal: new AbortController().signal }) });
|
|
227
|
+
await forkWorker.tick();
|
|
228
|
+
const forkInput = { network_id: net, source_node_id: row.child_node_id, session_id: row.session_id,
|
|
229
|
+
mode: "fork_independent", child_name: "native-fork", intent_id: "native-fork-first" };
|
|
230
|
+
const writesBeforeAttach = [...nativePosts];
|
|
231
|
+
const attach = await fetch(hubUrl + F, { method: "POST", headers: { authorization: `Bearer ${human.token}`, "content-type": "application/json" },
|
|
232
|
+
body: JSON.stringify({ ...forkInput, mode: "attach_existing", intent_id: "native-attach-refused" }) });
|
|
233
|
+
expect(attach.status).toBe(400); await attach.body?.cancel();
|
|
234
|
+
await forkWorker.tick(); expect(nativePosts).toEqual(writesBeforeAttach);
|
|
235
|
+
expect(() => process.kill(health.pid, 0)).not.toThrow();
|
|
236
|
+
console.log("NATIVE_BOUND_ATTACH", JSON.stringify({ status: attach.status, nativeWrites: 0, sourceBridgeAlive: true, scope: "existing_transport_rejects_attach_mode" }));
|
|
237
|
+
const forkReceipt = await api(F, forkInput);
|
|
238
|
+
console.log("NATIVE_FORK_ADMISSION", forkReceipt.status);
|
|
239
|
+
for (let i = 0; i < 4; i++) await forkWorker.tick();
|
|
240
|
+
const forkResult = await api(`${F}/${forkReceipt.request_id}?network_id=${net}`);
|
|
241
|
+
console.log("NATIVE_FORK_RECEIPT", JSON.stringify(forkResult));
|
|
242
|
+
expect(forkResult.status).toBe("registration_confirmed");
|
|
243
|
+
expect(forkResult.child_session_id).not.toBe(row.session_id);
|
|
244
|
+
const forkContext = await get(`/api/session/${forkResult.child_session_id}/context`);
|
|
245
|
+
expect(JSON.stringify(forkContext.data)).toContain("OFFLINE_FIXTURE_COMPLETE");
|
|
246
|
+
const forkDir = join(project, ".anet", "nodes", "native-fork");
|
|
247
|
+
const forkProfile = JSON.parse(readFileSync(join(forkDir, "config.json"), "utf8"));
|
|
248
|
+
expect(forkProfile.sessionId).toBe(forkResult.child_session_id);
|
|
249
|
+
const forkHealthText = readFileSync(join(forkDir, "source-resume-health.json"), "utf8");
|
|
250
|
+
const forkHealth = JSON.parse(forkHealthText);
|
|
251
|
+
expect(forkHealth.session_id).toBe(forkResult.child_session_id);
|
|
252
|
+
expect(forkHealth.pid).not.toBe(health.pid);
|
|
253
|
+
const writesAfterFork = [...nativePosts];
|
|
254
|
+
const tokenCount = db.get("SELECT COUNT(*) n FROM api_tokens").n;
|
|
255
|
+
expect((await api(F, forkInput)).request_id).toBe(forkReceipt.request_id);
|
|
256
|
+
await forkWorker.tick(); expect(nativePosts).toEqual(writesAfterFork);
|
|
257
|
+
expect(db.get("SELECT COUNT(*) n FROM api_tokens").n).toBe(tokenCount);
|
|
258
|
+
expect(readFileSync(join(forkDir, "source-resume-health.json"), "utf8")).toBe(forkHealthText);
|
|
259
|
+
expect(db.get("SELECT status FROM node_create_requests WHERE request_id=(SELECT admission_request_id FROM session_source_executions WHERE execution_id=(SELECT execution_id FROM session_source_transports WHERE request_id=?1))", forkReceipt.request_id).status).toBe("source_reserved");
|
|
260
|
+
await forkWorker.stop();
|
|
261
|
+
expect(() => process.kill(forkHealth.pid, 0)).toThrow();
|
|
262
|
+
expect(readFileSync(join(childDir, "opencode-launch-health.json"), "utf8")).toBe(sourceHealth);
|
|
263
|
+
expect((await get(`/api/session/${row.session_id}`)).data).toEqual(sourceInfo.data);
|
|
264
|
+
expect(await get(`/api/session/${row.session_id}/context`)).toEqual(sourceContext);
|
|
265
|
+
expect(() => process.kill(health.pid, 0)).not.toThrow(); expect((await get("/api/info")).pid).toBe(native.pid);
|
|
266
|
+
console.log("NATIVE_FORK_LIFECYCLE", JSON.stringify({ sourcePreserved: true, copiedContext: true,
|
|
267
|
+
exactResume: true, forkChildRegistered: true, sameIntentNoForkMintLaunch: true, forkChildStopPreservedSource: true }));
|
|
268
|
+
}
|
|
269
|
+
stage = "child-only-stop"; await worker.stop(); expect(() => process.kill(health.pid, 0)).toThrow();
|
|
270
|
+
expect((await get("/api/info")).pid).toBe(native.pid); expect((await get(`/api/session/${row.session_id}`)).data.id).toBe(row.session_id);
|
|
271
|
+
expect((await api(`${P}/${receipt.request_id}?network_id=${net}`)).status).toBe("registration_confirmed");
|
|
272
|
+
console.log("NATIVE_ACCEPTANCE", JSON.stringify({ identity, stock: false, session_id: row.session_id, nativePosts, initiallyEmpty: true, forkResponses,
|
|
273
|
+
exactResume: true, nativeSseObserver: { connections: sse, bytes: sseBytes, createdEvent: true }, childNativeSse: false,
|
|
274
|
+
providerCalls, registrationReceiptNotHealth: true, serverSurvivedChildStop: true, platform: "linux" }));
|
|
275
|
+
} catch (e) {
|
|
276
|
+
let sourceBridgeAlive = false;
|
|
277
|
+
try { const h = JSON.parse(readFileSync(join(project, ".anet", "nodes", "native-child", "source-resume-health.json"), "utf8")); process.kill(h.pid, 0); sourceBridgeAlive = true; } catch {}
|
|
278
|
+
let nativeServerAlive = false; try { process.kill(native.pid!, 0); nativeServerAlive = true; } catch {}
|
|
279
|
+
const forkDir = join(project, ".anet", "nodes", "native-fork");
|
|
280
|
+
let forkProfileHasModel = false;
|
|
281
|
+
try { forkProfileHasModel = typeof JSON.parse(readFileSync(join(forkDir, "config.json"), "utf8")).model === "string"; } catch {}
|
|
282
|
+
console.error("NATIVE_FIRST_FAILURE", JSON.stringify({ stage, nativePosts, forkResponses, sse, sseBytes, providerCalls, sourceBridgeAlive, nativeServerAlive,
|
|
283
|
+
forkLaunchClaim: existsSync(join(forkDir, "source-resume-launch-claim.json")), forkRuntimeClaim: existsSync(join(forkDir, "source-resume-runtime-claim.json")),
|
|
284
|
+
forkHealthPublished: existsSync(join(forkDir, "source-resume-health.json")),
|
|
285
|
+
forkProfileHasModel,
|
|
286
|
+
nativeExecutionEvents: events.map(e => e.type).filter(t => ["session.execution.started", "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted"].includes(t)),
|
|
287
|
+
sourceRegistered: db?.get("SELECT state FROM session_project_creates ORDER BY rowid LIMIT 1")?.state === "registration_confirmed" })); throw e;
|
|
288
|
+
}
|
|
289
|
+
finally { eventAbort.abort(); await eventPump?.catch(() => {}); await forkWorker?.stop(); await worker?.stop(); globalThis.fetch = realFetch; hub?.stop(true); proxy?.stop(true); provider.stop(true); await stopNative(); db?.close(); }
|
|
290
|
+
}, 60000);
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { db } from "./db";
|
|
3
|
+
import { resolveToken, createNetworkTokenForNode } from "./auth";
|
|
4
|
+
import { readSessionControlBody, readSessionControlCredential, isHumanCredential, resolveSessionControlNodeCaller } from "./node-session-control";
|
|
5
|
+
import { putPendingEnvBlob, takePendingEnvBlob } from "./create-node";
|
|
6
|
+
import { checkNodeName } from "./shared/node-name";
|
|
7
|
+
import { hasFreshChildRegistration } from "./session-source-delivery";
|
|
8
|
+
import { PROJECT_CREATE_ROOT as ROOT, PROJECT_CREATE_CAPABILITY as CAP, isProjectCreateId,
|
|
9
|
+
type ProjectCreateTask, type ProjectCreateSelection, type SessionAttachSelection, type ProjectOperation } from "./contracts/session-project-create";
|
|
10
|
+
|
|
11
|
+
export type ProjectRow = ProjectCreateTask & { user_id: string; requester_token_id: string; daemon_token_id: string;
|
|
12
|
+
daemon_instance_id: string; state: string; session_id: string | null; child_node_id: string | null;
|
|
13
|
+
child_token_id: string | null; credential_expires_at: number | null };
|
|
14
|
+
export type ProjectScope = { network_id: string; source_node_id: string; daemon_node_id: string; daemon_token_id: string; daemon_instance_id: string;
|
|
15
|
+
operation_kind?: ProjectOperation; selected_project_id?: string };
|
|
16
|
+
/** Uses the existing source HTTP handler/pin/declaration and directory scope.
|
|
17
|
+
* One journal for accepted writes, no source/fork evidence or recovery mutation. */
|
|
18
|
+
export function createSessionProjectTransport(deps: { enabled: boolean; attachEnabled?: boolean;
|
|
19
|
+
select: (s: ProjectCreateSelection | SessionAttachSelection, token: string, user: string) => ProjectScope | null;
|
|
20
|
+
permissions: (r: ProjectRow) => boolean; current: (r: ProjectScope) => boolean }) {
|
|
21
|
+
const live = new Set<string>();
|
|
22
|
+
const row = (id: string) => db.get<ProjectRow>("SELECT * FROM session_project_creates WHERE request_id=?1", id);
|
|
23
|
+
const terminal = (r: ProjectRow) => ["registration_confirmed", "unknown_rotation_required"].includes(r.state);
|
|
24
|
+
const unknown = (r: ProjectRow) => {
|
|
25
|
+
if (r.state === "registration_confirmed") return;
|
|
26
|
+
takePendingEnvBlob(r.request_id, r.daemon_node_id);
|
|
27
|
+
db.transaction(() => {
|
|
28
|
+
db.run("UPDATE session_project_creates SET state='unknown_rotation_required' WHERE request_id=?1 AND state!='registration_confirmed'", [r.request_id]);
|
|
29
|
+
if (r.child_token_id) db.run("UPDATE api_tokens SET revoked_at=datetime('now') WHERE token_id=?1", [r.child_token_id]);
|
|
30
|
+
}); live.delete(r.request_id);
|
|
31
|
+
};
|
|
32
|
+
const current = (r: ProjectRow) => deps.current(r) && deps.permissions(r) && Date.now() < r.expires_at;
|
|
33
|
+
const refresh = (r: ProjectRow) => { if (!terminal(r) && (!live.has(r.request_id) || !current(r)
|
|
34
|
+
|| (r.credential_expires_at !== null && Date.now() >= r.credential_expires_at))) unknown(r); return row(r.request_id)!; };
|
|
35
|
+
const view = (r: ProjectRow) => ({ request_id: r.request_id, network_id: r.network_id, daemon_node_id: r.daemon_node_id,
|
|
36
|
+
intent_id: r.intent_id, child_name: r.child_name, status: r.state, accepted_at: r.accepted_at, expires_at: r.expires_at,
|
|
37
|
+
operation_kind: r.operation_kind ?? "project_new_session",
|
|
38
|
+
session_creation: r.operation_kind === "attach_existing_session" ? "not_performed" : r.session_id ? "confirmed" : r.state === "create_pending" ? "not_started" : "unknown",
|
|
39
|
+
...(r.child_node_id ? { child_node_id: r.child_node_id } : {}),
|
|
40
|
+
registration_is_health: false, native_acceptance: "not_verified" });
|
|
41
|
+
const task = (r: ProjectRow): ProjectCreateTask => ({ request_id: r.request_id, network_id: r.network_id, source_node_id: r.source_node_id,
|
|
42
|
+
daemon_node_id: r.daemon_node_id, selection_scope: r.selection_scope, snapshot_id: r.snapshot_id, project_id: r.project_id,
|
|
43
|
+
child_name: r.child_name, intent_id: r.intent_id, accepted_at: r.accepted_at, expires_at: r.expires_at,
|
|
44
|
+
operation_kind: r.operation_kind ?? "project_new_session", selected_session_id: r.selected_session_id ?? null });
|
|
45
|
+
const keys = (o: object, names: string[]) => Object.keys(o).every(k => names.includes(k));
|
|
46
|
+
const ok = (o: object) => Response.json({ ok: true, ...o }, { headers: { "cache-control": "no-store" } });
|
|
47
|
+
const fail = (status = 409) => Response.json({ ok: false, error: "project_create_unavailable" }, { status, headers: { "cache-control": "no-store" } });
|
|
48
|
+
return async (req: Request, url: URL): Promise<Response | null> => {
|
|
49
|
+
if (url.pathname !== ROOT && !url.pathname.startsWith(`${ROOT}/`)) return null;
|
|
50
|
+
if (!deps.enabled && !deps.attachEnabled) return fail(404);
|
|
51
|
+
try {
|
|
52
|
+
const a = resolveToken(req.headers.get("authorization")?.match(/^Bearer (\S+)$/)?.[1] ?? "");
|
|
53
|
+
if (!a?.tokenId) return fail(401);
|
|
54
|
+
const credential = readSessionControlCredential(a.tokenId), suffix = url.pathname.slice(ROOT.length);
|
|
55
|
+
if (req.method === "GET") {
|
|
56
|
+
if (!isHumanCredential(credential) || !isProjectCreateId(suffix.slice(1))) return fail(403);
|
|
57
|
+
const r = row(suffix.slice(1));
|
|
58
|
+
if (!r || r.requester_token_id !== a.tokenId || r.user_id !== a.user.user_id || url.searchParams.getAll("network_id").length !== 1
|
|
59
|
+
|| [...url.searchParams.keys()].some(k => k !== "network_id") || url.searchParams.get("network_id") !== r.network_id || !deps.permissions(r)) return fail(403);
|
|
60
|
+
return ok(view(refresh(r)));
|
|
61
|
+
}
|
|
62
|
+
if (req.method !== "POST" || url.search) return fail(400);
|
|
63
|
+
const b: any = await readSessionControlBody(req, 16384); if (!b) return fail(400);
|
|
64
|
+
if (!suffix) {
|
|
65
|
+
const attach = Object.hasOwn(b, "session_id"), operation = attach ? "attach_existing_session" : "project_new_session";
|
|
66
|
+
if (attach ? !deps.attachEnabled : !deps.enabled) return fail(404);
|
|
67
|
+
if (!isHumanCredential(credential) || !keys(b, ["selection_scope", "snapshot_id", attach ? "session_id" : "project_id", "child_name", "intent_id"])
|
|
68
|
+
|| !/^srcdir_[a-f0-9-]{36}$/.test(b.selection_scope) || !/^snap_[a-f0-9-]{36}$/.test(b.snapshot_id)
|
|
69
|
+
|| !(attach ? /^oses_[a-f0-9-]{36}$/.test(b.session_id) : /^oprj_[a-f0-9-]{36}$/.test(b.project_id)) || typeof b.intent_id !== "string" || !/^[A-Za-z0-9_-]{1,200}$/.test(b.intent_id)) return fail(400);
|
|
70
|
+
const name = checkNodeName(b.child_name); if (!name.ok || name.name !== b.child_name) return fail(400);
|
|
71
|
+
// Resolve replay BEFORE looking at a possibly expired directory scope.
|
|
72
|
+
const existing = db.get<ProjectRow>("SELECT * FROM session_project_creates WHERE user_id=?1 AND intent_id=?2 AND selection_scope=?3", a.user.user_id, b.intent_id, b.selection_scope);
|
|
73
|
+
if (existing) {
|
|
74
|
+
if ((existing.operation_kind ?? "project_new_session") !== operation || existing.requester_token_id !== a.tokenId || existing.snapshot_id !== b.snapshot_id
|
|
75
|
+
|| (attach ? existing.selected_session_id !== b.session_id : existing.project_id !== b.project_id)
|
|
76
|
+
|| existing.child_name !== b.child_name || !deps.permissions(existing)) return fail(403);
|
|
77
|
+
return ok(view(refresh(existing)));
|
|
78
|
+
}
|
|
79
|
+
if (db.dialect !== "sqlite" || db.atomicTransactions !== true || db.transactionalFeaturesRefusal !== null || live.size >= 100) return fail();
|
|
80
|
+
const scope = deps.select(b, a.tokenId, a.user.user_id); if (!scope || !deps.current(scope)) return fail(403);
|
|
81
|
+
const id = `prjc_${randomUUID()}`, now = Date.now();
|
|
82
|
+
db.transaction(() => {
|
|
83
|
+
// A new project reservation never enters ordinary create's dispatch statuses.
|
|
84
|
+
if (db.get("SELECT 1 FROM nodes WHERE network_id=?1 AND alias=?2", scope.network_id, b.child_name)
|
|
85
|
+
|| db.get("SELECT 1 FROM node_create_requests WHERE network_id=?1 AND child_name=?2 AND status IN ('pending','delivered','source_reserved')", scope.network_id, b.child_name)) throw Error("name_reserved");
|
|
86
|
+
db.run(`INSERT INTO session_project_creates (request_id,user_id,requester_token_id,network_id,source_node_id,daemon_node_id,daemon_token_id,daemon_instance_id,
|
|
87
|
+
intent_id,selection_scope,snapshot_id,project_id,child_name,accepted_at,expires_at,state,operation_kind,selected_session_id)
|
|
88
|
+
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,'create_pending',?16,?17)`,
|
|
89
|
+
[id, a.user.user_id, a.tokenId, scope.network_id, scope.source_node_id, scope.daemon_node_id, scope.daemon_token_id, scope.daemon_instance_id,
|
|
90
|
+
b.intent_id, b.selection_scope, b.snapshot_id, attach ? scope.selected_project_id : b.project_id, b.child_name, now, now + 300000, operation, attach ? b.session_id : null]);
|
|
91
|
+
});
|
|
92
|
+
live.add(id);
|
|
93
|
+
const timer = setTimeout(() => { const r = row(id); if (r && !terminal(r)) unknown(r); }, 300000); timer.unref?.();
|
|
94
|
+
return ok(view(row(id)!));
|
|
95
|
+
}
|
|
96
|
+
if (suffix === "/child-register") {
|
|
97
|
+
if (!keys(b, ["request_id"]) || !isProjectCreateId(b.request_id)) return fail(400);
|
|
98
|
+
const r = row(b.request_id); if (!r || r.state !== "delivery_claimed" || !current(r) || Date.now() >= r.credential_expires_at!
|
|
99
|
+
|| a.tokenId !== r.child_token_id) return fail(403);
|
|
100
|
+
const n = resolveSessionControlNodeCaller(a.tokenId);
|
|
101
|
+
if (n?.node_id !== r.child_node_id || n.network_id !== r.network_id) return fail(403);
|
|
102
|
+
if (!hasFreshChildRegistration(r.child_node_id!, r.network_id, r.child_name, r.session_id!)) return fail(403);
|
|
103
|
+
db.transaction(() => { db.run("UPDATE session_project_creates SET state='registration_confirmed' WHERE request_id=?1", [r.request_id]);
|
|
104
|
+
db.run("UPDATE api_tokens SET expires_at=NULL WHERE token_id=?1 AND revoked_at IS NULL", [r.child_token_id]); });
|
|
105
|
+
live.delete(r.request_id); return ok({ status: "registration_confirmed" });
|
|
106
|
+
}
|
|
107
|
+
const n = resolveSessionControlNodeCaller(a.tokenId), expected = b.expected;
|
|
108
|
+
if (!n || !expected || Object.keys(expected).length !== 2 || expected.node_id !== n.node_id || expected.network_id !== n.network_id
|
|
109
|
+
|| b.capability !== CAP || typeof b.instance_id !== "string" || !deps.current({ network_id: n.network_id, daemon_node_id: n.node_id,
|
|
110
|
+
daemon_token_id: a.tokenId, daemon_instance_id: b.instance_id, source_node_id: "" })) return fail(403);
|
|
111
|
+
const rows = db.all<ProjectRow>("SELECT * FROM session_project_creates WHERE daemon_token_id=?1 AND daemon_instance_id=?2 ORDER BY accepted_at", a.tokenId, b.instance_id);
|
|
112
|
+
if (suffix === "/pull") {
|
|
113
|
+
if (!keys(b, ["expected", "capability", "instance_id"])) return fail(400);
|
|
114
|
+
for (const original of rows) {
|
|
115
|
+
const r = refresh(original); if (terminal(r)) continue;
|
|
116
|
+
if (!current(r)) continue;
|
|
117
|
+
if (r.state === "create_pending") {
|
|
118
|
+
db.run("UPDATE session_project_creates SET state='create_claimed' WHERE request_id=?1 AND state='create_pending'", [r.request_id]);
|
|
119
|
+
return ok({ task: { phase: "create", task: task(r) } });
|
|
120
|
+
}
|
|
121
|
+
if (r.state === "delivery_pending") {
|
|
122
|
+
const blob = takePendingEnvBlob(r.request_id, r.daemon_node_id);
|
|
123
|
+
const child = r.child_token_id && resolveSessionControlNodeCaller(r.child_token_id);
|
|
124
|
+
if (!blob || blob.child_token_id !== r.child_token_id || !child || child.node_id !== r.child_node_id || child.network_id !== r.network_id
|
|
125
|
+
|| Date.now() >= r.credential_expires_at!) { unknown(r); continue; }
|
|
126
|
+
db.run("UPDATE session_project_creates SET state='delivery_claimed' WHERE request_id=?1 AND state='delivery_pending'", [r.request_id]);
|
|
127
|
+
return ok({ task: { phase: "deliver", task: { ...task(r), session_id: r.session_id, child_node_id: r.child_node_id,
|
|
128
|
+
child_token: blob.child_token, credential_expires_at: r.credential_expires_at } } });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return ok({ task: null });
|
|
132
|
+
}
|
|
133
|
+
if (suffix === "/ack") {
|
|
134
|
+
if (!keys(b, ["expected", "capability", "instance_id", "request_id", "result"]) || !isProjectCreateId(b.request_id)) return fail(400);
|
|
135
|
+
const r = row(b.request_id);
|
|
136
|
+
if (!r || r.daemon_token_id !== a.tokenId || r.daemon_instance_id !== b.instance_id || !current(r)) return fail(403);
|
|
137
|
+
if (r.state === "registration_confirmed") return ok({ acknowledged: true });
|
|
138
|
+
if (!live.has(r.request_id)) { unknown(r); return fail(); }
|
|
139
|
+
const result = b.result;
|
|
140
|
+
if (result && keys(result, ["status"]) && result.status === "unknown_rotation_required") { unknown(r); return ok({ acknowledged: true }); }
|
|
141
|
+
if (r.state !== "create_claimed" || !result || !keys(result, ["status", "session_id"]) || result.status !== "session_ready"
|
|
142
|
+
|| typeof result.session_id !== "string" || !/^ses_[A-Za-z0-9]{1,190}$/.test(result.session_id)) return fail(400);
|
|
143
|
+
const child = `node_${r.request_id}`, expires = Math.min(r.expires_at, Date.now() + 60000);
|
|
144
|
+
const token = db.transaction(() => {
|
|
145
|
+
// Claim and credential are atomic. No secret is written into this journal.
|
|
146
|
+
if (db.run("UPDATE session_project_creates SET state='delivery_pending',session_id=?1,child_node_id=?2,credential_expires_at=?3 WHERE request_id=?4 AND state='create_claimed'",
|
|
147
|
+
[result.session_id, child, expires, r.request_id]).changes !== 1) throw Error("already_minted");
|
|
148
|
+
const t = createNetworkTokenForNode(r.user_id, r.network_id, r.child_name, child);
|
|
149
|
+
if (!t.ok || !t.token || !t.token_id) throw Error("child_credential_refused");
|
|
150
|
+
db.run("UPDATE api_tokens SET expires_at=?1 WHERE token_id=?2", [new Date(expires).toISOString().replace("T", " ").slice(0, 19), t.token_id]);
|
|
151
|
+
db.run("UPDATE session_project_creates SET child_token_id=?1 WHERE request_id=?2", [t.token_id, r.request_id]); return t;
|
|
152
|
+
});
|
|
153
|
+
putPendingEnvBlob({ request_id: r.request_id, daemon_node_id: r.daemon_node_id, child_token: token.token!, child_token_id: token.token_id!, env_blob: {} });
|
|
154
|
+
return ok({ acknowledged: true });
|
|
155
|
+
}
|
|
156
|
+
return fail(404);
|
|
157
|
+
} catch { return fail(); }
|
|
158
|
+
};
|
|
159
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// One durable association per user/network intent AND per evidence request.
|
|
2
|
+
// A lost/failed check is not reusable: a new grant cannot bypass this journal.
|
|
3
|
+
export const sessionSourceAdmissionSchema = `CREATE TABLE IF NOT EXISTS session_source_admission_intents (
|
|
4
|
+
user_id TEXT NOT NULL, network_id TEXT NOT NULL, intent_id TEXT NOT NULL,
|
|
5
|
+
evidence_request_id TEXT NOT NULL UNIQUE, requester_token_id TEXT NOT NULL,
|
|
6
|
+
lease_id TEXT NOT NULL UNIQUE, recheck_request_id TEXT NOT NULL UNIQUE,
|
|
7
|
+
authorized_until INTEGER NOT NULL,
|
|
8
|
+
execution_guard TEXT NOT NULL CHECK(execution_guard='daemon_recheck_in_execution_context_required'),
|
|
9
|
+
child_name TEXT NOT NULL, state TEXT NOT NULL CHECK(state IN ('checking','reserved','refused')),
|
|
10
|
+
source_ref TEXT UNIQUE, create_request_id TEXT UNIQUE,
|
|
11
|
+
PRIMARY KEY(user_id,network_id,intent_id)
|
|
12
|
+
);`;
|
|
13
|
+
|
|
14
|
+
export const sessionSourceExecutionSchema = `CREATE TABLE IF NOT EXISTS session_source_executions (
|
|
15
|
+
execution_id TEXT PRIMARY KEY, admission_request_id TEXT NOT NULL UNIQUE,
|
|
16
|
+
task_json TEXT NOT NULL, user_id TEXT NOT NULL, requester_token_id TEXT NOT NULL, daemon_token_id TEXT NOT NULL,
|
|
17
|
+
state TEXT NOT NULL CHECK(state IN ('pending','claimed','session_ready','refused','unknown')),
|
|
18
|
+
session_id TEXT, result_json TEXT
|
|
19
|
+
);`;
|
|
20
|
+
|
|
21
|
+
export const sessionSourceDeliverySchema = `CREATE TABLE IF NOT EXISTS session_source_node_deliveries (
|
|
22
|
+
delivery_id TEXT PRIMARY KEY, execution_id TEXT NOT NULL UNIQUE, child_node_id TEXT NOT NULL UNIQUE,
|
|
23
|
+
child_name TEXT NOT NULL, token_id TEXT NOT NULL UNIQUE, expires_at INTEGER NOT NULL,
|
|
24
|
+
state TEXT NOT NULL CHECK(state IN ('pending','delivered','registered','unknown'))
|
|
25
|
+
);`;
|
|
26
|
+
|
|
27
|
+
export const sessionSourceTransportSchema = `CREATE TABLE IF NOT EXISTS session_source_transports (
|
|
28
|
+
request_id TEXT PRIMARY KEY, user_id TEXT NOT NULL, requester_token_id TEXT NOT NULL,
|
|
29
|
+
network_id TEXT NOT NULL, intent_id TEXT NOT NULL, source_node_id TEXT NOT NULL,
|
|
30
|
+
daemon_node_id TEXT NOT NULL, daemon_token_id TEXT NOT NULL, daemon_instance_id TEXT NOT NULL, session_id TEXT NOT NULL,
|
|
31
|
+
child_name TEXT NOT NULL, state TEXT NOT NULL, expires_at INTEGER NOT NULL,
|
|
32
|
+
evidence_id TEXT NOT NULL, execution_id TEXT, delivery_id TEXT, child_node_id TEXT, child_session_id TEXT,
|
|
33
|
+
UNIQUE(user_id,network_id,intent_id)
|
|
34
|
+
);`;
|
|
35
|
+
|
|
36
|
+
// Project-new is not a managed-source admission and has no source_ref. This
|
|
37
|
+
// durable intent/name reservation is never an ordinary create outbox.
|
|
38
|
+
export const sessionProjectCreateSchema = `CREATE TABLE IF NOT EXISTS session_project_creates (
|
|
39
|
+
request_id TEXT PRIMARY KEY, user_id TEXT NOT NULL, requester_token_id TEXT NOT NULL,
|
|
40
|
+
network_id TEXT NOT NULL, source_node_id TEXT NOT NULL, daemon_node_id TEXT NOT NULL,
|
|
41
|
+
daemon_token_id TEXT NOT NULL, daemon_instance_id TEXT NOT NULL, intent_id TEXT NOT NULL,
|
|
42
|
+
selection_scope TEXT NOT NULL, snapshot_id TEXT NOT NULL, project_id TEXT NOT NULL, child_name TEXT NOT NULL,
|
|
43
|
+
accepted_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, state TEXT NOT NULL,
|
|
44
|
+
session_id TEXT, child_node_id TEXT, child_token_id TEXT, credential_expires_at INTEGER,
|
|
45
|
+
UNIQUE(user_id,network_id,intent_id), UNIQUE(network_id,child_name)
|
|
46
|
+
);`;
|
|
47
|
+
|
|
48
|
+
/** Idempotent additive migration, including databases created before attach. */
|
|
49
|
+
export function migrateProjectOperationJournal(db: { dialect: string; all: Function; exec: Function }) {
|
|
50
|
+
if (db.dialect !== "sqlite") {
|
|
51
|
+
db.exec("ALTER TABLE session_project_creates ADD COLUMN IF NOT EXISTS operation_kind TEXT NOT NULL DEFAULT 'project_new_session'");
|
|
52
|
+
db.exec("ALTER TABLE session_project_creates ADD COLUMN IF NOT EXISTS selected_session_id TEXT");
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const columns = new Set(db.all("PRAGMA table_info(session_project_creates)").map((c: any) => c.name));
|
|
56
|
+
if (!columns.has("operation_kind")) db.exec("ALTER TABLE session_project_creates ADD COLUMN operation_kind TEXT NOT NULL DEFAULT 'project_new_session'");
|
|
57
|
+
if (!columns.has("selected_session_id")) db.exec("ALTER TABLE session_project_creates ADD COLUMN selected_session_id TEXT");
|
|
58
|
+
}
|