@sleep2agi/commhub-server 0.9.0-preview.282 → 0.9.0-preview.284
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build-info.json +2 -2
- package/package.json +1 -1
- package/src/agent-acl-slice3-http.test.ts +3 -2
- package/src/create-node-department.test.ts +145 -0
- package/src/create-node.ts +18 -0
- package/src/db.ts +11 -0
- package/src/expiry-counters.test.ts +51 -0
- package/src/expiry-counters.ts +24 -5
- package/src/node-attrs-validate.ts +34 -0
- package/src/node-attrs.test.ts +32 -0
- package/src/node-description-http.test.ts +121 -0
- package/src/node-description.test.ts +34 -0
- package/src/server.ts +24 -7
- package/src/tool-audience-http.test.ts +5 -0
- package/src/tools.ts +71 -24
package/build-info.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/commhub-server",
|
|
3
|
-
"version": "0.9.0-preview.
|
|
3
|
+
"version": "0.9.0-preview.284",
|
|
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",
|
|
@@ -358,13 +358,14 @@ describe("update_node_config 响应键集(exact key set)", () => {
|
|
|
358
358
|
|
|
359
359
|
// 2026-10-31 —— #3171:再补两个「文件级算过、邻近级没有」的工具。
|
|
360
360
|
describe("projects_list / get_session_status: pinned key sets next to the call", () => {
|
|
361
|
-
|
|
361
|
+
// 2026-11-15:get_session_status 多一个 profile(节点职责介绍 + 展示名 / 团队 / 标签;admin「节点职责要让其他节点也能看到」)。
|
|
362
|
+
test("projects_list ⇒ {network_id, ok, projects}; get_session_status ⇒ {inbox_pending, ok, profile, recent_completions, session}", async () => {
|
|
362
363
|
const pl = await tool(adminToken, "projects_list", { network_id: NET });
|
|
363
364
|
expect(Object.keys(pl).sort()).toEqual(["network_id", "ok", "projects"]);
|
|
364
365
|
expect(Array.isArray(pl.projects)).toBe(true);
|
|
365
366
|
|
|
366
367
|
const gs = await tool(adminToken, "get_session_status", { alias: "acl3-agent-x", network_id: NET });
|
|
367
|
-
expect(Object.keys(gs).sort()).toEqual(["inbox_pending", "ok", "recent_completions", "session"]);
|
|
368
|
+
expect(Object.keys(gs).sort()).toEqual(["inbox_pending", "ok", "profile", "recent_completions", "session"]);
|
|
368
369
|
expect(Number.isInteger(gs.inbox_pending)).toBe(true);
|
|
369
370
|
expect(gs.inbox_pending).toBeGreaterThanOrEqual(0); // 2026-10-31:类型不是断言
|
|
370
371
|
expect(Array.isArray(gs.recent_completions)).toBe(true);
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
|
|
2
|
+
import "./require-explicit-test-db.js";
|
|
3
|
+
import { db } from "./db.js";
|
|
4
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
5
|
+
import { registerTools } from "./tools.js";
|
|
6
|
+
import { finalizeCreateOnFirstRegister } from "./create-node.js";
|
|
7
|
+
|
|
8
|
+
// 2026-11-14 —— 新建节点时选部门(admin:「创建人可能兼多个部门」→ 不猜,让创建人选)。
|
|
9
|
+
// ① create_node 带 department_id:部门不存在 → department_not_found,不建(不留请求行、不铸令牌)
|
|
10
|
+
// ② 请求行存下部门;节点首次注册(finalize)时写进 nodes.department_id
|
|
11
|
+
// ③ 只填空:节点已经有部门就不覆盖;部门在这期间被删了就跳过
|
|
12
|
+
// ④ 不带 department_id = 老行为(节点没有部门)
|
|
13
|
+
const NET = "net_create_dept";
|
|
14
|
+
const USER_ID = "u_create_dept_admin";
|
|
15
|
+
const DAEMON_ID = "node_create_dept_daemon";
|
|
16
|
+
const DAEMON_ALIAS = "create-dept-daemon";
|
|
17
|
+
const DAEMON_TOK = "tok_create_dept_daemon";
|
|
18
|
+
const ROOT = "/home/user";
|
|
19
|
+
|
|
20
|
+
interface ToolHandler { (args: any, extra?: any): Promise<{ content: Array<{ type: "text"; text: string }> }>; }
|
|
21
|
+
interface Reply { ok?: boolean; error?: string; request_id?: string; node_spec?: any; [k: string]: unknown; }
|
|
22
|
+
|
|
23
|
+
function cleanup() {
|
|
24
|
+
for (const t of ["node_create_requests", "audit_log", "nodes", "sessions", "api_tokens", "network_members", "network_departments"]) {
|
|
25
|
+
try { db.run(`DELETE FROM ${t} WHERE network_id = ?1`, [NET]); } catch {}
|
|
26
|
+
}
|
|
27
|
+
try { db.run("DELETE FROM networks WHERE network_id = ?1", [NET]); } catch {}
|
|
28
|
+
try { db.run("DELETE FROM users WHERE user_id = ?1", [USER_ID]); } catch {}
|
|
29
|
+
}
|
|
30
|
+
beforeEach(cleanup);
|
|
31
|
+
afterAll(cleanup);
|
|
32
|
+
|
|
33
|
+
function seed(caps: Record<string, unknown>) {
|
|
34
|
+
db.run(`INSERT INTO users (user_id, username, password_hash, role, created_at) VALUES (?1, ?1, 'x', 'user', datetime('now'))`, [USER_ID]);
|
|
35
|
+
db.run(`INSERT OR REPLACE INTO networks (network_id, network_name, owner_id, created_at) VALUES (?1, ?1, ?2, datetime('now'))`, [NET, USER_ID]);
|
|
36
|
+
db.run(`INSERT INTO network_members (user_id, network_id, role, joined_at) VALUES (?1, ?2, 'admin', datetime('now'))`, [USER_ID, NET]);
|
|
37
|
+
db.run(
|
|
38
|
+
`INSERT INTO nodes (node_id, node_name, alias, network_id, config_snapshot, hostname, created_at, updated_at, lifecycle_state)
|
|
39
|
+
VALUES (?1, ?2, ?2, ?3, ?4, 'host-x', datetime('now'), datetime('now'), 'active')`,
|
|
40
|
+
[DAEMON_ID, DAEMON_ALIAS, NET, JSON.stringify({ role: "host_supervisor", daemon_capabilities: { runtimes_supported: ["claude-agent-sdk"], ...caps } })],
|
|
41
|
+
);
|
|
42
|
+
db.run(
|
|
43
|
+
`INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash, expires_at, revoked_at)
|
|
44
|
+
VALUES (?1, ?2, ?3, 'network', ?4, ?5, NULL, NULL)`,
|
|
45
|
+
[DAEMON_TOK, USER_ID, NET, `node:${DAEMON_ALIAS}`, `hash_${DAEMON_TOK}`],
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function tools(callerTokenId: string | null = null): Record<string, ToolHandler> {
|
|
50
|
+
const server = new McpServer({ name: "test", version: "0" }) as any;
|
|
51
|
+
const out: Record<string, ToolHandler> = {};
|
|
52
|
+
const origTool = server.tool.bind(server);
|
|
53
|
+
server.tool = (name: string, d: string, schema: any, handler: ToolHandler) => { out[name] = handler; return origTool(name, d, schema, handler); };
|
|
54
|
+
const origRegisterTool = server.registerTool?.bind(server);
|
|
55
|
+
if (origRegisterTool) {
|
|
56
|
+
server.registerTool = (name: string, cfg: any, handler: ToolHandler) => { out[name] = handler; return origRegisterTool(name, cfg, handler); };
|
|
57
|
+
}
|
|
58
|
+
registerTools(server, undefined, NET, USER_ID, null, true, callerTokenId);
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function call(h: ToolHandler, args: any): Promise<Reply> {
|
|
63
|
+
return JSON.parse((await h(args)).content[0].text) as Reply;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const baseSpec = { name: "dept-child", runtime: "claude-agent-sdk", model: "claude-sonnet-4-5", flags: {} };
|
|
67
|
+
|
|
68
|
+
function rowCount(): number {
|
|
69
|
+
return db.get<{ n: number }>("SELECT COUNT(*) AS n FROM node_create_requests WHERE daemon_node_id = ?1", DAEMON_ID)?.n ?? -1;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const DEPT = "dept_create_a";
|
|
73
|
+
function seedDept(id = DEPT) {
|
|
74
|
+
db.run(`INSERT INTO network_departments (network_id, department_id, name, parent_id, leader_user_id, sort, created_by, created_at, updated_at)
|
|
75
|
+
VALUES (?1, ?2, ?2, NULL, NULL, 0, ?3, datetime('now'), datetime('now'))`, [NET, id, USER_ID]);
|
|
76
|
+
}
|
|
77
|
+
function registerChild(alias: string, nodeId: string, dept: string | null = null) {
|
|
78
|
+
db.run(`INSERT INTO nodes (node_id, node_name, alias, network_id, created_at, updated_at, lifecycle_state, department_id)
|
|
79
|
+
VALUES (?1, ?2, ?2, ?3, datetime('now'), datetime('now'), 'active', ?4)`, [nodeId, alias, NET, dept]);
|
|
80
|
+
return finalizeCreateOnFirstRegister({ node_id: nodeId, alias, network_id: NET });
|
|
81
|
+
}
|
|
82
|
+
const nodeDept = (id: string) => db.get<{ d: string | null }>("SELECT department_id AS d FROM nodes WHERE node_id = ?1", id)?.d ?? null;
|
|
83
|
+
|
|
84
|
+
describe("create_node department_id", () => {
|
|
85
|
+
beforeAll(() => {});
|
|
86
|
+
test("🔴 unknown department → department_not_found, nothing queued, no token minted", async () => {
|
|
87
|
+
seed({});
|
|
88
|
+
const tokensBefore = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM api_tokens WHERE network_id = ?1", NET)!.n;
|
|
89
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec, department_id: "dept_missing" });
|
|
90
|
+
expect(r.ok).toBe(false);
|
|
91
|
+
expect(r.error).toBe("department_not_found");
|
|
92
|
+
expect(rowCount()).toBe(0);
|
|
93
|
+
expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM api_tokens WHERE network_id = ?1", NET)!.n).toBe(tokensBefore);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test("🔴 chosen department is stored and lands on the node at first register", async () => {
|
|
97
|
+
seed({}); seedDept();
|
|
98
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec, department_id: DEPT });
|
|
99
|
+
expect(r.ok).toBe(true);
|
|
100
|
+
expect(r.department_id).toBe(DEPT);
|
|
101
|
+
expect(db.get<{ d: string }>("SELECT department_id AS d FROM node_create_requests WHERE request_id = ?1", r.request_id)!.d).toBe(DEPT);
|
|
102
|
+
expect(registerChild("dept-child", "node_dept_child").finalized).toBe(1);
|
|
103
|
+
expect(nodeDept("node_dept_child")).toBe(DEPT);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test("no department_id = old behaviour (node stays unassigned, reply has no department_id key)", async () => {
|
|
107
|
+
seed({}); seedDept();
|
|
108
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec });
|
|
109
|
+
expect(r.ok).toBe(true);
|
|
110
|
+
expect("department_id" in r).toBe(false);
|
|
111
|
+
registerChild("dept-child", "node_dept_child2");
|
|
112
|
+
expect(nodeDept("node_dept_child2")).toBeNull();
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test("empty string / null are treated as not set", async () => {
|
|
116
|
+
seed({}); seedDept();
|
|
117
|
+
for (const v of ["", " ", null]) {
|
|
118
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { ...baseSpec, name: `dept-child-${String(v).trim() || "x"}${Math.random().toString(36).slice(2, 6)}` }, department_id: v });
|
|
119
|
+
expect(r.ok).toBe(true);
|
|
120
|
+
expect("department_id" in r).toBe(false);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test("only fills a blank: a node someone already placed keeps its department", async () => {
|
|
125
|
+
seed({}); seedDept(); seedDept("dept_other");
|
|
126
|
+
await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec, department_id: DEPT });
|
|
127
|
+
registerChild("dept-child", "node_dept_child3", "dept_other");
|
|
128
|
+
expect(nodeDept("node_dept_child3")).toBe("dept_other");
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test("department deleted before the node came online → skipped, no dangling id", async () => {
|
|
132
|
+
seed({}); seedDept();
|
|
133
|
+
await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec, department_id: DEPT });
|
|
134
|
+
db.run("DELETE FROM network_departments WHERE network_id = ?1 AND department_id = ?2", [NET, DEPT]);
|
|
135
|
+
registerChild("dept-child", "node_dept_child4");
|
|
136
|
+
expect(nodeDept("node_dept_child4")).toBeNull();
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test("audit detail records the chosen department", async () => {
|
|
140
|
+
seed({}); seedDept();
|
|
141
|
+
const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec, department_id: DEPT });
|
|
142
|
+
const a = db.get<{ detail: string }>("SELECT detail FROM audit_log WHERE action = 'create_node_dispatch_attempted' AND target_id = ?1", r.request_id);
|
|
143
|
+
expect(a?.detail ?? "").toContain(DEPT);
|
|
144
|
+
});
|
|
145
|
+
});
|
package/src/create-node.ts
CHANGED
|
@@ -186,6 +186,23 @@ export function stopBackgroundTimersForTest(): void {
|
|
|
186
186
|
// in caller's network, mark it succeeded and stamp the real
|
|
187
187
|
// child_node_id. Mirrors RFC-024 finalizePendingMatchingUpdates.
|
|
188
188
|
|
|
189
|
+
/**
|
|
190
|
+
* 2026-11-14 —— create_node 时创建人选的部门,节点首次注册时落到 nodes.department_id。
|
|
191
|
+
* 只填空:节点已经有部门(别人先放好了)就不覆盖;部门在这期间被删了就跳过。Best effort。
|
|
192
|
+
*/
|
|
193
|
+
export function applyRequestedDepartment(requestId: string, childNodeId: string, networkId: string): void {
|
|
194
|
+
try {
|
|
195
|
+
const dept = db.get<{ department_id: string | null }>("SELECT department_id FROM node_create_requests WHERE request_id = ?1", requestId)?.department_id;
|
|
196
|
+
if (!dept) return;
|
|
197
|
+
if (!db.get("SELECT 1 AS x FROM network_departments WHERE network_id = ?1 AND department_id = ?2", networkId, dept)) return;
|
|
198
|
+
db.run(`UPDATE nodes SET department_id = ?2, updated_at = datetime('now')
|
|
199
|
+
WHERE node_id = ?1 AND network_id = ?3 AND (department_id IS NULL OR department_id = '')`,
|
|
200
|
+
[childNodeId, dept, networkId]);
|
|
201
|
+
} catch (e: any) {
|
|
202
|
+
console.warn(`[commhub] requested department apply failed: ${e?.message || e}`);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
189
206
|
/** A clone (fork to a new folder) lands in its source's department, unless
|
|
190
207
|
* someone already placed it. Same rule as the source fork (#3485). Best effort. */
|
|
191
208
|
export function inheritCloneDepartment(requestId: string, childNodeId: string, networkId: string): void {
|
|
@@ -224,6 +241,7 @@ export function finalizeCreateOnFirstRegister(
|
|
|
224
241
|
[incoming.node_id, Date.now(), row.request_id],
|
|
225
242
|
);
|
|
226
243
|
matchedIds.push(row.request_id);
|
|
244
|
+
applyRequestedDepartment(row.request_id, incoming.node_id, net);
|
|
227
245
|
inheritCloneDepartment(row.request_id, incoming.node_id, net);
|
|
228
246
|
console.log(`[commhub] ✓ create-node finalize: request=${row.request_id} child=${incoming.alias} (${incoming.node_id}) daemon=${row.daemon_node_id}`);
|
|
229
247
|
auditCreateNode({
|
package/src/db.ts
CHANGED
|
@@ -504,6 +504,9 @@ for (const ddl of [
|
|
|
504
504
|
`ALTER TABLE nodes ADD COLUMN team TEXT`,
|
|
505
505
|
`ALTER TABLE nodes ADD COLUMN tags TEXT`,
|
|
506
506
|
`ALTER TABLE nodes ADD COLUMN attrs_revision INTEGER NOT NULL DEFAULT 0`,
|
|
507
|
+
// admin 2026-11-15:节点「职责介绍」—— 给其他节点 / 人看的「我负责什么、能干什么」(AGENTS.md 是给自己看的)。
|
|
508
|
+
// 和 display_name / team 一样走 PUT /api/nodes/:id/attrs,受 attrs_revision 乐观锁保护。
|
|
509
|
+
`ALTER TABLE nodes ADD COLUMN description TEXT`,
|
|
507
510
|
]) {
|
|
508
511
|
try {
|
|
509
512
|
db.exec(ddl);
|
|
@@ -870,6 +873,14 @@ try {
|
|
|
870
873
|
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
871
874
|
}
|
|
872
875
|
|
|
876
|
+
// 2026-11-14 —— 新建节点时选部门(admin:「创建人可能兼多个部门」→ 不猜,让创建人选)。
|
|
877
|
+
// NULL = 不指定(老行为)。节点首次注册时写进 nodes.department_id(applyRequestedDepartment)。
|
|
878
|
+
try {
|
|
879
|
+
db.exec(`ALTER TABLE node_create_requests ADD COLUMN department_id TEXT`);
|
|
880
|
+
} catch (e: any) {
|
|
881
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
882
|
+
}
|
|
883
|
+
|
|
873
884
|
// Hub #938 — clone_node reuses this table (same token mint, sweeper, and
|
|
874
885
|
// register finalize) but must not be replayed as a blank create_node.
|
|
875
886
|
// NULL/empty = ordinary create. Non-empty JSON = clone directives.
|
|
@@ -234,3 +234,54 @@ describe("2026-11-13 内存计数也以「最后一次回复」为界(恢复
|
|
|
234
234
|
expect(parseHubTime("garbage")).toBeNull();
|
|
235
235
|
});
|
|
236
236
|
});
|
|
237
|
+
|
|
238
|
+
describe("2026-11-16 内存计数只数「最后一次回复之后」的那几条(admin:TMA客户端欧 内存 4、回复后实际 2,仍被拒)", () => {
|
|
239
|
+
const NOW = Date.parse("2026-11-16T03:00:00.000Z");
|
|
240
|
+
const sqlite = (ms: number) => new Date(ms).toISOString().replace("T", " ").slice(0, 19);
|
|
241
|
+
const iso = (ms: number) => new Date(ms).toISOString();
|
|
242
|
+
const memAt = (times: number[]) => ({
|
|
243
|
+
since: "2026-11-15T13:17:00.000Z", total: times.length, by_node: { tma: times.length },
|
|
244
|
+
last_at: { tma: iso(times[times.length - 1]) }, recent_at: { tma: times.map(iso) },
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
test("🔴 回复前 3 次 + 回复后 1 次 ⇒ 只算 1 次,放行", () => {
|
|
248
|
+
const h = 60 * 60_000;
|
|
249
|
+
const r = neverConsumeGate({
|
|
250
|
+
alias: "tma", counters: memAt([NOW - 13 * h, NOW - 12 * h, NOW - 11 * h, NOW - 1 * h]), force: false, forceAllowed: true, now: NOW,
|
|
251
|
+
persistent: { expiries: 1, last_at: sqlite(NOW - h), last_reply_at: sqlite(NOW - 2 * h) },
|
|
252
|
+
});
|
|
253
|
+
expect(r.ok).toBe(true);
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
test("负数用例:回复后又过期 3 次 ⇒ 仍然拒,拒绝体带 last_reply_at", () => {
|
|
257
|
+
const m = 60_000;
|
|
258
|
+
const r = neverConsumeGate({
|
|
259
|
+
alias: "tma", counters: memAt([NOW - 90 * m, NOW - 30 * m, NOW - 20 * m, NOW - 10 * m]), force: false, forceAllowed: true, now: NOW,
|
|
260
|
+
persistent: { expiries: 0, last_at: null, last_reply_at: sqlite(NOW - 60 * m) },
|
|
261
|
+
});
|
|
262
|
+
expect(r.ok).toBe(false);
|
|
263
|
+
if (!r.ok) {
|
|
264
|
+
expect(r.expiries).toBe(3);
|
|
265
|
+
expect(r.last_reply_at).toBe(sqlite(NOW - 60 * m));
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
test("没有 recent_at(旧快照)⇒ 退回原来的整桶计数", () => {
|
|
270
|
+
const m = 60_000;
|
|
271
|
+
const r = neverConsumeGate({
|
|
272
|
+
alias: "tma", counters: { since: "x", total: 4, by_node: { tma: 4 }, last_at: { tma: iso(NOW - 10 * m) } }, force: false, forceAllowed: true, now: NOW,
|
|
273
|
+
persistent: { expiries: 0, last_at: null, last_reply_at: sqlite(NOW - 60 * m) },
|
|
274
|
+
});
|
|
275
|
+
expect(r.ok).toBe(false);
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
test("noteNeverConsumedExpiry 记下逐条时刻,最多 16 条", () => {
|
|
279
|
+
resetNeverConsumedExpiryCountersForTest(new Date(NOW));
|
|
280
|
+
for (let i = 0; i < 20; i++) noteNeverConsumedExpiry("tma", NOW + i * 1000);
|
|
281
|
+
const c = neverConsumedExpiryCounters();
|
|
282
|
+
expect(c.by_node.tma).toBe(20);
|
|
283
|
+
expect(c.recent_at?.tma.length).toBe(16);
|
|
284
|
+
expect(c.recent_at?.tma[15]).toBe(iso(NOW + 19 * 1000));
|
|
285
|
+
expect(c.last_at.tma).toBe(iso(NOW + 19 * 1000));
|
|
286
|
+
});
|
|
287
|
+
});
|
package/src/expiry-counters.ts
CHANGED
|
@@ -25,9 +25,17 @@ export type NeverConsumedExpiryCounters = {
|
|
|
25
25
|
by_node: Record<string, number>;
|
|
26
26
|
/** 每个节点最近一次「从未取走」的时刻(ISO)。**光有计数会永久拉黑一台恢复了的节点。** */
|
|
27
27
|
last_at: Record<string, string>;
|
|
28
|
+
/**
|
|
29
|
+
* 2026-11-16 —— 每个节点最近几次「从未取走」的时刻(ISO,旧→新,最多 RECENT_CAP 条)。
|
|
30
|
+
* 闸要数的是「最后一次回复**之后**」的过期;只有 count + lastAt 时,回复之前攒下的过期
|
|
31
|
+
* 会和回复之后的一条一起被算进去(现场:TMA客户端欧 内存 4、库里回复之后只有 2,仍被拒)。
|
|
32
|
+
*/
|
|
33
|
+
recent_at?: Record<string, string[]>;
|
|
28
34
|
};
|
|
29
35
|
|
|
30
|
-
|
|
36
|
+
/** 每个节点保留的最近过期时刻条数(够判阈值 3,键有限、不随请求膨胀)。 */
|
|
37
|
+
const RECENT_CAP = 16;
|
|
38
|
+
type Bucket = { count: number; lastAt: number; recent: number[] };
|
|
31
39
|
const counters = new Map<string, Bucket>();
|
|
32
40
|
let since = new Date().toISOString();
|
|
33
41
|
|
|
@@ -35,19 +43,22 @@ let since = new Date().toISOString();
|
|
|
35
43
|
export function noteNeverConsumedExpiry(node: string, now = Date.now()): void {
|
|
36
44
|
const key = node || "(unknown)";
|
|
37
45
|
const prev = counters.get(key);
|
|
38
|
-
|
|
46
|
+
const recent = [...(prev?.recent ?? []), now].slice(-RECENT_CAP);
|
|
47
|
+
counters.set(key, { count: (prev?.count ?? 0) + 1, lastAt: now, recent });
|
|
39
48
|
}
|
|
40
49
|
|
|
41
50
|
export function neverConsumedExpiryCounters(): NeverConsumedExpiryCounters {
|
|
42
51
|
let total = 0;
|
|
43
52
|
const by_node: Record<string, number> = {};
|
|
44
53
|
const last_at: Record<string, string> = {};
|
|
54
|
+
const recent_at: Record<string, string[]> = {};
|
|
45
55
|
for (const [k, v] of [...counters.entries()].sort(([a], [b]) => a.localeCompare(b))) {
|
|
46
56
|
by_node[k] = v.count;
|
|
47
57
|
last_at[k] = new Date(v.lastAt).toISOString();
|
|
58
|
+
recent_at[k] = v.recent.map(t => new Date(t).toISOString());
|
|
48
59
|
total += v.count;
|
|
49
60
|
}
|
|
50
|
-
return { since, total, by_node, last_at };
|
|
61
|
+
return { since, total, by_node, last_at, recent_at };
|
|
51
62
|
}
|
|
52
63
|
|
|
53
64
|
/** 仅测试用:清零并重置窗口。 */
|
|
@@ -166,7 +177,7 @@ export function persistentNeverConsumedExpiries(
|
|
|
166
177
|
|
|
167
178
|
export type NeverConsumeGate =
|
|
168
179
|
| { ok: true }
|
|
169
|
-
| { ok: false; error: "target_never_consumes"; alias: string; expiries: number; window_since: string; message: string };
|
|
180
|
+
| { ok: false; error: "target_never_consumes"; alias: string; expiries: number; window_since: string; last_reply_at: string | null; message: string };
|
|
170
181
|
|
|
171
182
|
export function neverConsumeGate(input: {
|
|
172
183
|
alias: string;
|
|
@@ -190,7 +201,13 @@ export function neverConsumeGate(input: {
|
|
|
190
201
|
const memLastAt = parseHubTime(input.counters.last_at?.[input.alias]);
|
|
191
202
|
const lastReplyAt = parseHubTime(input.persistent?.last_reply_at ?? undefined);
|
|
192
203
|
const memorySupersededByReply = memLastAt !== null && lastReplyAt !== null && lastReplyAt >= memLastAt;
|
|
193
|
-
|
|
204
|
+
// 2026-11-16 —— 只比「最近一次」不够:回复之后哪怕再过期一条,回复之前攒的也会全部复活。
|
|
205
|
+
// 有逐条时刻时,只数**晚于最后一次回复**的那几条(与 DB 证据同一条边界)。
|
|
206
|
+
const recent = input.counters.recent_at?.[input.alias];
|
|
207
|
+
const fromMemory = memorySupersededByReply ? 0
|
|
208
|
+
: recent && lastReplyAt !== null
|
|
209
|
+
? recent.map(parseHubTime).filter((t): t is number => t !== null && t > lastReplyAt).length
|
|
210
|
+
: (input.counters.by_node[input.alias] ?? 0);
|
|
194
211
|
const fromDb = input.persistent?.expiries ?? 0;
|
|
195
212
|
const expiries = Math.max(fromMemory, fromDb);
|
|
196
213
|
if (expiries < limit) return { ok: true };
|
|
@@ -204,6 +221,7 @@ export function neverConsumeGate(input: {
|
|
|
204
221
|
alias: input.alias,
|
|
205
222
|
expiries,
|
|
206
223
|
window_since: input.counters.since,
|
|
224
|
+
last_reply_at: input.persistent?.last_reply_at ?? null,
|
|
207
225
|
message:
|
|
208
226
|
`this target has ${fromDb} expired task(s) with no reply since its last reply`
|
|
209
227
|
+ `${input.persistent?.last_reply_at ? ` (${input.persistent.last_reply_at})` : " (it has never replied)"}; `
|
|
@@ -231,6 +249,7 @@ export function neverConsumeGate(input: {
|
|
|
231
249
|
alias: input.alias,
|
|
232
250
|
expiries,
|
|
233
251
|
window_since: input.counters.since,
|
|
252
|
+
last_reply_at: input.persistent?.last_reply_at ?? null,
|
|
234
253
|
message:
|
|
235
254
|
`this target has expired ${expiries} task(s) without ever taking one (window since ${input.counters.since}); `
|
|
236
255
|
+ `nothing will queue correctly here until it consumes again — pass force:true (user tokens) if you know it recovered`,
|
|
@@ -86,3 +86,37 @@ export function parseStoredTags(stored: unknown): string[] {
|
|
|
86
86
|
return [];
|
|
87
87
|
}
|
|
88
88
|
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 节点「职责介绍」(admin 2026-11-15「每个节点的职责需要让其他节点也能看到;desc 里放介绍而不是 AGENTS.md,
|
|
92
|
+
* AGENTS.md 是给自己看的,需要设计个给其他节点看的自己的职责、能干什么」)。
|
|
93
|
+
*
|
|
94
|
+
* 和 display_name / team 同一种姿态(类型错 → 400,不强转),但它是一段多行文字:
|
|
95
|
+
* - 保留换行和制表(写「能干什么 / 不干什么 / 怎么找我」要分行);其余控制字符换成空格;
|
|
96
|
+
* - 每行去掉行尾空白,连续空行最多留一行;
|
|
97
|
+
* - 上限 MAX_DESCRIPTION_LEN 字符(按 Unicode 码点数),超了拒绝 —— 让人看到,而不是悄悄截掉。
|
|
98
|
+
*/
|
|
99
|
+
export const MAX_DESCRIPTION_LEN = 1000;
|
|
100
|
+
|
|
101
|
+
export function validateDescription(raw: unknown): ScalarAttrResult {
|
|
102
|
+
if (raw === undefined || raw === null) return { ok: true, value: null };
|
|
103
|
+
if (typeof raw !== "string") return { ok: false, reason: "description must be a string or null" };
|
|
104
|
+
// eslint-disable-next-line no-control-regex
|
|
105
|
+
const clean = raw.replace(/\r\n?/g, "\n").replace(/[\u0000-\u0008\u000b-\u001f\u007f]+/g, " ")
|
|
106
|
+
.split("\n").map(line => line.replace(/\s+$/u, "")).join("\n")
|
|
107
|
+
.replace(/\n{3,}/g, "\n\n").trim();
|
|
108
|
+
if (clean.length === 0) return { ok: true, value: null };
|
|
109
|
+
if ([...clean].length > MAX_DESCRIPTION_LEN) {
|
|
110
|
+
return { ok: false, reason: `description exceeds ${MAX_DESCRIPTION_LEN} characters` };
|
|
111
|
+
}
|
|
112
|
+
return { ok: true, value: clean };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 状态列表里只放一行摘要(整段在 get_session_status / GET /api/nodes 里):第一段非空行,最多 n 个字。 */
|
|
116
|
+
export function descriptionSummary(description: string | null | undefined, n = 120): string | null {
|
|
117
|
+
if (!description) return null;
|
|
118
|
+
const first = description.split("\n").map(s => s.trim()).find(Boolean) ?? "";
|
|
119
|
+
if (!first) return null;
|
|
120
|
+
const chars = [...first];
|
|
121
|
+
return chars.length > n ? `${chars.slice(0, n - 1).join("")}…` : first;
|
|
122
|
+
}
|
package/src/node-attrs.test.ts
CHANGED
|
@@ -256,3 +256,35 @@ describe("#2293 opencode bits on GET /api/nodes (real HTTP)", () => {
|
|
|
256
256
|
expect(row.opencode_catalog ?? null).toBeNull();
|
|
257
257
|
});
|
|
258
258
|
});
|
|
259
|
+
|
|
260
|
+
// admin 2026-11-15 —— 节点职责介绍(给别的节点 / 人看的「我负责什么、能干什么」)。
|
|
261
|
+
describe("node description (职责介绍)", () => {
|
|
262
|
+
test("PUT description round-trips through GET /api/nodes, keeps line breaks, bumps attrs_revision", async () => {
|
|
263
|
+
const before = (await listNodes()).find((r) => r.node_id === LEGACY_NODE)!;
|
|
264
|
+
const rev = Number(before.attrs_revision);
|
|
265
|
+
const text = "负责 App 发版:dispatch release、跑 verify。\n\n找我:发版、签名、TestFlight。\n不做:Hub 改动。";
|
|
266
|
+
const w = await putAttrs(LEGACY_ALIAS, { base_attrs_revision: rev, description: ` ${text} ` });
|
|
267
|
+
expect(w.status).toBe(200);
|
|
268
|
+
expect(w.json.description).toBe(text);
|
|
269
|
+
expect(w.json.attrs_revision).toBe(rev + 1);
|
|
270
|
+
const row = (await listNodes()).find((r) => r.node_id === LEGACY_NODE)!;
|
|
271
|
+
expect(row.description).toBe(text);
|
|
272
|
+
// 只改 description 时别的展示字段不动
|
|
273
|
+
expect(row.display_name).toBe(before.display_name ?? null);
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
test("null / blank clears it; wrong type and > 1000 chars are rejected without writing", async () => {
|
|
277
|
+
const rev = Number((await listNodes()).find((r) => r.node_id === LEGACY_NODE)!.attrs_revision);
|
|
278
|
+
const bad = await putAttrs(LEGACY_ALIAS, { base_attrs_revision: rev, description: { x: 1 } });
|
|
279
|
+
expect(bad.status).toBe(400);
|
|
280
|
+
expect(bad.json.error).toBe("invalid_description");
|
|
281
|
+
const long = await putAttrs(LEGACY_ALIAS, { base_attrs_revision: rev, description: "字".repeat(1001) });
|
|
282
|
+
expect(long.status).toBe(400);
|
|
283
|
+
const still = (await listNodes()).find((r) => r.node_id === LEGACY_NODE)!;
|
|
284
|
+
expect(still.attrs_revision).toBe(rev);
|
|
285
|
+
expect(typeof still.description).toBe("string");
|
|
286
|
+
const clear = await putAttrs(LEGACY_ALIAS, { base_attrs_revision: rev, description: " " });
|
|
287
|
+
expect(clear.status).toBe(200);
|
|
288
|
+
expect((await listNodes()).find((r) => r.node_id === LEGACY_NODE)!.description ?? null).toBeNull();
|
|
289
|
+
});
|
|
290
|
+
});
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// admin 2026-11-15 —— 节点职责介绍要让「其他节点」也看得到。HTTP 集成(真实 Bun.serve,私有端口,临时库)。
|
|
2
|
+
//
|
|
3
|
+
// 钉住:
|
|
4
|
+
// 1. 网络 owner 经 PUT /api/nodes/:id/attrs 写 description(和 display_name 同一把 attrs_revision 锁);
|
|
5
|
+
// 2. 另一个节点用自己的节点令牌调 MCP get_all_status:目标那一行带 description(一行摘要,≤ 120 字);
|
|
6
|
+
// 没写的节点行里没有这个键(不给全网每行加一个 null);
|
|
7
|
+
// 3. MCP get_session_status:profile.description 是整段(含换行),另带 display_name / team / tags。
|
|
8
|
+
// 4. 自助:节点用**自己的**节点令牌能写**自己的** description(谁最清楚自己干什么);写别的节点 → 403(只有人能改别人)。
|
|
9
|
+
//
|
|
10
|
+
// 跑法:cd server && bun test src/node-description-http.test.ts
|
|
11
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
12
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
13
|
+
import { tmpdir } from "node:os";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
|
|
16
|
+
const DIR = mkdtempSync(join(tmpdir(), "anet-node-desc-"));
|
|
17
|
+
process.env.COMMHUB_DB ||= join(DIR, "hub.db");
|
|
18
|
+
process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
|
|
19
|
+
process.env.HOST = "127.0.0.1";
|
|
20
|
+
const stamp = Date.now();
|
|
21
|
+
|
|
22
|
+
let db: any;
|
|
23
|
+
let hub: any = null;
|
|
24
|
+
let BASE = "";
|
|
25
|
+
let NET = "";
|
|
26
|
+
let bossToken = "";
|
|
27
|
+
type Node = { alias: string; nodeId: string; token: string };
|
|
28
|
+
const nodes: Record<"reader" | "target" | "blank", Node> = {} as any;
|
|
29
|
+
|
|
30
|
+
async function tool(token: string, name: string, args: Record<string, unknown>) {
|
|
31
|
+
const res = await fetch(`${BASE}/mcp`, {
|
|
32
|
+
method: "POST",
|
|
33
|
+
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26" },
|
|
34
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
|
|
35
|
+
});
|
|
36
|
+
const raw = await res.text();
|
|
37
|
+
const data = raw.split("\n").filter((x) => x.startsWith("data:"));
|
|
38
|
+
const payload = data.length ? JSON.parse(data.at(-1)!.slice(5).trim()) : JSON.parse(raw);
|
|
39
|
+
return JSON.parse(payload.result.content[0].text);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
beforeAll(async () => {
|
|
43
|
+
({ db } = await import("./db.js"));
|
|
44
|
+
const { createNetworkTokenForNode, register } = await import("./auth.js");
|
|
45
|
+
const boss = register(`desc_boss_${stamp}`, "NodeDesc123!x");
|
|
46
|
+
expect(boss.ok).toBe(true);
|
|
47
|
+
bossToken = boss.token!; NET = boss.network_id!;
|
|
48
|
+
for (const key of ["reader", "target", "blank"] as const) {
|
|
49
|
+
const alias = `desc-${key}-${stamp}`;
|
|
50
|
+
const nodeId = `n_desc_${key}_${stamp}`;
|
|
51
|
+
const minted = createNetworkTokenForNode(boss.user!.user_id, NET, alias, nodeId);
|
|
52
|
+
expect(minted.ok).toBe(true);
|
|
53
|
+
nodes[key] = { alias, nodeId, token: minted.token! };
|
|
54
|
+
db.run(`INSERT OR IGNORE INTO nodes (node_id, node_name, alias, runtime, network_id) VALUES (?1, ?2, ?2, 'claude-agent-sdk', ?3)`, [nodeId, alias, NET]);
|
|
55
|
+
}
|
|
56
|
+
const mod: any = await import("./server.js");
|
|
57
|
+
hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
58
|
+
BASE = `http://127.0.0.1:${hub.port}`;
|
|
59
|
+
for (const n of Object.values(nodes)) {
|
|
60
|
+
expect((await tool(n.token, "report_status", { resume_id: `sdk-${n.nodeId}`, alias: n.alias, status: "idle", node_id: n.nodeId, network_id: NET })).ok).toBe(true);
|
|
61
|
+
}
|
|
62
|
+
}, 30_000);
|
|
63
|
+
|
|
64
|
+
afterAll(() => {
|
|
65
|
+
try { hub?.stop?.(true); } catch {}
|
|
66
|
+
try { rmSync(DIR, { recursive: true, force: true }); } catch {}
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
const DESC = `负责 App 发版:派发 release-desktop / ios-build,跑 finish-release 与 verify。${"细节".repeat(80)}\n\n找我:发版、签名、TestFlight。\n不做:Hub 改动。`;
|
|
70
|
+
|
|
71
|
+
describe("node description is visible to other nodes", () => {
|
|
72
|
+
test("owner writes it through PUT /api/nodes/:id/attrs", async () => {
|
|
73
|
+
const res = await fetch(`${BASE}/api/nodes/${encodeURIComponent(nodes.target.nodeId)}/attrs?network_id=${NET}`, {
|
|
74
|
+
method: "PUT",
|
|
75
|
+
headers: { Authorization: `Bearer ${bossToken}`, "Content-Type": "application/json" },
|
|
76
|
+
body: JSON.stringify({ base_attrs_revision: 0, description: DESC, team: "发版" }),
|
|
77
|
+
});
|
|
78
|
+
const body = await res.json() as any;
|
|
79
|
+
expect(res.status).toBe(200);
|
|
80
|
+
expect(body.description).toBe(DESC);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("get_all_status (another node's token): target row carries a one-line summary; unwritten nodes carry no key", async () => {
|
|
84
|
+
const r = await tool(nodes.reader.token, "get_all_status", {});
|
|
85
|
+
expect(r.ok).toBe(true);
|
|
86
|
+
const target = r.sessions.find((s: any) => s.alias === nodes.target.alias);
|
|
87
|
+
const blank = r.sessions.find((s: any) => s.alias === nodes.blank.alias);
|
|
88
|
+
expect(target).toBeDefined();
|
|
89
|
+
expect(typeof target.description).toBe("string");
|
|
90
|
+
expect(target.description.startsWith("负责 App 发版")).toBe(true);
|
|
91
|
+
expect([...target.description].length).toBeLessThanOrEqual(120);
|
|
92
|
+
expect(target.description.endsWith("…")).toBe(true);
|
|
93
|
+
expect(target.description).not.toContain("\n");
|
|
94
|
+
expect(blank).toBeDefined();
|
|
95
|
+
expect("description" in blank).toBe(false);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test("self-service: a node writes its OWN description with its node token; writing another node is refused", async () => {
|
|
99
|
+
const put = (token: string, ref: string, rev: number, description: string) => fetch(`${BASE}/api/nodes/${encodeURIComponent(ref)}/attrs?network_id=${NET}`, {
|
|
100
|
+
method: "PUT", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
|
|
101
|
+
body: JSON.stringify({ base_attrs_revision: rev, description }),
|
|
102
|
+
});
|
|
103
|
+
const own = await put(nodes.reader.token, nodes.reader.nodeId, 0, "负责读别人的名片。");
|
|
104
|
+
expect(own.status).toBe(200);
|
|
105
|
+
expect(((await own.json()) as any).description).toBe("负责读别人的名片。");
|
|
106
|
+
const other = await put(nodes.reader.token, nodes.blank.nodeId, 0, "冒名顶替");
|
|
107
|
+
expect(other.status).toBe(403);
|
|
108
|
+
expect(((await other.json()) as any).error).toBe("description_self_only");
|
|
109
|
+
expect(db.get("SELECT description FROM nodes WHERE node_id = ?1", nodes.blank.nodeId)?.description ?? null).toBeNull();
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test("get_session_status: profile carries the full text plus team", async () => {
|
|
113
|
+
const r = await tool(nodes.reader.token, "get_session_status", { alias: nodes.target.alias });
|
|
114
|
+
expect(r.ok).toBe(true);
|
|
115
|
+
expect(r.profile.description).toBe(DESC);
|
|
116
|
+
expect(r.profile.team).toBe("发版");
|
|
117
|
+
expect(Array.isArray(r.profile.tags)).toBe(true);
|
|
118
|
+
const blank = await tool(nodes.reader.token, "get_session_status", { alias: nodes.blank.alias });
|
|
119
|
+
expect(blank.profile.description).toBeNull();
|
|
120
|
+
});
|
|
121
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// admin 2026-11-15 —— 节点职责介绍:边界校验 + 状态列表里的一行摘要。纯函数,不起服务。
|
|
2
|
+
import { describe, expect, test } from "bun:test";
|
|
3
|
+
import { MAX_DESCRIPTION_LEN, descriptionSummary, validateDescription } from "./node-attrs-validate.js";
|
|
4
|
+
|
|
5
|
+
describe("validateDescription", () => {
|
|
6
|
+
test("undefined / null / blank → clear (null)", () => {
|
|
7
|
+
expect(validateDescription(undefined)).toEqual({ ok: true, value: null });
|
|
8
|
+
expect(validateDescription(null)).toEqual({ ok: true, value: null });
|
|
9
|
+
expect(validateDescription(" \n\t ")).toEqual({ ok: true, value: null });
|
|
10
|
+
});
|
|
11
|
+
test("non-string is rejected, never coerced", () => {
|
|
12
|
+
expect(validateDescription(42).ok).toBe(false);
|
|
13
|
+
expect(validateDescription(["a"]).ok).toBe(false);
|
|
14
|
+
});
|
|
15
|
+
test("keeps newlines, normalises CRLF, strips other control chars, trims line ends, folds 3+ blank lines", () => {
|
|
16
|
+
const r = validateDescription("第一行 \r\n第二\u0007行\n\n\n\n第三行");
|
|
17
|
+
expect(r).toEqual({ ok: true, value: "第一行\n第二 行\n\n第三行" });
|
|
18
|
+
});
|
|
19
|
+
test("length cap counts code points, not UTF-16 units", () => {
|
|
20
|
+
expect(validateDescription("😀".repeat(MAX_DESCRIPTION_LEN)).ok).toBe(true);
|
|
21
|
+
expect(validateDescription("😀".repeat(MAX_DESCRIPTION_LEN + 1)).ok).toBe(false);
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
describe("descriptionSummary", () => {
|
|
26
|
+
test("first non-empty line, capped with an ellipsis", () => {
|
|
27
|
+
expect(descriptionSummary("\n\n 负责发版 \n其余")).toBe("负责发版");
|
|
28
|
+
expect(descriptionSummary("字".repeat(200), 10)).toBe(`${"字".repeat(9)}…`);
|
|
29
|
+
});
|
|
30
|
+
test("nothing written → null (the key is omitted from get_all_status rows)", () => {
|
|
31
|
+
expect(descriptionSummary(null)).toBeNull();
|
|
32
|
+
expect(descriptionSummary(" \n ")).toBeNull();
|
|
33
|
+
});
|
|
34
|
+
});
|
package/src/server.ts
CHANGED
|
@@ -57,7 +57,7 @@ import { getTaskAccessMode, isTaskScoped, listProjectGrants, replaceTaskGrants,
|
|
|
57
57
|
import { canMessageAgent, isAgentRestricted, visibleAgents, listAgentGrants, listGroupGrants, getAgentAccessMode, replaceAgentGrants, restrictedNetworkIds, usernameIsAgentAlias, listAgentGroups, createAgentGroup, updateAgentGroup, replaceAgentGroupMembers, deleteAgentGroup, usersGrantedGroup, listDepartmentGrants, departmentCoverage } from "./agent-access.js";
|
|
58
58
|
import { broadcastVerdict, dispatchVerdict, filterBroadcastByInbox, humanOnlyVerdict, inboxDenied, inboxSenderFromAuth, NODE_PERMISSION_MODES, nodeDecide, nodeIdentity, nodePermissionDeniedBody, nodePermissionsFlag, streamVerdict, writeVerdict, type InboxSender, type NodeIdentity, type NodePermissionMode, type Verdict } from "./node-permissions.js";
|
|
59
59
|
import { validateAvatarUrl } from "./avatar-validate.js";
|
|
60
|
-
import { narrowTags, parseStoredTags, validateScalarAttr } from "./node-attrs-validate.js";
|
|
60
|
+
import { narrowTags, parseStoredTags, validateDescription, validateScalarAttr } from "./node-attrs-validate.js";
|
|
61
61
|
import { daemonDefaultWorkdirRoot } from "./create-node-validate.js";
|
|
62
62
|
import { register, login, resolveToken, tokenRejection, isExpiredSessionToken, sessionIdleDays, listSessions, revokeSession, revokeOtherSessions, getUserNetworks, getUserAllNetworks, createNetwork, deleteNetwork, adminDeleteEmptyNetwork, renameNetwork, changePassword, issueUserToken, getUserTokenMeta, listTokens, createToken, revokeToken, getNetworkMembers, getNetworkHumans, getUserNetworkRole, addNetworkMember, adminCreateUser, listUsersWithMemberships, updateMemberRole, removeNetworkMember, createInvite, joinByInvite, createNetworkTokenForNode, type AuthUser } from "./auth.js";
|
|
63
63
|
import { abortRename, cleanupCommittedRenameSessions, commitRename, prepareRename, resolveCanonicalAlias } from "./rename.js";
|
|
@@ -229,7 +229,7 @@ const SERVER_VERSION_SOURCE = RESOLVED_VERSION.source;
|
|
|
229
229
|
// 还在跑的回 409 schedule_not_stopped(先 cancel)。
|
|
230
230
|
// node_inbox_allowlist_dept:收件白名单认 dept:<department_id>(该部门及子部门里的节点和人)。
|
|
231
231
|
// node_grants:节点管理授权 GET/PUT /api/nodes/:id/grants(能力 schedules × 范围 network/department/node × read/edit)。
|
|
232
|
-
export const HUB_HEALTH_CAPABILITIES = ["status_node_id", "node_permission_mode", "chat_groups", "node_inbox_allowlist", "scheduled_task_purge", "node_inbox_allowlist_dept", "node_grants"] as const;
|
|
232
|
+
export const HUB_HEALTH_CAPABILITIES = ["status_node_id", "node_permission_mode", "chat_groups", "node_inbox_allowlist", "scheduled_task_purge", "node_inbox_allowlist_dept", "node_grants", "create_node_department"] as const;
|
|
233
233
|
|
|
234
234
|
// In-memory log ring buffer — last N lines streamed via /api/server-logs.
|
|
235
235
|
// Wraps console.log/info/warn/error so EVERY existing log call lands here
|
|
@@ -3923,7 +3923,8 @@ return Bun.serve({
|
|
|
3923
3923
|
since: startedAtIso,
|
|
3924
3924
|
task_rejections: taskRejectionCounters(),
|
|
3925
3925
|
// #3271 —— 「到死都没被取走」按节点分桶。窗口用同一个 since。
|
|
3926
|
-
|
|
3926
|
+
// recent_at 只给闸用(逐条时刻,按节点最多 16 条),不进这个读数,免得读数随节点数膨胀。
|
|
3927
|
+
task_expiries_never_consumed: (({ recent_at: _recent, ...rest }) => rest)(neverConsumedExpiryCounters()),
|
|
3927
3928
|
// #3314 B 类 —— 故意匿名的那两条路由(register / login)没有身份门,
|
|
3928
3929
|
// 它们的健康度只能从「限流与锁定命中了几次、打到了几个不同来源」读出来。
|
|
3929
3930
|
// 比值才是有意义的部分:命中数 ≫ 去重数 ⇒ 单点重试;两者接近 ⇒ 换 IP / 撒网。
|
|
@@ -6684,7 +6685,7 @@ return Bun.serve({
|
|
|
6684
6685
|
}
|
|
6685
6686
|
const ref = decodeURIComponent(nodeAttrsMatch[1]);
|
|
6686
6687
|
const params: any[] = [ref, ref, ref];
|
|
6687
|
-
let sql = "SELECT node_id, alias, network_id, display_name, team, tags, attrs_revision FROM nodes WHERE (node_id = ?1 OR node_name = ?2 OR alias = ?3)";
|
|
6688
|
+
let sql = "SELECT node_id, alias, network_id, display_name, team, tags, description, attrs_revision FROM nodes WHERE (node_id = ?1 OR node_name = ?2 OR alias = ?3)";
|
|
6688
6689
|
sql = addNetworkScope(sql, params, restScope);
|
|
6689
6690
|
sql += " ORDER BY updated_at DESC LIMIT 1";
|
|
6690
6691
|
const node = db.get<any>(sql, ...params);
|
|
@@ -6727,6 +6728,20 @@ return Bun.serve({
|
|
|
6727
6728
|
return withCors(req, Response.json({ ok: false, error: "invalid_team", reason: nextTeam.reason }, { status: 400 }));
|
|
6728
6729
|
}
|
|
6729
6730
|
const nextTags = "tags" in attrsBody ? narrowTags(attrsBody.tags) : null;
|
|
6731
|
+
// 职责介绍(多行,≤ 1000 字);类型错 → 400,和 display_name 同一姿态。
|
|
6732
|
+
const nextDescription = "description" in attrsBody ? validateDescription(attrsBody.description) : null;
|
|
6733
|
+
if (nextDescription && !nextDescription.ok) {
|
|
6734
|
+
return withCors(req, Response.json({ ok: false, error: "invalid_description", reason: nextDescription.reason }, { status: 400 }));
|
|
6735
|
+
}
|
|
6736
|
+
// 职责介绍是节点对外的「名片」:节点令牌只许写**自己的**,不看 node-permissions 开关(那个开关在 off / log 时会放行
|
|
6737
|
+
// 「写别的节点」—— 对展示名还算无害,对名片就是冒名)。人(用户令牌)照旧按网络写权限。
|
|
6738
|
+
if (nextDescription && restAuth?.networkId) {
|
|
6739
|
+
const caller = nodeIdentity(restAuth.tokenId, restAuth.networkId);
|
|
6740
|
+
const self = !!caller && ((!!caller.nodeId && caller.nodeId === node.node_id) || (!!node.alias && caller.aliases.includes(node.alias)));
|
|
6741
|
+
if (!self) {
|
|
6742
|
+
return withCors(req, Response.json({ ok: false, error: "description_self_only", message: "a node may only edit its own description; ask a person to edit another node's" }, { status: 403 }));
|
|
6743
|
+
}
|
|
6744
|
+
}
|
|
6730
6745
|
|
|
6731
6746
|
// Only the supplied fields move; the rest keep their stored value.
|
|
6732
6747
|
const sets: string[] = [];
|
|
@@ -6734,6 +6749,7 @@ return Bun.serve({
|
|
|
6734
6749
|
if (nextDisplay) { sets.push(`display_name = ?${vals.length + 1}`); vals.push(nextDisplay.value); }
|
|
6735
6750
|
if (nextTeam) { sets.push(`team = ?${vals.length + 1}`); vals.push(nextTeam.value); }
|
|
6736
6751
|
if (nextTags) { sets.push(`tags = ?${vals.length + 1}`); vals.push(JSON.stringify(nextTags)); }
|
|
6752
|
+
if (nextDescription) { sets.push(`description = ?${vals.length + 1}`); vals.push(nextDescription.value); }
|
|
6737
6753
|
// A no-op patch still bumps the revision: the caller observed a state
|
|
6738
6754
|
// and asserted it, so honouring the CAS keeps client counters in step.
|
|
6739
6755
|
sets.push(`attrs_revision = ?${vals.length + 1}`); vals.push(currentRev + 1);
|
|
@@ -6756,10 +6772,10 @@ return Bun.serve({
|
|
|
6756
6772
|
}, { status: 409 }));
|
|
6757
6773
|
}
|
|
6758
6774
|
logAudit(restAuth?.userId ?? null, restAuth?.username ?? null, "node_attrs_updated", "node", node.node_id,
|
|
6759
|
-
JSON.stringify({ display_name: nextDisplay?.value ?? undefined, team: nextTeam?.value ?? undefined, tags: nextTags ?? undefined }),
|
|
6775
|
+
JSON.stringify({ display_name: nextDisplay?.value ?? undefined, team: nextTeam?.value ?? undefined, tags: nextTags ?? undefined, description_changed: nextDescription ? true : undefined }),
|
|
6760
6776
|
undefined, nodeNetId ?? undefined);
|
|
6761
6777
|
const after = db.get<any>(
|
|
6762
|
-
"SELECT display_name, team, tags, attrs_revision FROM nodes WHERE node_id = ?1", node.node_id);
|
|
6778
|
+
"SELECT display_name, team, tags, description, attrs_revision FROM nodes WHERE node_id = ?1", node.node_id);
|
|
6763
6779
|
return withCors(req, Response.json({
|
|
6764
6780
|
ok: true,
|
|
6765
6781
|
node_id: node.node_id,
|
|
@@ -6767,6 +6783,7 @@ return Bun.serve({
|
|
|
6767
6783
|
display_name: after?.display_name ?? null,
|
|
6768
6784
|
team: after?.team ?? null,
|
|
6769
6785
|
tags: parseStoredTags(after?.tags),
|
|
6786
|
+
description: after?.description ?? null,
|
|
6770
6787
|
attrs_revision: Number(after?.attrs_revision ?? currentRev + 1),
|
|
6771
6788
|
}));
|
|
6772
6789
|
}
|
|
@@ -7092,7 +7109,7 @@ return Bun.serve({
|
|
|
7092
7109
|
config_path, channels, server, hostname,
|
|
7093
7110
|
network_id, created_at, updated_at,
|
|
7094
7111
|
config_snapshot, lifecycle_state, avatar_url,
|
|
7095
|
-
display_name, team, tags, attrs_revision, permission_mode, owner_user_id,
|
|
7112
|
+
display_name, team, tags, description, attrs_revision, permission_mode, owner_user_id,
|
|
7096
7113
|
department_id, peer_allowlist, tool_allowlist, rest_allowlist, inbox_allowlist
|
|
7097
7114
|
FROM nodes WHERE 1=1`;
|
|
7098
7115
|
const params: any[] = [];
|
|
@@ -243,6 +243,11 @@ describe("bytes per role (#476 ceilings stay meaningful per role)", () => {
|
|
|
243
243
|
// 压到 "Build commit (hex)"(19 字符)⇒ node 64,497 B,余量 **3 B**。
|
|
244
244
|
// ⚠️ 3 B 不是「刚好」,是**陷阱**:下一个人加一个字段名就会撞墙,而这条测试的失败会
|
|
245
245
|
// 读成「谁又把描述写长了」。所以下面把余量打出来,余量低于 100 B 时大声说一句。
|
|
246
|
+
// 2026-11-14:create_node 新增 department_id(新节点归哪个部门)。all 先撞墙 86,534 > 86,500(+34 B)。
|
|
247
|
+
// 照规矩**不抬上限**:去掉工具描述末尾的 RFC / issue 编号(RFC-024/026/027/028、app#225、Hub #938,共 13 处,
|
|
248
|
+
// 调用方用不上这些编号,上下文都在代码注释里),clone_node 描述顺手压短 —— 合计约 −156 B。
|
|
249
|
+
// 2026-11-15:get_all_status / get_session_status 描述里点名 description / profile.description(节点职责介绍,
|
|
250
|
+
// 让调用方知道去哪读别的节点「负责什么」)。照规矩不抬上限,两句都压到最短。
|
|
246
251
|
const CEILINGS = { node: 64_500, user: 60_500, all: 86_500 } as const;
|
|
247
252
|
const MARGIN_FLOOR = 100;
|
|
248
253
|
test("node / user / all", async () => {
|
package/src/tools.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { allStatusCacheKey, cachedAllStatus } from "./all-status-cache.js";
|
|
2
|
+
import { descriptionSummary } from "./node-attrs-validate.js";
|
|
2
3
|
import { parseScheduledWorkOutcome, qualifyScheduledWorkOutcome, saveScheduledWorkOutcome } from "./scheduled-work-outcome.js";
|
|
3
4
|
import { enqueueBroadcast } from "./broadcast-fanout.js";
|
|
4
5
|
import { selectHumanInboxIds } from "./human-inbox.js";
|
|
@@ -1561,6 +1562,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
1561
1562
|
// A copied node_id must not relabel the row. The heartbeat itself still
|
|
1562
1563
|
// succeeds: only a token rejected as impersonation fails the whole call.
|
|
1563
1564
|
// identity_mismatch must not leave this session pointing at the other row.
|
|
1565
|
+
// #3585 —— 这一格只做判定,不改变控制流;写入仍在下面的 if (node_id) 里。
|
|
1566
|
+
const configSnapshotRejected = cfgSnap != null && !node_id;
|
|
1564
1567
|
if (node_id) {
|
|
1565
1568
|
try {
|
|
1566
1569
|
const nodeRuntime = ag?.includes(":") ? ag.split(":")[1] + "-sdk" : ag ?? null;
|
|
@@ -1601,6 +1604,10 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
1601
1604
|
alias: effectiveAlias,
|
|
1602
1605
|
...(canonical.renamed ? { renamed_from: alias } : {}),
|
|
1603
1606
|
...(offlineDeferred ? { offline_deferred: true, reason: "node_identity_conflict" } : {}),
|
|
1607
|
+
// #3585 —— config_snapshot 没有 node_id 时不写入,但**必须在回执里说出来**。
|
|
1608
|
+
// 以前是静默丢弃 + 200 ok,调用方以为报上去了(能力声明丢失 ⇒ 客户端入口永远是灰的)。
|
|
1609
|
+
// 仍不整条失败:在线状态/心跳照常更新,只拒这一个字段。
|
|
1610
|
+
...(configSnapshotRejected ? { config_snapshot: "rejected (node_id required)" } : {}),
|
|
1604
1611
|
inbox_count: row?.cnt ?? 0,
|
|
1605
1612
|
}),
|
|
1606
1613
|
},
|
|
@@ -2001,9 +2008,23 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
2001
2008
|
// Hub Tools (5)
|
|
2002
2009
|
// ═══════════════════════════════════════════
|
|
2003
2010
|
|
|
2011
|
+
/** node_id → 职责介绍(只取写了的)。一条 IN 查询,不按行回查。 */
|
|
2012
|
+
const nodeDescriptions = (ids: string[]): Map<string, string> => {
|
|
2013
|
+
const out = new Map<string, string>();
|
|
2014
|
+
const uniq = [...new Set(ids)];
|
|
2015
|
+
for (let i = 0; i < uniq.length; i += 500) {
|
|
2016
|
+
const chunk = uniq.slice(i, i + 500);
|
|
2017
|
+
const marks = chunk.map((_, j) => `?${j + 1}`).join(", ");
|
|
2018
|
+
for (const r of db.all<any>(`SELECT node_id, description FROM nodes WHERE description IS NOT NULL AND node_id IN (${marks})`, ...chunk)) {
|
|
2019
|
+
if (typeof r.description === "string" && r.description) out.set(r.node_id, r.description);
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
return out;
|
|
2023
|
+
};
|
|
2024
|
+
|
|
2004
2025
|
server.tool(
|
|
2005
2026
|
"get_all_status",
|
|
2006
|
-
"Session status for Hub patrol; queue_depth = open tasks. Use comma-separated filter_alias for specific nodes. Unfiltered: one row/session, 31 columns; large fleets can exceed client limits.",
|
|
2027
|
+
"Session status for Hub patrol; queue_depth = open tasks; description = node's role (full: get_session_status). Use comma-separated filter_alias for specific nodes. Unfiltered: one row/session, 31 columns; large fleets can exceed client limits.",
|
|
2007
2028
|
{
|
|
2008
2029
|
filter_status: z.string().max(50).optional(),
|
|
2009
2030
|
filter_server: z.string().max(200).optional(),
|
|
@@ -2043,7 +2064,13 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
2043
2064
|
// #500 step 2 — queue_depth = open tasks on that node (task-queue-ahead.ts); one GROUP BY, not one query per row.
|
|
2044
2065
|
const rows = db.all<any>(sql, ...params);
|
|
2045
2066
|
const depth = queueDepthByNode(rows.map((r: any) => r.alias));
|
|
2046
|
-
|
|
2067
|
+
// admin 2026-11-15 —— 节点职责介绍:别的节点挑人派活前就能看到「它负责什么、能干什么」。
|
|
2068
|
+
// 列表里只给一行摘要(description,≤ 120 字;没写就不带这个键),整段在 get_session_status。
|
|
2069
|
+
const duty = nodeDescriptions(rows.map((r: any) => r.node_id).filter((id: unknown): id is string => typeof id === "string" && !!id));
|
|
2070
|
+
const sessions = rows.map((s: any) => {
|
|
2071
|
+
const summary = descriptionSummary(s.node_id ? duty.get(s.node_id) : null);
|
|
2072
|
+
return { ...s, queue_depth: depth.get(queueDepthKey(s.network_id, s.alias)) ?? 0, ...(summary ? { description: summary } : {}) };
|
|
2073
|
+
});
|
|
2047
2074
|
|
|
2048
2075
|
// `summary` has always counted every session in the read scope, ignoring
|
|
2049
2076
|
// filter_status / filter_server — and now filter_alias. That is fine for
|
|
@@ -2076,7 +2103,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
2076
2103
|
|
|
2077
2104
|
server.tool(
|
|
2078
2105
|
"get_session_status",
|
|
2079
|
-
"Get detailed status of a specific session by alias.",
|
|
2106
|
+
"Get detailed status of a specific session by alias; profile.description = its role.",
|
|
2080
2107
|
{ alias: z.string().min(1).max(200).describe("Session alias") },
|
|
2081
2108
|
async ({ alias }) => {
|
|
2082
2109
|
const readScope = resolveReadScope(null);
|
|
@@ -2098,11 +2125,22 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
2098
2125
|
recentSql += " ORDER BY completed_at DESC LIMIT 5";
|
|
2099
2126
|
const recent = db.all(recentSql, ...recentParams);
|
|
2100
2127
|
|
|
2128
|
+
// admin 2026-11-15 —— 节点的「名片」:职责介绍整段 + 展示名 / 团队 / 标签(都是给别人看的,不是它自己的 AGENTS.md)。
|
|
2129
|
+
const sid = (session as any)?.node_id;
|
|
2130
|
+
const node = typeof sid === "string" && sid
|
|
2131
|
+
? db.get<any>("SELECT display_name, team, tags, description FROM nodes WHERE node_id = ?1", sid)
|
|
2132
|
+
: null;
|
|
2133
|
+
const profile = node ? {
|
|
2134
|
+
description: node.description ?? null,
|
|
2135
|
+
display_name: node.display_name ?? null,
|
|
2136
|
+
team: node.team ?? null,
|
|
2137
|
+
tags: (() => { try { const t = JSON.parse(node.tags ?? "[]"); return Array.isArray(t) ? t : []; } catch { return []; } })(),
|
|
2138
|
+
} : null;
|
|
2101
2139
|
return {
|
|
2102
2140
|
content: [
|
|
2103
2141
|
{
|
|
2104
2142
|
type: "text" as const,
|
|
2105
|
-
text: JSON.stringify({ ok: true, session, inbox_pending: pending?.cnt ?? 0, recent_completions: recent }),
|
|
2143
|
+
text: JSON.stringify({ ok: true, session, profile, inbox_pending: pending?.cnt ?? 0, recent_completions: recent }),
|
|
2106
2144
|
},
|
|
2107
2145
|
],
|
|
2108
2146
|
};
|
|
@@ -3824,7 +3862,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
3824
3862
|
|
|
3825
3863
|
server.tool(
|
|
3826
3864
|
"update_node_config",
|
|
3827
|
-
"Set the per-node config (model + flags) and push a doorbell; the node pulls, validates and applies (hot or restart per field).
|
|
3865
|
+
"Set the per-node config (model + flags) and push a doorbell; the node pulls, validates and applies (hot or restart per field).",
|
|
3828
3866
|
{
|
|
3829
3867
|
...NODE_ID_ALIAS_FIELDS,
|
|
3830
3868
|
base_revision: z.number().int().min(0).describe("Revision from the dashboard's last GET — 409 if the hub's differs."),
|
|
@@ -4191,7 +4229,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
4191
4229
|
|
|
4192
4230
|
server.tool(
|
|
4193
4231
|
"get_config_update",
|
|
4194
|
-
"Node pulls its pending config update (called from agent-node when SSE config_update doorbell arrives).
|
|
4232
|
+
"Node pulls its pending config update (called from agent-node when SSE config_update doorbell arrives).",
|
|
4195
4233
|
{},
|
|
4196
4234
|
async () => {
|
|
4197
4235
|
// F-A (CHANGE_REQ): require ntok_ + non-null enforceNetworkId.
|
|
@@ -4246,7 +4284,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
4246
4284
|
|
|
4247
4285
|
server.tool(
|
|
4248
4286
|
"ack_config_update",
|
|
4249
|
-
"Node acknowledges a config update — applied / rejected / restarting / timeout.
|
|
4287
|
+
"Node acknowledges a config update — applied / rejected / restarting / timeout.",
|
|
4250
4288
|
{
|
|
4251
4289
|
update_id: z.string().min(1).max(200),
|
|
4252
4290
|
status: z.enum(["applied", "rejected", "restarting", "timeout"]),
|
|
@@ -4501,7 +4539,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
4501
4539
|
|
|
4502
4540
|
server.tool(
|
|
4503
4541
|
"read_node_rules_file",
|
|
4504
|
-
"Read the node's workdir rules file (CLAUDE.md for claude, else AGENTS.md). No path argument. Poll get_rules_file_result with request_id.
|
|
4542
|
+
"Read the node's workdir rules file (CLAUDE.md for claude, else AGENTS.md). No path argument. Poll get_rules_file_result with request_id.",
|
|
4505
4543
|
{
|
|
4506
4544
|
...NODE_ID_ALIAS_FIELDS,
|
|
4507
4545
|
alias: z.string().min(1).max(200).optional().describe("Instead of node_id: node or rules_file_capable session alias."),
|
|
@@ -4587,7 +4625,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
4587
4625
|
|
|
4588
4626
|
server.tool(
|
|
4589
4627
|
"get_rules_file_request",
|
|
4590
|
-
"Node pulls its oldest pending rules-file request (called from agent-node when the SSE rules_file doorbell arrives).
|
|
4628
|
+
"Node pulls its oldest pending rules-file request (called from agent-node when the SSE rules_file doorbell arrives).",
|
|
4591
4629
|
{},
|
|
4592
4630
|
async () => {
|
|
4593
4631
|
// 同 get_config_update 的 F-A 闸:必须是网络 token + alias。
|
|
@@ -4632,7 +4670,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
4632
4670
|
|
|
4633
4671
|
server.tool(
|
|
4634
4672
|
"ack_rules_file_request",
|
|
4635
|
-
"Node reports the outcome of a rules-file request — done (with content for reads) or failed (with error).
|
|
4673
|
+
"Node reports the outcome of a rules-file request — done (with content for reads) or failed (with error).",
|
|
4636
4674
|
{
|
|
4637
4675
|
request_id: z.string().min(1).max(200),
|
|
4638
4676
|
status: z.enum(["done", "failed"]),
|
|
@@ -4684,7 +4722,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
4684
4722
|
|
|
4685
4723
|
server.tool(
|
|
4686
4724
|
"get_rules_file_result",
|
|
4687
|
-
"Poll a read_node_rules_file / write_node_rules_file / node-file / node-log request. Returns status pending|in_progress|done|failed|timeout plus the file name and (reads) content.
|
|
4725
|
+
"Poll a read_node_rules_file / write_node_rules_file / node-file / node-log request. Returns status pending|in_progress|done|failed|timeout plus the file name and (reads) content.",
|
|
4688
4726
|
{ request_id: z.string().min(1).max(200), network_id: z.string().max(200).optional() },
|
|
4689
4727
|
async ({ request_id: requestId, network_id: clientNetId }) => {
|
|
4690
4728
|
const effectiveNetId = getNetworkId(clientNetId);
|
|
@@ -5090,8 +5128,11 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
5090
5128
|
workdir: z.string().max(1024).optional().nullable(),
|
|
5091
5129
|
}),
|
|
5092
5130
|
network_id: z.string().max(200).optional(),
|
|
5131
|
+
// 2026-11-14:新节点归哪个部门。缺席 / null / "" = 不指定(老行为)。create_node 已要求 admin / owner,
|
|
5132
|
+
// 所以本网络任何存在的部门都可以选;不存在 → department_not_found,不建。
|
|
5133
|
+
department_id: z.string().max(200).optional().nullable(),
|
|
5093
5134
|
},
|
|
5094
|
-
async ({ daemon_node_id, node_spec, network_id: clientNetId }) => {
|
|
5135
|
+
async ({ daemon_node_id, node_spec, network_id: clientNetId, department_id: requestedDepartment }) => {
|
|
5095
5136
|
const effectiveNetId = getNetworkId(clientNetId);
|
|
5096
5137
|
if (!canWrite(effectiveNetId)) return writeDeniedReply(effectiveNetId, "write");
|
|
5097
5138
|
|
|
@@ -5315,6 +5356,11 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
5315
5356
|
const childToken = generateNetworkToken();
|
|
5316
5357
|
const childTokenId = generateId("tok");
|
|
5317
5358
|
const networkIdForChild = daemon.network_id || effectiveNetId || "default";
|
|
5359
|
+
// 2026-11-14:部门必须在新节点所在的网络里存在;在派单之前拒,不留半成品请求。
|
|
5360
|
+
const departmentForChild = typeof requestedDepartment === "string" && requestedDepartment.trim() ? requestedDepartment.trim() : null;
|
|
5361
|
+
if (departmentForChild && !db.get("SELECT 1 AS x FROM network_departments WHERE network_id = ?1 AND department_id = ?2", networkIdForChild, departmentForChild)) {
|
|
5362
|
+
return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "department_not_found", department_id: departmentForChild }) }] };
|
|
5363
|
+
}
|
|
5318
5364
|
const requestId = newRequestId();
|
|
5319
5365
|
// Use the dashboard caller's user_id as the token's user_id so
|
|
5320
5366
|
// resolveToken returns sane role / network on the child's side
|
|
@@ -5340,13 +5386,13 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
5340
5386
|
const envKeys = Object.keys(envBlob);
|
|
5341
5387
|
db.run(
|
|
5342
5388
|
`INSERT INTO node_create_requests
|
|
5343
|
-
(request_id, daemon_node_id, child_name, network_id, runtime, model, flags_json, env_keys, status, child_token_id, created_at, created_by_token, workdir)
|
|
5344
|
-
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'pending', ?9, ?10, ?11, ?12)`,
|
|
5389
|
+
(request_id, daemon_node_id, child_name, network_id, runtime, model, flags_json, env_keys, status, child_token_id, created_at, created_by_token, workdir, department_id)
|
|
5390
|
+
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'pending', ?9, ?10, ?11, ?12, ?13)`,
|
|
5345
5391
|
[
|
|
5346
5392
|
requestId, daemon_node_id, node_spec.name, networkIdForChild,
|
|
5347
5393
|
node_spec.runtime, node_spec.model ?? null, JSON.stringify(node_spec.flags || {}),
|
|
5348
5394
|
JSON.stringify(envKeys), childTokenId, Date.now(), callerTokenId || "unknown",
|
|
5349
|
-
requestedWorkdir,
|
|
5395
|
+
requestedWorkdir, departmentForChild,
|
|
5350
5396
|
],
|
|
5351
5397
|
);
|
|
5352
5398
|
|
|
@@ -5370,11 +5416,12 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
5370
5416
|
flag_keys: Object.keys(node_spec.flags || {}),
|
|
5371
5417
|
env_keys: envKeys,
|
|
5372
5418
|
workdir: requestedWorkdir,
|
|
5419
|
+
department_id: departmentForChild,
|
|
5373
5420
|
},
|
|
5374
5421
|
});
|
|
5375
5422
|
|
|
5376
5423
|
return {
|
|
5377
|
-
content: [{ type: "text" as const, text: JSON.stringify({ ok: true, request_id: requestId }) }],
|
|
5424
|
+
content: [{ type: "text" as const, text: JSON.stringify({ ok: true, request_id: requestId, ...(departmentForChild ? { department_id: departmentForChild } : {}) }) }],
|
|
5378
5425
|
};
|
|
5379
5426
|
},
|
|
5380
5427
|
);
|
|
@@ -5385,7 +5432,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
5385
5432
|
// the policy and the runtime's session capability (see clone-node.ts).
|
|
5386
5433
|
server.tool(
|
|
5387
5434
|
"clone_node",
|
|
5388
|
-
"Clone a daemon child
|
|
5435
|
+
"Clone a daemon child to a new node (new name + token). copy_session default true; workdir_policy new_empty (default) or share_source.",
|
|
5389
5436
|
{
|
|
5390
5437
|
source_node_id: z.string().min(1).max(200),
|
|
5391
5438
|
name: z.string().min(1).max(256),
|
|
@@ -5726,7 +5773,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
5726
5773
|
// record fork-side info.
|
|
5727
5774
|
server.tool(
|
|
5728
5775
|
"ack_create_request",
|
|
5729
|
-
"Daemon acks a create-node request (called after fork). status='started' | 'failed' | 'rejected' | 'runtime_capability_check_failed'.
|
|
5776
|
+
"Daemon acks a create-node request (called after fork). status='started' | 'failed' | 'rejected' | 'runtime_capability_check_failed'.",
|
|
5730
5777
|
{
|
|
5731
5778
|
request_id: z.string().min(1).max(200),
|
|
5732
5779
|
// RFC-026 §9.3 D2 — runtime_capability_check_failed signals the
|
|
@@ -6175,7 +6222,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
6175
6222
|
|
|
6176
6223
|
server.tool(
|
|
6177
6224
|
"delete_node",
|
|
6178
|
-
"Stop child + revoke token + delete hub row + (default) back up config to ~/.anet/deleted/<ts>-<alias>/ for 30d. confirm_alias must match. daemon_node_id auto-resolved.
|
|
6225
|
+
"Stop child + revoke token + delete hub row + (default) back up config to ~/.anet/deleted/<ts>-<alias>/ for 30d. confirm_alias must match. daemon_node_id auto-resolved.",
|
|
6179
6226
|
{
|
|
6180
6227
|
...NODE_ID_ALIAS_FIELDS,
|
|
6181
6228
|
daemon_node_id: z.string().min(1).max(200).regex(/^node_[a-z0-9_-]+$/).optional(),
|
|
@@ -6205,7 +6252,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
6205
6252
|
|
|
6206
6253
|
server.tool(
|
|
6207
6254
|
"get_stop_request",
|
|
6208
|
-
"Daemon pulls a pending stop/delete request (called when SSE stop_node doorbell arrives).
|
|
6255
|
+
"Daemon pulls a pending stop/delete request (called when SSE stop_node doorbell arrives).",
|
|
6209
6256
|
{
|
|
6210
6257
|
request_id: z.string().min(1).max(200),
|
|
6211
6258
|
},
|
|
@@ -6249,7 +6296,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
6249
6296
|
|
|
6250
6297
|
server.tool(
|
|
6251
6298
|
"ack_stop_request",
|
|
6252
|
-
"Daemon reports stop/delete completion (or per-status failure). On 'stopped' status finalizes the lifecycle: stop→stopped + keep config; delete→DB row gone + revoke ntok.
|
|
6299
|
+
"Daemon reports stop/delete completion (or per-status failure). On 'stopped' status finalizes the lifecycle: stop→stopped + keep config; delete→DB row gone + revoke ntok.",
|
|
6253
6300
|
{
|
|
6254
6301
|
request_id: z.string().min(1).max(200),
|
|
6255
6302
|
status: z.enum(["stopped", "stop_failed", "noop_not_my_child"]),
|
|
@@ -6676,7 +6723,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
6676
6723
|
// §2.3.4 — upsert_network_secret (OWNER-ONLY; vault write).
|
|
6677
6724
|
server.tool(
|
|
6678
6725
|
"upsert_network_secret",
|
|
6679
|
-
"Create or replace one vault secret by key (value never read back).
|
|
6726
|
+
"Create or replace one vault secret by key (value never read back).",
|
|
6680
6727
|
{
|
|
6681
6728
|
key: z.string().min(1).max(64).regex(/^[A-Z][A-Z0-9_]{0,63}$/),
|
|
6682
6729
|
value: z.string().min(1).max(16 * 1024),
|
|
@@ -6708,7 +6755,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
6708
6755
|
// §2.3.4b — list_network_secrets (key names only; viewer+).
|
|
6709
6756
|
server.tool(
|
|
6710
6757
|
"list_network_secrets",
|
|
6711
|
-
"List vault key NAMES (NEVER values) for a network.
|
|
6758
|
+
"List vault key NAMES (NEVER values) for a network.",
|
|
6712
6759
|
{ network_id: z.string().max(200).optional() },
|
|
6713
6760
|
async ({ network_id: clientNetId }) => {
|
|
6714
6761
|
const effectiveNetId = getNetworkId(clientNetId);
|
|
@@ -6725,7 +6772,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
6725
6772
|
// §2.3.1 — upsert_provider (admin+).
|
|
6726
6773
|
server.tool(
|
|
6727
6774
|
"upsert_provider",
|
|
6728
|
-
"Create or update a provider (vendor + base_url + secret_key_ref + initial models). Admin+.
|
|
6775
|
+
"Create or update a provider (vendor + base_url + secret_key_ref + initial models). Admin+.",
|
|
6729
6776
|
{
|
|
6730
6777
|
name: z.string().min(1).max(100),
|
|
6731
6778
|
vendor: z.string().min(1).max(64),
|