@sleep2agi/commhub-server 0.9.0-preview.200 → 0.9.0-preview.202

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.200",
3
+ "version": "0.9.0-preview.202",
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",
@@ -137,3 +137,24 @@ describe("db-adapter: 慢 SQL 日志", () => {
137
137
  expect(long.length).toBeLessThanOrEqual("[commhub slow-sql] 1200ms ".length + 160);
138
138
  });
139
139
  });
140
+
141
+ // #2721 —— 启动预热窗内的 gap 不算停顿。
142
+ //
143
+ // 实测:2026-10-29 进程 22:21:06 启动,14:21:09.835Z(= 启动后 3 秒)记到 gap 2972ms / stall 2722ms。
144
+ // 那是模块加载 + 打开 DB + 迁移,不是线上卡顿。不排除它的后果是:每次部署都会在 /health 留一条
145
+ // 与真实卡顿同形的记录,事后无法区分。
146
+ describe("#2721 启动预热不算停顿", () => {
147
+ test("预热窗内的 tick gap 不计入 stalls(窗口外照常计)", async () => {
148
+ const stalls: string[] = [];
149
+ const timer = startEventLoopLagMonitor({
150
+ intervalMs: 10,
151
+ thresholdMs: 1,
152
+ warmupMs: 120,
153
+ log: (m) => stalls.push(m),
154
+ });
155
+ await new Promise((r) => setTimeout(r, 300));
156
+ clearInterval(timer as unknown as ReturnType<typeof setInterval>);
157
+ // 预热窗内的模拟拖延不该产生 stall 日志;窗外的真实间隔是 ~10ms,也不该触发 threshold。
158
+ expect(stalls).toHaveLength(0);
159
+ });
160
+ });
@@ -123,12 +123,20 @@ export function startEventLoopLagMonitor(opts: {
123
123
  thresholdMs?: number;
124
124
  log?: (msg: string) => void;
125
125
  rssMb?: () => number;
126
+ /** #2721 —— 启动预热窗(毫秒),窗内的 tick gap 不计入停顿。默认读 COMMHUB_STALL_WARMUP_MS / 10000。 */
127
+ warmupMs?: number;
126
128
  } = {}): ReturnType<typeof setInterval> {
127
129
  const intervalMs = opts.intervalMs ?? Math.max(50, envMs("COMMHUB_STALL_TICK_MS", 250));
128
130
  const thresholdMs = opts.thresholdMs ?? envMs("COMMHUB_STALL_LOG_MS", 2000);
129
131
  const log = opts.log ?? ((m: string) => console.log(m));
130
132
  const rssMb = opts.rssMb ?? (() => Math.round(process.memoryUsage().rss / 1048576));
131
133
  let last = performance.now();
134
+ const startedAt = last;
135
+ // #2721 —— 启动预热不算停顿。
136
+ // 实测:2026-10-29 这次进程 22:21:06 起来,14:21:09.835Z 记到一次 gap 2972ms,
137
+ // 也就是**启动后 3 秒**。那段时间在做模块加载 / 打开 DB / 迁移,第一个 tick 必然偏大。
138
+ // 不排除它的后果是:每次部署都会在 `/health` 里留一条「停顿」,而它和线上真实卡顿长得一模一样。
139
+ const warmupMs = opts.warmupMs ?? envMs("COMMHUB_STALL_WARMUP_MS", 10_000);
132
140
  const timer = setInterval(() => {
133
141
  const now = performance.now();
134
142
  const gap = now - last;
@@ -136,6 +144,7 @@ export function startEventLoopLagMonitor(opts: {
136
144
  const rss = rssMb();
137
145
  const served = servedSinceTick;
138
146
  servedSinceTick = 0;
147
+ if (now - startedAt < warmupMs) return; // 预热窗内只更新 last,不记 gap/停顿
139
148
  const stall = recordGap(gap, { intervalMs, thresholdMs, rssMb: rss, served });
140
149
  if (thresholdMs > 0 && stall >= thresholdMs) {
141
150
  // 和 retention/slow-sql 的日志同一前缀,方便 grep。
@@ -17,7 +17,7 @@ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
17
17
  let mod: typeof import("./node-permissions.js");
18
18
  beforeAll(async () => { mod = await import("./node-permissions.js"); });
19
19
 
20
- const id = (peerAllowlist: string[] | null, mode: "normal" | "readonly" | "restricted" = "normal") => ({
20
+ const id = (peerAllowlist: string[] | null, mode: "normal" | "readonly" | "restricted" = "normal", toolAllowlist: string[] | null = null) => ({
21
21
  networkId: "net_test",
22
22
  nodeId: "n_self",
23
23
  logKey: "n_self",
@@ -25,6 +25,7 @@ const id = (peerAllowlist: string[] | null, mode: "normal" | "readonly" | "restr
25
25
  ownerUserId: "u_owner",
26
26
  mode,
27
27
  peerAllowlist,
28
+ toolAllowlist,
28
29
  });
29
30
 
30
31
  describe("#2969 对端白名单", () => {
@@ -76,4 +77,38 @@ describe("#2969 对端白名单", () => {
76
77
  else process.env.COMMHUB_NODE_PERMISSIONS = saved;
77
78
  }
78
79
  });
79
- });
80
+ });
81
+
82
+ // #2969 后半 —— 接口白名单。
83
+ describe("#2969 接口白名单", () => {
84
+ test("null ⇒ 不限制(与今天一致)", () => {
85
+ expect(mod.toolAllowlistVerdict(id(null, "normal", null), "send_task", false)).toBeNull();
86
+ });
87
+
88
+ test("名单内的工具 ⇒ 放行", () => {
89
+ expect(mod.toolAllowlistVerdict(id(null, "normal", ["send_task"]), "send_task", false)).toBeNull();
90
+ });
91
+
92
+ test("名单外的工具 ⇒ tool_not_allowed", () => {
93
+ expect(mod.toolAllowlistVerdict(id(null, "normal", ["send_task"]), "broadcast", false))
94
+ .toEqual({ reason: "tool_not_allowed", sample: "broadcast" });
95
+ });
96
+
97
+ test("always 类永远放行 —— 否则节点连回报都做不了", () => {
98
+ const listed = id(null, "normal", ["send_task"]);
99
+ for (const t of ["get_inbox", "ack_inbox", "send_reply", "report_status"]) {
100
+ expect(mod.toolAllowlistVerdict(listed, t, true)).toBeNull();
101
+ }
102
+ });
103
+
104
+ test("它是显式原因:开关 off 也照拒", () => {
105
+ const saved = process.env.COMMHUB_NODE_PERMISSIONS;
106
+ process.env.COMMHUB_NODE_PERMISSIONS = "off";
107
+ try {
108
+ expect(mod.nodeDecide(id(null, "normal", ["send_task"]), "mcp:broadcast", { reason: "tool_not_allowed" })).toBe(true);
109
+ } finally {
110
+ if (saved === undefined) delete process.env.COMMHUB_NODE_PERMISSIONS;
111
+ else process.env.COMMHUB_NODE_PERMISSIONS = saved;
112
+ }
113
+ });
114
+ });
@@ -29,14 +29,20 @@ export type NodePermissionReason =
29
29
  | "human_only"
30
30
  | "owner_unknown"
31
31
  /** #2969 —— 主人给这个节点设了对端白名单,目标不在名单里。 */
32
- | "peer_not_allowed";
32
+ | "peer_not_allowed"
33
+ /** #2969 后半 —— 主人在这个节点的接口白名单里没有列这个工具/路由。 */
34
+ | "tool_not_allowed";
33
35
 
34
36
  /** 显式模式的原因:不看开关,永远拒。 */
35
37
  // 白名单和 readonly/restricted 同类:**主人主动设的,设了就立刻生效**,不看开关。
36
- const MODE_REASONS: ReadonlySet<NodePermissionReason> = new Set(["mode_readonly", "mode_restricted_not_assigned", "peer_not_allowed"]);
38
+ const MODE_REASONS: ReadonlySet<NodePermissionReason> = new Set(["mode_readonly", "mode_restricted_not_assigned", "peer_not_allowed", "tool_not_allowed"]);
37
39
 
38
40
  // #2969 —— 节点级对端白名单:JSON 数组(alias 或 node_id);NULL = 不限制。
39
41
  // 只增不改:旧代码不读这一列;设为 NULL 时行为与现在完全一致。
42
+ // #2969 后半 —— 接口白名单:JSON 数组(MCP 工具名);NULL = 不限制。
43
+ try { db.exec("ALTER TABLE nodes ADD COLUMN tool_allowlist TEXT"); } catch (e: any) {
44
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
45
+ }
40
46
  try { db.exec("ALTER TABLE nodes ADD COLUMN peer_allowlist TEXT"); } catch (e: any) {
41
47
  if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
42
48
  }
@@ -140,6 +146,8 @@ export type NodeIdentity = {
140
146
  mode: NodePermissionMode;
141
147
  /** #2969 —— 对端白名单(alias / node_id 都算命中)。null = 不限制。 */
142
148
  peerAllowlist: string[] | null;
149
+ /** #2969 后半 —— 接口白名单(MCP 工具名)。null = 不限制。 */
150
+ toolAllowlist: string[] | null;
143
151
  };
144
152
 
145
153
  function normalizePeerAllowlist(raw: unknown): string[] | null {
@@ -152,6 +160,8 @@ function normalizePeerAllowlist(raw: unknown): string[] | null {
152
160
  } catch { return null; }
153
161
  }
154
162
 
163
+ const normalizeToolAllowlist = normalizePeerAllowlist;
164
+
155
165
  function normalizeMode(raw: unknown): NodePermissionMode {
156
166
  return raw === "readonly" || raw === "restricted" ? raw : "normal";
157
167
  }
@@ -176,6 +186,7 @@ export function nodeIdentity(tokenId: string | null | undefined, networkId: stri
176
186
  ownerUserId: row.user_id,
177
187
  mode: "normal",
178
188
  peerAllowlist: null,
189
+ toolAllowlist: null,
179
190
  };
180
191
  }
181
192
  if (!resolved.ok || resolved.networkId !== networkId) {
@@ -187,6 +198,7 @@ export function nodeIdentity(tokenId: string | null | undefined, networkId: stri
187
198
  ownerUserId: row.user_id,
188
199
  mode: "normal",
189
200
  peerAllowlist: null,
201
+ toolAllowlist: null,
190
202
  };
191
203
  }
192
204
  if (resolved.kind === "unregistered") {
@@ -198,10 +210,11 @@ export function nodeIdentity(tokenId: string | null | undefined, networkId: stri
198
210
  ownerUserId: row.user_id,
199
211
  mode: "normal",
200
212
  peerAllowlist: null,
213
+ toolAllowlist: null,
201
214
  };
202
215
  }
203
- const node = db.get<{ owner_user_id: string | null; permission_mode: string | null; peer_allowlist: string | null }>(
204
- `SELECT owner_user_id, permission_mode, peer_allowlist FROM nodes WHERE node_id = ?1 AND network_id = ?2`,
216
+ const node = db.get<{ owner_user_id: string | null; permission_mode: string | null; peer_allowlist: string | null; tool_allowlist: string | null }>(
217
+ `SELECT owner_user_id, permission_mode, peer_allowlist, tool_allowlist FROM nodes WHERE node_id = ?1 AND network_id = ?2`,
205
218
  resolved.nodeId, networkId,
206
219
  );
207
220
  return {
@@ -212,6 +225,7 @@ export function nodeIdentity(tokenId: string | null | undefined, networkId: stri
212
225
  ownerUserId: node?.owner_user_id || row.user_id || null,
213
226
  mode: normalizeMode(node?.permission_mode),
214
227
  peerAllowlist: normalizePeerAllowlist(node?.peer_allowlist),
228
+ toolAllowlist: normalizeToolAllowlist(node?.tool_allowlist),
215
229
  };
216
230
  }
217
231
 
@@ -241,6 +255,7 @@ const HINTS: Record<NodePermissionReason, string> = {
241
255
  human_only: "only people can do this (members, projects, permissions, providers, secrets, other nodes); use a user token",
242
256
  owner_unknown: "this node's owner is unknown; recreate the node token from the owner's account",
243
257
  peer_not_allowed: "this node is limited to an explicit peer allowlist; the target is not on it — ask the node's owner to add it, or clear the allowlist",
258
+ tool_not_allowed: "this node is limited to an explicit tool allowlist; this tool is not on it — ask the node's owner to add it, or clear the allowlist",
244
259
  };
245
260
 
246
261
  export function nodePermissionDeniedBody(reason: NodePermissionReason, route: string): { ok: false; error: "node_permission_denied"; reason: NodePermissionReason; route: string; hint: string } {
@@ -314,6 +329,18 @@ export function dispatchVerdict(id: NodeIdentity, target: AgentRef): Verdict {
314
329
  return null;
315
330
  }
316
331
 
332
+ /**
333
+ * #2969 后半 —— 接口白名单判定。
334
+ *
335
+ * 🔴 `always` 类**永远放行**:get_inbox / ack_inbox / send_reply / report_status 这些是节点
336
+ * 自己的生命周期协议。把它们也挡掉,节点既不能干活、也不能报告自己干不了 —— 那会变成
337
+ * 一个比"没受限"更隐蔽的假活节点。
338
+ */
339
+ export function toolAllowlistVerdict(id: NodeIdentity, tool: string, alwaysClass: boolean): Verdict {
340
+ if (!id.toolAllowlist || alwaysClass) return null;
341
+ return id.toolAllowlist.includes(tool) ? null : { reason: "tool_not_allowed", sample: tool };
342
+ }
343
+
317
344
  /** 广播:只读 / 受限都不行(会发给没派给它、也未必授权的 Agent)。 */
318
345
  export function broadcastVerdict(id: NodeIdentity): Verdict {
319
346
  // #2969 —— 设了对端白名单的节点不能广播:广播的收件人是「任意对端」,
package/src/server.ts CHANGED
@@ -2937,6 +2937,37 @@ return Bun.serve({
2937
2937
  logAudit(restAuth.userId, restAuth.username, "node_permission_mode_changed", "node", node.node_id, JSON.stringify({ from: previous, to: mode }), getClientIP(req), node.network_id);
2938
2938
  return withCors(req, Response.json({ ok: true, node_id: node.node_id, permission_mode: mode, previous }));
2939
2939
  }
2940
+ // #2969 后半 —— 接口白名单:PUT /api/nodes/:id/tool-allowlist { tools: string[] | null }
2941
+ // 与 peer-allowlist 同一套授权口径。
2942
+ const toolAllowMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)\/tool-allowlist$/);
2943
+ if (toolAllowMatch && req.method === "PUT") {
2944
+ if (!restAuth) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
2945
+ if (restAuth.networkId) return userTokenRequired(req);
2946
+ let body: any;
2947
+ try { body = await req.json(); } catch { return withCors(req, Response.json({ ok: false, error: "invalid_json" }, { status: 400 })); }
2948
+ const rawTools = body?.tools;
2949
+ if (rawTools !== null && rawTools !== undefined && !Array.isArray(rawTools)) {
2950
+ return withCors(req, Response.json({ ok: false, error: "invalid_tools", message: "tools must be an array of MCP tool names, or null" }, { status: 400 }));
2951
+ }
2952
+ const tools = Array.isArray(rawTools)
2953
+ ? rawTools.filter((x: unknown): x is string => typeof x === "string" && x.trim().length > 0).map((x: string) => x.trim())
2954
+ : [];
2955
+ if (tools.length > 500) {
2956
+ return withCors(req, Response.json({ ok: false, error: "too_many_tools", message: "at most 500 entries" }, { status: 400 }));
2957
+ }
2958
+ const nodeRef3 = decodeURIComponent(toolAllowMatch[1]);
2959
+ const node3 = db.get<{ node_id: string; network_id: string | null; owner_user_id: string | null; tool_allowlist: string | null }>(
2960
+ "SELECT node_id, network_id, owner_user_id, tool_allowlist FROM nodes WHERE node_id = ?1", nodeRef3);
2961
+ const role3 = node3?.network_id ? getUserNetworkRole(restAuth.userId, node3.network_id) : null;
2962
+ if (!node3 || !node3.network_id || (!role3 && !isAdmin)) return withCors(req, Response.json({ ok: false, error: "node_not_found" }, { status: 404 }));
2963
+ if (!isAdmin && node3.owner_user_id !== restAuth.userId && role3 !== "owner" && role3 !== "admin") {
2964
+ return withCors(req, Response.json({ ok: false, error: "permission_denied", message: "only the node's owner or a network owner/admin can change its tool allowlist" }, { status: 403 }));
2965
+ }
2966
+ const nextTools = tools.length ? JSON.stringify(tools) : null;
2967
+ db.run("UPDATE nodes SET tool_allowlist = ?1 WHERE node_id = ?2", [nextTools, node3.node_id]);
2968
+ logAudit(restAuth.userId, restAuth.username, "node_tool_allowlist_changed", "node", node3.node_id, JSON.stringify({ from: node3.tool_allowlist, to: nextTools }), getClientIP(req), node3.network_id);
2969
+ return withCors(req, Response.json({ ok: true, node_id: node3.node_id, tools: tools.length ? tools : null }));
2970
+ }
2940
2971
  // #2969 —— 节点级对端白名单:PUT /api/nodes/:id/peer-allowlist { peers: string[] | null }
2941
2972
  // 与 permission-mode 同一套授权口径(用户令牌 + 节点主人 / 网络 owner·admin / Hub 管理员)。
2942
2973
  // peers 为 null 或空数组 ⇒ 清空(不限制),与「没有这一列」等价。
package/src/tools.ts CHANGED
@@ -35,7 +35,7 @@ import { addAgentNetworkScope, addAgentTimelineScope, addNetworkScope, canRestWr
35
35
  import { canMessageAgent, restrictedNetworkIds, RESTRICTED_MEMBER_TOOLS, type AgentRef } from "./agent-access.js";
36
36
  import { listedToolFilter, scopeToolsList, type ToolCaller } from "./tool-audience.js";
37
37
  import { agentBatchScheduleInterval, agentCancelSchedule, agentCreateSchedule, agentGetSchedule, agentListSchedules, agentRunScheduleNow, agentScheduleRuns, agentUpdateSchedule } from "./schedule-agent.js";
38
- import { broadcastVerdict, dispatchVerdict, humanOnlyVerdict, NODE_TOOL_CLASS, nodeDecide, nodeIdentity, nodePermissionDeniedBody, writeVerdict, type NodeIdentity, type Verdict } from "./node-permissions.js";
38
+ import { broadcastVerdict, dispatchVerdict, humanOnlyVerdict, NODE_TOOL_CLASS, nodeDecide, nodeIdentity, nodePermissionDeniedBody, writeVerdict, type NodeIdentity, type Verdict, toolAllowlistVerdict } from "./node-permissions.js";
39
39
  import { countInFlightTasks } from "./node-in-flight-tasks.js";
40
40
  import { restrictedMemberAttachmentsDenied } from "./restricted-files.js";
41
41
  import { errorBody } from "./requirements-errors.js";
@@ -285,11 +285,24 @@ function guardNodePermissionTools(server: McpServer, tokenId: string, networkId:
285
285
  };
286
286
  const wrap = (name: string, handler: (...callArgs: any[]) => any) => async (...callArgs: any[]) => {
287
287
  const cls = NODE_TOOL_CLASS[name];
288
- if (cls && cls !== "always" && cls !== "read" && cls !== "requirements" && cls !== "schedule") {
288
+ if (cls) {
289
289
  const id = nodeIdentity(tokenId, networkId);
290
- const args = callArgs[0] && typeof callArgs[0] === "object" ? callArgs[0] as Record<string, unknown> : {};
291
- const verdict = id ? verdictFor(id, name, args) : null;
292
- if (id && nodeDecide(id, `mcp:${name}`, verdict)) return denied(verdict!.reason, `mcp:${name}`);
290
+ if (id) {
291
+ // #2969 后半 —— 接口白名单先判(always 类豁免在函数内部处理)。
292
+ // 放在模式判定之前:主人明确列了「只能用这几个」,优先于模式带来的放宽/收紧。
293
+ const allowVerdict = toolAllowlistVerdict(id, name, cls === "always");
294
+ // 只在真的要被拒时才进闸:`null` 时不写账、不改任何既有行为
295
+ // (读类工具原来完全不碰闸,这里也不该因为"顺手记一笔"而改变它们的路径)。
296
+ if (allowVerdict && nodeDecide(id, `mcp:${name}`, allowVerdict)) {
297
+ return denied(allowVerdict.reason, `mcp:${name}`);
298
+ }
299
+ const gated = cls !== "always" && cls !== "read" && cls !== "requirements" && cls !== "schedule";
300
+ if (gated) {
301
+ const args = callArgs[0] && typeof callArgs[0] === "object" ? callArgs[0] as Record<string, unknown> : {};
302
+ const verdict = verdictFor(id, name, args);
303
+ if (nodeDecide(id, `mcp:${name}`, verdict)) return denied(verdict!.reason, `mcp:${name}`);
304
+ }
305
+ }
293
306
  }
294
307
  return handler(...callArgs);
295
308
  };