@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.
- package/build-info.json +2 -2
- package/package.json +1 -1
- package/src/agent-access-batch.test.ts +7 -2
- package/src/agent-acl-slice3-http.test.ts +4 -1
- package/src/agent-groups-perf.test.ts +6 -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 +47 -4
- 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 +890 -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 +368 -0
- package/src/task-not-found-error-domain.test.ts +4 -1
- package/src/token-usage-http.test.ts +10 -0
- package/src/tool-audience-http.test.ts +18 -0
- package/src/tool-audience.ts +1 -1
- package/src/tools.ts +154 -51
|
@@ -233,3 +233,40 @@ describe("#1545 report_status 子对象的 strict 分布(注释里那张表的
|
|
|
233
233
|
expect(results.filter(r => r === "rejected").length).toBeGreaterThan(0);
|
|
234
234
|
});
|
|
235
235
|
});
|
|
236
|
+
|
|
237
|
+
/** #4150 — the source directory/attach/fork previews read these four capability
|
|
238
|
+
* literals off this same snapshot. zod objects here are non-strict, so a field
|
|
239
|
+
* missing from the schema is dropped silently and the transport answers 403
|
|
240
|
+
* forever (observed on the upgraded production hub). */
|
|
241
|
+
describe("#4150 source direct/attach/fork capabilities survive report_status", () => {
|
|
242
|
+
const caps = () => schemas.report_status.config_snapshot;
|
|
243
|
+
|
|
244
|
+
test("the four transport capabilities are preserved verbatim", () => {
|
|
245
|
+
const parsed = caps().parse({
|
|
246
|
+
flags: {}, config_update_capable: false, peer_reply_inbox_capable: true,
|
|
247
|
+
daemon_capabilities: {
|
|
248
|
+
source_directory_read: "source-directory-read-v1-opencode-2.0.22",
|
|
249
|
+
project_new_session: "project-new-session-v1-opencode-2.0.22",
|
|
250
|
+
session_attach: "existing-session-attach-v1-opencode-2.0.22",
|
|
251
|
+
source_fork_transport: "source-fork-transport-v1-opencode-2.0.22",
|
|
252
|
+
},
|
|
253
|
+
});
|
|
254
|
+
expect(parsed.daemon_capabilities.source_directory_read).toBe("source-directory-read-v1-opencode-2.0.22");
|
|
255
|
+
expect(parsed.daemon_capabilities.project_new_session).toBe("project-new-session-v1-opencode-2.0.22");
|
|
256
|
+
expect(parsed.daemon_capabilities.session_attach).toBe("existing-session-attach-v1-opencode-2.0.22");
|
|
257
|
+
expect(parsed.daemon_capabilities.source_fork_transport).toBe("source-fork-transport-v1-opencode-2.0.22");
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
test("an older or mismatched value degrades to absent, never rejecting the report", () => {
|
|
261
|
+
const parsed = caps().parse({
|
|
262
|
+
flags: {}, config_update_capable: false, peer_reply_inbox_capable: true,
|
|
263
|
+
daemon_capabilities: {
|
|
264
|
+
source_directory_read: "source-directory-read-v0-old",
|
|
265
|
+
source_fork_transport: 42, can_create_nodes: true,
|
|
266
|
+
},
|
|
267
|
+
});
|
|
268
|
+
expect(parsed.daemon_capabilities.source_directory_read).toBeUndefined();
|
|
269
|
+
expect(parsed.daemon_capabilities.source_fork_transport).toBeUndefined();
|
|
270
|
+
expect(parsed.daemon_capabilities.can_create_nodes).toBe(true);
|
|
271
|
+
});
|
|
272
|
+
});
|
|
@@ -89,6 +89,15 @@ async function connect(id: Identity) {
|
|
|
89
89
|
beforeEach(() => { cleanup(); seedWorld(); });
|
|
90
90
|
afterAll(cleanup);
|
|
91
91
|
|
|
92
|
+
test("variant config update rejects a target from another network over MCP", async () => {
|
|
93
|
+
const u = await connect(asUser);
|
|
94
|
+
try {
|
|
95
|
+
const result = await u.call("update_node_config", { node_id: OTHER_NODE_ID, base_revision: 0, patch: { modelVariant: "high" } });
|
|
96
|
+
expect(result).toMatchObject({ ok: false, error: "cross_network_node" });
|
|
97
|
+
expect(db.get<{ n: number }>("SELECT count(*) AS n FROM node_config_updates WHERE node_id = ?1", OTHER_NODE_ID)?.n).toBe(0);
|
|
98
|
+
} finally { await u.close(); }
|
|
99
|
+
}, 20_000);
|
|
100
|
+
|
|
92
101
|
describe("app#225 rules file — schema has no path", () => {
|
|
93
102
|
test("read/write tool inputs are node id + content only; no path / file_name / dir field anywhere", async () => {
|
|
94
103
|
// 🔴 不走 client.listTools():main 上 report_status / send_desktop_message /
|
package/src/server.ts
CHANGED
|
@@ -117,6 +117,7 @@ import { enforceImpactOf, normalizePeerAllowlist, normalizeToolAllowlist, restAl
|
|
|
117
117
|
import { labelRoute, mcpRouteLabel, recordRouteTiming, routeStats, setRouteCallerMasterToken, setRouteCallerTokenReader } from "./route-timing.js";
|
|
118
118
|
import { handleExternalScheduleEditRequest } from "./external-schedule-edits.js";
|
|
119
119
|
import { createNodeSessionControlRelay } from "./node-session-control.js";
|
|
120
|
+
import { createSessionSourceTransport } from "./session-source-transport.js";
|
|
120
121
|
import { recordDeliveredStaleEvents } from "./task-lifecycle-watcher.js";
|
|
121
122
|
import { SIDE_THREAD_FEATURE_FLAG, SideThreadCoordinator, SideThreadPortRegistry, SideThreadStore, type SideThreadActor, type SideThreadAttachmentRef, type SideThreadExecutionPort } from "./side-thread.js";
|
|
122
123
|
import { handleSideThreadHttpRequest } from "./side-thread-http.js";
|
|
@@ -2032,6 +2033,8 @@ function patrolDeliveredStaleTasks(): void {
|
|
|
2032
2033
|
// would swallow a legitimate `0`. Same for hostname.
|
|
2033
2034
|
export function bootServer(opts?: { port?: number; hostname?: string }): ReturnType<typeof Bun.serve> {
|
|
2034
2035
|
const nodeSessionControl = createNodeSessionControlRelay();
|
|
2036
|
+
const sessionSourceTransport = createSessionSourceTransport({ enabled: process.env.COMMHUB_SOURCE_FORK_PREVIEW === "1",
|
|
2037
|
+
directoryEnabled: process.env.COMMHUB_SOURCE_DIRECTORY_PREVIEW === "1", projectEnabled: process.env.COMMHUB_PROJECT_NEW_SESSION_PREVIEW === "1" });
|
|
2035
2038
|
return Bun.serve({
|
|
2036
2039
|
port: opts?.port ?? PORT,
|
|
2037
2040
|
hostname: opts?.hostname ?? HOST,
|
|
@@ -4051,6 +4054,8 @@ return Bun.serve({
|
|
|
4051
4054
|
});
|
|
4052
4055
|
if (externalScheduleEditResponse) return withCors(req, externalScheduleEditResponse);
|
|
4053
4056
|
|
|
4057
|
+
const sourceResponse = await sessionSourceTransport(req, url);
|
|
4058
|
+
if (sourceResponse) return withCors(req, sourceResponse);
|
|
4054
4059
|
const sessionControlResponse = await nodeSessionControl(req, url);
|
|
4055
4060
|
if (sessionControlResponse) return withCors(req, sessionControlResponse);
|
|
4056
4061
|
|
|
@@ -6409,7 +6414,20 @@ return Bun.serve({
|
|
|
6409
6414
|
// 且 denied 分支在上面统一 return 403。**不要**再在这里自己查一次网络:
|
|
6410
6415
|
// 上一版调了一个本文件里不存在的 `getNetworkId()` ⇒ 这个端点自 .273 上线起一直 500,
|
|
6411
6416
|
// 而所有人都只会看到「空了」,不会看到「坏了」。(#3951 由 HTTP 测试抓出)
|
|
6412
|
-
|
|
6417
|
+
// 与 catalog 端点(/api/providers 等)**同一口径**:显式给了就用,没给就回退到
|
|
6418
|
+
// 「唯一所属网络」,多个/零个才 400。上一版只认 restScope.networkId,
|
|
6419
|
+
// 于是一个只属于一个网络的用户在这里拿到 400、在同一页的 /api/providers 上拿到 200 ——
|
|
6420
|
+
// 相邻两个端点对同一用户给不同答案,客户端被迫多写一条分支。
|
|
6421
|
+
// 三档,按"信息量从高到低"取:
|
|
6422
|
+
// ① restScope.networkId —— 显式参数 / 节点绑定 / 管理员指定
|
|
6423
|
+
// ② restScope.networkIds 长度==1 —— 普通用户只属于一个网络
|
|
6424
|
+
// ③ 以上都拿不到时,退回「这个**人**自己所属的网络」再判一次唯一性
|
|
6425
|
+
// 为什么需要 ③:authCtx 为 null(无鉴权/遗留全局模式)时 resolveRestNetworkScope
|
|
6426
|
+
// 会返回 {networkId: requested||null, networkIds: null} —— 那不是「属于所有网络」,
|
|
6427
|
+
// 而是「这份 scope 没带成员信息」。此时若直接 400,唯一所属网络的用户会被拒,
|
|
6428
|
+
// 而同一页的 /api/providers 却放行。
|
|
6429
|
+
const scopeIds = restScope.networkIds ?? (restScope.networkId ? null : getUserNetworkIds(resolved.user.user_id));
|
|
6430
|
+
const netId = restScope.networkId ?? (scopeIds && scopeIds.length === 1 ? scopeIds[0] : null);
|
|
6413
6431
|
if (!netId) return withCors(req, Response.json({ ok: false, error: "network_required" }, { status: 400 }));
|
|
6414
6432
|
const raw = Number(url.searchParams.get("since_hours") ?? 24);
|
|
6415
6433
|
const sinceHours = Number.isFinite(raw) ? Math.max(1, Math.min(24 * 90, Math.floor(raw))) : 24;
|
|
@@ -6462,6 +6480,14 @@ return Bun.serve({
|
|
|
6462
6480
|
network_id: node.network_id,
|
|
6463
6481
|
config_revision: node.config_revision || 0,
|
|
6464
6482
|
model: snapshot.model ?? null,
|
|
6483
|
+
...(typeof snapshot.model_effective === "string" ? { model_effective: snapshot.model_effective } : {}),
|
|
6484
|
+
...(Object.prototype.hasOwnProperty.call(snapshot, "modelVariant") ? { modelVariant: snapshot.modelVariant } : {}),
|
|
6485
|
+
// Agent (Build): the live session's agent, plus whether this node can
|
|
6486
|
+
// switch it at all. Absent key = node never reported (not "build").
|
|
6487
|
+
opencode_agent_config_capable: snapshot.opencode_agent_config_capable === true,
|
|
6488
|
+
...(typeof snapshot.opencode_agent_current === "string" ? { agent: snapshot.opencode_agent_current } : {}),
|
|
6489
|
+
...(Array.isArray(snapshot.opencode_agents) ? { agents: snapshot.opencode_agents } : {}),
|
|
6490
|
+
opencode_variant_config_capable: snapshot.opencode_variant_config_capable === true,
|
|
6465
6491
|
flags: snapshot.flags ?? {},
|
|
6466
6492
|
config_update_capable: snapshot.config_update_capable ?? false,
|
|
6467
6493
|
// null = 这个节点从来没有被下发过配置(与「下发过但还没终局」是两件事)
|
|
@@ -7055,6 +7081,12 @@ return Bun.serve({
|
|
|
7055
7081
|
let opencodeMode: string | null = null;
|
|
7056
7082
|
let opencodeServer: string | null = null;
|
|
7057
7083
|
const snap = r.config_snapshot;
|
|
7084
|
+
// #4150-Build — declared outside the `if (snap)` block: the projection below is
|
|
7085
|
+
// evaluated for every row, and a block-scoped `let` here made /api/nodes throw
|
|
7086
|
+
// "opencodeAgents is not defined" on the deployed hub.
|
|
7087
|
+
let opencodeAgents: string[] | null = null;
|
|
7088
|
+
let opencodeAgentsSeenAt: string | null = null;
|
|
7089
|
+
let opencodeAgentCurrent: string | null = null;
|
|
7058
7090
|
if (snap) {
|
|
7059
7091
|
let parsed: any = null;
|
|
7060
7092
|
try { parsed = typeof snap === "string" ? JSON.parse(snap) : snap; }
|
|
@@ -7075,6 +7107,17 @@ return Bun.serve({
|
|
|
7075
7107
|
// PR #1092 之前从 `node.config_snapshot` 读,但这个端点**刻意不带整个快照**
|
|
7076
7108
|
// (见上方 #312 注释)⇒ 真机上两行是空的/整行不出现。这里只放三个标量出来,
|
|
7077
7109
|
// 仍不暴露 flags 里的其它内容,更不暴露任何凭据。
|
|
7110
|
+
// #4150-Build — agents this node's server exposes; [] means none configured.
|
|
7111
|
+
const rawAgents = parsed?.opencode_agents;
|
|
7112
|
+
if (Array.isArray(rawAgents) && rawAgents.every((a: unknown) => typeof a === "string" && a.length <= 200)) {
|
|
7113
|
+
opencodeAgents = rawAgents.slice(0, 200);
|
|
7114
|
+
const seenAgents = parsed?.opencode_agents_seen_at;
|
|
7115
|
+
opencodeAgentsSeenAt = typeof seenAgents === "string" && seenAgents.length > 0 && seenAgents.length <= 40 ? seenAgents : null;
|
|
7116
|
+
}
|
|
7117
|
+
const rawAgentCurrent = parsed?.opencode_agent_current;
|
|
7118
|
+
if (typeof rawAgentCurrent === "string" && rawAgentCurrent.length > 0 && rawAgentCurrent.length <= 200) {
|
|
7119
|
+
opencodeAgentCurrent = rawAgentCurrent;
|
|
7120
|
+
}
|
|
7078
7121
|
const flags = parsed?.flags;
|
|
7079
7122
|
if (flags?.opencodeGeneration === "v1" || flags?.opencodeGeneration === "v2") opencodeGeneration = flags.opencodeGeneration;
|
|
7080
7123
|
if (typeof flags?.opencodeMode === "string" && flags.opencodeMode.length <= 32) opencodeMode = flags.opencodeMode;
|
|
@@ -7097,6 +7140,9 @@ return Bun.serve({
|
|
|
7097
7140
|
attrs_revision: Number(r.attrs_revision ?? 0),
|
|
7098
7141
|
role,
|
|
7099
7142
|
opencode_catalog: opencodeCatalog,
|
|
7143
|
+
opencode_agents: opencodeAgents,
|
|
7144
|
+
opencode_agent_current: opencodeAgentCurrent,
|
|
7145
|
+
opencode_agents_seen_at: opencodeAgentsSeenAt,
|
|
7100
7146
|
// 见上:null 表示 daemon 未上报;非 null 是它自己给的采集时刻
|
|
7101
7147
|
opencode_catalog_seen_at: opencodeCatalogSeenAt,
|
|
7102
7148
|
opencode_generation: opencodeGeneration,
|
|
@@ -7705,6 +7751,3 @@ export function hostDiskState(): { path: string; total_gb: number; used_gb: numb
|
|
|
7705
7751
|
return null;
|
|
7706
7752
|
}
|
|
7707
7753
|
}
|
|
7708
|
-
|
|
7709
|
-
|
|
7710
|
-
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { Database } from "bun:sqlite";
|
|
3
|
+
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { SQLiteAdapter } from "./db-adapter";
|
|
7
|
+
import { createSessionForkStore, type ForkEntry } from "./session-fork-store";
|
|
8
|
+
|
|
9
|
+
test("fork journal persists intent and prevents two independent connections claiming the same write", () => {
|
|
10
|
+
const root = mkdtempSync(join(tmpdir(), "fork590-store-"));
|
|
11
|
+
const file = join(root, "journal.db");
|
|
12
|
+
const a = new SQLiteAdapter(new Database(file));
|
|
13
|
+
let b = new SQLiteAdapter(new Database(file));
|
|
14
|
+
try {
|
|
15
|
+
const source = readFileSync(new URL("./db.ts", import.meta.url), "utf8");
|
|
16
|
+
const schema = source.match(/db\.exec\(`(CREATE TABLE IF NOT EXISTS session_fork_requests[\s\S]*?)`\);/)?.[1];
|
|
17
|
+
expect(schema).toBeDefined(); a.exec(schema!);
|
|
18
|
+
const first = createSessionForkStore(a), second = createSessionForkStore(b);
|
|
19
|
+
const e: ForkEntry = { request_id: "fk_test_one", intent_id: "intent_one", operation: "fork",
|
|
20
|
+
networkId: "net_one", nodeId: "node_one", tokenId: "token_row", requester: "user_token_row", requesterUser: "user_one",
|
|
21
|
+
session_id: "ses_source", binding_id: "generation_one", expires_at: 1000, status: "pending" };
|
|
22
|
+
expect(first.reserve(e).request_id).toBe(e.request_id);
|
|
23
|
+
expect(second.reserve({ ...e, request_id: "fk_duplicate" }).request_id).toBe(e.request_id);
|
|
24
|
+
expect(() => second.reserve({ ...e, request_id: "fk_busy", intent_id: "another_intent" })).toThrow();
|
|
25
|
+
expect(second.intent("user_other", e.networkId, e.intent_id)).toBeUndefined();
|
|
26
|
+
expect(first.claim(e, 999)).toBe(true);
|
|
27
|
+
expect(second.claim(e, 999)).toBe(false);
|
|
28
|
+
// Reopen the actual file, not just a new facade over the same connection.
|
|
29
|
+
b.close(); b = new SQLiteAdapter(new Database(file));
|
|
30
|
+
const restarted = createSessionForkStore(b);
|
|
31
|
+
expect(restarted.get(e.request_id)?.status).toBe("in_progress");
|
|
32
|
+
expect(restarted.claim(e, 999)).toBe(false);
|
|
33
|
+
expect(restarted.settle({ ...e, status: "unknown", error: "session_fork_outcome_unknown" }, "in_progress").status).toBe("unknown");
|
|
34
|
+
expect(first.settle({ ...e, status: "done", result: { session_id: "ses_child" } }, "in_progress").status).toBe("unknown");
|
|
35
|
+
expect(first.reserve({ ...e, request_id: "fk_after_unknown" }).status).toBe("unknown");
|
|
36
|
+
expect(first.claim(e, 999)).toBe(false);
|
|
37
|
+
const next = { ...e, request_id: "fk_next", intent_id: "intent_next" };
|
|
38
|
+
expect(first.reserve(next).status).toBe("pending");
|
|
39
|
+
expect(first.claim(next, 1000)).toBe(false);
|
|
40
|
+
expect(first.settle({ ...next, status: "expired", error: "session_control_request_expired" }, "pending").status).toBe("expired");
|
|
41
|
+
expect(first.active()).toEqual([]);
|
|
42
|
+
} finally { a.close(); b.close(); rmSync(root, { recursive: true, force: true }); }
|
|
43
|
+
});
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { DbAdapter } from "./db-adapter";
|
|
2
|
+
|
|
3
|
+
export type ForkEntry = {
|
|
4
|
+
request_id: string; intent_id: string; operation: "fork";
|
|
5
|
+
networkId: string; nodeId: string; tokenId: string; requester: string; requesterUser: string;
|
|
6
|
+
session_id: string; binding_id: string; expires_at: number;
|
|
7
|
+
status: "pending" | "in_progress" | "done" | "failed" | "unknown" | "expired";
|
|
8
|
+
result?: { session_id: string }; error?: string;
|
|
9
|
+
};
|
|
10
|
+
const columns = `request_id,intent_id,network_id,node_id,token_id,requester_token_id,
|
|
11
|
+
requester_user_id,session_id,binding_id,expires_at,status,result_session_id,error`;
|
|
12
|
+
function decode(r: any): ForkEntry | undefined {
|
|
13
|
+
if (!r) return;
|
|
14
|
+
return { request_id: r.request_id, intent_id: r.intent_id, operation: "fork",
|
|
15
|
+
networkId: r.network_id, nodeId: r.node_id, tokenId: r.token_id,
|
|
16
|
+
requester: r.requester_token_id, requesterUser: r.requester_user_id,
|
|
17
|
+
session_id: r.session_id, binding_id: r.binding_id, expires_at: Number(r.expires_at), status: r.status,
|
|
18
|
+
...(r.result_session_id === null ? {} : { result: { session_id: r.result_session_id } }),
|
|
19
|
+
...(r.error === null ? {} : { error: r.error }) };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** No token values or prompts. CAS claims never return to pending, including
|
|
23
|
+
* after timeout, ACK loss, restart or another store instance reading the row. */
|
|
24
|
+
export function createSessionForkStore(db: DbAdapter) {
|
|
25
|
+
const get = (requestId: string) => decode(db.get(`SELECT ${columns} FROM session_fork_requests WHERE request_id=?1`, requestId));
|
|
26
|
+
return {
|
|
27
|
+
get,
|
|
28
|
+
intent(userId: string, networkId: string, intentId: string) {
|
|
29
|
+
return decode(db.get(`SELECT ${columns} FROM session_fork_requests WHERE requester_user_id=?1 AND network_id=?2 AND intent_id=?3`, userId, networkId, intentId));
|
|
30
|
+
},
|
|
31
|
+
active(): ForkEntry[] {
|
|
32
|
+
return db.all(`SELECT ${columns} FROM session_fork_requests WHERE status IN ('pending','in_progress')`).map(r => decode(r)!);
|
|
33
|
+
},
|
|
34
|
+
reserve(e: ForkEntry): ForkEntry {
|
|
35
|
+
db.run(`INSERT INTO session_fork_requests (${columns}) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'pending',NULL,NULL)
|
|
36
|
+
ON CONFLICT(requester_user_id,network_id,intent_id) DO NOTHING`,
|
|
37
|
+
[e.request_id,e.intent_id,e.networkId,e.nodeId,e.tokenId,e.requester,e.requesterUser,e.session_id,e.binding_id,e.expires_at]);
|
|
38
|
+
return decode(db.get(`SELECT ${columns} FROM session_fork_requests WHERE requester_user_id=?1 AND network_id=?2 AND intent_id=?3`, e.requesterUser,e.networkId,e.intent_id))!;
|
|
39
|
+
},
|
|
40
|
+
claim(e: ForkEntry, now: number): boolean {
|
|
41
|
+
return db.run(`UPDATE session_fork_requests SET status='in_progress' WHERE request_id=?1 AND status='pending' AND expires_at>?2`, [e.request_id,now]).changes === 1;
|
|
42
|
+
},
|
|
43
|
+
settle(e: ForkEntry, previous: "pending" | "in_progress"): ForkEntry {
|
|
44
|
+
if (e.status === "pending" || e.status === "in_progress") throw Error("fork_transition_invalid");
|
|
45
|
+
if (previous === "pending" && e.status !== "expired" && e.status !== "failed") throw Error("fork_transition_invalid");
|
|
46
|
+
db.run(`UPDATE session_fork_requests SET status=?1,result_session_id=?2,error=?3 WHERE request_id=?4 AND status=?5`,
|
|
47
|
+
[e.status,e.result?.session_id ?? null,e.error ?? null,e.request_id,previous]);
|
|
48
|
+
return get(e.request_id)!;
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { test, expect } from "bun:test";
|
|
2
|
+
import { Database } from "bun:sqlite";
|
|
3
|
+
import { mkdtempSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { sessionProjectCreateSchema, migrateProjectOperationJournal } from "./session-source-admission-store";
|
|
6
|
+
|
|
7
|
+
test("actual old on-disk journal migrates twice and keeps new-session rows and intent tombstones", () => {
|
|
8
|
+
const path = join(mkdtempSync("/work/attach-migration-"), "old.db");
|
|
9
|
+
let sql = new Database(path);
|
|
10
|
+
sql.exec(sessionProjectCreateSchema);
|
|
11
|
+
sql.run(`INSERT INTO session_project_creates
|
|
12
|
+
(request_id,user_id,requester_token_id,network_id,source_node_id,daemon_node_id,daemon_token_id,daemon_instance_id,
|
|
13
|
+
intent_id,selection_scope,snapshot_id,project_id,child_name,accepted_at,expires_at,state,session_id)
|
|
14
|
+
VALUES ('old','u','t','n','s','d','dt','di','intent','scope','snap','oprj_old','child',1,2,'unknown_rotation_required','ses_Old')`);
|
|
15
|
+
sql.close(); sql = new Database(path);
|
|
16
|
+
const adapter = { dialect: "sqlite", all: (q: string) => sql.query(q).all(), exec: (q: string) => sql.exec(q) };
|
|
17
|
+
migrateProjectOperationJournal(adapter); migrateProjectOperationJournal(adapter);
|
|
18
|
+
expect(sql.query("SELECT operation_kind,selected_session_id,project_id,session_id,state FROM session_project_creates").get()).toEqual({
|
|
19
|
+
operation_kind: "project_new_session", selected_session_id: null, project_id: "oprj_old", session_id: "ses_Old", state: "unknown_rotation_required" });
|
|
20
|
+
expect(() => sql.run("INSERT INTO session_project_creates SELECT * FROM session_project_creates")).toThrow();
|
|
21
|
+
sql.close();
|
|
22
|
+
});
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Opt-in, exact SHA verified patched ELF. No new/fork acceptance rerun.
|
|
2
|
+
import { test, expect } from "bun:test";
|
|
3
|
+
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, symlinkSync, existsSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { createSessionSourceTransportWorker } from "../../agent-node/src/runtime/session-source-transport";
|
|
8
|
+
import { createSessionControlPin } from "../../agent-node/src/runtime/session-control-bridge";
|
|
9
|
+
import { observeHostSharedServe } from "../../agent-node/src/runtime/opencode-host-shared-observer";
|
|
10
|
+
import { SOURCE_DIRECTORY_CAPABILITY as DIR } from "../../contracts/session-source-directory";
|
|
11
|
+
import { PROJECT_CREATE_ROOT as P, SESSION_ATTACH_CAPABILITY as CAP } from "../../contracts/session-project-create";
|
|
12
|
+
|
|
13
|
+
const delegated = process.env.TEST4150_NATIVE_ATTACH_DERIVED === "1";
|
|
14
|
+
test.skipIf(!process.env.TEST4150_NATIVE_BINARY)(delegated ? "real patched Linux delegated policy -> one empty existing Session attach, exact CLI registration, zero native mutation" : "real patched Linux existing empty/materialized Session attach, occupied refusal, exact child register and zero attach native writes", async () => {
|
|
15
|
+
const root = mkdtempSync("/work/native-attach-"), home = join(root, "home"), project = join(root, "project"), daemonDir = join(root, "daemon");
|
|
16
|
+
for (const d of [home, project, daemonDir, join(home, ".anet"), join(project, ".anet"), join(project, ".anet", "nodes"), join(daemonDir, ".anet")]) mkdirSync(d, { mode: 0o700 });
|
|
17
|
+
process.env.COMMHUB_DB = join(root, "hub.db"); process.env.COMMHUB_SOURCE_DIRECTORY_PREVIEW = "1"; process.env.COMMHUB_SESSION_ATTACH_PREVIEW = "1";
|
|
18
|
+
delete process.env.COMMHUB_PROJECT_NEW_SESSION_PREVIEW; delete process.env.COMMHUB_SOURCE_FORK_PREVIEW;
|
|
19
|
+
let providerCalls = 0, stage = "start", attachWrites: string[] = [], fixtureWrites: string[] = [], preparing = true;
|
|
20
|
+
const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(r) {
|
|
21
|
+
providerCalls++; if (providerCalls > 4 || new URL(r.url).pathname !== "/v1/chat/completions" || r.method !== "POST") return new Response("refused", { status: 400 });
|
|
22
|
+
const body = await r.json() as any, base = { id: "chatcmpl-attach-fixture", created: 1, model: "test-model" };
|
|
23
|
+
if (!body.stream) return Response.json({ ...base, object: "chat.completion", choices: [{ index: 0, message: { role: "assistant", content: "ATTACH_FIXTURE_COMPLETE" }, finish_reason: "stop" }] });
|
|
24
|
+
return new Response([
|
|
25
|
+
{ ...base, object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "ATTACH_FIXTURE_COMPLETE" }, finish_reason: null }] },
|
|
26
|
+
{ ...base, object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 8, completion_tokens: 4, total_tokens: 12 } },
|
|
27
|
+
].map(c => `data: ${JSON.stringify(c)}\n\n`).join("") + "data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } });
|
|
28
|
+
} });
|
|
29
|
+
const configEnv = { OPENCODE_SERVER_PASSWORD: "attach-sandbox-only", OPENCODE_CONFIG_CONTENT: JSON.stringify({ model: "test-provider/test-model", enabled_providers: ["test-provider"],
|
|
30
|
+
provider: { "test-provider": { npm: "@ai-sdk/openai-compatible", options: { baseURL: `http://127.0.0.1:${provider.port}/v1`, apiKey: "synthetic" }, models: { "test-model": { name: "test-model", limit: { context: 128000, output: 16000 } } } } } }) };
|
|
31
|
+
const reservation = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("") }); const port = reservation.port; reservation.stop(true);
|
|
32
|
+
const url = `http://127.0.0.1:${port}`, binary = process.env.TEST4150_NATIVE_BINARY!, identity = process.env.TEST4150_NATIVE_IDENTITY!;
|
|
33
|
+
const native = spawn(binary, ["serve", "--hostname", "127.0.0.1", "--port", String(port)], { cwd: project, env: { ...process.env, ...configEnv, HOME: home }, stdio: ["ignore", "pipe", "pipe"] });
|
|
34
|
+
const originalFetch = globalThis.fetch;
|
|
35
|
+
let worker: ReturnType<typeof createSessionSourceTransportWorker> | undefined, hub: any, db: any;
|
|
36
|
+
globalThis.fetch = (async (input: any, init: any) => {
|
|
37
|
+
const u = new URL(typeof input === "string" || input instanceof URL ? String(input) : input.url), method = init?.method ?? input?.method ?? "GET";
|
|
38
|
+
if (u.origin === url && !["GET", "HEAD"].includes(method)) (preparing ? fixtureWrites : attachWrites).push(`${method} ${u.pathname}`);
|
|
39
|
+
const r = await originalFetch(input, init);
|
|
40
|
+
if (u.pathname === `${P}/child-register`) console.log("NATIVE_ATTACH_REGISTER_HTTP", r.status);
|
|
41
|
+
return r;
|
|
42
|
+
}) as typeof fetch;
|
|
43
|
+
const nativeApi = async (path: string, body?: object) => { const r = await fetch(url + path, { method: body ? "POST" : "GET", signal: AbortSignal.timeout(15000),
|
|
44
|
+
headers: { authorization: `Basic ${Buffer.from("opencode:attach-sandbox-only").toString("base64")}`, "content-type": "application/json", "x-opencode-directory": project },
|
|
45
|
+
...(body ? { body: JSON.stringify(body) } : {}) }); expect(r.ok).toBe(true); return r.status === 204 ? null : r.json() as any; };
|
|
46
|
+
try {
|
|
47
|
+
await new Promise<void>((resolve, reject) => { const t = setTimeout(() => reject(Error("native_start_timeout")), 15000); let text = "";
|
|
48
|
+
const onData = (b: Buffer) => { text = (text + String(b)).slice(-32768); if (text.includes(url)) { clearTimeout(t); resolve(); } };
|
|
49
|
+
native.stdout!.on("data", onData); native.stderr!.on("data", onData); native.once("exit", () => { clearTimeout(t); reject(Error("native_early_exit")); }); });
|
|
50
|
+
const info = await nativeApi("/api/info"); expect(info.version).toBe(identity); expect(info.pid).toBe(native.pid);
|
|
51
|
+
stage = "prepare-existing-sessions";
|
|
52
|
+
const empty = (await nativeApi("/api/session", { title: "Empty attach fixture", location: { directory: project } })).data.id;
|
|
53
|
+
const materialized = delegated ? empty : (await nativeApi("/api/session", { title: "Materialized attach fixture", location: { directory: project } })).data.id;
|
|
54
|
+
if (!delegated) {
|
|
55
|
+
await nativeApi(`/api/session/${materialized}/prompt`, { text: "Reply ATTACH_FIXTURE_COMPLETE, no tools.", resume: true });
|
|
56
|
+
const wait = await fetch(`${url}/api/experimental/session/${materialized}/wait`, { method: "POST", signal: AbortSignal.timeout(15000),
|
|
57
|
+
headers: { authorization: `Basic ${Buffer.from("opencode:attach-sandbox-only").toString("base64")}`, "x-opencode-directory": project } }); expect(wait.status).toBe(204);
|
|
58
|
+
}
|
|
59
|
+
const selectedIds = delegated ? [empty] : [empty, materialized];
|
|
60
|
+
const before = new Map<string, any>();
|
|
61
|
+
for (const id of selectedIds) before.set(id, { info: await nativeApi(`/api/session/${id}`), context: await nativeApi(`/api/session/${id}/context`) });
|
|
62
|
+
expect(before.get(empty).context.data).toEqual([]); if (!delegated) expect(JSON.stringify(before.get(materialized).context)).toContain("ATTACH_FIXTURE_COMPLETE");
|
|
63
|
+
console.log("NATIVE_ATTACH_FIXTURE", JSON.stringify({ emptyMessages: 0, materializedMessages: before.get(materialized).context.data.length, fixtureWrites, providerCalls }));
|
|
64
|
+
({ db } = await import("./db")); const { register, createNetworkTokenForNode } = await import("./auth"); register("attach_bootstrap", "Synthetic-Attach-4150!");
|
|
65
|
+
const human = register("attach_owner", "Synthetic-Attach-4150!"), net = human.network_id;
|
|
66
|
+
const daemon = createNetworkTokenForNode(human.user.user_id, net, "attach-daemon", "attach_daemon"); createNetworkTokenForNode(human.user.user_id, net, "attach-source", "attach_source");
|
|
67
|
+
db.run("UPDATE nodes SET runtime='opencode-cli', config_snapshot=?1 WHERE node_id='attach_source'", [JSON.stringify({ flags: { opencodeGeneration: "v2", opencodeMode: "copresence" } })]);
|
|
68
|
+
db.run("UPDATE nodes SET config_snapshot=?1 WHERE node_id='attach_daemon'", [JSON.stringify({ role: "host_supervisor", daemon_capabilities: { source_directory_read: DIR, session_attach: CAP } })]);
|
|
69
|
+
db.run("INSERT INTO sessions (resume_id,alias,node_id,network_id,env_transport,last_seen_at) VALUES ('attach_daemon','attach-daemon','attach_daemon',?1,'loopback',datetime('now'))", [net]);
|
|
70
|
+
writeFileSync(join(home, ".anet", "password"), "attach-sandbox-only", { mode: 0o600 });
|
|
71
|
+
writeFileSync(join(home, ".anet", "opencode-shared-server.json"), JSON.stringify({ url, passwordFile: join(home, ".anet", "password") }), { mode: 0o600 });
|
|
72
|
+
const observed = observeHostSharedServe(url); expect(observed.ok).toBe(true); if (!observed.ok) throw Error("native_observation_refused");
|
|
73
|
+
const serverId = `osrv_${randomUUID()}`;
|
|
74
|
+
const grants = selectedIds.map(session_id => ({ grant_id: randomUUID(), daemon_id: "attach_daemon", directory: project, session_id,
|
|
75
|
+
server_pid: observed.processEvidence.pid, server_start_ticks: observed.processEvidence.startTicks, expires_at: Date.now() + 180000 }));
|
|
76
|
+
const grantPath = join(daemonDir, ".anet", "opencode-directory-authorities.json");
|
|
77
|
+
const policy = { enabled: true, policy_id: randomUUID(), daemon_id: "attach_daemon", directories: [project], expires_at: Date.now() + 86400000, grant_ttl_ms: 120000 };
|
|
78
|
+
const writeGrants = () => writeFileSync(grantPath, JSON.stringify({ version: 1, grants: [{ server_id: serverId, network_id: net, source_node_id: "attach_source", directories: [project], opencode_unsafe_tools: true,
|
|
79
|
+
...(delegated ? { allow_attach_existing: policy } : { attach_sessions: grants }) }] }), { mode: 0o600 }); writeGrants();
|
|
80
|
+
if (delegated) { const text = readFileSync(grantPath, "utf8"); expect(text).not.toContain(empty); expect(text).not.toContain("server_pid"); expect(text).not.toContain("server_start_ticks"); }
|
|
81
|
+
const { bootServer } = await import("./server"); hub = bootServer({ hostname: "127.0.0.1", port: 0 }); const hubUrl = `http://127.0.0.1:${hub.port}`;
|
|
82
|
+
const pkg = join(root, "node_modules", "@sleep2agi", "agent-node"); mkdirSync(pkg, { recursive: true }); writeFileSync(join(pkg, "package.json"), readFileSync(join(import.meta.dir, "../../agent-node/package.json")));
|
|
83
|
+
for (const dep of ["@anthropic-ai", "@openai", "node-pty"]) symlinkSync(join(import.meta.dir, "../../agent-node/node_modules", dep), join(root, "node_modules", dep));
|
|
84
|
+
const built = await Bun.build({ entrypoints: [join(import.meta.dir, "../../agent-node/src/cli.ts")], outdir: join(pkg, "dist"), target: "bun", external: ["@anthropic-ai/claude-agent-sdk", "@openai/codex-sdk", "node-pty"] }); expect(built.success).toBe(true);
|
|
85
|
+
mkdirSync(join(root, "bin")); symlinkSync(binary, join(root, "bin", "opencode")); mkdirSync(join(root, "safe"), { mode: 0o700 });
|
|
86
|
+
const auditPath = join(root, "child-native-audit.jsonl");
|
|
87
|
+
worker = createSessionSourceTransportWorker({ hubUrl, home, daemonWorkDir: daemonDir, directoryEnabled: true, projectEnabled: false, attachEnabled: true, forkEnabled: false,
|
|
88
|
+
nativeLaunch: { command: process.execPath, argsPrefix: [join(import.meta.dir, "../../agent-network/bin/cli.ts")], timeoutMs: 12000,
|
|
89
|
+
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"), TEST4150_NATIVE_ORIGIN: url, TEST4150_NATIVE_AUDIT: auditPath } },
|
|
90
|
+
pin: createSessionControlPin({ hubUrl, token: daemon.token, nodeId: "attach_daemon", networkId: net, epoch: 0, currentEpoch: () => 0, currentToken: () => daemon.token, signal: new AbortController().signal }) });
|
|
91
|
+
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" }, ...(body ? { body: JSON.stringify(body) } : {}) }); expect(r.status).toBe(200); return r.json() as any; };
|
|
92
|
+
const D = "/api/node-session-control/source/directory", selection = { network_id: net, source_node_id: "attach_source", daemon_node_id: "attach_daemon" };
|
|
93
|
+
const snapshot = async () => { await worker!.tick(); const q = await api(D, selection); await worker!.tick(); const q2 = await api(D, { ...selection, selection_scope: q.request_id, server_id: serverId }); await worker!.tick(); return { q: q2, s: (await api(`${D}/${q2.request_id}?network_id=${net}`)).snapshot }; };
|
|
94
|
+
preparing = false; stage = "attach-existing"; const providerBeforeAttach = providerCalls;
|
|
95
|
+
const children: Array<{ id: string; health: any }> = [];
|
|
96
|
+
for (const [i, id] of selectedIds.entries()) {
|
|
97
|
+
const { q, s } = await snapshot(); expect(s.sessions).toHaveLength(selectedIds.length);
|
|
98
|
+
const selected = s.sessions.find((v: any) => v.title === (i === 0 ? "Empty attach fixture" : "Materialized attach fixture")); expect(selected).toBeDefined();
|
|
99
|
+
const intent = { selection_scope: q.request_id, snapshot_id: s.snapshot_id, session_id: selected.session_id, child_name: `attached-${i}`, intent_id: `attach-${i}` };
|
|
100
|
+
const receipt = await api(P, intent); await worker.tick(); const result = await api(`${P}/${receipt.request_id}?network_id=${net}`);
|
|
101
|
+
console.log("NATIVE_ATTACH_RECEIPT", JSON.stringify({ status: result.status, operation_kind: result.operation_kind, session_creation: result.session_creation }));
|
|
102
|
+
expect(result.status).toBe("registration_confirmed"); expect(result.session_creation).toBe("not_performed"); expect(result.registration_is_health).toBe(false);
|
|
103
|
+
const row = db.get("SELECT * FROM session_project_creates WHERE request_id=?1", receipt.request_id); expect(row.session_id).toBe(id);
|
|
104
|
+
const h = JSON.parse(readFileSync(join(project, ".anet", "nodes", `attached-${i}`, "source-resume-health.json"), "utf8")); expect(h.session_id).toBe(id); children.push({ id, health: h });
|
|
105
|
+
const tokens = db.get("SELECT COUNT(*) n FROM api_tokens").n; expect((await api(P, intent)).request_id).toBe(receipt.request_id); await worker.tick(); expect(db.get("SELECT COUNT(*) n FROM api_tokens").n).toBe(tokens);
|
|
106
|
+
expect(await nativeApi(`/api/session/${id}`)).toEqual(before.get(id).info); expect(await nativeApi(`/api/session/${id}/context`)).toEqual(before.get(id).context);
|
|
107
|
+
}
|
|
108
|
+
if (!delegated) {
|
|
109
|
+
stage = "occupied-refusal"; for (const grant of grants) grant.grant_id = randomUUID(); writeGrants(); const { q, s } = await snapshot();
|
|
110
|
+
const beforeTokens = db.get("SELECT COUNT(*) n FROM api_tokens").n;
|
|
111
|
+
const r = await api(P, { selection_scope: q.request_id, snapshot_id: s.snapshot_id, session_id: s.sessions[0].session_id, child_name: "occupied-attempt", intent_id: "occupied" }); await worker.tick();
|
|
112
|
+
expect((await api(`${P}/${r.request_id}?network_id=${net}`)).status).toBe("unknown_rotation_required"); expect(db.get("SELECT COUNT(*) n FROM api_tokens").n).toBe(beforeTokens);
|
|
113
|
+
}
|
|
114
|
+
for (const c of children) expect(() => process.kill(c.health.pid, 0)).not.toThrow();
|
|
115
|
+
await worker.stop(); for (const c of children) { expect(() => process.kill(c.health.pid, 0)).toThrow(); expect(await nativeApi(`/api/session/${c.id}/context`)).toEqual(before.get(c.id).context); }
|
|
116
|
+
expect((await nativeApi("/api/info")).pid).toBe(native.pid); expect(providerCalls).toBe(providerBeforeAttach); expect(attachWrites).toEqual([]);
|
|
117
|
+
const audit = existsSync(auditPath) ? readFileSync(auditPath, "utf8").trim().split("\n").filter(Boolean).map(l => JSON.parse(l)) : []; expect(audit.length).toBeGreaterThan(0); expect(audit.filter(v => v.method !== "GET")).toEqual([]);
|
|
118
|
+
console.log("NATIVE_ATTACH_ACCEPTANCE", JSON.stringify({ identity, stock: false, delegated, fixtureWrites, providerCalls, attachWrites, childWrites: 0, registeredChildren: children.length, occupiedRefused: !delegated, preservedContext: true, sameServer: true, childStopPreservedSessions: true, platform: "linux" }));
|
|
119
|
+
} catch (e) { console.error("NATIVE_ATTACH_FIRST_FAILURE", JSON.stringify({ stage, fixtureWrites, attachWrites, providerCalls })); throw e; }
|
|
120
|
+
finally { await worker?.stop(); globalThis.fetch = originalFetch; hub?.stop(true); provider.stop(true); if (native.exitCode === null && native.signalCode === null) { native.kill("SIGTERM"); await new Promise<void>(resolve => { const t = setTimeout(() => { native.kill("SIGKILL"); resolve(); }, 1500); native.once("exit", () => { clearTimeout(t); resolve(); }); }); } db?.close(); }
|
|
121
|
+
}, 60000);
|