@sleep2agi/commhub-server 0.9.0-preview.83 → 0.9.0-preview.84

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.83",
3
+ "version": "0.9.0-preview.84",
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,115 @@
1
+ // #448 — report_status.health passthrough (layered node health, report-only).
2
+ //
3
+ // Hub-side contract verified here:
4
+ // 1. A well-formed `health` from the node's own token is kept (memory-only) and readable.
5
+ // 2. Malformed `health` never rejects the report — the node stays online, health reads as null.
6
+ // 3. Another node / a user login cannot speak for this node's health.
7
+ // 4. Stale (> TTL) health reads as null, never as "healthy".
8
+ //
9
+ // 跑法:cd server && COMMHUB_DB=/tmp/node-health.db bun test src/node-health-passthrough.test.ts
10
+ import { afterAll, beforeEach, describe, expect, test } from "bun:test";
11
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
12
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
13
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
14
+ import { db } from "./db.js";
15
+ import { registerTools } from "./tools.js";
16
+ import { clearNodeHealthStore, NODE_HEALTH_TTL_MS, readNodeHealth, recordNodeHealth } from "./node-health-store.js";
17
+
18
+ const NET = "net_health_t";
19
+ const OWNER = "u_health_owner";
20
+ const NODE_A = "health-node-a";
21
+ const NODE_B = "health-node-b";
22
+ const NODE_A_ID = "node_health_a";
23
+ const NODE_B_ID = "node_health_b";
24
+ const T_A = "tok_health_node_a";
25
+ const T_B = "tok_health_node_b";
26
+
27
+ function cleanup() {
28
+ for (const t of ["sessions", "nodes", "api_tokens", "network_members", "networks"]) {
29
+ try { db.run(`DELETE FROM ${t} WHERE network_id = ?1`, [NET]); } catch {}
30
+ }
31
+ try { db.run("DELETE FROM users WHERE user_id = ?1", [OWNER]); } catch {}
32
+ clearNodeHealthStore();
33
+ }
34
+ function seed() {
35
+ db.run(`INSERT INTO users (user_id, username, password_hash, role, created_at) VALUES (?1, ?2, 'x', 'user', datetime('now'))`, [OWNER, OWNER]);
36
+ db.run(`INSERT INTO networks (network_id, network_name, owner_id, created_at) VALUES (?1, ?2, ?3, datetime('now'))`, [NET, NET, OWNER]);
37
+ db.run(`INSERT INTO network_members (user_id, network_id, role, joined_at) VALUES (?1, ?2, 'owner', datetime('now'))`, [OWNER, NET]);
38
+ for (const [id, alias, tok] of [[NODE_A_ID, NODE_A, T_A], [NODE_B_ID, NODE_B, T_B]]) {
39
+ db.run(`INSERT INTO nodes (node_id, node_name, alias, network_id, owner_user_id, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, datetime('now'), datetime('now'))`, [id, alias, alias, NET, OWNER]);
40
+ db.run(`INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash, expires_at, revoked_at, bound_node_id) VALUES (?1, ?2, ?3, 'network', ?4, ?5, NULL, NULL, ?6)`, [tok, OWNER, NET, `node:${alias}`, `hash_${tok}`, id]);
41
+ }
42
+ }
43
+
44
+ async function connectAs(alias: string, tokenId: string) {
45
+ const server = new McpServer({ name: "health-test", version: "1" });
46
+ registerTools(server, undefined, NET, OWNER, alias, true, tokenId);
47
+ const client = new Client({ name: "health-client", version: "1" });
48
+ const [ct, st] = InMemoryTransport.createLinkedPair();
49
+ await server.connect(st);
50
+ await client.connect(ct);
51
+ const call = async (args: Record<string, unknown>) => {
52
+ const r: any = await client.callTool({ name: "report_status", arguments: args });
53
+ return { isError: r.isError === true, body: JSON.parse(r.content?.[0]?.text ?? "null") };
54
+ };
55
+ return { call, close: async () => { await client.close(); await server.close(); } };
56
+ }
57
+
58
+ const HEALTH = {
59
+ bridge: "ok",
60
+ app_server: { ok: false, rtt_ms: null, last_error: "connection refused" },
61
+ tui: { ok: false, reason: "sleep-placeholder" },
62
+ model_auth: "revoked",
63
+ };
64
+
65
+ beforeEach(() => { cleanup(); seed(); });
66
+ afterAll(cleanup);
67
+
68
+ describe("#448 report_status.health passthrough", () => {
69
+ test("node's own token: stored and readable as reported", async () => {
70
+ const a = await connectAs(NODE_A, T_A);
71
+ try {
72
+ const r = await a.call({ resume_id: `sdk-${NODE_A_ID}`, alias: NODE_A, status: "idle", node_id: NODE_A_ID, health: HEALTH });
73
+ expect(r.isError).toBe(false);
74
+ expect(r.body.ok).not.toBe(false);
75
+ } finally { await a.close(); }
76
+ expect(readNodeHealth(NET, NODE_A)?.health).toEqual(HEALTH as any);
77
+ });
78
+
79
+ test("malformed health never rejects the report (node stays online); it reads as not reported", async () => {
80
+ const a = await connectAs(NODE_A, T_A);
81
+ try {
82
+ for (const bad of [42, "ok", { app_server: { ok: "yes" }, model_auth: "weird", tui: [] }, { app_server: { ok: true, rtt_ms: NaN, last_error: 5 } }]) {
83
+ const r = await a.call({ resume_id: `sdk-${NODE_A_ID}`, alias: NODE_A, status: "idle", node_id: NODE_A_ID, health: bad });
84
+ expect(r.isError).toBe(false);
85
+ }
86
+ } finally { await a.close(); }
87
+ expect(db.get<{ s: string }>("SELECT status AS s FROM sessions WHERE alias = ?1 AND network_id = ?2", NODE_A, NET)?.s).toBe("idle");
88
+ // 最后一份里 app_server.ok 合法、其余两格降级成 null —— 留下的是能证实的部分,不是编出来的。
89
+ expect(readNodeHealth(NET, NODE_A)?.health.app_server).toEqual({ ok: true, rtt_ms: null, last_error: null });
90
+ });
91
+
92
+ test("another node's token cannot speak for this node", async () => {
93
+ const b = await connectAs(NODE_B, T_B);
94
+ try {
95
+ await b.call({ resume_id: `sdk-${NODE_A_ID}`, alias: NODE_A, status: "idle", node_id: NODE_A_ID, health: HEALTH });
96
+ } finally { await b.close(); }
97
+ expect(readNodeHealth(NET, NODE_A)).toBeNull();
98
+ });
99
+
100
+ test("stale health reads as null, never as healthy", () => {
101
+ const t0 = 1_000_000;
102
+ recordNodeHealth(NET, NODE_A, { bridge: "ok", model_auth: "ok" }, t0);
103
+ expect(readNodeHealth(NET, NODE_A, t0 + 1_000)?.observed_ms_ago).toBe(1_000);
104
+ expect(readNodeHealth(NET, NODE_A, t0 + NODE_HEALTH_TTL_MS + 1)).toBeNull();
105
+ });
106
+
107
+ test("a report without health leaves the last one (heartbeats from older code paths do not erase it)", async () => {
108
+ const a = await connectAs(NODE_A, T_A);
109
+ try {
110
+ await a.call({ resume_id: `sdk-${NODE_A_ID}`, alias: NODE_A, status: "idle", node_id: NODE_A_ID, health: HEALTH });
111
+ await a.call({ resume_id: `sdk-${NODE_A_ID}`, alias: NODE_A, status: "working", node_id: NODE_A_ID });
112
+ } finally { await a.close(); }
113
+ expect(readNodeHealth(NET, NODE_A)?.health.model_auth).toBe("revoked");
114
+ });
115
+ });
@@ -0,0 +1,57 @@
1
+ // #448 —— agent-node 上报的分层健康(`report_status.health`)的 Hub 侧透传。
2
+ //
3
+ // 「在线」只说明桥进程还活着:现场 ~40 台 codex 共存节点里,有的在 Hub 上 idle / in_flight=0,
4
+ // 实际 app-server 端口没人监听、TUI pane 变成 `sleep infinity`、或登录态 "refresh token revoked"。
5
+ // 节点把这几层分开报上来;这里只负责**收下、按节点存最新一份、在 /api/status 和 status_update 里带出去**。
6
+ //
7
+ // 刻意只放内存,不加列:它是**几秒钟一变的观测值**,不是需要跨重启保留的状态 —— Hub 重启后下一次
8
+ // 心跳(≤3 分钟,翻转时立即)就会补上;持久化一份旧观测值反而会在节点死掉后继续说「app_server ok」。
9
+ // 同理,超过 TTL 的那份按「没报」处理(null),不按「健康」处理。
10
+
11
+ import { z } from "zod/v4";
12
+
13
+ export const NODE_HEALTH_TTL_MS = 10 * 60_000;
14
+
15
+ // 🔴 `.catch(undefined)`:这一格是纯诊断信息,**任何形状都不许拒掉整份 report_status**
16
+ // (zod 对象里一个已知字段验证失败 = 整份被拒 = 节点在 Hub 上失联,#1225 的形状)。
17
+ // 合法的透传,其余一律当没报。子对象不 strict:新节点多报的键丢掉即可。
18
+ export const nodeHealthSchema = z.object({
19
+ bridge: z.literal("ok").optional(),
20
+ app_server: z.object({
21
+ ok: z.boolean(),
22
+ rtt_ms: z.number().nullable().catch(null),
23
+ last_error: z.string().max(200).nullable().catch(null),
24
+ }).optional().catch(undefined),
25
+ tui: z.object({
26
+ ok: z.boolean(),
27
+ reason: z.string().max(40),
28
+ }).optional().catch(undefined),
29
+ model_auth: z.enum(["ok", "revoked", "expired", "unknown"]).optional().catch(undefined),
30
+ }).optional().catch(undefined);
31
+
32
+ export type NodeHealth = NonNullable<z.infer<typeof nodeHealthSchema>>;
33
+
34
+ const store = new Map<string, { health: NodeHealth; at: number }>();
35
+ const keyOf = (networkId: string | null | undefined, alias: string) => `${networkId ?? "default"}\0${alias}`;
36
+
37
+ export function recordNodeHealth(networkId: string | null | undefined, alias: string, health: NodeHealth, now = Date.now()): void {
38
+ store.set(keyOf(networkId, alias), { health, at: now });
39
+ // 有界:按 TTL 顺手清掉过期的,别让改过名/删掉的节点在内存里攒着。
40
+ if (store.size > 256) {
41
+ for (const [k, v] of store) if (now - v.at > NODE_HEALTH_TTL_MS) store.delete(k);
42
+ }
43
+ }
44
+
45
+ /** 最新一份;没有或已过 TTL → null(读的人必须把它当「不知道」,而不是「健康」)。 */
46
+ export function readNodeHealth(
47
+ networkId: string | null | undefined, alias: string, now = Date.now(),
48
+ ): { health: NodeHealth; observed_ms_ago: number } | null {
49
+ const hit = store.get(keyOf(networkId, alias));
50
+ if (!hit) return null;
51
+ const age = now - hit.at;
52
+ if (age > NODE_HEALTH_TTL_MS) { store.delete(keyOf(networkId, alias)); return null; }
53
+ return { health: hit.health, observed_ms_ago: Math.max(0, age) };
54
+ }
55
+
56
+ /** 测试用。 */
57
+ export function clearNodeHealthStore(): void { store.clear(); }
@@ -46,6 +46,8 @@ const GOLDEN_RESPONSE_KEYS = {
46
46
  "process_in_flight_count", "network_id", "registered_at", "updated_at",
47
47
  "node_id", "session_id", "config_path", "channels", "last_seen_at", "model",
48
48
  "external_schedules", "rules_file_capable", "skills_capable", "files_capable", "logs_capable", "runtime", "host", "process_telemetry",
49
+ // #448 — layered node health (memory-only; null when not reported or stale).
50
+ "health", "health_observed_ms_ago",
49
51
  ],
50
52
  task: [
51
53
  "task_id", "from_node_id", "from_name", "to_node_id", "to_name", "priority",
package/src/server.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { buildServeErrorResponse } from "./serve-error.js";
2
2
  import { maybeGzipResponse, trimLightTask } from "./http-gzip";
3
3
  import { statusAliasResolverRead } from "./status-alias-resolver.js";
4
+ import { readNodeHealth } from "./node-health-store.js";
4
5
  import { redactMessageRow } from "./redact-tokens.js";
5
6
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
7
  import { parseDbTimestampMs } from "./db-timestamp.js";
@@ -2297,6 +2298,12 @@ return Bun.serve({
2297
2298
  uptime_seconds: s.process_uptime_seconds ?? null,
2298
2299
  in_flight_count: s.process_in_flight_count ?? null,
2299
2300
  },
2301
+ // #448 — latest layered health the node reported (memory-only, 10 min TTL);
2302
+ // null = not reported / stale / older agent-node — never "healthy".
2303
+ ...(() => {
2304
+ const h = readNodeHealth(s.network_id, s.alias);
2305
+ return { health: h?.health ?? null, health_observed_ms_ago: h?.observed_ms_ago ?? null };
2306
+ })(),
2300
2307
  };
2301
2308
  });
2302
2309
  const summary = sessions.reduce((acc: any, session: any) => {
package/src/tools.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { parseDbTimestampMs } from "./db-timestamp.js";
3
3
  import { z } from "zod/v4";
4
+ import { nodeHealthSchema, recordNodeHealth } from "./node-health-store.js";
4
5
  import { parseAliasFilter } from "./alias-filter.js";
5
6
  import { createHash } from "node:crypto";
6
7
  import { db, uuidv4, logTaskEvent, chainReplyToParent, hashToken, generateId, generateNetworkToken, syncScheduledRunForTask } from "./db.js";
@@ -827,8 +828,12 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
827
828
  files_capable: z.literal(true).optional(),
828
829
  // Node run-log view — same doorbell, op logs_tail.
829
830
  logs_capable: z.literal(true).optional(),
831
+ // #448 — layered node health (bridge / app_server / tui / model_auth).
832
+ // Report-only, memory-only; any malformed shape degrades to "not reported"
833
+ // instead of rejecting the whole report (see node-health-store.ts).
834
+ health: nodeHealthSchema,
830
835
  },
831
- async ({ resume_id, alias, status, task, output, score, progress, server: srv, hostname: hn, agent: ag, project_dir: pd, 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 }) => {
836
+ async ({ resume_id, alias, status, task, output, score, progress, server: srv, hostname: hn, agent: ag, project_dir: pd, 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, health: nodeHealth }) => {
832
837
  const effectiveNetId = getNetworkId(netId);
833
838
  const sessionNetId = effectiveNetId ?? "default";
834
839
  if (!callerTokenIsNetwork || !enforceNetworkId) {
@@ -1051,6 +1056,12 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1051
1056
  );
1052
1057
  }
1053
1058
  });
1059
+ // #448 — only the node token bound to this alias may speak for its health
1060
+ // (same rule as the *_capable flags above).
1061
+ const acceptedHealth = nodeHealth && callerTokenIsNetwork && callerAlias && callerAlias === effectiveAlias
1062
+ ? nodeHealth
1063
+ : undefined;
1064
+ if (acceptedHealth) recordNodeHealth(sessionNetId, effectiveAlias, acceptedHealth);
1054
1065
  pushEvent(effectiveAlias, {
1055
1066
  type: "status_update",
1056
1067
  alias: effectiveAlias,
@@ -1059,6 +1070,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1059
1070
  progress: progress ?? null,
1060
1071
  host: statusHostTelemetry,
1061
1072
  process_telemetry: statusProcessTelemetry,
1073
+ ...(acceptedHealth ? { health: acceptedHealth } : {}),
1062
1074
  }, sessionNetId);
1063
1075
 
1064
1076
  // V2: sync tasks table — report_status(working) → tasks.running