@sleep2agi/commhub-server 0.9.0-preview.183 → 0.9.0-preview.184

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.183",
3
+ "version": "0.9.0-preview.184",
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,31 @@
1
+ // #1511 — 「本节点正在做的工作」的唯一计数口径(任务在飞,不是 MCP 请求在飞 ——
2
+ // 后者见 mcp-inflight.ts,两者无关,别混)。
3
+ //
4
+ // 为什么单独一个模块:stop_node 与 restart_node 两个闸门必须用**同一份 SQL**,
5
+ // 客户端要显示的 `restart_readiness.in_flight` 也只能来自这里。
6
+ // 三处各自写一份 SQL 会漂移,而漂移的后果是「客户端说空闲、实际拒绝重启」。
7
+ //
8
+ // 计数规则(#2022/#2029 修订,判据本身未变):
9
+ // · 只算能成为「本节点正在做的工作」的行:`inbox.acked = 0` 且是本会话;
10
+ // · tasks 行按状态判,终态(replied/failed/cancelled/expired)不算,且**不设龄上限**;
11
+ // · 没有对应 tasks 行的(无状态)按 60 分钟龄判,超过就不算。
12
+ import { db } from "./db.js";
13
+
14
+ export const IN_FLIGHT_MAX_AGE_MINUTES = 60;
15
+
16
+ export function countInFlightTasks(alias: string, networkId: string | null): number {
17
+ const row = db.get<{ n: number }>(
18
+ `SELECT COUNT(*) AS n FROM inbox i
19
+ LEFT JOIN tasks t
20
+ ON i.type = 'task'
21
+ AND t.task_id = COALESCE(i.task_id, i.id)
22
+ WHERE i.session_name = ?1 AND i.acked = 0
23
+ AND COALESCE(i.network_id, ?2) = ?2
24
+ AND ((t.task_id IS NOT NULL
25
+ AND t.status NOT IN ('replied', 'failed', 'cancelled', 'expired'))
26
+ OR (t.task_id IS NULL
27
+ AND i.created_at >= datetime('now', ?3)))`,
28
+ alias, networkId, `-${IN_FLIGHT_MAX_AGE_MINUTES} minutes`,
29
+ );
30
+ return row?.n ?? 0;
31
+ }
@@ -253,6 +253,62 @@ describe("GET /api/networks/:id/node-permission-report", () => {
253
253
  });
254
254
  });
255
255
 
256
+ // #2823 —— 调用面计数:拒绝日志给不了分母。
257
+ // 生产 30 天 `node_permission_log` 0 行,分不清「没人越界」和「没人碰过这些工具」,
258
+ // 而 #525 要切 enforce,恰恰需要一个分母。
259
+ describe("#2823 调用面计数(node_tool_calls)", () => {
260
+ const callHits = (nodeId: string, tool: string) => Number(
261
+ db.get<{ h: number | string | null }>(
262
+ "SELECT SUM(hits) AS h FROM node_tool_calls WHERE network_id = ?1 AND node_id = ?2 AND tool = ?3",
263
+ net, nodeId, tool,
264
+ )?.h ?? 0);
265
+ const denyRows = (nodeId: string) => logRows(nodeId).length;
266
+ const toolCallTotal = (nodeId: string) => Number(
267
+ db.get<{ h: number | string | null }>(
268
+ "SELECT SUM(hits) AS h FROM node_tool_calls WHERE network_id = ?1 AND node_id = ?2",
269
+ net, nodeId,
270
+ )?.h ?? 0);
271
+
272
+ test("放行的调用也计数,但**不进**拒绝日志(两张表分开)", async () => {
273
+ const before = { calls: toolCallTotal(node.nN.id), denials: denyRows(node.nN.id) };
274
+ expect((await mcp(node.nN.token, "send_task", { alias: node.other.alias, task: "counted" })).ok).toBe(true);
275
+ expect((await mcp(node.nN.token, "send_task", { alias: node.other.alias, task: "counted again" })).ok).toBe(true);
276
+ expect(toolCallTotal(node.nN.id)).toBe(before.calls + 2);
277
+ expect(callHits(node.nN.id, "mcp:send_task")).toBeGreaterThanOrEqual(2);
278
+ // 关键:分母涨了,分子(拒绝)没动 —— 这才叫「命中率」可算。
279
+ expect(denyRows(node.nN.id)).toBe(before.denials);
280
+ });
281
+
282
+ test("本来会被拒的调用两个表都记(分子与分母同源)", async () => {
283
+ const beforeCalls = callHits(node.nN.id, "mcp:projects_create");
284
+ const beforeDeny = hitsOf(node.nN.id, "mcp:projects_create", "human_only");
285
+ const p = await mcp(node.nN.token, "projects_create", { network_id: net, name: `p-count-${stamp}` });
286
+ expect(p.error).not.toBe("node_permission_denied");
287
+ expect(callHits(node.nN.id, "mcp:projects_create")).toBe(beforeCalls + 1);
288
+ expect(hitsOf(node.nN.id, "mcp:projects_create", "human_only")).toBe(beforeDeny + 1);
289
+ });
290
+
291
+ test("报表同时给分母与分子,且拒绝口径 total 不被放行调用污染", async () => {
292
+ const before = await call(user.boss.token, "GET", `/api/networks/${net}/node-permission-report`);
293
+ expect(before.status).toBe(200);
294
+ const beforeDenied = Number(before.body.total);
295
+ const beforeCalls = Number(before.body.tool_calls.total);
296
+
297
+ expect((await mcp(node.nN.token, "send_task", { alias: node.other.alias, task: "report bump" })).ok).toBe(true);
298
+
299
+ const after = await call(user.boss.token, "GET", `/api/networks/${net}/node-permission-report`);
300
+ expect(after.status).toBe(200);
301
+ expect(Number(after.body.tool_calls.total)).toBe(beforeCalls + 1);
302
+ expect(Number(after.body.total)).toBe(beforeDenied);
303
+ expect(Array.isArray(after.body.tool_calls.by_tool)).toBe(true);
304
+ expect(after.body.tool_calls.by_tool.every((r: any) => typeof r.tool === "string" && typeof r.hits === "number")).toBe(true);
305
+ });
306
+
307
+ test("节点令牌读不到报表(分母同样只给人看)", async () => {
308
+ expect((await call(node.nN.token, "GET", `/api/networks/${net}/node-permission-report`)).status).toBe(403);
309
+ });
310
+ });
311
+
256
312
  describe("bookkeeping", () => {
257
313
  test("every MCP tool a node can call has a permission class", async () => {
258
314
  const s = new McpServer({ name: "np", version: "1" });
@@ -49,6 +49,59 @@ db.exec(`
49
49
  CREATE INDEX IF NOT EXISTS idx_node_permission_log_hour ON node_permission_log(network_id, hour);
50
50
  `);
51
51
 
52
+ // #2823 —— 调用面计数。
53
+ //
54
+ // 为什么需要第二张表:`node_permission_log` 只记 **would-be denial**(`if (!verdict) return false`),
55
+ // 所以它回答不了「节点到底有没有在调这些受限工具」。生产实测 30 天 0 行,
56
+ // 分不清「没人越界」和「几乎没人碰过」——而这两者的结论完全相反(#525 的切 enforce 决策就卡在这)。
57
+ //
58
+ // 设计取舍:
59
+ // · 只记**到达闸的调用**(nodeDecide 的入参就是 classified 工具),不记全部 MCP 调用;
60
+ // · 与拒绝日志同一条纪律:按 (网络, 节点, 工具, 小时) 合并成一行 + hits,不逐次插行;
61
+ // · 同样的 30 天保留期与 20000 行上限,超限后只加已有的行;
62
+ // · 与 `node_permission_log` **分开**,绝不把放行样本混进拒绝统计(那会把既有报表口径改坏)。
63
+ db.exec(`
64
+ CREATE TABLE IF NOT EXISTS node_tool_calls (
65
+ network_id TEXT NOT NULL,
66
+ node_id TEXT NOT NULL,
67
+ tool TEXT NOT NULL,
68
+ hour TEXT NOT NULL,
69
+ hits INTEGER NOT NULL DEFAULT 1,
70
+ PRIMARY KEY (network_id, node_id, tool, hour)
71
+ );
72
+ CREATE INDEX IF NOT EXISTS idx_node_tool_calls_hour ON node_tool_calls(network_id, hour);
73
+ `);
74
+
75
+ let callLogFull = false;
76
+ export const TOOL_CALL_MAX_ROWS = 20_000;
77
+
78
+ /** 计一次「到达权限闸」的工具调用。绝不影响请求本身 —— 出错只写日志。 */
79
+ export function recordNodeToolCall(id: NodeIdentity, tool: string): void {
80
+ try {
81
+ const now = new Date();
82
+ if (now.getTime() - lastPrune > PRUNE_EVERY_MS) {
83
+ pruneNodePermissionLog(now);
84
+ const calls = Number(db.get<{ n: number | string }>("SELECT COUNT(*) AS n FROM node_tool_calls")?.n ?? 0);
85
+ callLogFull = calls >= TOOL_CALL_MAX_ROWS;
86
+ db.run("DELETE FROM node_tool_calls WHERE hour < ?1", [hourOf(new Date(now.getTime() - LOG_RETENTION_DAYS * 86_400_000))]);
87
+ }
88
+ const hour = hourOf(now);
89
+ const name = tool.slice(0, 120);
90
+ const updated = db.run(
91
+ "UPDATE node_tool_calls SET hits = hits + 1 WHERE network_id = ?1 AND node_id = ?2 AND tool = ?3 AND hour = ?4",
92
+ [id.networkId, id.logKey, name, hour],
93
+ );
94
+ if (Number(updated?.changes ?? 0) > 0 || callLogFull) return;
95
+ db.run(
96
+ `INSERT INTO node_tool_calls (network_id, node_id, tool, hour, hits) VALUES (?1, ?2, ?3, ?4, 1)
97
+ ON CONFLICT(network_id, node_id, tool, hour) DO UPDATE SET hits = node_tool_calls.hits + 1`,
98
+ [id.networkId, id.logKey, name, hour],
99
+ );
100
+ } catch (e) {
101
+ console.error(`[node-permissions] tool-call counter failed: ${(e as Error).message}`);
102
+ }
103
+ }
104
+
52
105
  /** 开关。未设 / 写错 → log(安全的默认:只记不拦)。每次现读:测试和运维改环境变量后无需重启模块。 */
53
106
  export function nodePermissionsFlag(): NodePermissionsFlag {
54
107
  const raw = (process.env.COMMHUB_NODE_PERMISSIONS ?? "").trim().toLowerCase();
@@ -131,6 +184,9 @@ export type Verdict = { reason: NodePermissionReason; sample?: string } | null;
131
184
  * 返回 true = 拒绝。
132
185
  */
133
186
  export function nodeDecide(id: NodeIdentity, route: string, verdict: Verdict): boolean {
187
+ // #2823 —— 先计数,再判定。放行与拒绝都算一次「到达闸的调用」,
188
+ // 这样「受限工具被调了 N 次、其中本来会被拒 M 次」才可测;否则分母永远是 0。
189
+ recordNodeToolCall(id, route);
134
190
  if (!verdict) return false;
135
191
  const explicit = MODE_REASONS.has(verdict.reason);
136
192
  const flag = nodePermissionsFlag();
@@ -0,0 +1,121 @@
1
+ // #1511 —— `/api/nodes` 要给客户端一份「能不能替你重启」的判断,而且要和在途任务一致。
2
+ //
3
+ // 客户端场景:保存密钥/env 之后,必须能立刻二选一告诉用户
4
+ // 「已安排重启」 vs 「需要你自己重启(命令:…)」
5
+ // 判据必须和 restart_node / stop_node 同一份,否则会出现「客户端说空闲、一点就被拒」。
6
+
7
+ import { describe, expect, test, beforeAll, afterAll } from "bun:test";
8
+ import { mkdtempSync, rmSync } from "fs";
9
+ import { join } from "path";
10
+ import { tmpdir } from "os";
11
+ import { register, createNetworkTokenForNode } from "./auth.js";
12
+ import { db } from "./db.js";
13
+
14
+ const DIR = mkdtempSync(join(tmpdir(), "anet-restart-readiness-"));
15
+ let BASE = "";
16
+ let hub: any = null;
17
+ const PW = "RestartReadinessPassw0rd!";
18
+ let NET = "";
19
+ let TOKEN = "";
20
+ let USER = "";
21
+
22
+ async function send(method: string, path: string, body?: unknown) {
23
+ const res = await fetch(`${BASE}${path}`, { method, headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
24
+ const text = await res.text();
25
+ let json: any = null; try { json = JSON.parse(text); } catch {}
26
+ return { status: res.status, body: json };
27
+ }
28
+
29
+ let seq = 0;
30
+ function mkNode(prefix: "node" | "n", alias: string, opts: { role?: string; lifecycle?: string } = {}) {
31
+ const id = `${prefix}_rr_${seq++}_${Date.now()}`;
32
+ const snap = opts.role ? JSON.stringify({ role: opts.role }) : null;
33
+ db.run("INSERT INTO nodes (node_id, node_name, alias, runtime, network_id, lifecycle_state, config_snapshot, owner_user_id) VALUES (?1,?2,?2,'codex',?3,?4,?5,?6)",
34
+ [id, alias, NET, opts.lifecycle ?? "active", snap, USER]);
35
+ return id;
36
+ }
37
+ function mkTaskFor(alias: string, status: string) {
38
+ const taskId = `t_rr_${seq++}`;
39
+ db.run("INSERT INTO tasks (task_id, from_name, to_name, priority, status, content, created_at, network_id) VALUES (?1,'x',?2,'normal',?3,'c',datetime('now'),?4)", [taskId, alias, status, NET]);
40
+ db.run("INSERT INTO inbox (id, session_name, type, task_id, acked, content, created_at, network_id) VALUES (?1,?2,'task',?3,0,'c',datetime('now'),?4)", [`i_rr_${seq++}`, alias, taskId, NET]);
41
+ return taskId;
42
+ }
43
+
44
+ function mkCreateRequest(nodeId: string) {
45
+ db.run(`INSERT INTO node_create_requests
46
+ (request_id, network_id, daemon_node_id, child_name, runtime, flags_json, env_keys, status, created_at, created_by_token)
47
+ VALUES (?1,?2,'node_daemon_rr',?3,'codex','{}','[]','succeeded',?4,'t')`,
48
+ [`cr_${nodeId.slice(5)}`, NET, `child-${seq++}`, Date.now()]);
49
+ }
50
+
51
+ const rowOf = async (nodeId: string) => {
52
+ const r = await send("GET", `/api/nodes?network_id=${NET}&node_id=${nodeId}`);
53
+ expect(r.status).toBe(200);
54
+ return (r.body.nodes as any[])[0];
55
+ };
56
+
57
+ beforeAll(async () => {
58
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
59
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
60
+ process.env.HOST = "127.0.0.1";
61
+ const a = register(`rr_owner_${Date.now()}`, PW, undefined, "Owner");
62
+ expect(a.ok).toBe(true);
63
+ TOKEN = a.token!; USER = a.user!.user_id; NET = a.network_id!;
64
+ const mod: any = await import("./server.js");
65
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
66
+ BASE = `http://127.0.0.1:${hub.port}`;
67
+ }, 30_000);
68
+
69
+ afterAll(() => {
70
+ try { hub?.stop?.(true); } catch {}
71
+ try { rmSync(DIR, { recursive: true, force: true }); } catch {}
72
+ });
73
+
74
+ describe("#1511 restart_readiness", () => {
75
+ test("没人管的节点 = manual,且 can_restart_now=false", async () => {
76
+ const id = mkNode("n", `solo-${seq}`);
77
+ const row = await rowOf(id);
78
+ expect(row.restart_readiness).toEqual({ path: "manual", in_flight: 0, can_restart_now: false });
79
+ });
80
+
81
+ test("created-daemon 的节点 = restart_node;在途任务让它变 false", async () => {
82
+ const id = mkNode("node", `supervised-${seq}`);
83
+ mkCreateRequest(id);
84
+ let row = await rowOf(id);
85
+ expect(row.restart_readiness.path).toBe("restart_node");
86
+ expect(row.restart_readiness.can_restart_now).toBe(true);
87
+
88
+ mkTaskFor(row.alias, "running");
89
+ row = await rowOf(id);
90
+ expect(row.restart_readiness.in_flight).toBe(1);
91
+ expect(row.restart_readiness.can_restart_now).toBe(false);
92
+ });
93
+
94
+ test("终态任务不算在途(与 stop_node 同一判据)", async () => {
95
+ const id = mkNode("node", `replied-${seq}`);
96
+ mkCreateRequest(id);
97
+ const row = await rowOf(id);
98
+ mkTaskFor(row.alias, "replied");
99
+ const after = await rowOf(id);
100
+ expect(after.restart_readiness.in_flight).toBe(0);
101
+ expect(after.restart_readiness.can_restart_now).toBe(true);
102
+ });
103
+
104
+ test("adopt 来的节点 = stop_then_start(restart_node 会被拒,但 daemon 仍能 Stop→Start)", async () => {
105
+ const id = mkNode("n", `adopted-${seq}`);
106
+ db.run("INSERT INTO node_daemon_bindings (request_id, network_id, node_id, daemon_node_id, workdir, requested_by, status, created_at, updated_at) VALUES (?1,?2,?3,'node_daemon_rr','/tmp','u','active',0,0)",
107
+ [`adopt_rr_${seq}`, NET, id]);
108
+ const row = await rowOf(id);
109
+ expect(row.restart_readiness).toEqual({ path: "stop_then_start", in_flight: 0, can_restart_now: true });
110
+ });
111
+
112
+ test("stopped 节点:在途计数不挡路(restart 是把 lifecycle 翻回 active 的出口)", async () => {
113
+ const id = mkNode("node", `stopped-${seq}`, { lifecycle: "stopped" });
114
+ mkCreateRequest(id);
115
+ const row = await rowOf(id);
116
+ mkTaskFor(row.alias, "running");
117
+ const after = await rowOf(id);
118
+ expect(after.restart_readiness.in_flight).toBe(1);
119
+ expect(after.restart_readiness.can_restart_now).toBe(true);
120
+ });
121
+ });
package/src/server.ts CHANGED
@@ -14,6 +14,8 @@ import { readNodeHealth } from "./node-health-store.js";
14
14
  import { wantsAllTools } from "./tool-audience.js";
15
15
  import { assertNodeHealthy, degradedLayers } from "./node-health-guard.js";
16
16
  import { auditDepartment, createDepartment, deleteDepartment, listDepartments, setAgentDepartment, setMemberDepartment, updateDepartment } from "./departments.js";
17
+ import { activeBinding, createdDaemon } from "./node-daemon-bindings.js";
18
+ import { countInFlightTasks } from "./node-in-flight-tasks.js";
17
19
  import { addManualMember, canManageGroup, createDepartmentGroup, getDepartmentGroup, groupById, groupTx, groupViewerCan, isGroupMember, listGroupMembers, listVisibleGroups, readGroup, removeManualMember, renameGroup, syncDepartmentGroups } from "./department-groups.js";
18
20
  import { DEPARTMENT_SCOPE_DENIED, departmentLeaders, departmentSubtree, headScope, listDepartmentProjectGrants, managedDepartmentIds, membersIn, replaceDepartmentProjectGrants } from "./department-heads.js";
19
21
  import { redactMessageRow } from "./redact-tokens.js";
@@ -3000,7 +3002,24 @@ return Bun.serve({
3000
3002
  entry.routes.push({ route: r.route, reason: r.reason, hits, sample: r.sample, last_hour: r.last_hour });
3001
3003
  }
3002
3004
  const nodes = [...byNode.values()].sort((a, b) => b.total - a.total || a.node_id.localeCompare(b.node_id));
3003
- return withCors(req, Response.json({ ok: true, network_id: networkId, since: new Date(sinceMs).toISOString(), mode: nodePermissionsFlag(), total: nodes.reduce((n, e) => n + e.total, 0), nodes }));
3005
+ // #2823 —— 调用面分母。`total` 只数「本来会被拒」的次数;没有分母时
3006
+ // 「0 命中」既可能是没人越界,也可能是没人碰过这些工具,两者结论相反。
3007
+ // 这里单独给一份 classified 工具的真实调用数(按小时合并后的 hits 之和),
3008
+ // 与拒绝统计**分表分字段**,不改上面 `total` 的口径。
3009
+ const callRows = db.all<{ tool: string; hits: number | string }>(
3010
+ `SELECT tool, SUM(hits) AS hits FROM node_tool_calls
3011
+ WHERE network_id = ?1 AND hour >= ?2 GROUP BY tool ORDER BY SUM(hits) DESC`,
3012
+ networkId, sinceHour,
3013
+ );
3014
+ const toolCalls = callRows.map((r) => ({ tool: r.tool, hits: Number(r.hits) }));
3015
+ const deniedTotal = nodes.reduce((n, e) => n + e.total, 0);
3016
+ const callsTotal = toolCalls.reduce((n, e) => n + e.hits, 0);
3017
+ return withCors(req, Response.json({
3018
+ ok: true, network_id: networkId, since: new Date(sinceMs).toISOString(), mode: nodePermissionsFlag(),
3019
+ total: deniedTotal,
3020
+ nodes,
3021
+ tool_calls: { total: callsTotal, by_tool: toolCalls },
3022
+ }));
3004
3023
  }
3005
3024
 
3006
3025
  // ── #1473 (#909): read-only Hub catalogs for the desktop client ──
@@ -5260,6 +5279,41 @@ return Bun.serve({
5260
5279
  if (alias) { sql += ` AND alias = ?${params.length + 1}`; params.push(alias); }
5261
5280
  sql += " ORDER BY updated_at DESC";
5262
5281
  const rawRows = db.all<Record<string, any>>(sql, ...params);
5282
+ // #1511 —— 「能不能替你重启」必须在客户端保存密钥前就说清楚:
5283
+ // path='restart_node' 被 created-daemon 监督,exit-75 会被自动拉起
5284
+ // path='stop_then_start' 是 adopt 来的节点:restart_node 明确拒绝,但 daemon 仍能 Stop→Start
5285
+ // path='manual' 没人管它,必须上机
5286
+ // in_flight 用与 stop_node / restart_node 同一份 SQL(node-in-flight-tasks.ts),
5287
+ // 否则会出现「客户端说空闲、一点就被拒」。
5288
+ // 批量化:daemon 创建记录与 adopt 绑定各一条 IN 查询取齐;在途计数只对
5289
+ // 非 manual 的节点现算(绝大多数节点没有绑定 ⇒ 一次都不查)。
5290
+ const createdIds = new Map<string, string>();
5291
+ const bindingIds = new Map<string, string>();
5292
+ const wanted = rawRows.filter((r) => typeof r.node_id === "string");
5293
+ if (wanted.length) {
5294
+ const placeholders = wanted.map((_, i) => `?${i + 1}`).join(",");
5295
+ // createdDaemon 的键是 `cr_` + node_id 去掉 `node_`;一次 IN 取回。
5296
+ const crKeys = wanted.filter((r) => String(r.node_id).startsWith("node_")).map((r) => `cr_${String(r.node_id).slice(5)}`);
5297
+ if (crKeys.length) {
5298
+ const ph = crKeys.map((_, i) => `?${i + 1}`).join(",");
5299
+ for (const row of db.all<{ request_id: string; daemon_node_id: string }>(
5300
+ `SELECT request_id, daemon_node_id FROM node_create_requests WHERE request_id IN (${ph})`, ...crKeys,
5301
+ )) createdIds.set(`node_${row.request_id.slice(3)}`, row.daemon_node_id);
5302
+ }
5303
+ for (const row of db.all<{ node_id: string; daemon_node_id: string }>(
5304
+ `SELECT node_id, daemon_node_id FROM node_daemon_bindings WHERE status = 'active' AND node_id IN (${placeholders})`,
5305
+ ...wanted.map((r) => r.node_id),
5306
+ )) bindingIds.set(row.node_id, row.daemon_node_id);
5307
+ }
5308
+ const restartReadiness = (nodeId: string, alias: string | null, networkId: string | null, role: string | null, lifecycle: string | null) => {
5309
+ const supervised = createdIds.has(nodeId) || role === "host_supervisor";
5310
+ const adopted = !supervised && bindingIds.has(nodeId);
5311
+ const path = supervised ? "restart_node" : adopted ? "stop_then_start" : "manual";
5312
+ // 手动节点不需要在途计数:算出来也用不上,白查一次。
5313
+ const inFlight = path === "manual" || !alias ? 0 : countInFlightTasks(alias, networkId);
5314
+ const blockedByInFlight = lifecycle === "active" && inFlight > 0;
5315
+ return { path, in_flight: inFlight, can_restart_now: path !== "manual" && !blockedByInFlight };
5316
+ };
5263
5317
  // Add a single new field `role: string | null` per row, extracted from
5264
5318
  // config_snapshot JSON. Daemon nodes that posted role='host_supervisor'
5265
5319
  // via report_status surface here; dashboard uses this for daemon
@@ -5358,6 +5412,7 @@ return Bun.serve({
5358
5412
  lifecycle_daemon_node_id: controllable.get(r.node_id) ?? null,
5359
5413
  ...(management ? (management.get(r.node_id) ?? { managed: "none", adoption: null }) : {}),
5360
5414
  viewer_can: { permission_mode: canSetPermissionMode(r) },
5415
+ restart_readiness: restartReadiness(r.node_id, r.alias, r.network_id, role, r.lifecycle_state ?? null),
5361
5416
  };
5362
5417
  });
5363
5418
  return withCors(req, Response.json({ ok: true, nodes: rows, count: rows.length }));
package/src/tools.ts CHANGED
@@ -36,6 +36,7 @@ import { canMessageAgent, restrictedNetworkIds, RESTRICTED_MEMBER_TOOLS, type Ag
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
38
  import { broadcastVerdict, dispatchVerdict, humanOnlyVerdict, NODE_TOOL_CLASS, nodeDecide, nodeIdentity, nodePermissionDeniedBody, writeVerdict, type NodeIdentity, type Verdict } from "./node-permissions.js";
39
+ import { countInFlightTasks } from "./node-in-flight-tasks.js";
39
40
  import { restrictedMemberAttachmentsDenied } from "./restricted-files.js";
40
41
  import { errorBody } from "./requirements-errors.js";
41
42
  import { handleRequirementsRequest } from "./requirements.js";
@@ -4264,23 +4265,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
4264
4265
  // 计数规则见 stop_node 内的长注释(#2022/#2029 修订:能成为「本节点正在做的
4265
4266
  // 工作」的行才算——tasks 行按状态判、终态不算且不设龄上限;无状态行按 60 分钟
4266
4267
  // 龄判)。抽成一处后,两个闸门共享同一份 SQL,不再各自漂移。
4267
- const IN_FLIGHT_MAX_AGE_MINUTES = 60;
4268
- function countInFlightTasks(alias: string, networkId: string | null): number {
4269
- const row = db.get<{ n: number }>(
4270
- `SELECT COUNT(*) AS n FROM inbox i
4271
- LEFT JOIN tasks t
4272
- ON i.type = 'task'
4273
- AND t.task_id = COALESCE(i.task_id, i.id)
4274
- WHERE i.session_name = ?1 AND i.acked = 0
4275
- AND COALESCE(i.network_id, ?2) = ?2
4276
- AND ((t.task_id IS NOT NULL
4277
- AND t.status NOT IN ('replied', 'failed', 'cancelled', 'expired'))
4278
- OR (t.task_id IS NULL
4279
- AND i.created_at >= datetime('now', ?3)))`,
4280
- alias, networkId, `-${IN_FLIGHT_MAX_AGE_MINUTES} minutes`,
4281
- );
4282
- return row?.n ?? 0;
4283
- }
4268
+ // #1511 —— 计数口径抽到 `in-flight.ts`:stop_node / restart_node / REST 的
4269
+ // restart_readiness 三处共用同一份 SQL。这里保留一个同名别名,调用点不动。
4284
4270
 
4285
4271
  server.tool(
4286
4272
  "restart_node",
@@ -5592,7 +5578,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
5592
5578
  // ever retire them, so they get the age ceiling
5593
5579
  // IN_FLIGHT_MAX_AGE_MINUTES on inbox.created_at.
5594
5580
  // The count stays a per-alias inbox count: one PK join per row.
5595
- // 计数实现在上方 countInFlightTasks。#1511 让 restart_node 共用同一份规则,判据本身未变。
5581
+ // 计数统一在 node-in-flight-tasks.ts:stop_node / restart_node / REST 的 restart_readiness 共用。
5596
5582
  const inFlight = countInFlightTasks(node.alias, node.network_id);
5597
5583
  if (inFlight > 0 && !args.force) {
5598
5584
  return { ok: false, error: "node_busy_in_flight", in_flight_count: inFlight, hint: "set force=true to override (audit logged)" };