@sleep2agi/commhub-server 0.9.0-preview.182 → 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 +1 -1
- package/src/agent-teams-http.test.ts +8 -1
- package/src/departments-agent-count.test.ts +129 -0
- package/src/departments.ts +41 -2
- package/src/node-in-flight-tasks.ts +31 -0
- package/src/node-permissions-http.test.ts +56 -0
- package/src/node-permissions.ts +56 -0
- package/src/restart-readiness-http.test.ts +121 -0
- package/src/server.ts +59 -2
- package/src/tools.ts +8 -26
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.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",
|
|
@@ -316,7 +316,14 @@ describe("#764 network deletion removes team rows", () => {
|
|
|
316
316
|
describe("#764 existing endpoints unchanged", () => {
|
|
317
317
|
test("departments / humans / node config byte-identical after all team operations", async () => {
|
|
318
318
|
const after = await snapshot();
|
|
319
|
-
|
|
319
|
+
// #2822 —— `/departments` 新增了 `agents_unassigned`(轴2:没有显式部门的 Agent 数)。
|
|
320
|
+
// 它是**活跃的节点普查**,而本文件在 #764 用例里故意 `DELETE /api/nodes/<n2>` 删了一个节点,
|
|
321
|
+
// 所以这一格必然从 3 变 2。部门/成员结构仍然要求逐字节相同;节点普查单独钉住差额,
|
|
322
|
+
// 不把「删节点」当成「团队操作改了部门」。
|
|
323
|
+
const dept = (t: string) => { const o = JSON.parse(t); const n = o.agents_unassigned; delete o.agents_unassigned; return { body: JSON.stringify(o), n }; };
|
|
324
|
+
const a = dept(after.departments), b = dept(before.departments);
|
|
325
|
+
expect(a.body).toBe(b.body);
|
|
326
|
+
expect(a.n).toBe((b.n as number) - 1);
|
|
320
327
|
expect(after.humans).toBe(before.humans);
|
|
321
328
|
expect(after.node).toBe(before.node);
|
|
322
329
|
});
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// #2822 —— 部门 → Agent 计数(轴2)必须是接口直接给出的,而且要和客户端同一口径。
|
|
2
|
+
//
|
|
3
|
+
// 背景:admin 看到 Dashboard 部门盘「未分组 105 / TMAI 1 / 其余 0」,客户端同一棵树却是
|
|
4
|
+
// 「TMWork 15 / TM智能体空间 2」。根因是**两个轴**被混成了一个:
|
|
5
|
+
// 轴1 人 network_members.department_id
|
|
6
|
+
// 轴2 Agent nodes.department_id ← 权威
|
|
7
|
+
// 本测试钉住:HTTP `GET …/departments` 与 MCP `departments list` 都直接用 nodes.department_id,
|
|
8
|
+
// 并且按 #2596 的口径去重(同 alias 只算一个,保留 updated_at 最新的那一行)。
|
|
9
|
+
|
|
10
|
+
import { describe, expect, test, beforeAll, afterAll } from "bun:test";
|
|
11
|
+
import { mkdtempSync, rmSync } from "fs";
|
|
12
|
+
import { join } from "path";
|
|
13
|
+
import { tmpdir } from "os";
|
|
14
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
15
|
+
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
16
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
17
|
+
import { register } from "./auth.js";
|
|
18
|
+
import { db } from "./db.js";
|
|
19
|
+
import { registerTools } from "./tools.js";
|
|
20
|
+
|
|
21
|
+
const DIR = mkdtempSync(join(tmpdir(), "anet-dept-agent-count-"));
|
|
22
|
+
let BASE = "";
|
|
23
|
+
let hub: any = null;
|
|
24
|
+
const PW = "DeptAgentCountPassw0rd!";
|
|
25
|
+
let NET = "";
|
|
26
|
+
let TOKEN = "";
|
|
27
|
+
const UID: string[] = [];
|
|
28
|
+
|
|
29
|
+
async function send(token: string, method: string, path: string, body?: unknown) {
|
|
30
|
+
const res = await fetch(`${BASE}${path}`, { method, headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
31
|
+
const text = await res.text();
|
|
32
|
+
let json: any = null;
|
|
33
|
+
try { json = JSON.parse(text); } catch {}
|
|
34
|
+
return { status: res.status, body: json };
|
|
35
|
+
}
|
|
36
|
+
const D = () => `/api/networks/${NET}/departments`;
|
|
37
|
+
|
|
38
|
+
function mkDept(name: string): string {
|
|
39
|
+
const id = `dept_${name.toLowerCase().replace(/[^a-z0-9]/g, "")}_${Math.random().toString(36).slice(2, 8)}`;
|
|
40
|
+
db.run("INSERT INTO network_departments (network_id, department_id, name) VALUES (?1, ?2, ?3)", [NET, id, name]);
|
|
41
|
+
return id;
|
|
42
|
+
}
|
|
43
|
+
let seq = 0;
|
|
44
|
+
function mkNode(alias: string | null, departmentId: string | null, updatedAt: string) {
|
|
45
|
+
const nodeId = `n_c_${Date.now()}_${seq++}`;
|
|
46
|
+
db.run(
|
|
47
|
+
"INSERT INTO nodes (node_id, node_name, alias, runtime, network_id, department_id, updated_at) VALUES (?1, ?2, ?3, 'codex', ?4, ?5, ?6)",
|
|
48
|
+
[nodeId, alias || nodeId, alias, NET, departmentId, updatedAt],
|
|
49
|
+
);
|
|
50
|
+
return nodeId;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
beforeAll(async () => {
|
|
54
|
+
process.env.COMMHUB_DB ||= join(DIR, "hub.db");
|
|
55
|
+
process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
|
|
56
|
+
process.env.HOST = "127.0.0.1";
|
|
57
|
+
const a = register(`dca_owner_${Date.now()}`, PW, undefined, "Owner");
|
|
58
|
+
expect(a.ok).toBe(true);
|
|
59
|
+
TOKEN = a.token!;
|
|
60
|
+
UID.push(a.user!.user_id);
|
|
61
|
+
NET = a.network_id!;
|
|
62
|
+
db.run("UPDATE users SET role = 'admin' WHERE user_id = ?1", [a.user!.user_id]);
|
|
63
|
+
const mod: any = await import("./server.js");
|
|
64
|
+
hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
65
|
+
BASE = `http://127.0.0.1:${hub.port}`;
|
|
66
|
+
}, 30_000);
|
|
67
|
+
|
|
68
|
+
afterAll(() => {
|
|
69
|
+
try { hub?.stop?.(true); } catch {}
|
|
70
|
+
try { rmSync(DIR, { recursive: true, force: true }); } catch {}
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
describe("#2822 部门 → Agent 计数走 nodes.department_id(轴2)", () => {
|
|
74
|
+
test("agent_count 只数显式归属的 Agent;agents_unassigned 单独给;人的部门不参与", async () => {
|
|
75
|
+
const work = mkDept("TMWork");
|
|
76
|
+
const space = mkDept("TM智能体空间");
|
|
77
|
+
const infra = mkDept("TM基建");
|
|
78
|
+
|
|
79
|
+
// 轴2:TMWork 3 个(其中两个同 alias,旧的应被去重掉)→ 期望 2
|
|
80
|
+
mkNode("alice", work, "2026-10-01 00:00:00");
|
|
81
|
+
mkNode("alice", work, "2026-10-20 00:00:00"); // 更新 ⇒ 保留这一行
|
|
82
|
+
mkNode("bob", work, "2026-10-20 00:00:00");
|
|
83
|
+
// TM智能体空间 1 个
|
|
84
|
+
mkNode("carol", space, "2026-10-20 00:00:00");
|
|
85
|
+
// TM基建:同 alias 但更新的一行被移到了别的部门 ⇒ 计数要跟着最新那一行走
|
|
86
|
+
mkNode("dave", infra, "2026-10-01 00:00:00");
|
|
87
|
+
mkNode("dave", space, "2026-10-25 00:00:00");
|
|
88
|
+
// 未归属 2 个
|
|
89
|
+
mkNode("eve", null, "2026-10-20 00:00:00");
|
|
90
|
+
mkNode("frank", "", "2026-10-20 00:00:00");
|
|
91
|
+
// 把负责人放进 TM基建(轴1)—— 轴1 有任何值都不能影响轴2 的计数
|
|
92
|
+
db.run("UPDATE network_members SET department_id = ?2 WHERE network_id = ?1 AND user_id = ?3", [NET, infra, UID[0]]);
|
|
93
|
+
|
|
94
|
+
const r = await send(TOKEN, "GET", D());
|
|
95
|
+
expect(r.status).toBe(200);
|
|
96
|
+
const byName = new Map<string, any>((r.body.departments as any[]).map((d) => [d.name, d]));
|
|
97
|
+
|
|
98
|
+
expect(byName.get("TMWork").agent_count).toBe(2); // alice 去重后 + bob
|
|
99
|
+
expect(byName.get("TM智能体空间").agent_count).toBe(2); // carol + dave(最新那一行在这里)
|
|
100
|
+
expect(byName.get("TM基建").agent_count).toBe(0); // dave 已被移走;人的部门不算
|
|
101
|
+
expect(r.body.agents_unassigned).toBe(2); // eve + frank(domain: department_id 空)
|
|
102
|
+
|
|
103
|
+
// 轴1 仍然是直属人数,不受影响
|
|
104
|
+
expect(byName.get("TM基建").member_count).toBe(1);
|
|
105
|
+
expect(byName.get("TMWork").member_count).toBe(0);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("MCP departments list 与 HTTP 同一口径(不再各自算一遍)", async () => {
|
|
109
|
+
// 真的走 in-process MCP transport(不是直调函数):要验的正是「工具返回的就是同一份口径」。
|
|
110
|
+
const server = new McpServer({ name: "dept-agent-count", version: "1" });
|
|
111
|
+
registerTools(server, undefined, NET, UID[0], "owner-agent", true, null);
|
|
112
|
+
const client = new Client({ name: "dept-agent-count-client", version: "1" });
|
|
113
|
+
const [ct, st] = InMemoryTransport.createLinkedPair();
|
|
114
|
+
await server.connect(st);
|
|
115
|
+
await client.connect(ct);
|
|
116
|
+
try {
|
|
117
|
+
const raw: any = await client.callTool({ name: "departments", arguments: { action: "list" } });
|
|
118
|
+
const mcp = JSON.parse(String(raw.content?.[0]?.text ?? "{}"));
|
|
119
|
+
const http = (await send(TOKEN, "GET", D())).body;
|
|
120
|
+
const httpByName = new Map<string, any>((http.departments as any[]).map((d) => [d.name, d]));
|
|
121
|
+
expect(mcp.departments.length).toBeGreaterThan(0);
|
|
122
|
+
for (const d of mcp.departments as any[]) expect(d.agent_count).toBe(httpByName.get(d.name).agent_count);
|
|
123
|
+
expect(mcp.unassigned_agents).toBe(http.agents_unassigned);
|
|
124
|
+
} finally {
|
|
125
|
+
await client.close();
|
|
126
|
+
await server.close();
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
});
|
package/src/departments.ts
CHANGED
|
@@ -40,7 +40,17 @@ const NAME_MAX = 40;
|
|
|
40
40
|
const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
41
41
|
|
|
42
42
|
type DeptRow = { network_id: string; department_id: string; name: string; parent_id: string | null; leader_user_id: string | null; sort: number; created_at: string; updated_at: string };
|
|
43
|
-
|
|
43
|
+
/**
|
|
44
|
+
* 部门(轴1 = 人)。
|
|
45
|
+
*
|
|
46
|
+
* `member_count` 是**直属人数**(不含子树)。
|
|
47
|
+
* `agent_count` 是**轴2**:Agent 显式归属 `nodes.department_id` 指向本部门的数量,
|
|
48
|
+
* 与「成员的 Agent」无关(RFC-040 / #1976:Agent 部门只由显式设置决定,不再按负责人推断)。
|
|
49
|
+
* 没有这一格时,任何客户端想画「部门 → Agent 数」都得自己拉全量
|
|
50
|
+
* `people/directory` 再去重,各端口径必然分叉(#2822:Dashboard 105/TMAI 1
|
|
51
|
+
* vs 客户端 TMWork 15/TM智能体空间 2)。
|
|
52
|
+
*/
|
|
53
|
+
export type Department = { id: string; name: string; parent_id: string | null; leader_user_id: string | null; sort: number; member_count: number; agent_count: number; created_at: string; updated_at: string };
|
|
44
54
|
|
|
45
55
|
type Fail = { ok: false; status: number; error: string };
|
|
46
56
|
type Ok<T> = { ok: true } & T;
|
|
@@ -64,7 +74,12 @@ function isMember(networkId: string, userId: string): boolean {
|
|
|
64
74
|
}
|
|
65
75
|
|
|
66
76
|
/** 读:部门(带直属人数)+ 每个成员在哪个部门。负责人不在本网络了 → null。 */
|
|
67
|
-
export function listDepartments(networkId: string): {
|
|
77
|
+
export function listDepartments(networkId: string): {
|
|
78
|
+
departments: Department[];
|
|
79
|
+
members: Array<{ user_id: string; department_id: string | null }>;
|
|
80
|
+
/// 轴2 里没有显式归属的 Agent 数(Dashboard 的「未分组」不该拿人的未分配去填)。
|
|
81
|
+
agents_unassigned: number;
|
|
82
|
+
} {
|
|
68
83
|
const members = db.all<{ user_id: string; department_id: string | null }>(
|
|
69
84
|
"SELECT user_id, department_id FROM network_members WHERE network_id = ?1 ORDER BY joined_at, user_id",
|
|
70
85
|
networkId,
|
|
@@ -76,6 +91,28 @@ export function listDepartments(networkId: string): { departments: Department[];
|
|
|
76
91
|
const placed = members.map((m) => ({ user_id: m.user_id, department_id: m.department_id && ids.has(m.department_id) ? m.department_id : null }));
|
|
77
92
|
const counts = new Map<string, number>();
|
|
78
93
|
for (const m of placed) if (m.department_id) counts.set(m.department_id, (counts.get(m.department_id) ?? 0) + 1);
|
|
94
|
+
// ── 轴2:Agent 的显式部门(nodes.department_id)────────────────────────────
|
|
95
|
+
// 去重口径与 #2596 一致:同一个 alias 只算一个 Agent,保留 updated_at 最新的那一行,
|
|
96
|
+
// 它落在哪个部门就计入哪个部门(没有 alias 的用 node_id 当键)。
|
|
97
|
+
// 不在这里做「近 7 天」过滤:那是展示策略,接口只给事实。
|
|
98
|
+
const agentRows = db.all<{ department_id: string; alias: string | null; node_id: string; updated_at: string | null }>(
|
|
99
|
+
"SELECT department_id, alias, node_id, updated_at FROM nodes WHERE network_id = ?1 AND department_id IS NOT NULL AND department_id != ''",
|
|
100
|
+
networkId,
|
|
101
|
+
);
|
|
102
|
+
const newestByKey = new Map<string, { department_id: string; updated_at: string | null }>();
|
|
103
|
+
for (const n of agentRows) {
|
|
104
|
+
const key = n.alias || n.node_id;
|
|
105
|
+
const prev = newestByKey.get(key);
|
|
106
|
+
if (!prev || (n.updated_at ?? "") > (prev.updated_at ?? "")) {
|
|
107
|
+
newestByKey.set(key, { department_id: n.department_id, updated_at: n.updated_at });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const agentCounts = new Map<string, number>();
|
|
111
|
+
for (const v of newestByKey.values()) agentCounts.set(v.department_id, (agentCounts.get(v.department_id) ?? 0) + 1);
|
|
112
|
+
const unassigned = db.get<{ n: number }>(
|
|
113
|
+
"SELECT COUNT(*) AS n FROM nodes WHERE network_id = ?1 AND (department_id IS NULL OR department_id = '')",
|
|
114
|
+
networkId,
|
|
115
|
+
)?.n ?? 0;
|
|
79
116
|
return {
|
|
80
117
|
departments: all.map((d) => ({
|
|
81
118
|
id: d.department_id,
|
|
@@ -84,10 +121,12 @@ export function listDepartments(networkId: string): { departments: Department[];
|
|
|
84
121
|
leader_user_id: d.leader_user_id && memberIds.has(d.leader_user_id) ? d.leader_user_id : null,
|
|
85
122
|
sort: d.sort,
|
|
86
123
|
member_count: counts.get(d.department_id) ?? 0,
|
|
124
|
+
agent_count: agentCounts.get(d.department_id) ?? 0,
|
|
87
125
|
created_at: d.created_at,
|
|
88
126
|
updated_at: d.updated_at,
|
|
89
127
|
})),
|
|
90
128
|
members: placed,
|
|
129
|
+
agents_unassigned: unassigned,
|
|
91
130
|
};
|
|
92
131
|
}
|
|
93
132
|
|
|
@@ -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" });
|
package/src/node-permissions.ts
CHANGED
|
@@ -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";
|
|
@@ -2237,7 +2239,9 @@ return Bun.serve({
|
|
|
2237
2239
|
// viewer_can:manage = 能改名 / 移动 / 删除 / 换负责人;create_child = 能在它下面建子部门。
|
|
2238
2240
|
// project_grants(部门项目授权)只给 owner / admin:项目 id 不对只看相关任务的成员公开。
|
|
2239
2241
|
const departments = listed.departments.map((d) => ({ ...d, viewer_can: { manage: canManage || head.strict.has(d.id), create_child: canManage || head.managed.has(d.id) } }));
|
|
2240
|
-
|
|
2242
|
+
// agents_unassigned = 轴2 里没有显式归属的 Agent 数。Dashboard 的「未分组」必须用它,
|
|
2243
|
+
// 不能用「人的未分配」去填(#2822:那是另一个轴,混了就会出现「105 个 Agent 在未分组」)。
|
|
2244
|
+
return withCors(req, Response.json({ ok: true, network_id: netId, departments, members: listed.members, agents_unassigned: listed.agents_unassigned, ...(canManage ? { project_grants: listDepartmentProjectGrants(netId) } : {}) }));
|
|
2241
2245
|
}
|
|
2242
2246
|
if (deptSubMatch) {
|
|
2243
2247
|
const deptId = decodeURIComponent(deptSubMatch[2]);
|
|
@@ -2998,7 +3002,24 @@ return Bun.serve({
|
|
|
2998
3002
|
entry.routes.push({ route: r.route, reason: r.reason, hits, sample: r.sample, last_hour: r.last_hour });
|
|
2999
3003
|
}
|
|
3000
3004
|
const nodes = [...byNode.values()].sort((a, b) => b.total - a.total || a.node_id.localeCompare(b.node_id));
|
|
3001
|
-
|
|
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
|
+
}));
|
|
3002
3023
|
}
|
|
3003
3024
|
|
|
3004
3025
|
// ── #1473 (#909): read-only Hub catalogs for the desktop client ──
|
|
@@ -5258,6 +5279,41 @@ return Bun.serve({
|
|
|
5258
5279
|
if (alias) { sql += ` AND alias = ?${params.length + 1}`; params.push(alias); }
|
|
5259
5280
|
sql += " ORDER BY updated_at DESC";
|
|
5260
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
|
+
};
|
|
5261
5317
|
// Add a single new field `role: string | null` per row, extracted from
|
|
5262
5318
|
// config_snapshot JSON. Daemon nodes that posted role='host_supervisor'
|
|
5263
5319
|
// via report_status surface here; dashboard uses this for daemon
|
|
@@ -5356,6 +5412,7 @@ return Bun.serve({
|
|
|
5356
5412
|
lifecycle_daemon_node_id: controllable.get(r.node_id) ?? null,
|
|
5357
5413
|
...(management ? (management.get(r.node_id) ?? { managed: "none", adoption: null }) : {}),
|
|
5358
5414
|
viewer_can: { permission_mode: canSetPermissionMode(r) },
|
|
5415
|
+
restart_readiness: restartReadiness(r.node_id, r.alias, r.network_id, role, r.lifecycle_state ?? null),
|
|
5359
5416
|
};
|
|
5360
5417
|
});
|
|
5361
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";
|
|
@@ -464,15 +465,11 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
464
465
|
const agents = db.all<{ node_id: string; alias: string; department_id: string | null }>(
|
|
465
466
|
"SELECT node_id, alias, department_id FROM nodes WHERE network_id = ?1 ORDER BY alias", netId,
|
|
466
467
|
);
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
for (const a of agents) {
|
|
470
|
-
if (a.department_id) counts.set(a.department_id, (counts.get(a.department_id) ?? 0) + 1);
|
|
471
|
-
else unassigned += 1;
|
|
472
|
-
}
|
|
468
|
+
// agent_count / agents_unassigned 一律取 listDepartments 的口径(含 #2596 的 alias 去重),
|
|
469
|
+
// 不在这里再算一遍 —— 否则 MCP 和 HTTP 会给出两个数(#2822 的教训)。
|
|
473
470
|
return deptReply({
|
|
474
|
-
ok: true, network_id: netId, unassigned_agents:
|
|
475
|
-
departments: listed.departments
|
|
471
|
+
ok: true, network_id: netId, unassigned_agents: listed.agents_unassigned, agents,
|
|
472
|
+
departments: listed.departments,
|
|
476
473
|
});
|
|
477
474
|
}
|
|
478
475
|
if (!canManageDepartments(netId)) return writeDeniedReply(netId, "write") as any;
|
|
@@ -4268,23 +4265,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
4268
4265
|
// 计数规则见 stop_node 内的长注释(#2022/#2029 修订:能成为「本节点正在做的
|
|
4269
4266
|
// 工作」的行才算——tasks 行按状态判、终态不算且不设龄上限;无状态行按 60 分钟
|
|
4270
4267
|
// 龄判)。抽成一处后,两个闸门共享同一份 SQL,不再各自漂移。
|
|
4271
|
-
|
|
4272
|
-
|
|
4273
|
-
const row = db.get<{ n: number }>(
|
|
4274
|
-
`SELECT COUNT(*) AS n FROM inbox i
|
|
4275
|
-
LEFT JOIN tasks t
|
|
4276
|
-
ON i.type = 'task'
|
|
4277
|
-
AND t.task_id = COALESCE(i.task_id, i.id)
|
|
4278
|
-
WHERE i.session_name = ?1 AND i.acked = 0
|
|
4279
|
-
AND COALESCE(i.network_id, ?2) = ?2
|
|
4280
|
-
AND ((t.task_id IS NOT NULL
|
|
4281
|
-
AND t.status NOT IN ('replied', 'failed', 'cancelled', 'expired'))
|
|
4282
|
-
OR (t.task_id IS NULL
|
|
4283
|
-
AND i.created_at >= datetime('now', ?3)))`,
|
|
4284
|
-
alias, networkId, `-${IN_FLIGHT_MAX_AGE_MINUTES} minutes`,
|
|
4285
|
-
);
|
|
4286
|
-
return row?.n ?? 0;
|
|
4287
|
-
}
|
|
4268
|
+
// #1511 —— 计数口径抽到 `in-flight.ts`:stop_node / restart_node / REST 的
|
|
4269
|
+
// restart_readiness 三处共用同一份 SQL。这里保留一个同名别名,调用点不动。
|
|
4288
4270
|
|
|
4289
4271
|
server.tool(
|
|
4290
4272
|
"restart_node",
|
|
@@ -5596,7 +5578,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
5596
5578
|
// ever retire them, so they get the age ceiling
|
|
5597
5579
|
// IN_FLIGHT_MAX_AGE_MINUTES on inbox.created_at.
|
|
5598
5580
|
// The count stays a per-alias inbox count: one PK join per row.
|
|
5599
|
-
//
|
|
5581
|
+
// 计数统一在 node-in-flight-tasks.ts:stop_node / restart_node / REST 的 restart_readiness 共用。
|
|
5600
5582
|
const inFlight = countInFlightTasks(node.alias, node.network_id);
|
|
5601
5583
|
if (inFlight > 0 && !args.force) {
|
|
5602
5584
|
return { ok: false, error: "node_busy_in_flight", in_flight_count: inFlight, hint: "set force=true to override (audit logged)" };
|