@sleep2agi/commhub-server 0.9.0-preview.211 → 0.9.0-preview.213
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/broadcast-fanout-2721.test.ts +31 -0
- package/src/broadcast-fanout.ts +21 -2
- package/src/node-permissions-http.test.ts +67 -1
- package/src/poll-pacing.test.ts +74 -0
- package/src/poll-pacing.ts +123 -0
- package/src/server.ts +81 -0
- package/src/task-late-reply-http.test.ts +37 -0
- package/src/tools.ts +39 -2
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.213",
|
|
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",
|
|
@@ -115,4 +115,35 @@ describe('broadcastRecentState', () => {
|
|
|
115
115
|
expect(typeof rec!.took_ms).toBe('number');
|
|
116
116
|
expect(Number.isNaN(Date.parse(rec!.at))).toBe(false);
|
|
117
117
|
});
|
|
118
|
+
|
|
119
|
+
// 🔴 这条是 2026-10-30 补的:上半句只把 INSERT 摊开,notify 仍然在所有批次之后。
|
|
120
|
+
// 那等于「入库分 3 批、唤醒仍旧同一 tick」—— 而唤醒才是让 Hub 停顿 143.9 秒的原因。
|
|
121
|
+
test("通知与入库同批(不是全部入库完再一起推)", async () => {
|
|
122
|
+
const order: string[] = [];
|
|
123
|
+
const targets = Array.from({ length: 120 }, (_, i) => ({ alias: `a${i}`, node_id: null, network_id: "net_x" }));
|
|
124
|
+
await enqueueBroadcast(targets, "hi", "hub", "net_x", {
|
|
125
|
+
isActive: () => true,
|
|
126
|
+
notify: (alias) => order.push(`n:${alias}`),
|
|
127
|
+
yieldBetweenChunks: async () => { order.push("y"); },
|
|
128
|
+
chunkSize: 50,
|
|
129
|
+
});
|
|
130
|
+
// 结构应为 n×50 y n×50 y n×20 y —— 每一批后面紧跟一个让出,而不是 n×120 全在末尾
|
|
131
|
+
const firstYield = order.indexOf("y");
|
|
132
|
+
expect(firstYield).toBe(50);
|
|
133
|
+
expect(order.filter((x) => x === "y").length).toBe(3);
|
|
134
|
+
// 最后一批的通知必须在最后一次让出之前
|
|
135
|
+
const lastNotify = order.lastIndexOf(order.filter((x) => x.startsWith("n:")).at(-1)!);
|
|
136
|
+
expect(lastNotify).toBeLessThan(order.lastIndexOf("y"));
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test("某一条通知抛错:其余收件人照常入库(不能因为推不出去就漏发)", async () => {
|
|
140
|
+
const targets = Array.from({ length: 120 }, (_, i) => ({ alias: `b${i}`, node_id: null, network_id: "net_y" }));
|
|
141
|
+
const { ids } = await enqueueBroadcast(targets, "hi", "hub", "net_y", {
|
|
142
|
+
isActive: () => true,
|
|
143
|
+
notify: (alias) => { if (alias === "b0") throw new Error("sse down"); },
|
|
144
|
+
yieldBetweenChunks: async () => {},
|
|
145
|
+
chunkSize: 50,
|
|
146
|
+
});
|
|
147
|
+
expect(ids.length).toBe(120);
|
|
148
|
+
});
|
|
118
149
|
});
|
package/src/broadcast-fanout.ts
CHANGED
|
@@ -11,6 +11,11 @@
|
|
|
11
11
|
// 但每 50 个收件人一批、批间让出事件循环,把「同一毫秒 384 次 commit」
|
|
12
12
|
// 变成「8 批、每批一次事务」。
|
|
13
13
|
//
|
|
14
|
+
// 2026-10-30 补下半句:**通知(SSE 推送)也必须在批内**。
|
|
15
|
+
// 上半句只摊开了入库,通知仍是「所有批次之后一次性循环」——
|
|
16
|
+
// 于是 384 个 agent 还是在同一个 tick 里被唤醒。入库摊开对客户端几乎无感,
|
|
17
|
+
// 唤醒摊开才是「随机大停顿」的解法。
|
|
18
|
+
//
|
|
14
19
|
// 为什么有用:真正的负载大头是收件 agent 随后各自的 report_status/get_inbox/send_reply
|
|
15
20
|
// (实测一条广播 ≈ 500+ 次调用)。把入库摊开几百毫秒,能让唤醒时刻自然分散,
|
|
16
21
|
// 而不是让 384 个 agent 在同一秒同时醒来。
|
|
@@ -68,6 +73,7 @@ export async function enqueueBroadcast(
|
|
|
68
73
|
|
|
69
74
|
for (let i = 0; i < targets.length; i += chunk) {
|
|
70
75
|
const slice = targets.slice(i, i + chunk);
|
|
76
|
+
const batch: BroadcastDelivered[] = [];
|
|
71
77
|
// 一批一个事务:把 N 次 autocommit 变成 1 次,既快又不会长时间占写锁。
|
|
72
78
|
db.transaction(() => {
|
|
73
79
|
for (const t of slice) {
|
|
@@ -80,14 +86,27 @@ export async function enqueueBroadcast(
|
|
|
80
86
|
[id, t.alias, t.node_id ?? null, message, fromSession, netId],
|
|
81
87
|
);
|
|
82
88
|
ids.push(id);
|
|
83
|
-
|
|
89
|
+
const d = { alias: t.alias, netId };
|
|
90
|
+
delivered.push(d);
|
|
91
|
+
batch.push(d);
|
|
84
92
|
}
|
|
85
93
|
});
|
|
94
|
+
// #2721 下半 —— 通知也必须在批内做。
|
|
95
|
+
// 原来这句循环在**所有批次之后**:入库摊开了,但 384 次 SSE 推送又落回同一个 tick,
|
|
96
|
+
// 于是「同一秒全员唤醒」这个真正的问题一点没变 —— 只是把 INSERT 挪开了。
|
|
97
|
+
// 推送失败绝不能中断后续批次:原来通知在所有入库之后,抛错时「入库已全」;
|
|
98
|
+
// 现在挪进批内,一次推送异常会让剩下的人**收不到广播**。这里逐条兜住。
|
|
99
|
+
for (const d of batch) {
|
|
100
|
+
try {
|
|
101
|
+
deps.notify(d.alias, d.netId);
|
|
102
|
+
} catch (e) {
|
|
103
|
+
console.error(`[broadcast] notify failed alias=${d.alias}: ${(e as Error).message}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
86
106
|
// 批间让出:没有这一句,384 行仍然是在同一个 tick 里写完的。
|
|
87
107
|
await yieldNow();
|
|
88
108
|
}
|
|
89
109
|
|
|
90
|
-
for (const d of delivered) deps.notify(d.alias, d.netId);
|
|
91
110
|
lastBroadcast = {
|
|
92
111
|
at: new Date().toISOString(),
|
|
93
112
|
recipients: delivered.length,
|
|
@@ -17,7 +17,7 @@ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
|
17
17
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
18
18
|
import { addNetworkMember, createNetworkTokenForNode, register } from "./auth.js";
|
|
19
19
|
import { replaceTaskGrants } from "./task-access.js";
|
|
20
|
-
import { db } from "./db.js";
|
|
20
|
+
import { db, hashToken } from "./db.js";
|
|
21
21
|
import { NODE_TOOL_CLASS, pruneNodePermissionLog, __resetNodePermissionLogStateForTest } from "./node-permissions.js";
|
|
22
22
|
import { registerTools } from "./tools.js";
|
|
23
23
|
|
|
@@ -548,6 +548,31 @@ describe("未绑定令牌的写调用:默认只记录,不拦", () => {
|
|
|
548
548
|
expect(after).toBe(before + 1); // 但记了一笔
|
|
549
549
|
});
|
|
550
550
|
|
|
551
|
+
// 🔴 令牌前缀必须是 `ntok_`:`atok_` 会被当成**用户**令牌(服务端按前缀分流),
|
|
552
|
+
// 那样测出来的是「用户派活」,不是「未绑定节点令牌派活」—— 我第一次就这么写错了,
|
|
553
|
+
// 结果任务记在 boss 名下、账本一行都没有。
|
|
554
|
+
// 🔴 上面两条只调了**判据函数**(nodeDecide),而生产里真正决定「记不记」的是
|
|
555
|
+
// tools.ts 里那层 MCP 包装:它只在 `if (id)` 内部才走到判据。如果哪天有人把包装
|
|
556
|
+
// 改成「只对绑定节点记账」,上面两条测试仍然全绿,而未绑定令牌的写调用会**静默消失** ——
|
|
557
|
+
// 那正是 #3221 想解决的问题。所以这里补一条真正走 HTTP + MCP 的端到端。
|
|
558
|
+
test("HTTP 端到端:未绑定令牌真的调 MCP send_task ⇒ 进 node_permission_log", async () => {
|
|
559
|
+
const alias = `ghost-e2e-${stamp}`;
|
|
560
|
+
const tokenId = `tok_ghost_e2e_${stamp}`;
|
|
561
|
+
const plain = `ntok_ghost_e2e_${stamp}`;
|
|
562
|
+
db.run("INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope) VALUES (?1, ?2, ?3, ?4, ?5, 'network') ON CONFLICT (token_id) DO NOTHING",
|
|
563
|
+
[tokenId, hashToken(plain), user.boss.id, net, `node:${alias}`]);
|
|
564
|
+
|
|
565
|
+
const out = await mcp(plain, "send_task", { alias: node.nN.alias, task: "hello from a ghost token" });
|
|
566
|
+
// log 模式(默认):不因「未绑定」被拦 —— 拦不拦是另一个开关的事
|
|
567
|
+
expect(out.error ?? "").not.toBe("unbound_token");
|
|
568
|
+
|
|
569
|
+
const hits = Number(db.get<{ h: number | string | null }>(
|
|
570
|
+
`SELECT SUM(hits) AS h FROM node_permission_log
|
|
571
|
+
WHERE network_id = ?1 AND node_id = ?2 AND reason = 'unbound_token' AND route = 'mcp:send_task'`,
|
|
572
|
+
net, `token:${tokenId}`)?.h ?? 0);
|
|
573
|
+
expect(hits).toBe(1);
|
|
574
|
+
});
|
|
575
|
+
|
|
551
576
|
test("enforce 模式:同一个调用被拒,原因是 unbound_token", async () => {
|
|
552
577
|
process.env.COMMHUB_NODE_PERMISSIONS = "enforce";
|
|
553
578
|
const { nodeIdentity, nodeDecide } = await import("./node-permissions.js");
|
|
@@ -556,6 +581,47 @@ describe("未绑定令牌的写调用:默认只记录,不拦", () => {
|
|
|
556
581
|
});
|
|
557
582
|
});
|
|
558
583
|
|
|
584
|
+
// #2719 —— 凭据台账:把「哪把钥匙、绑没绑、还在不在用」变成可查的东西。
|
|
585
|
+
//
|
|
586
|
+
// 为什么需要它:node-permission-report 是按**流量**聚合的,只列出「近 N 天有调用」的身份。
|
|
587
|
+
// 生产实测 760 个未吊销令牌里 381 个是 `node:` 开头但未绑定,而其中只有 4 个近 24h 出现过 ——
|
|
588
|
+
// 剩下 377 个在任何报表里都不存在,于是「这把钥匙还有人在用吗」永远答不清,也就不敢吊销。
|
|
589
|
+
describe("#2719 凭据台账", () => {
|
|
590
|
+
test("owner 能看到未绑定令牌,区分「有流量」与「零流量」", async () => {
|
|
591
|
+
const loudId = `tok_ledger_loud_${stamp}`;
|
|
592
|
+
const quietId = `tok_ledger_quiet_${stamp}`;
|
|
593
|
+
for (const [id, nm] of [[loudId, "node:ledger-loud"], [quietId, "node:ledger-quiet"]] as const) {
|
|
594
|
+
db.run("INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope) VALUES (?1, ?2, ?3, ?4, ?5, 'network') ON CONFLICT (token_id) DO NOTHING",
|
|
595
|
+
[id, `hash_${id}`, user.boss.id, net, nm]);
|
|
596
|
+
}
|
|
597
|
+
const hour = new Date().toISOString().slice(0, 13);
|
|
598
|
+
db.run(`INSERT INTO node_tool_calls (network_id, node_id, tool, hour, hits) VALUES (?1, ?2, 'mcp:send_task', ?3, 5)
|
|
599
|
+
ON CONFLICT(network_id, node_id, tool, hour) DO UPDATE SET hits = node_tool_calls.hits + 5`,
|
|
600
|
+
[net, `token:${loudId}`, hour]);
|
|
601
|
+
|
|
602
|
+
const r = await call(user.boss.token, "GET", `/api/networks/${net}/token-ledger?limit=1000`);
|
|
603
|
+
expect(r.status).toBe(200);
|
|
604
|
+
const loud = r.body.tokens.find((t: any) => t.token_id === loudId);
|
|
605
|
+
const quiet = r.body.tokens.find((t: any) => t.token_id === quietId);
|
|
606
|
+
expect(loud.unbound_node).toBe(true);
|
|
607
|
+
expect(loud.calls_24h).toBe(5);
|
|
608
|
+
expect(loud.writes_24h).toBe(5);
|
|
609
|
+
expect(quiet.calls_24h).toBe(0); // 零流量也要在名单里 —— 这正是它存在的理由
|
|
610
|
+
expect(r.body.summary.unbound_node).toBeGreaterThanOrEqual(2);
|
|
611
|
+
// 绑定的节点令牌必须被标成「已绑定」,不能被算进未绑定
|
|
612
|
+
const bound = r.body.tokens.find((t: any) => t.token_id === node.nN.tokenId);
|
|
613
|
+
expect(bound.bound_node_id).toBe(node.nN.id);
|
|
614
|
+
expect(bound.unbound_node).toBe(false);
|
|
615
|
+
});
|
|
616
|
+
|
|
617
|
+
test("成员(非 owner/admin)看不到;节点令牌也看不到", async () => {
|
|
618
|
+
const r = await call(user.mem.token, "GET", `/api/networks/${net}/token-ledger`);
|
|
619
|
+
expect(r.status).toBe(403);
|
|
620
|
+
const n = await call(node.nN.token, "GET", `/api/networks/${net}/token-ledger`);
|
|
621
|
+
expect(n.status).toBe(403);
|
|
622
|
+
});
|
|
623
|
+
});
|
|
624
|
+
|
|
559
625
|
// #2969 续 —— REST 写接口白名单:唯一 choke point。
|
|
560
626
|
//
|
|
561
627
|
// 为什么必须在中央判一次:节点令牌的 REST 写面分散在两套判据里
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { POLL_PACING_NOTE, POLL_NUDGE_THRESHOLD, POLL_RECOMMENDED_SECONDS, createPollPacer } from "./poll-pacing";
|
|
3
|
+
|
|
4
|
+
// #3001 —— Hub 侧的轮询节奏提示。
|
|
5
|
+
// 现场:一个节点在空闲等待里以约 13 次/分钟连续拉了 8 小时 get_task(约 6000 次),
|
|
6
|
+
// 每次都是一整轮 LLM。这里钉住三件事:什么时候提示、什么时候**不**提示、提示里说了什么。
|
|
7
|
+
describe("#3001 get_task 轮询节奏提示", () => {
|
|
8
|
+
function pacerWithClock() {
|
|
9
|
+
let t = 1_000_000;
|
|
10
|
+
const pacer = createPollPacer({ now: () => t });
|
|
11
|
+
return { pacer, advance: (ms: number) => { t += ms; } };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
test("偶发查询不提示(正常等子任务不会被这句打扰)", () => {
|
|
15
|
+
const { pacer, advance } = pacerWithClock();
|
|
16
|
+
for (let i = 0; i < POLL_NUDGE_THRESHOLD; i++) {
|
|
17
|
+
expect(pacer.record("tok:t1:task-a")).toBeNull();
|
|
18
|
+
advance(3_000);
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test("60 秒内超过阈值才提示,且带次数与建议间隔", () => {
|
|
23
|
+
const { pacer, advance } = pacerWithClock();
|
|
24
|
+
let pacing = null as ReturnType<typeof pacer.record>;
|
|
25
|
+
for (let i = 0; i <= POLL_NUDGE_THRESHOLD; i++) {
|
|
26
|
+
pacing = pacer.record("tok:t1:task-a");
|
|
27
|
+
advance(4_600); // 约 13 次/分钟:实测的失控频率
|
|
28
|
+
}
|
|
29
|
+
expect(pacing).not.toBeNull();
|
|
30
|
+
expect(pacing!.calls_last_60s).toBeGreaterThan(POLL_NUDGE_THRESHOLD);
|
|
31
|
+
expect(pacing!.recommended_interval_seconds).toBe(POLL_RECOMMENDED_SECONDS);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test("隔一分钟以上再看,计数清零、不再提示(纪律生效后自动安静)", () => {
|
|
35
|
+
const { pacer, advance } = pacerWithClock();
|
|
36
|
+
for (let i = 0; i <= POLL_NUDGE_THRESHOLD; i++) {
|
|
37
|
+
pacer.record("tok:t1:task-a");
|
|
38
|
+
advance(500);
|
|
39
|
+
}
|
|
40
|
+
advance(POLL_RECOMMENDED_SECONDS * 1000 + 1);
|
|
41
|
+
expect(pacer.record("tok:t1:task-a")).toBeNull();
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test("不同 task_id 互不累加(同时等多个子任务不算连环打)", () => {
|
|
45
|
+
const { pacer, advance } = pacerWithClock();
|
|
46
|
+
for (let i = 0; i <= POLL_NUDGE_THRESHOLD; i++) {
|
|
47
|
+
expect(pacer.record(`tok:t1:task-${i}`)).toBeNull();
|
|
48
|
+
advance(500);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test("身份查询用更宽的阈值(p50 约 2.3 次/分钟是设计频率,不该被提示打扰)", () => {
|
|
53
|
+
const { pacer } = pacerWithClock();
|
|
54
|
+
// 同一个 60 秒窗口内:task_poll 第 5 次就提示,identity_poll 要到第 9 次
|
|
55
|
+
for (let i = 1; i <= 8; i++) expect(pacer.record("whoami:x", "identity_poll")).toBeNull();
|
|
56
|
+
const pacing = pacer.record("whoami:x", "identity_poll");
|
|
57
|
+
expect(pacing).not.toBeNull();
|
|
58
|
+
expect(pacing!.calls_last_60s).toBe(9);
|
|
59
|
+
expect(pacing!.note).toContain("org_whoami");
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("提示文案必须说明「结果会自动 chain」——否则 agent 仍会紧盯", () => {
|
|
63
|
+
expect(POLL_PACING_NOTE).toContain("60 秒");
|
|
64
|
+
expect(POLL_PACING_NOTE).toContain("chain 回上游");
|
|
65
|
+
expect(POLL_PACING_NOTE).toContain("一整轮 LLM");
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test("key 数量有上限(调用方是外部输入,不能当它只查自己的任务)", () => {
|
|
69
|
+
const pacer = createPollPacer({ maxKeys: 10, windowMs: 1, now: () => 1_000_000 });
|
|
70
|
+
for (let i = 0; i < 500; i++) pacer.record(`tok:t1:task-${i}`);
|
|
71
|
+
// 窗口 1ms,每次 record 时旧条目都已过期,应被回收
|
|
72
|
+
expect(pacer.size()).toBeLessThanOrEqual(11);
|
|
73
|
+
});
|
|
74
|
+
});
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #3001 —— get_task 的轮询节奏提示(Hub 侧)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么放在 Hub 而不是只改 agent-node 的提示词:
|
|
5
|
+
* 提示词在 `agent-node/src/cli.ts` 里,改完要发 agent-node + CLI 配对版本,
|
|
6
|
+
* 而且**只有升级过的节点才会变**。而 `get_task` 是 Hub 提供的 MCP 工具 ——
|
|
7
|
+
* 在响应里加一句话,所有节点下一次调用就能看到,不需要任何客户端升级。
|
|
8
|
+
*
|
|
9
|
+
* 现场(TMW微软欧,2026-10-29 16:00Z → 10-30 01:00Z):
|
|
10
|
+
*
|
|
11
|
+
* 每小时 get_task:256 / 565 / 647 / 703 / 770 / 855 / 893 / 972 / 736
|
|
12
|
+
* ⇒ 约 13 次/分钟、连续 8 小时、合计约 6000 次
|
|
13
|
+
*
|
|
14
|
+
* 每次 `get_task` 都是一整轮 LLM 调用。这 6000 次没有推进任何工作,
|
|
15
|
+
* 只是在问「好没好」。而子任务的最终结果本来就会通过 parent_task_id 自动 chain 回上游。
|
|
16
|
+
*
|
|
17
|
+
* 设计取舍:
|
|
18
|
+
* · **不返回错误、不改状态**,只在同一个响应里多一个 `pacing` 字段 ——
|
|
19
|
+
* 调用方即使完全忽略它也照常工作(信息不缺,行为不破)。
|
|
20
|
+
* · 阈值 4 次/60 秒:正常的「隔几分钟看一眼」永远碰不到;
|
|
21
|
+
* 只有真正在连环打的才会看到这句提示。
|
|
22
|
+
* · 计数按 (调用方, task_id) 分开,避免把「同时等多个子任务」误判成连环打。
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
export type PollPacing = {
|
|
26
|
+
calls_last_60s: number;
|
|
27
|
+
recommended_interval_seconds: number;
|
|
28
|
+
note: string;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export const WHOAMI_PACING_NOTE =
|
|
32
|
+
"org_whoami 只需要在「不确定自己是谁/团队变了」时查。实测有节点以约 4–6 次/分钟连续查询、" +
|
|
33
|
+
"同时窗口内没接到任何任务 —— 这些调用没有推进工作。建议隔 60 秒以上再看。";
|
|
34
|
+
|
|
35
|
+
export const POLL_PACING_NOTE =
|
|
36
|
+
"每次 get_task 都是一整轮 LLM 调用。子任务的最终结果会通过 parent_task_id 自动 chain 回上游," +
|
|
37
|
+
"所以不必连续轮询 —— 建议隔 60 秒以上再看。";
|
|
38
|
+
|
|
39
|
+
export const POLL_WINDOW_MS = 60_000;
|
|
40
|
+
export const POLL_NUDGE_THRESHOLD = 4;
|
|
41
|
+
export const POLL_RECOMMENDED_SECONDS = 60;
|
|
42
|
+
|
|
43
|
+
/** 两类轮询的阈值与文案。分开是因为「正常频率」差一个数量级。 */
|
|
44
|
+
export const PACE_KINDS = {
|
|
45
|
+
/** 等子任务:正常是「隔几分钟看一眼」,1 分钟内 4 次以上基本就是连环打。 */
|
|
46
|
+
task_poll: { threshold: POLL_NUDGE_THRESHOLD, note: POLL_PACING_NOTE },
|
|
47
|
+
/** 身份查询:p50 约 2.3 次/分钟是设计频率,1 分钟内 8 次以上才提示。 */
|
|
48
|
+
identity_poll: { threshold: 8, note: WHOAMI_PACING_NOTE },
|
|
49
|
+
} as const;
|
|
50
|
+
|
|
51
|
+
export type PaceKind = keyof typeof PACE_KINDS;
|
|
52
|
+
|
|
53
|
+
export type PollPacer = {
|
|
54
|
+
/** 记一次调用;超过阈值时返回提示,否则返回 null。 */
|
|
55
|
+
record(key: string, kind?: PaceKind): PollPacing | null;
|
|
56
|
+
/** 仅测试用:当前记录的 key 数。 */
|
|
57
|
+
size(): number;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export function createPollPacer(opts: {
|
|
61
|
+
windowMs?: number;
|
|
62
|
+
threshold?: number;
|
|
63
|
+
maxKeys?: number;
|
|
64
|
+
now?: () => number;
|
|
65
|
+
} = {}): PollPacer {
|
|
66
|
+
const windowMs = opts.windowMs ?? POLL_WINDOW_MS;
|
|
67
|
+
const defaultThreshold = opts.threshold ?? POLL_NUDGE_THRESHOLD;
|
|
68
|
+
const maxKeys = opts.maxKeys ?? 2000;
|
|
69
|
+
const now = opts.now ?? Date.now;
|
|
70
|
+
const seen = new Map<string, number[]>();
|
|
71
|
+
|
|
72
|
+
function prune(ts: number[], cutoff: number): number[] {
|
|
73
|
+
// 时间戳按升序追加,从头部删到窗口内为止。
|
|
74
|
+
let i = 0;
|
|
75
|
+
while (i < ts.length && ts[i] <= cutoff) i++;
|
|
76
|
+
return i === 0 ? ts : ts.slice(i);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
record(key: string, kind: PaceKind = "task_poll"): PollPacing | null {
|
|
81
|
+
// 显式传了 threshold(测试用)就压过 kind 表
|
|
82
|
+
const spec = opts.threshold !== undefined
|
|
83
|
+
? { threshold: defaultThreshold, note: PACE_KINDS[kind].note }
|
|
84
|
+
: PACE_KINDS[kind];
|
|
85
|
+
const t = now();
|
|
86
|
+
const cutoff = t - windowMs;
|
|
87
|
+
const prev = seen.get(key);
|
|
88
|
+
const ts = prune(prev ?? [], cutoff);
|
|
89
|
+
ts.push(t);
|
|
90
|
+
seen.set(key, ts);
|
|
91
|
+
|
|
92
|
+
// 无上限的 Map 就是一条内存泄漏 —— 调用方是外部输入,不能假设它只查自己的任务。
|
|
93
|
+
if (seen.size > maxKeys) {
|
|
94
|
+
for (const k of seen.keys()) {
|
|
95
|
+
if (seen.size <= maxKeys) break;
|
|
96
|
+
const keep = prune(seen.get(k) ?? [], cutoff);
|
|
97
|
+
if (keep.length === 0) seen.delete(k);
|
|
98
|
+
else seen.set(k, keep);
|
|
99
|
+
}
|
|
100
|
+
// 光靠过期回收不够:如果所有 key 都在窗口内(例如有人用几百个 task_id 乱打),
|
|
101
|
+
// 过期一条也删不掉,长度仍然无界 —— 这里再按插入顺序硬砍到上限。
|
|
102
|
+
while (seen.size > maxKeys) {
|
|
103
|
+
const oldest = seen.keys().next();
|
|
104
|
+
if (oldest.done) break;
|
|
105
|
+
seen.delete(oldest.value);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (ts.length <= spec.threshold) return null;
|
|
110
|
+
return {
|
|
111
|
+
calls_last_60s: ts.length,
|
|
112
|
+
recommended_interval_seconds: POLL_RECOMMENDED_SECONDS,
|
|
113
|
+
note: spec.note,
|
|
114
|
+
};
|
|
115
|
+
},
|
|
116
|
+
size(): number {
|
|
117
|
+
return seen.size;
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** 进程级单例:Hub 只需要看「最近一分钟这位调用方问了多少次」。 */
|
|
123
|
+
export const pollPacer = createPollPacer();
|
package/src/server.ts
CHANGED
|
@@ -3193,6 +3193,87 @@ return Bun.serve({
|
|
|
3193
3193
|
}));
|
|
3194
3194
|
}
|
|
3195
3195
|
|
|
3196
|
+
// ── #2719 —— 凭据台账:哪把钥匙、绑没绑、最后一次用是什么时候、用它调过什么 ──
|
|
3197
|
+
//
|
|
3198
|
+
// 为什么不能只用 node-permission-report:那张报表是**按流量**聚合的,
|
|
3199
|
+
// 只列出「近 N 天有调用」的身份。生产实测 760 个未吊销令牌里有 381 个是
|
|
3200
|
+
// `node:` 开头但没绑定节点的,而其中只有 4 个在近 24h 出现过。
|
|
3201
|
+
// 剩下 377 个**在任何报表里都不存在** —— 于是「这把钥匙还有人在用吗」
|
|
3202
|
+
// 这个问题永远答不清,也就永远不敢吊销。
|
|
3203
|
+
//
|
|
3204
|
+
// 这里只读、只列元信息(不返回 token 值,Hub 本来也只存 hash),
|
|
3205
|
+
// 且要求「人的令牌 + 网络 owner/admin」—— 节点不能枚举网络的钥匙。
|
|
3206
|
+
const ledgerMatch = url.pathname.match(/^\/api\/networks\/([^/]+)\/token-ledger$/);
|
|
3207
|
+
if (ledgerMatch && req.method === "GET") {
|
|
3208
|
+
if (!restAuth) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
|
|
3209
|
+
if (restAuth.networkId) return userTokenRequired(req);
|
|
3210
|
+
const networkId = decodeURIComponent(ledgerMatch[1]);
|
|
3211
|
+
const role = getUserNetworkRole(restAuth.userId, networkId);
|
|
3212
|
+
if (!isAdmin && role !== "owner" && role !== "admin") {
|
|
3213
|
+
return withCors(req, Response.json({ ok: false, error: "permission_denied", message: "network owner/admin only" }, { status: 403 }));
|
|
3214
|
+
}
|
|
3215
|
+
const limit = Math.min(Math.max(Number(url.searchParams.get("limit") ?? 200) || 200, 1), 1000);
|
|
3216
|
+
const rows = db.all<{ token_id: string; name: string | null; bound_node_id: string | null; scope: string | null; created_at: string | null; last_used_at: string | null }>(
|
|
3217
|
+
`SELECT token_id, name, bound_node_id, scope, created_at, last_used_at
|
|
3218
|
+
FROM api_tokens
|
|
3219
|
+
WHERE network_id = ?1 AND revoked_at IS NULL
|
|
3220
|
+
ORDER BY name, created_at DESC LIMIT ?2`,
|
|
3221
|
+
networkId, limit,
|
|
3222
|
+
);
|
|
3223
|
+
// 近 24h 的调用面(按账本键 `token:<id>`)。没有这一列,台账只是一份名单;
|
|
3224
|
+
// 有了它才能回答「这条要不要吊销」。
|
|
3225
|
+
const sinceHour = new Date(Date.now() - 86_400_000).toISOString().slice(0, 13);
|
|
3226
|
+
const calls = db.all<{ node_id: string; tool: string; hits: number | string }>(
|
|
3227
|
+
`SELECT node_id, tool, SUM(hits) AS hits FROM node_tool_calls
|
|
3228
|
+
WHERE network_id = ?1 AND hour >= ?2 AND node_id LIKE 'token:%'
|
|
3229
|
+
GROUP BY node_id, tool ORDER BY SUM(hits) DESC`,
|
|
3230
|
+
networkId, sinceHour,
|
|
3231
|
+
);
|
|
3232
|
+
const byToken = new Map<string, Array<{ tool: string; hits: number }>>();
|
|
3233
|
+
for (const c of calls) {
|
|
3234
|
+
const id = c.node_id.slice(6);
|
|
3235
|
+
const list = byToken.get(id) ?? [];
|
|
3236
|
+
list.push({ tool: c.tool, hits: Number(c.hits) });
|
|
3237
|
+
byToken.set(id, list);
|
|
3238
|
+
}
|
|
3239
|
+
const tokens = rows.map((r) => {
|
|
3240
|
+
const tools = byToken.get(r.token_id) ?? [];
|
|
3241
|
+
const writes = tools.filter((t) => t.tool.startsWith("mcp:send_") || t.tool.startsWith("mcp:requirements_")
|
|
3242
|
+
|| t.tool.startsWith("mcp:projects_") || ["POST", "PUT", "PATCH", "DELETE"].includes(t.tool.split(" ")[0]))
|
|
3243
|
+
.reduce((n, t) => n + t.hits, 0);
|
|
3244
|
+
return {
|
|
3245
|
+
token_id: r.token_id,
|
|
3246
|
+
name: r.name,
|
|
3247
|
+
scope: r.scope,
|
|
3248
|
+
bound_node_id: r.bound_node_id,
|
|
3249
|
+
// 名字说自己是节点、却没有绑定 ⇒ 三张白名单都管不到它(nodeIdentity 会退化成 token: 键)
|
|
3250
|
+
looks_like_node: !!r.name && r.name.startsWith("node:"),
|
|
3251
|
+
unbound_node: !!r.name && r.name.startsWith("node:") && !r.bound_node_id,
|
|
3252
|
+
created_at: r.created_at,
|
|
3253
|
+
last_used_at: r.last_used_at,
|
|
3254
|
+
calls_24h: tools.reduce((n, t) => n + t.hits, 0),
|
|
3255
|
+
writes_24h: writes,
|
|
3256
|
+
top_tools: tools.slice(0, 3),
|
|
3257
|
+
};
|
|
3258
|
+
});
|
|
3259
|
+
const unbound = tokens.filter((t) => t.unbound_node);
|
|
3260
|
+
return withCors(req, Response.json({
|
|
3261
|
+
ok: true,
|
|
3262
|
+
network_id: networkId,
|
|
3263
|
+
since: new Date(Date.now() - 86_400_000).toISOString(),
|
|
3264
|
+
limit,
|
|
3265
|
+
summary: {
|
|
3266
|
+
total: tokens.length,
|
|
3267
|
+
bound: tokens.filter((t) => !!t.bound_node_id).length,
|
|
3268
|
+
unbound_node: unbound.length,
|
|
3269
|
+
// 「名义上还在、实际上没人用」的数量:这才是能不能吊销的判据
|
|
3270
|
+
unused_24h: tokens.filter((t) => t.calls_24h === 0).length,
|
|
3271
|
+
unbound_node_in_use: unbound.filter((t) => t.calls_24h > 0).length,
|
|
3272
|
+
},
|
|
3273
|
+
tokens,
|
|
3274
|
+
}));
|
|
3275
|
+
}
|
|
3276
|
+
|
|
3196
3277
|
// ── #1473 (#909): read-only Hub catalogs for the desktop client ──
|
|
3197
3278
|
//
|
|
3198
3279
|
// Skills / network secrets / Providers have existed on this Hub only as
|
|
@@ -150,3 +150,40 @@ test("nonterminal legacy reply retains its established behavior", async () => {
|
|
|
150
150
|
expect(db.get("SELECT status,result FROM tasks WHERE task_id=?1", openId)).toEqual({ status: "replied", result: "ordinary final" });
|
|
151
151
|
expect(db.get("SELECT COUNT(*) AS n FROM task_late_replies WHERE task_id=?1", openId).n).toBe(0);
|
|
152
152
|
});
|
|
153
|
+
|
|
154
|
+
// #3061 —— 任务**从未记下 turn 上下文**时,迟到结果也必须能收。
|
|
155
|
+
//
|
|
156
|
+
// 现场(2026-10-30 生产实测):
|
|
157
|
+
// 「仍在 TUI 会话里运行,等待回复已达 30 分钟上限」的失败任务 289 条,
|
|
158
|
+
// 其中 thread_id/turn_id 非空的 **0 条**;「任务未提交」781 条里只有 1 条有。
|
|
159
|
+
// ⇒ 这类任务的迟到结果永远匹配不上上下文,等于「活干完了但结果必定丢弃」。
|
|
160
|
+
// 全库 task_late_replies 只有 4 行,正是这条路走不通的证据。
|
|
161
|
+
test("既有任务没有 turn 上下文时,迟到结果仍可落账并投递给发送方", async () => {
|
|
162
|
+
const contextlessId = "task_late710_noctx";
|
|
163
|
+
db.run(`INSERT INTO tasks
|
|
164
|
+
(task_id,from_name,to_name,to_node_id,status,content,result,network_id,thread_id,turn_id,completed_at)
|
|
165
|
+
VALUES(?1,?2,'late710-worker',?3,'failed','never started a turn','共享会话忙,30 分钟内未提交',?4,NULL,NULL,datetime('now'))`,
|
|
166
|
+
[contextlessId, owner.user.username, workerId, owner.network_id]);
|
|
167
|
+
|
|
168
|
+
const accepted = await mcp(workerToken, "send_reply", {
|
|
169
|
+
in_reply_to: contextlessId,
|
|
170
|
+
text: "结果其实跑完了",
|
|
171
|
+
status: "replied",
|
|
172
|
+
thread_id: "thread_from_runtime_any",
|
|
173
|
+
turn_id: "turn_from_runtime_any",
|
|
174
|
+
});
|
|
175
|
+
expect(accepted).toMatchObject({ ok: true, late: true, duplicate: false });
|
|
176
|
+
// 任务行不被改写
|
|
177
|
+
expect(db.get("SELECT status,result FROM tasks WHERE task_id=?1", contextlessId))
|
|
178
|
+
.toEqual({ status: "failed", result: "共享会话忙,30 分钟内未提交" });
|
|
179
|
+
// 落进 append-only 账,并带上运行时给的上下文
|
|
180
|
+
const row = db.get("SELECT thread_id,turn_id,status,result FROM task_late_replies WHERE task_id=?1", contextlessId);
|
|
181
|
+
expect(row).toMatchObject({ thread_id: "thread_from_runtime_any", turn_id: "turn_from_runtime_any", status: "replied", result: "结果其实跑完了" });
|
|
182
|
+
// 发送方能在 inbox 里看到它(否则「活干完了没人知道」)
|
|
183
|
+
const inbox = await mcp(owner.token, "get_inbox", { alias: owner.user.username, limit: 100 });
|
|
184
|
+
expect(inbox.messages).toContainEqual(expect.objectContaining({ id: accepted.message_id, late: true, content: "结果其实跑完了" }));
|
|
185
|
+
// 不是这个任务的负责人,仍然拒(放宽只针对上下文,不放宽归属)
|
|
186
|
+
expect(await mcp(siblingToken, "send_reply", {
|
|
187
|
+
in_reply_to: contextlessId, text: "impostor", thread_id: "t", turn_id: "u",
|
|
188
|
+
})).toMatchObject({ ok: false, error: "late_reply_task_not_owned" });
|
|
189
|
+
});
|
package/src/tools.ts
CHANGED
|
@@ -109,6 +109,7 @@ import { dispatchQueueInfo, queueDepthByNode, queueDepthKey } from "./task-queue
|
|
|
109
109
|
import { parseHubTimestamp } from "./hub-timestamp";
|
|
110
110
|
import { noteTerminalResultRead, purgeLogsResultNow, sweepNodeRequestContent } from "./node-request-retention.js";
|
|
111
111
|
import { listTaskLateReplies } from "./task-late-replies.js";
|
|
112
|
+
import { pollPacer } from "./poll-pacing.js";
|
|
112
113
|
import { auditDepartment, createDepartment, deleteDepartment, listDepartments, setAgentDepartment, updateDepartment } from "./departments.js";
|
|
113
114
|
|
|
114
115
|
function ts(): string {
|
|
@@ -136,6 +137,21 @@ function lateReplyContextMatches(
|
|
|
136
137
|
threadId: string,
|
|
137
138
|
turnId: string,
|
|
138
139
|
): boolean {
|
|
140
|
+
// #3061 —— 任务**从未记下 turn 上下文**时,不能用「上下文不符」把它挡回去。
|
|
141
|
+
//
|
|
142
|
+
// 现场(2026-10-30 生产实测):
|
|
143
|
+
// 「仍在 TUI 会话里运行,等待回复已达 30 分钟上限」的失败任务 289 条,
|
|
144
|
+
// 其中 thread_id/turn_id **非空的 0 条**;「任务未提交」781 条里只有 1 条有。
|
|
145
|
+
// ⇒ 这类任务的迟到结果永远匹配不上,等于**工作做完了但结果必定丢弃**。
|
|
146
|
+
// 全库 task_late_replies 只有 4 行,正是这条路走不通的证据。
|
|
147
|
+
//
|
|
148
|
+
// 放宽的边界(三条同时满足才放行):
|
|
149
|
+
// · 存的两个 id 都是 null(不是「存了 A 却来了 B」——那种仍然拒)
|
|
150
|
+
// · 任务已经是终态(调用点在别处已判)
|
|
151
|
+
// · 令牌就是该任务的负责人(late_reply_task_not_owned 的检查在调用点,未改动)
|
|
152
|
+
// 在这种情况下,迟到结果只会写进 append-only 的 task_late_replies,并投递给原发送方;
|
|
153
|
+
// 不改写任务行、不跑父任务回链,所以不会把已完成的任务「再改一遍」。
|
|
154
|
+
if (storedThreadId === null && storedTurnId === null) return true;
|
|
139
155
|
return storedThreadId === threadId && storedTurnId === turnId;
|
|
140
156
|
}
|
|
141
157
|
|
|
@@ -2996,10 +3012,17 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
2996
3012
|
if (task) {
|
|
2997
3013
|
task.late_replies = listTaskLateReplies(db, task_id, typeof task.network_id === "string" ? task.network_id : null);
|
|
2998
3014
|
}
|
|
3015
|
+
// #3001 —— 轮询节奏提示。只多一个字段,不改状态、不返回错误:
|
|
3016
|
+
// 调用方忽略它照常工作;连着打的才会看到这句话。
|
|
3017
|
+
// 放在 Hub 侧而不是只改 agent-node,是因为 get_task 由 Hub 提供 ——
|
|
3018
|
+
// 发版即对所有节点生效,不必等客户端升级。
|
|
3019
|
+
const pacing = pollPacer.record(`${callerTokenId ?? callerAlias ?? "anon"}:${task_id}`);
|
|
2999
3020
|
return {
|
|
3000
3021
|
content: [{
|
|
3001
3022
|
type: "text" as const,
|
|
3002
|
-
text: JSON.stringify(task
|
|
3023
|
+
text: JSON.stringify(task
|
|
3024
|
+
? { ok: true, task, ...(pacing ? { pacing } : {}) }
|
|
3025
|
+
: { ok: false, error: "task not found", ...(pacing ? { pacing } : {}) }),
|
|
3003
3026
|
}],
|
|
3004
3027
|
};
|
|
3005
3028
|
}
|
|
@@ -7088,7 +7111,21 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
7088
7111
|
|
|
7089
7112
|
// #765: exact authenticated node; team tree is independent of human departments.
|
|
7090
7113
|
server.tool("org_whoami", "Your Agent team, ancestors, lead, owner and up to 50 teammates. Read-only.", {},
|
|
7091
|
-
async () =>
|
|
7114
|
+
async () => {
|
|
7115
|
+
const res = scheduleCall(id => agentTeamWhoami(id.networkId, id.nodeId));
|
|
7116
|
+
// #3001 续 —— 全舰队 6 小时 52522 次工具调用里,org_whoami 占 21900(42%),
|
|
7117
|
+
// 而其中十来个节点在同期收到 0 个任务(实测 1420–2190 次/6h)。
|
|
7118
|
+
// 这些调用与 get_task 那一类一样:每次都跑完一轮 LLM,却没有推进任何工作。
|
|
7119
|
+
// 阈值比 get_task 宽(8 次/60 秒)—— p50 约 2.3 次/分钟是设计频率,不该被提示打扰。
|
|
7120
|
+
const pacing = pollPacer.record(`whoami:${callerTokenId ?? callerAlias ?? "anon"}`, "identity_poll");
|
|
7121
|
+
if (!pacing) return res;
|
|
7122
|
+
try {
|
|
7123
|
+
const body = JSON.parse(res.content[0].text);
|
|
7124
|
+
return { content: [{ type: "text" as const, text: JSON.stringify({ ...body, pacing }) }] };
|
|
7125
|
+
} catch {
|
|
7126
|
+
return res; // 解析失败就原样返回:提示绝不该让一个只读工具失败
|
|
7127
|
+
}
|
|
7128
|
+
});
|
|
7092
7129
|
|
|
7093
7130
|
// #478:tools/list 只列这个调用者真能用的工具(tool-audience.ts)。只滤列表,tools/call 不变。
|
|
7094
7131
|
const caller: ToolCaller = callerTokenIsNetwork
|