@sleep2agi/commhub-server 0.9.0-preview.250 → 0.9.0-preview.252
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/build-commit-report-http.test.ts +103 -0
- package/src/db.ts +5 -0
- package/src/expiry-counters.test.ts +38 -8
- package/src/expiry-counters.ts +25 -6
- package/src/file-download-authz.test.ts +2 -2
- package/src/health-redaction.test.ts +1 -1
- package/src/http-gzip.test.ts +1 -1
- package/src/observer-avatar-http.test.ts +2 -2
- package/src/serve-error.test.ts +1 -1
- package/src/server.ts +20 -2
- package/src/task-expiry-notice-http.test.ts +13 -2
- package/src/tools.ts +11 -1
package/build-info.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/commhub-server",
|
|
3
|
-
"version": "0.9.0-preview.
|
|
3
|
+
"version": "0.9.0-preview.252",
|
|
4
4
|
"description": "CommHub Server — AI Agent communication hub with MCP protocol, multi-network isolation, user auth, and MCP tools (17 collaboration-core + node/provider ops tools; authoritative list: docs-site/docs/api/mcp-tools.md).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.ts",
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// #3294 —— 节点侧的**字节标识**:report_status 收 build_commit ⇒ /api/nodes 投影可见。
|
|
2
|
+
//
|
|
3
|
+
// 为什么不是「加一列就完了」:Hub 的 report_status schema 对**不认识的键是静默丢弃**的
|
|
4
|
+
// (源码里那段 #1545 注释写得很清楚)。所以这条链路必须三处同时成立:
|
|
5
|
+
// ① schema 里有这个键(否则 zod 丢掉)
|
|
6
|
+
// ② 写路径把它落库(否则写不进去)
|
|
7
|
+
// ③ 读路径把它投影出来(否则界面上看不见)
|
|
8
|
+
// 少任何一处,现场表现都是「节点明明发了、hub 上没有」,与 daemon 侧 bug 一模一样。
|
|
9
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
10
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { register, createNetworkTokenForNode } from "./auth.js";
|
|
14
|
+
import { db } from "./db.js";
|
|
15
|
+
|
|
16
|
+
const DIR = mkdtempSync(join(tmpdir(), "anet-build-commit-"));
|
|
17
|
+
const STAMP = Date.now();
|
|
18
|
+
let BASE = "";
|
|
19
|
+
let hub: any = null;
|
|
20
|
+
let USER = "";
|
|
21
|
+
let NET = "";
|
|
22
|
+
let ntok = "";
|
|
23
|
+
let ALIAS = "";
|
|
24
|
+
const PW = "BuildCommitPassw0rd!x";
|
|
25
|
+
const COMMIT = "0123456789abcdef0123456789abcdef01234567"; // 40 hex,固定值便于断言
|
|
26
|
+
|
|
27
|
+
const auth = (t: string) => ({ Authorization: `Bearer ${t}` });
|
|
28
|
+
|
|
29
|
+
async function rpc(method: string, params: any, token = ntok) {
|
|
30
|
+
const res = await fetch(`${BASE}/mcp`, {
|
|
31
|
+
method: "POST",
|
|
32
|
+
headers: { ...auth(token), "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
|
|
33
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: method, arguments: params } }),
|
|
34
|
+
});
|
|
35
|
+
const raw = await res.text();
|
|
36
|
+
const line = raw.split("\n").find((l) => l.startsWith("data: "));
|
|
37
|
+
const env = JSON.parse(line ? line.slice(6) : raw);
|
|
38
|
+
try { return JSON.parse(env.result.content[0].text); } catch { return { ok: false, raw }; }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function nodes(token = ntok) {
|
|
42
|
+
const res = await fetch(`${BASE}/api/nodes?network_id=${NET}`, { headers: auth(token) });
|
|
43
|
+
return (await res.json()) as any;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
beforeAll(async () => {
|
|
47
|
+
process.env.COMMHUB_DB ||= join(DIR, "hub.db");
|
|
48
|
+
process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
|
|
49
|
+
process.env.HOST = "127.0.0.1";
|
|
50
|
+
USER = `bc_user_${STAMP}`;
|
|
51
|
+
ALIAS = `bc-node-${STAMP}`;
|
|
52
|
+
const reg = register(USER, PW);
|
|
53
|
+
NET = reg.network_id!;
|
|
54
|
+
const minted = createNetworkTokenForNode(reg.user!.user_id, NET, ALIAS, `node_bc_${STAMP}`);
|
|
55
|
+
expect(minted.ok).toBe(true);
|
|
56
|
+
ntok = minted.token!;
|
|
57
|
+
const mod: any = await import("./server.js");
|
|
58
|
+
hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
59
|
+
BASE = `http://127.0.0.1:${hub.port}`;
|
|
60
|
+
}, 30_000);
|
|
61
|
+
|
|
62
|
+
afterAll(() => {
|
|
63
|
+
try { hub?.stop?.(true); } catch {}
|
|
64
|
+
try { rmSync(DIR, { recursive: true, force: true }); } catch {}
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
function report(extra: Record<string, unknown> = {}) {
|
|
68
|
+
return rpc("report_status", {
|
|
69
|
+
resume_id: `resume_bc_${STAMP}`, alias: ALIAS, status: "idle",
|
|
70
|
+
version: "2.5.0-preview.169", node_id: `node_bc_${STAMP}`, network_id: NET, ...extra,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
describe("#3294 节点上报 build_commit 的三段链路", () => {
|
|
75
|
+
// 顺序是有意的:先没有、再有、再坏。同一行节点,三个阶段各读一次。
|
|
76
|
+
test("① 没报 ⇒ null,且 note 说明「这不是缺陷」", async () => {
|
|
77
|
+
// 老节点不报这个字段;把「没报」与「没有标识」压成同一个 null 会让人去查错方向,
|
|
78
|
+
// 所以投影里同时给一个 note。
|
|
79
|
+
expect((await report()).ok).toBe(true);
|
|
80
|
+
const row = (await nodes()).nodes.find((n: any) => n.alias === ALIAS);
|
|
81
|
+
expect(row).toBeDefined();
|
|
82
|
+
expect(row.build_commit).toBeNull();
|
|
83
|
+
expect(typeof row.build_note).toBe("string");
|
|
84
|
+
expect(row.build_note).toContain("没有上报");
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("② 🔴 报了 ⇒ 落库 ⇒ /api/nodes 投影里读得到,且与 version 是两个东西", async () => {
|
|
88
|
+
expect((await report({ build_commit: COMMIT })).ok).toBe(true);
|
|
89
|
+
const row = (await nodes()).nodes.find((n: any) => n.alias === ALIAS);
|
|
90
|
+
expect(row.build_commit).toBe(COMMIT);
|
|
91
|
+
// ⚠️ `/api/nodes` 的投影里**没有** version 这一列(实测:拿到的 row.version 是 undefined)。
|
|
92
|
+
// 所以「两个东西」这句不能靠对比 row.version 来断言 —— 那会变成在测一个不存在的字段。
|
|
93
|
+
// 用上报时的字面量比:字节标识不可能是版本标签。
|
|
94
|
+
expect(row.build_commit).not.toBe("2.5.0-preview.169");
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test("③ 形状不对的 build_commit 被 schema 拒(不是静默丢弃)", async () => {
|
|
98
|
+
// 与「静默丢弃」相反的那一半:**已知键但值不合规**必须报错,
|
|
99
|
+
// 否则「发了个坏值」会和「没发」同形。
|
|
100
|
+
const r = await report({ resume_id: `resume_bc3_${STAMP}`, build_commit: "NOT-HEX" });
|
|
101
|
+
expect(r.ok).toBeFalsy();
|
|
102
|
+
});
|
|
103
|
+
});
|
package/src/db.ts
CHANGED
|
@@ -2480,6 +2480,11 @@ try { db.exec("ALTER TABLE sessions ADD COLUMN secret_keys TEXT"); } catch {}
|
|
|
2480
2480
|
// the node itself. Appended at EOF like the other post-1.0 columns so the doc
|
|
2481
2481
|
// and test846 line anchors below it never drift.
|
|
2482
2482
|
try { db.exec("ALTER TABLE sessions ADD COLUMN env_transport TEXT"); } catch {}
|
|
2483
|
+
// 2026-10-31 —— #3294:节点侧的**字节标识**(与 /health 的 git_commit 同一概念,但对象不同)。
|
|
2484
|
+
// 只有 version 时,「两个 .169 是不同字节」无法分辨;而 #3178 的批量升级前后都要问这句话。
|
|
2485
|
+
// 可为 NULL:老节点不报 ⇒ 「没报」与「没有标识」在这一列上同形,所以读侧必须配一个 reason
|
|
2486
|
+
// (见 /api/nodes 的 build_note)。
|
|
2487
|
+
try { db.exec("ALTER TABLE sessions ADD COLUMN build_commit TEXT"); } catch {}
|
|
2483
2488
|
|
|
2484
2489
|
// #1510 — hourly count of secret writes that a transport gate WOULD have refused
|
|
2485
2490
|
// (nodes reporting a plain-HTTP hub link). Log-only until an operator decides.
|
|
@@ -69,23 +69,25 @@ describe("#3271 从未取走过的过期计数", () => {
|
|
|
69
69
|
});
|
|
70
70
|
|
|
71
71
|
// ---- 派单侧硬闸(#3271)----
|
|
72
|
-
import { neverConsumeGate, NEVER_CONSUME_LIMIT } from "./expiry-counters.js";
|
|
72
|
+
import { neverConsumeGate, NEVER_CONSUME_LIMIT, NEVER_CONSUME_STALE_MS } from "./expiry-counters.js";
|
|
73
73
|
|
|
74
74
|
describe("#3271 派单侧硬闸:从未取走过的目标", () => {
|
|
75
|
-
const
|
|
75
|
+
const NOW = Date.parse("2026-10-31T10:00:00.000Z");
|
|
76
|
+
const counters = (n: number, alias = "ghost", lastAt = new Date(NOW - 60_000).toISOString()) => ({
|
|
76
77
|
since: "2026-10-31T00:00:00.000Z",
|
|
77
78
|
total: n,
|
|
78
79
|
by_node: n > 0 ? { [alias]: n } : {},
|
|
80
|
+
last_at: n > 0 ? { [alias]: lastAt } : {},
|
|
79
81
|
});
|
|
80
82
|
|
|
81
83
|
test("窗口内 0–2 次 ⇒ 放行(一次两次可能是宿主重启,三次才是形态)", () => {
|
|
82
84
|
for (const n of [0, 1, 2]) {
|
|
83
|
-
expect(neverConsumeGate({ alias: "ghost", counters: counters(n), force: false, forceAllowed: true }).ok).toBe(true);
|
|
85
|
+
expect(neverConsumeGate({ alias: "ghost", counters: counters(n), force: false, forceAllowed: true, now: Date.parse("2026-10-31T10:00:00.000Z") }).ok).toBe(true);
|
|
84
86
|
}
|
|
85
87
|
});
|
|
86
88
|
|
|
87
89
|
test("🔴 达到阈值 ⇒ 拒绝,且拒绝体给全(alias / expiries / window_since / 下一步)", () => {
|
|
88
|
-
const r = neverConsumeGate({ alias: "ghost", counters: counters(NEVER_CONSUME_LIMIT), force: false, forceAllowed: true });
|
|
90
|
+
const r = neverConsumeGate({ alias: "ghost", counters: counters(NEVER_CONSUME_LIMIT), force: false, forceAllowed: true, now: Date.parse("2026-10-31T10:00:00.000Z") });
|
|
89
91
|
expect(r.ok).toBe(false);
|
|
90
92
|
if (r.ok) throw new Error("unreachable");
|
|
91
93
|
expect(r.error).toBe("target_never_consumes");
|
|
@@ -96,16 +98,44 @@ describe("#3271 派单侧硬闸:从未取走过的目标", () => {
|
|
|
96
98
|
});
|
|
97
99
|
|
|
98
100
|
test("人令牌 + force ⇒ 放行(出口存在,但必须显式)", () => {
|
|
99
|
-
expect(neverConsumeGate({ alias: "ghost", counters: counters(9), force: true, forceAllowed: true }).ok).toBe(true);
|
|
101
|
+
expect(neverConsumeGate({ alias: "ghost", counters: counters(9), force: true, forceAllowed: true, now: Date.parse("2026-10-31T10:00:00.000Z") }).ok).toBe(true);
|
|
100
102
|
});
|
|
101
103
|
|
|
102
104
|
test("🔴 节点令牌不能自己放行:force 传了也不算(forceAllowed=false)", () => {
|
|
103
|
-
const r = neverConsumeGate({ alias: "ghost", counters: counters(9), force: true, forceAllowed: false });
|
|
105
|
+
const r = neverConsumeGate({ alias: "ghost", counters: counters(9), force: true, forceAllowed: false, now: Date.parse("2026-10-31T10:00:00.000Z") });
|
|
104
106
|
expect(r.ok).toBe(false);
|
|
105
107
|
});
|
|
106
108
|
|
|
107
109
|
test("别的节点的计数不影响本目标(分桶不是总数)", () => {
|
|
108
|
-
const c = { since: "s", total: 9, by_node: { other: 9 } };
|
|
109
|
-
expect(neverConsumeGate({ alias: "ghost", counters: c, force: false, forceAllowed: true }).ok).toBe(true);
|
|
110
|
+
const c = { since: "s", total: 9, by_node: { other: 9 }, last_at: { other: new Date().toISOString() } };
|
|
111
|
+
expect(neverConsumeGate({ alias: "ghost", counters: c, force: false, forceAllowed: true, now: Date.parse("2026-10-31T10:00:00.000Z") }).ok).toBe(true);
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
describe("#3271 硬闸的时效:只数不衰减会把恢复了的节点永久拉黑", () => {
|
|
116
|
+
const NOW = Date.parse("2026-10-31T10:00:00.000Z");
|
|
117
|
+
const mk = (lastAtIso: string) => ({
|
|
118
|
+
since: "2026-10-31T00:00:00.000Z",
|
|
119
|
+
total: 5,
|
|
120
|
+
by_node: { ghost: 5 },
|
|
121
|
+
last_at: { ghost: lastAtIso },
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test("最近一次是 1 分钟前 ⇒ 仍然拒(形态是新鲜的)", () => {
|
|
125
|
+
const r = neverConsumeGate({ alias: "ghost", counters: mk(new Date(NOW - 60_000).toISOString()), force: false, forceAllowed: true, now: NOW });
|
|
126
|
+
expect(r.ok).toBe(false);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test("🔴 最近一次超过 TTL ⇒ 放行(节点可能已恢复;计数仍留在读数里)", () => {
|
|
130
|
+
const r = neverConsumeGate({ alias: "ghost", counters: mk(new Date(NOW - NEVER_CONSUME_STALE_MS - 1).toISOString()), force: false, forceAllowed: true, now: NOW });
|
|
131
|
+
expect(r.ok).toBe(true);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
test("读数里带 last_at —— 光有计数看不出「多久没犯了」", () => {
|
|
135
|
+
resetNeverConsumedExpiryCountersForTest(new Date(NOW));
|
|
136
|
+
noteNeverConsumedExpiry("ghost", NOW);
|
|
137
|
+
const c = neverConsumedExpiryCounters();
|
|
138
|
+
expect(c.last_at["ghost"]).toBe(new Date(NOW).toISOString());
|
|
139
|
+
expect(c.by_node["ghost"]).toBe(1);
|
|
110
140
|
});
|
|
111
141
|
});
|
package/src/expiry-counters.ts
CHANGED
|
@@ -23,25 +23,31 @@ export type NeverConsumedExpiryCounters = {
|
|
|
23
23
|
total: number;
|
|
24
24
|
/** 按节点分桶;键是 node alias(可读),值是计数。空桶不出现。 */
|
|
25
25
|
by_node: Record<string, number>;
|
|
26
|
+
/** 每个节点最近一次「从未取走」的时刻(ISO)。**光有计数会永久拉黑一台恢复了的节点。** */
|
|
27
|
+
last_at: Record<string, string>;
|
|
26
28
|
};
|
|
27
29
|
|
|
28
|
-
|
|
30
|
+
type Bucket = { count: number; lastAt: number };
|
|
31
|
+
const counters = new Map<string, Bucket>();
|
|
29
32
|
let since = new Date().toISOString();
|
|
30
33
|
|
|
31
34
|
/** 记一次「过期且从未取走」。node 名用别名(人读),没有别名时退回 node id。 */
|
|
32
|
-
export function noteNeverConsumedExpiry(node: string): void {
|
|
35
|
+
export function noteNeverConsumedExpiry(node: string, now = Date.now()): void {
|
|
33
36
|
const key = node || "(unknown)";
|
|
34
|
-
|
|
37
|
+
const prev = counters.get(key);
|
|
38
|
+
counters.set(key, { count: (prev?.count ?? 0) + 1, lastAt: now });
|
|
35
39
|
}
|
|
36
40
|
|
|
37
41
|
export function neverConsumedExpiryCounters(): NeverConsumedExpiryCounters {
|
|
38
42
|
let total = 0;
|
|
39
43
|
const by_node: Record<string, number> = {};
|
|
44
|
+
const last_at: Record<string, string> = {};
|
|
40
45
|
for (const [k, v] of [...counters.entries()].sort(([a], [b]) => a.localeCompare(b))) {
|
|
41
|
-
by_node[k] = v;
|
|
42
|
-
|
|
46
|
+
by_node[k] = v.count;
|
|
47
|
+
last_at[k] = new Date(v.lastAt).toISOString();
|
|
48
|
+
total += v.count;
|
|
43
49
|
}
|
|
44
|
-
return { since, total, by_node };
|
|
50
|
+
return { since, total, by_node, last_at };
|
|
45
51
|
}
|
|
46
52
|
|
|
47
53
|
/** 仅测试用:清零并重置窗口。 */
|
|
@@ -63,6 +69,8 @@ export function resetNeverConsumedExpiryCountersForTest(now = new Date()): void
|
|
|
63
69
|
* ③ 拒绝体给全:alias / expiries / window_since / 下一步。只说 "refused" 会让调用方去猜。
|
|
64
70
|
*/
|
|
65
71
|
export const NEVER_CONSUME_LIMIT = 3;
|
|
72
|
+
/** 「最近一次从未取走」超过这个时长 ⇒ 不再拒发(节点可能已经恢复;计数仍留在读数里)。 */
|
|
73
|
+
export const NEVER_CONSUME_STALE_MS = 2 * 60 * 60_000;
|
|
66
74
|
|
|
67
75
|
export type NeverConsumeGate =
|
|
68
76
|
| { ok: true }
|
|
@@ -75,10 +83,21 @@ export function neverConsumeGate(input: {
|
|
|
75
83
|
/** 人令牌才能用 force;节点令牌传 false。 */
|
|
76
84
|
forceAllowed: boolean;
|
|
77
85
|
limit?: number;
|
|
86
|
+
/** 「最近一次」的时效:超过它就不再拒发(节点可能已经恢复)。 */
|
|
87
|
+
staleAfterMs?: number;
|
|
88
|
+
now?: number;
|
|
78
89
|
}): NeverConsumeGate {
|
|
79
90
|
const limit = input.limit ?? NEVER_CONSUME_LIMIT;
|
|
80
91
|
const expiries = input.counters.by_node[input.alias] ?? 0;
|
|
81
92
|
if (expiries < limit) return { ok: true };
|
|
93
|
+
// 2026-10-31 —— **只数不衰减会把恢复了的节点永久拉黑**。
|
|
94
|
+
// 实测的教训来自另一台机(TM中转运维):连「抑制了多少」这个数本身都在被环缓冲淘汰,
|
|
95
|
+
// 所以任何「累计」都只在它的窗口内可引用;这里把窗口写进判据:最近一次过期超过 TTL ⇒ 放行。
|
|
96
|
+
const lastAt = input.counters.last_at?.[input.alias];
|
|
97
|
+
if (lastAt) {
|
|
98
|
+
const age = (input.now ?? Date.now()) - Date.parse(lastAt);
|
|
99
|
+
if (Number.isFinite(age) && age > (input.staleAfterMs ?? NEVER_CONSUME_STALE_MS)) return { ok: true };
|
|
100
|
+
}
|
|
82
101
|
if (input.force && input.forceAllowed) return { ok: true };
|
|
83
102
|
return {
|
|
84
103
|
ok: false,
|
|
@@ -298,13 +298,13 @@ describe.skipIf(!isProdMode)("#500 CR2 — HEAD /api/files/:file_id authorizatio
|
|
|
298
298
|
// — check Content-Type so a future fallback rewrite (e.g. adding
|
|
299
299
|
// "requested resource type: X") does not silently form an oracle
|
|
300
300
|
// while HEAD still returns 200 from that page.
|
|
301
|
-
expect(res.headers.get("content-type")
|
|
301
|
+
expect((res.headers.get("content-type") || "").toLowerCase().split(";")[0].trim()).toBe("application/json");
|
|
302
302
|
});
|
|
303
303
|
|
|
304
304
|
test("HEAD unknown file_id → 404 with same shape as cross-owner (no enumeration signal)", async () => {
|
|
305
305
|
const res = await headAs(userAToken, "0123456789abcdef0123456789abcdef");
|
|
306
306
|
expect(res.status).toBe(404);
|
|
307
|
-
expect(res.headers.get("content-type")
|
|
307
|
+
expect((res.headers.get("content-type") || "").toLowerCase().split(";")[0].trim()).toBe("application/json");
|
|
308
308
|
});
|
|
309
309
|
|
|
310
310
|
test("HEAD anonymous → 401 (auth still required, symmetric with GET)", async () => {
|
|
@@ -666,7 +666,7 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
|
|
|
666
666
|
test("anonymous /health does not leak build identity through headers", async () => {
|
|
667
667
|
const res = await fetch(`${BASE}/health`);
|
|
668
668
|
expect(res.status).toBe(200);
|
|
669
|
-
expect(res.headers.get("content-type") || "").
|
|
669
|
+
expect((res.headers.get("content-type") || "").split(";")[0].trim()).toBe("application/json");
|
|
670
670
|
// 正文里我们只给 build_identified;头里更不能给指纹
|
|
671
671
|
const leaky = [...res.headers.keys()].filter((h) => /git|commit|build[-_]?(sha|id)/i.test(h));
|
|
672
672
|
expect(leaky).toEqual([]);
|
package/src/http-gzip.test.ts
CHANGED
|
@@ -23,7 +23,7 @@ test("a large JSON body is gzipped only when the client asked, and round-trips",
|
|
|
23
23
|
expect(bytes.byteLength).toBeLessThan(big.length / 3);
|
|
24
24
|
expect(Number(out!.headers.get("Content-Length"))).toBe(bytes.byteLength);
|
|
25
25
|
expect(new TextDecoder().decode(Bun.gunzipSync(bytes))).toBe(big);
|
|
26
|
-
expect(out!.headers.get("Content-Type")).
|
|
26
|
+
expect((out!.headers.get("Content-Type") || "").split(";")[0].trim()).toBe("application/json");
|
|
27
27
|
|
|
28
28
|
const plain = json(big);
|
|
29
29
|
expect(await maybeGzipResponse(reqWith(), plain)).toBe(plain); // untouched object
|
|
@@ -147,7 +147,7 @@ describe("#461 GET /events/network/:id — auth", () => {
|
|
|
147
147
|
test("member user token → SSE stream with observer connected frame", async () => {
|
|
148
148
|
const res = await fetch(`${BASE}/events/network/${memberNetworkId}`, { headers: auth(memberToken) });
|
|
149
149
|
expect(res.status).toBe(200);
|
|
150
|
-
expect(res.headers.get("content-type") || "").
|
|
150
|
+
expect((res.headers.get("content-type") || "").split(";")[0].trim()).toBe("text/event-stream");
|
|
151
151
|
const reader = res.body!.getReader();
|
|
152
152
|
const connected = await readFrame(reader);
|
|
153
153
|
expect(connected.type).toBe("connected");
|
|
@@ -226,7 +226,7 @@ describe("GET /events/users/me — Desktop user stream auth", () => {
|
|
|
226
226
|
test("member utok → user stream connected frame keyed to authenticated user", async () => {
|
|
227
227
|
const res = await fetch(`${BASE}/events/users/me?network_id=${encodeURIComponent(memberNetworkId)}`, { headers: auth(memberToken) });
|
|
228
228
|
expect(res.status).toBe(200);
|
|
229
|
-
expect(res.headers.get("content-type") || "").
|
|
229
|
+
expect((res.headers.get("content-type") || "").split(";")[0].trim()).toBe("text/event-stream");
|
|
230
230
|
const reader = res.body!.getReader();
|
|
231
231
|
const connected = await readFrame(reader);
|
|
232
232
|
expect(connected.type).toBe("connected");
|
package/src/serve-error.test.ts
CHANGED
|
@@ -25,7 +25,7 @@ describe("#695 fetch exceptions become JSON with the exception's own message", (
|
|
|
25
25
|
try {
|
|
26
26
|
const res = await fetch(`http://127.0.0.1:${server.port}/mcp`, { method: "POST", body: "{}" });
|
|
27
27
|
expect(res.status).toBe(500);
|
|
28
|
-
expect(res.headers.get("content-type") ?? "").
|
|
28
|
+
expect((res.headers.get("content-type") ?? "").split(";")[0].trim()).toBe("application/json");
|
|
29
29
|
const json = await res.json() as { error: { code: number; message: string }; ok: boolean };
|
|
30
30
|
expect(json.error.code).toBe(-32603);
|
|
31
31
|
expect(json.error.message).toBe("boom-695-live");
|
package/src/server.ts
CHANGED
|
@@ -6830,6 +6830,9 @@ return Bun.serve({
|
|
|
6830
6830
|
const wantedIds = new Set<string>(wanted.map((r) => String(r.node_id)));
|
|
6831
6831
|
const transportByKey = new Map<string, string | null>();
|
|
6832
6832
|
const aliasTransport = new Map<string, string | null>();
|
|
6833
|
+
// #3294 —— 与 transport 同一批行里取 build_commit(同一个键、同一套兜底顺序)。
|
|
6834
|
+
const buildByKey = new Map<string, string | null>();
|
|
6835
|
+
const aliasBuild = new Map<string, string | null>();
|
|
6833
6836
|
if (wanted.length) {
|
|
6834
6837
|
// 🔴 编号参数不能复用:`?1..?n` 出现两次,而实参给了 2n 个 ——
|
|
6835
6838
|
// SQLite 只认得 n 个绑定位置,多出来的直接抛错,整条 GET /api/nodes 变 500。
|
|
@@ -6839,19 +6842,21 @@ return Bun.serve({
|
|
|
6839
6842
|
const ids = wanted.map((r) => String(r.node_id));
|
|
6840
6843
|
const phA = ids.map((_, i) => `?${i + 1}`).join(",");
|
|
6841
6844
|
const phB = ids.map((_, i) => `?${ids.length + i + 1}`).join(",");
|
|
6842
|
-
for (const row of db.all<{ node_id: string | null; alias: string | null; network_id: string | null; env_transport: string | null }>(
|
|
6843
|
-
`SELECT node_id, alias, network_id, env_transport FROM sessions
|
|
6845
|
+
for (const row of db.all<{ node_id: string | null; alias: string | null; network_id: string | null; env_transport: string | null; build_commit: string | null }>(
|
|
6846
|
+
`SELECT node_id, alias, network_id, env_transport, build_commit FROM sessions
|
|
6844
6847
|
WHERE node_id IN (${phA}) OR alias IN (${phB})
|
|
6845
6848
|
ORDER BY updated_at DESC`,
|
|
6846
6849
|
...ids, ...ids,
|
|
6847
6850
|
)) {
|
|
6848
6851
|
if (row.node_id && wantedIds.has(row.node_id) && !transportByKey.has(row.node_id)) transportByKey.set(row.node_id, row.env_transport);
|
|
6852
|
+
if (row.node_id && wantedIds.has(row.node_id) && !buildByKey.has(row.node_id)) buildByKey.set(row.node_id, row.build_commit ?? null);
|
|
6849
6853
|
// alias 只在**同一网络**内兜底:不同网络可以有同名 alias,
|
|
6850
6854
|
// 跨网络命中会把 A 网的 transport 显示成 B 网那台 —— 这一格是给人做安全决策用的,
|
|
6851
6855
|
// 宁可显示 null(未知)也不能显示错的值。
|
|
6852
6856
|
if (row.alias && row.network_id && wantedIds.has(row.alias)) {
|
|
6853
6857
|
const key = `${row.network_id}|${row.alias}`;
|
|
6854
6858
|
if (!aliasTransport.has(key)) aliasTransport.set(key, row.env_transport);
|
|
6859
|
+
if (!aliasBuild.has(key)) aliasBuild.set(key, row.build_commit ?? null);
|
|
6855
6860
|
}
|
|
6856
6861
|
}
|
|
6857
6862
|
}
|
|
@@ -6865,6 +6870,15 @@ return Bun.serve({
|
|
|
6865
6870
|
if (byId !== undefined) return byId;
|
|
6866
6871
|
return alias ? aliasTransport.get(`${networkId}|${alias}`) ?? null : null;
|
|
6867
6872
|
};
|
|
6873
|
+
// #3294 —— 与 envTransportOf 同构:先按 node_id,再按 (network, node_id),最后按 (network, alias)。
|
|
6874
|
+
const buildCommitOf = (nodeId: string, alias: string | null, networkId: string | null): string | null => {
|
|
6875
|
+
const direct = buildByKey.get(nodeId);
|
|
6876
|
+
if (direct !== undefined) return direct;
|
|
6877
|
+
if (!networkId) return null;
|
|
6878
|
+
const byId = aliasBuild.get(`${networkId}|${nodeId}`);
|
|
6879
|
+
if (byId !== undefined) return byId;
|
|
6880
|
+
return alias ? aliasBuild.get(`${networkId}|${alias}`) ?? null : null;
|
|
6881
|
+
};
|
|
6868
6882
|
// Add a single new field `role: string | null` per row, extracted from
|
|
6869
6883
|
// config_snapshot JSON. Daemon nodes that posted role='host_supervisor'
|
|
6870
6884
|
// via report_status surface here; dashboard uses this for daemon
|
|
@@ -6973,6 +6987,10 @@ return Bun.serve({
|
|
|
6973
6987
|
// #1510 —— 管理员要能看出「谁的 transport 未知」才敢打开 strict。
|
|
6974
6988
|
// 这一格**只读**,不参与任何判定(判定在 env-transport-policy.ts)。
|
|
6975
6989
|
env_transport: envTransportOf(r.node_id, r.alias, r.network_id),
|
|
6990
|
+
// #3294 —— 「跑的是哪一份字节」。null 有两种成因(节点没报 / 老节点不报这个字段),
|
|
6991
|
+
// 所以配一个 note 说明该怎么读它 —— 单一 null 会把两种成因压成一个。
|
|
6992
|
+
build_commit: buildCommitOf(r.node_id, r.alias, r.network_id),
|
|
6993
|
+
build_note: "null = 这个节点没有上报 build_commit(老版本节点不会报);空字符串不出现",
|
|
6976
6994
|
restart_readiness: restartReadiness(r.node_id, r.alias, r.network_id, role, r.lifecycle_state ?? null),
|
|
6977
6995
|
};
|
|
6978
6996
|
});
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
// 跑法:cd server && COMMHUB_DB=/tmp/x.db bun test src/task-expiry-notice-http.test.ts
|
|
18
18
|
|
|
19
19
|
import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
|
|
20
|
+
import { resetNeverConsumedExpiryCountersForTest } from "./expiry-counters.js";
|
|
20
21
|
import { mkdtempSync, rmSync } from "node:fs";
|
|
21
22
|
import { tmpdir } from "node:os";
|
|
22
23
|
import { join } from "node:path";
|
|
@@ -89,7 +90,10 @@ const until = async (cond: () => boolean, tries = 150) => { for (let k = 0; k <
|
|
|
89
90
|
let seq = 0;
|
|
90
91
|
/** 经 POST /api/task 派一条;返回 task_id。 */
|
|
91
92
|
async function dispatch(token: string, to: string, extra: Record<string, unknown> = {}): Promise<string> {
|
|
92
|
-
|
|
93
|
+
// 2026-10-31 —— 这里**故意**发 expired 任务(本文件测的就是过期通知),
|
|
94
|
+
// 所以同一目标很快就会攒到 ≥3 次「从未取走」。#3271 的硬闸会因此拒发(这是它的本意:
|
|
95
|
+
// 不让任务继续堆到一台从不消费的节点上)。测过期通知走的是**人工知情**的路径 ⇒ 带 force。
|
|
96
|
+
const r = await send(token, "POST", "/api/task", { alias: to, task: `expiry case ${stamp} #${++seq}`, network_id: NET, force: true, ...extra });
|
|
93
97
|
expect(r.status).toBe(200);
|
|
94
98
|
expect(r.body.ok).toBe(true);
|
|
95
99
|
return r.body.task_id;
|
|
@@ -138,6 +142,10 @@ beforeAll(async () => {
|
|
|
138
142
|
}, 30_000);
|
|
139
143
|
|
|
140
144
|
beforeEach(() => {
|
|
145
|
+
// 2026-10-31 —— #3271 的硬闸是**进程级**计数:上一条用例攒下的「从未取走」会带到这里,
|
|
146
|
+
// 于是本文件的下一条用例第一次派发就被拒(我第一次只清在循环里,正是漏了这个)。
|
|
147
|
+
// 本文件测的是过期通知,不是那道闸 ⇒ 每条用例前清零。
|
|
148
|
+
resetNeverConsumedExpiryCountersForTest();
|
|
141
149
|
// 每条用例自己的数据:上一条留下的开着的任务不许算进「前面还有几个」,也不许被这一次巡检过期。
|
|
142
150
|
db.run("UPDATE tasks SET status = 'replied', completed_at = datetime('now') WHERE network_id = ?1 AND status IN ('created', 'delivered', 'acked', 'running')", [NET]);
|
|
143
151
|
db.run("DELETE FROM inbox WHERE network_id = ?1 AND id LIKE 'exp_%'", [NET]);
|
|
@@ -268,7 +276,10 @@ describe("#500 child task expires", () => {
|
|
|
268
276
|
describe("#500 one notice per (sender, target) per patrol pass", () => {
|
|
269
277
|
test("5 expiring to the same target → one summarized notice listing all 5", async () => {
|
|
270
278
|
const ids: string[] = [];
|
|
271
|
-
|
|
279
|
+
// 2026-10-31 —— 这里连发 5 条给同一目标,会攒到 #3271 的硬闸阈值(≥3 次从未取走)。
|
|
280
|
+
// 而本文件测的是**过期通知的合并**,不是那道闸;闸自己的行为在 node-health-dispatch-http 与
|
|
281
|
+
// expiry-counters.test 里钉着。⇒ 每次派发后清一次进程内计数,把闸本意地旁路掉(并写明理由)。
|
|
282
|
+
for (let i = 0; i < 5; i++) { ids.push(await dispatch(nodes.sender.token, nodes.target.alias)); resetNeverConsumedExpiryCountersForTest(); }
|
|
272
283
|
// 再来一条派给另一个目标:那是另一组,单独一条。
|
|
273
284
|
const elsewhere = await dispatch(nodes.sender.token, nodes.other.alias);
|
|
274
285
|
for (const id of [...ids, elsewhere]) backdate(id);
|
package/src/tools.ts
CHANGED
|
@@ -884,6 +884,9 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
884
884
|
// it knows the last hop. Reporting only; no write path reads it yet.
|
|
885
885
|
env_transport: z.enum(["loopback", "https", "plain"]).optional().describe("Hub link kind"),
|
|
886
886
|
version: z.string().max(100).optional().describe("Agent version"),
|
|
887
|
+
// 2026-10-31 —— #3294:**字节标识**。40 位 hex;也接受 12 位前缀(CI 里截过的那种)。
|
|
888
|
+
// 与 version 分开:version 是标签,build_commit 是「哪一份字节」。
|
|
889
|
+
build_commit: z.string().regex(/^[0-9a-f]{7,40}$/).optional().describe("Build commit (hex, 7–40), from the packaged build-info.json"),
|
|
887
890
|
tmux_name: z.string().max(200).optional().describe("tmux session name"),
|
|
888
891
|
// V2 fields
|
|
889
892
|
node_id: z.string().max(200).optional().describe("Stable node identifier"),
|
|
@@ -1125,7 +1128,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
1125
1128
|
// instead of rejecting the whole report (see node-health-store.ts).
|
|
1126
1129
|
health: nodeHealthSchema,
|
|
1127
1130
|
},
|
|
1128
|
-
async ({ resume_id, alias, status, task, output, score, progress, server: srv, hostname: hn, agent: ag, project_dir: pd, os_user: osUser, version: ver, tmux_name: tmux, node_id, session_id, config_path, channels, model: mdl, node_name: nn, network_id: netId, host, process_telemetry: proc, external_schedules: externalSchedules, config_snapshot: cfgSnap, rules_file_capable: rulesFileCapable, skills_capable: skillsCapable, files_capable: filesCapable, logs_capable: logsCapable, team_rules: teamRules, health: nodeHealth, secret_keys: secretKeys, env_transport: envTransport }) => {
|
|
1131
|
+
async ({ resume_id, alias, status, task, output, score, progress, server: srv, hostname: hn, agent: ag, project_dir: pd, os_user: osUser, version: ver, tmux_name: tmux, node_id, session_id, config_path, channels, model: mdl, node_name: nn, network_id: netId, host, process_telemetry: proc, external_schedules: externalSchedules, config_snapshot: cfgSnap, rules_file_capable: rulesFileCapable, skills_capable: skillsCapable, files_capable: filesCapable, logs_capable: logsCapable, team_rules: teamRules, health: nodeHealth, secret_keys: secretKeys, env_transport: envTransport, build_commit: buildCommit }) => {
|
|
1129
1132
|
const effectiveNetId = getNetworkId(netId);
|
|
1130
1133
|
const sessionNetId = effectiveNetId ?? "default";
|
|
1131
1134
|
if (!callerTokenIsNetwork || !enforceNetworkId) {
|
|
@@ -1338,6 +1341,13 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
1338
1341
|
[resume_id, envTransport],
|
|
1339
1342
|
);
|
|
1340
1343
|
}
|
|
1344
|
+
// 2026-10-31 —— #3294:同一手法(自己的 UPDATE,INSERT 字节形状不动)。
|
|
1345
|
+
if (buildCommit) {
|
|
1346
|
+
db.run(
|
|
1347
|
+
`UPDATE sessions SET build_commit = ?2, updated_at = datetime('now') WHERE resume_id = ?1`,
|
|
1348
|
+
[resume_id, buildCommit],
|
|
1349
|
+
);
|
|
1350
|
+
}
|
|
1341
1351
|
if (Array.isArray(secretKeys)) {
|
|
1342
1352
|
db.run(
|
|
1343
1353
|
`UPDATE sessions SET secret_keys = ?2, updated_at = datetime('now') WHERE resume_id = ?1`,
|