@sleep2agi/commhub-server 0.9.0-preview.281 → 0.9.0-preview.282

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.
Files changed (35) hide show
  1. package/build-info.json +2 -2
  2. package/package.json +1 -1
  3. package/src/api-host-supervisors-source-capabilities.test.ts +107 -0
  4. package/src/auth_login_guard.test.ts +15 -0
  5. package/src/auth_login_guard.ts +20 -1
  6. package/src/board-grants.test.ts +134 -0
  7. package/src/broadcast-attribution.test.ts +93 -0
  8. package/src/build-commit-report-http.test.ts +10 -0
  9. package/src/clone-node-adopted-db.test.ts +78 -0
  10. package/src/clone-node.ts +5 -1
  11. package/src/create-node.ts +17 -0
  12. package/src/department-heads.ts +3 -0
  13. package/src/expiry-counters.test.ts +50 -1
  14. package/src/expiry-counters.ts +31 -9
  15. package/src/mcp-write-network-resolution.test.ts +36 -0
  16. package/src/node-config-last-update.test.ts +103 -1
  17. package/src/node-config-last-update.ts +70 -5
  18. package/src/node-daemon-bindings.ts +9 -0
  19. package/src/node-grants-http.test.ts +239 -0
  20. package/src/node-grants.ts +234 -0
  21. package/src/node-inbox-allowlist-http.test.ts +35 -0
  22. package/src/node-permissions.ts +37 -2
  23. package/src/opencode-v2-catalog.test.ts +22 -1
  24. package/src/opencode-v2-catalog.ts +36 -3
  25. package/src/peer-allowlist.test.ts +29 -0
  26. package/src/registration-switch-http.test.ts +60 -0
  27. package/src/reply-bare-infer-4315.test.ts +86 -0
  28. package/src/requirements.ts +29 -4
  29. package/src/schedule-agent.ts +45 -10
  30. package/src/scheduled-tasks-http.test.ts +25 -0
  31. package/src/scheduled-tasks.ts +46 -2
  32. package/src/server.ts +111 -6
  33. package/src/steer-send-message.test.ts +121 -0
  34. package/src/task-access.ts +21 -1
  35. package/src/tools.ts +76 -18
@@ -0,0 +1,121 @@
1
+ // #4685 —— send_message 的 steer 参数(与 control:"interrupt" 并列):
2
+ // 1. steer 与 control 互斥(两个都给 → steer_conflicts_with_control);
3
+ // 2. steer:true 落库 meta_json={"delivery":"steer"},type 仍为 message(不新增 type,不惊动唤醒分叉);
4
+ // 3. 响应带 delivery:"steer";不传 steer 时 meta_json 为 null(回归)。
5
+ import { afterAll, beforeEach, afterEach, describe, expect, test } from "bun:test";
6
+ import { db } from "./db.js";
7
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
8
+ import { registerTools } from "./tools.js";
9
+ import { __resetSSEClientsForTest, createSSEStream } from "./push.js";
10
+
11
+ const NET = "steer-test-net", OWNER = "steer-owner", RECV = "steer-recv";
12
+ type ToolHandler = (args: any) => Promise<{ content: Array<{ type: "text"; text: string }> }>;
13
+
14
+ function cleanup() {
15
+ for (const t of ["inbox", "tasks", "task_events"]) { try { db.run(`DELETE FROM ${t} WHERE network_id = ?1`, [NET]); } catch {} }
16
+ try { db.run("DELETE FROM sessions WHERE network_id = ?1", [NET]); } catch {}
17
+ try { db.run("DELETE FROM nodes WHERE network_id = ?1", [NET]); } catch {}
18
+ try { db.run("DELETE FROM network_members WHERE network_id = ?1", [NET]); } catch {}
19
+ try { db.run("DELETE FROM networks WHERE network_id = ?1", [NET]); } catch {}
20
+ try { db.run("DELETE FROM users WHERE user_id = ?1", [OWNER]); } catch {}
21
+ }
22
+ function seed() {
23
+ db.run(`INSERT INTO users (user_id, username, password_hash, role, created_at) VALUES (?1, ?1, 'x', 'user', datetime('now'))`, [OWNER]);
24
+ db.run(`INSERT INTO networks (network_id, network_name, owner_id, created_at) VALUES (?1, ?1, ?2, datetime('now'))`, [NET, OWNER]);
25
+ db.run(`INSERT INTO network_members (user_id, network_id, role, joined_at) VALUES (?1, ?2, 'owner', datetime('now'))`, [OWNER, NET]);
26
+ db.run(`INSERT INTO nodes (node_id, node_name, alias, network_id, hostname, created_at, updated_at, lifecycle_state) VALUES (?1, ?2, ?2, ?3, 'host', datetime('now'), datetime('now'), 'active')`, [`node_${RECV}`, RECV, NET]);
27
+ db.run(`INSERT INTO sessions (resume_id, alias, status, node_id, network_id, updated_at, last_seen_at) VALUES (?1, ?2, 'idle', ?3, ?4, datetime('now'), datetime('now'))`, [`res_${RECV}`, RECV, `node_${RECV}`, NET]);
28
+ }
29
+
30
+ beforeEach(() => { cleanup(); seed(); });
31
+ afterEach(() => { __resetSSEClientsForTest(); });
32
+ afterAll(cleanup);
33
+
34
+ function buildHandlers(alias: string): Record<string, ToolHandler> {
35
+ const server = new McpServer({ name: "test", version: "0" }) as any;
36
+ const tools: Record<string, ToolHandler> = {};
37
+ const origTool = server.tool.bind(server);
38
+ server.tool = (name: string, _desc: string, schema: any, handler: ToolHandler) => {
39
+ tools[name] = handler;
40
+ return origTool(name, _desc, schema, handler);
41
+ };
42
+ registerTools(server, undefined, NET, OWNER, alias, true, null);
43
+ return tools;
44
+ }
45
+ async function call(handler: ToolHandler, args: any): Promise<Record<string, any>> {
46
+ const r = await handler(args);
47
+ return JSON.parse(r.content[0].text);
48
+ }
49
+
50
+ async function readFrame(reader: ReadableStreamDefaultReader<Uint8Array>, timeoutMs = 2_000): Promise<Record<string, any>> {
51
+ const decoder = new TextDecoder();
52
+ let buf = "";
53
+ const deadline = Date.now() + timeoutMs;
54
+ while (Date.now() < deadline) {
55
+ const result = await Promise.race([
56
+ reader.read(),
57
+ new Promise<never>((_, rej) => setTimeout(() => rej(new Error(`no SSE frame within ${timeoutMs}ms`)), deadline - Date.now())),
58
+ ]);
59
+ if (result.done) throw new Error("SSE stream ended unexpectedly");
60
+ buf += decoder.decode(result.value, { stream: true });
61
+ const sep = buf.indexOf("\n\n");
62
+ if (sep === -1) continue;
63
+ const dataLine = buf.slice(0, sep).split("\n").find((l) => l.startsWith("data: "));
64
+ if (!dataLine) continue;
65
+ return JSON.parse(dataLine.slice(6));
66
+ }
67
+ throw new Error(`no SSE frame within ${timeoutMs}ms`);
68
+ }
69
+
70
+ describe("#4685 send_message steer", () => {
71
+ test("steer 与 control 互斥 → steer_conflicts_with_control", async () => {
72
+ const tools = buildHandlers(OWNER);
73
+ const r = await call(tools.send_message, { alias: RECV, message: "x", control: "interrupt", steer: true, network_id: NET });
74
+ expect(r.ok).toBe(false);
75
+ expect(r.error).toBe("steer_conflicts_with_control");
76
+ });
77
+
78
+ test("steer:true 落库 meta_json={\"delivery\":\"steer\"},响应带 delivery", async () => {
79
+ const tools = buildHandlers(OWNER);
80
+ const r = await call(tools.send_message, { alias: RECV, message: "请改口", steer: true, network_id: NET });
81
+ expect(r.ok).toBe(true);
82
+ expect(r.delivery).toBe("steer");
83
+ expect(r.accepted).toBe(true);
84
+ const row = db.get<{ type: string; meta_json: string | null }>("SELECT type, meta_json FROM inbox WHERE network_id = ?1", NET);
85
+ expect(row!.type).toBe("message");
86
+ expect(JSON.parse(row!.meta_json!)).toEqual({ delivery: "steer" });
87
+ });
88
+
89
+ test("不传 steer → meta_json 为 null(回归)", async () => {
90
+ const tools = buildHandlers(OWNER);
91
+ const r = await call(tools.send_message, { alias: RECV, message: "普通", network_id: NET });
92
+ expect(r.ok).toBe(true);
93
+ expect(r.delivery).toBeUndefined();
94
+ const row = db.get<{ meta_json: string | null }>("SELECT meta_json FROM inbox WHERE network_id = ?1", NET);
95
+ expect(row!.meta_json).toBeNull();
96
+ });
97
+
98
+ // #4685 —— control:"interrupt" 必须让 SSE new_message 事件带上 control 字段:
99
+ // 节点侧(cli.ts copresence 分支)靠 ev.control 决定是否唤醒工作通道去捞 type=control 的 inbox 行。
100
+ // 这里不写,control 行会卡在「信息/工作」两条 lane 之间,节点永远不取 → 真机「停止」不生效。
101
+ test("control:interrupt 落库 type=control,且 SSE new_message 带 control 字段", async () => {
102
+ const reader = createSSEStream(RECV, NET).body!.getReader();
103
+ await readFrame(reader); // swallow connected
104
+
105
+ const tools = buildHandlers(OWNER);
106
+ const r = await call(tools.send_message, { alias: RECV, message: "x", control: "interrupt", network_id: NET });
107
+ expect(r.ok).toBe(true);
108
+ expect(r.control).toBe("interrupt");
109
+ expect(r.accepted).toBe(true);
110
+
111
+ const row = db.get<{ type: string; content: string; priority: string }>(
112
+ "SELECT type, content, priority FROM inbox WHERE network_id = ?1", NET);
113
+ expect(row!.type).toBe("control");
114
+ expect(JSON.parse(row!.content)).toEqual({ op: "interrupt" });
115
+ expect(row!.priority).toBe("high");
116
+
117
+ const evt = await readFrame(reader);
118
+ expect(evt.type).toBe("new_message");
119
+ expect(evt.control).toBe("interrupt");
120
+ });
121
+ });
@@ -138,7 +138,15 @@ function headOf(userId: string, row: CardRow): boolean {
138
138
  * only=false(正常模式、执行开关打开)—— 主人能改的能改,另外「派给这个节点的」在主人看得见时也能改;
139
139
  * only=true (受限模式)—— 只看、只改派给这个节点的卡(负责 Agent / 参与人 / 它建的,及这些卡的子任务)。
140
140
  */
141
- export type TaskCaller = { userId: string; node?: { id: string; only: boolean } } | null;
141
+ export type TaskCaller = {
142
+ userId: string;
143
+ node?: { id: string; only: boolean };
144
+ /**
145
+ * 节点管理授权(第二期 board)带来的**额外**可见范围。
146
+ * 有它才拼额外的析取项;没有它,SQL 必须逐字节不变(测试钉住这一点)。
147
+ */
148
+ board?: { network: boolean; users: ReadonlySet<string>; nodes: ReadonlySet<string> };
149
+ } | null;
142
150
 
143
151
  export const nodeRefPattern = (nodeId: string) => `%${likeEscape(`"kind":"node","id":"${nodeId}"`)}%`;
144
152
  const nodeRefIs = (json: string | null | undefined, nodeId: string) => !!json && json.includes(`"kind":"node","id":"${nodeId}"`);
@@ -315,6 +323,18 @@ function addTaskVisibilityScopeAsUser(sql: string, params: unknown[], caller: Ta
315
323
  const ph = (ids: string[]) => ids.map((id) => `?${params.push(id)}`).join(", ");
316
324
  const all = scoped.map((s) => s.networkId);
317
325
  const parts = [`network_id NOT IN (${ph(all)})`];
326
+ // #board —— 节点管理授权(第二期):**只加析取项**,且只在 caller 带 board 时才动 SQL。
327
+ // 没有授权(人 / 普通节点)时这里一行都不执行 ⇒ SQL 逐字节不变。
328
+ if (caller.board) {
329
+ if (caller.board.network) {
330
+ parts.push("1 = 1"); // network 范围:放开这个节点能看的卡(不拼巨大 IN 列表)
331
+ } else {
332
+ const extra: string[] = [];
333
+ if (caller.board.users.size) extra.push(`owner_json IN (${ph([...caller.board.users].map((id) => JSON.stringify({ kind: "user", id })))})`);
334
+ if (caller.board.nodes.size) extra.push(`agent_owner_json IN (${ph([...caller.board.nodes].map((id) => JSON.stringify({ kind: "node", id })))})`);
335
+ if (extra.length) parts.push(`(${extra.join(" OR ")})`);
336
+ }
337
+ }
318
338
  if (members.length) {
319
339
  const pat = params.push(userRefPattern(caller.userId));
320
340
  const mine = `owner_json LIKE ?${pat} ESCAPE '\\' OR participants_json LIKE ?${pat} ESCAPE '\\' OR created_by_json LIKE ?${pat} ESCAPE '\\' OR (created_by_json IS NULL AND created_by = ?${uid})`;
package/src/tools.ts CHANGED
@@ -8,7 +8,7 @@ import { markTaskActivity } from "./task-activity.js";
8
8
  import { requestProviderSnapshot, requestProviderWrite, requestProviderCollection, requestProviderApplication, requestProviderLogin, getProviderSnapshot, pullProviderSnapshots, ackProviderSnapshot } from "./daemon-provider-snapshots.js";
9
9
  import { readHubProviders, putHubProvider, bindHubProvider } from './hub-provider-config.js';
10
10
  import { requestScopedSecrets, getScopedSecrets, pullScopedSecrets, ackScopedSecrets, requestNodeSecrets, pullNodeSecrets, ackNodeSecrets } from './scoped-secrets.js';
11
- import { requestAdopt, getAdopt, ackAdopt, unadopt, resolveManagedDaemon, activeBinding, createdDaemon } from "./node-daemon-bindings.js";
11
+ import { adoptedCloneSourceRow, requestAdopt, getAdopt, ackAdopt, unadopt, resolveManagedDaemon, activeBinding, createdDaemon } from "./node-daemon-bindings.js";
12
12
  import { runtimeReadinessSchema } from "./runtime-readiness.js";
13
13
  import { adoptionCandidatesReportSchema } from "./adoption-candidates.js";
14
14
  import { forkRecoveryRequestSchema, forkRecoveryResultSchema, publicForkResult } from "./codex-fork-contract.js";
@@ -1008,6 +1008,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1008
1008
  // (#3294 的 build_commit 就是同一个坑)。`.catch(undefined)` 与邻居一致:
1009
1009
  // 形状不对只丢这一格,绝不拒掉整份心跳。
1010
1010
  opencode_catalog_seen_at: z.string().max(40).optional().catch(undefined),
1011
+ // 每个模型的思考档位:`provider/model=none,low,high,max`(只有 id)。不写进 schema 会被静默剥掉。
1012
+ opencode_catalog_variants: z.array(z.string().max(600)).optional().catch(undefined),
1011
1013
  // #4150-Build —— 这台节点的 OpenCode V2 暴露的 agent 列表(`build`/`plan`…)。
1012
1014
  // 🔴 与上面 catalog 同一个陷阱:不写进这个 schema,daemon 报上来也**会被静默剥掉**,
1013
1015
  // `/api/nodes` 的投影读到的永远是 null。空数组合法 =「确实没有 agent」。
@@ -2119,7 +2121,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2119
2121
  ttl_seconds: z.number().min(1).max(86400).optional().describe("Task TTL in seconds (default: 3600)"),
2120
2122
  network_id: z.string().max(200).optional().describe("Network scope"),
2121
2123
  parent_task_id: z.string().max(200).optional().describe("Parent task this dispatch serves; the reply auto-chains to its originator."),
2122
- meta: z.any().optional().describe("Optional task metadata, e.g. { attachments: [{type,path,url,mime,name,size}] }."),
2124
+ meta: z.any().optional().describe("Optional task metadata (e.g. attachments)."),
2123
2125
  force: z.boolean().optional().describe("dispatch even if the target is degraded (user tokens only)"),
2124
2126
  },
2125
2127
  async ({ alias, task, priority, context, from_session: _fromIn, ttl_seconds, network_id: netId, parent_task_id: parentIn, meta, force }) => {
@@ -2464,14 +2466,19 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2464
2466
 
2465
2467
  server.tool(
2466
2468
  "send_message",
2467
- "Send a message to a session (no task lifecycle, just chat). Use for replies, status updates, or casual communication.",
2469
+ "Send a chat message (no task lifecycle). control=interrupt stops the running turn.",
2468
2470
  {
2469
2471
  alias: z.string().min(1).max(200).describe("Target session alias"),
2470
- message: z.string().min(1).max(10000).describe("Message content"),
2472
+ message: z.string().min(1).max(100_000).describe("Message"),
2473
+ control: z.enum(["interrupt"]).optional().describe("Interrupt turn"),
2474
+ steer: z.boolean().optional().describe("Inject into running turn"),
2471
2475
  from_session: z.string().max(200).optional(),
2472
- network_id: z.string().max(200).optional().describe("Network; auto-resolved for single-network user tokens"),
2476
+ network_id: z.string().max(200).optional().describe("Network (auto for single-network)"),
2473
2477
  },
2474
- async ({ alias, message, from_session: _fromIn, network_id: netId }) => { const fromMismatch = fromIdentityMismatchReply(_fromIn); if (fromMismatch) return fromMismatch; const from_session = defaultFrom(_fromIn);
2478
+ async ({ alias, message, control, steer, from_session: _fromIn, network_id: netId }) => { const fromMismatch = fromIdentityMismatchReply(_fromIn); if (fromMismatch) return fromMismatch; const from_session = defaultFrom(_fromIn);
2479
+ if (control !== undefined && steer !== undefined) {
2480
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "steer_conflicts_with_control", message: "control 与 steer 互斥:一次只能要一样" }) }] };
2481
+ }
2475
2482
  const effectiveNetId = getNetworkId(netId);
2476
2483
  { const sendDenied = agentSendDenied(effectiveNetId, alias, _fromIn, "write"); if (sendDenied) return sendDenied; }
2477
2484
  const canonical = resolveCanonicalAlias(effectiveNetId, alias);
@@ -2485,15 +2492,23 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2485
2492
  if (!lc.ok) return { content: [{ type: "text" as const, text: JSON.stringify(lc) }] };
2486
2493
  }
2487
2494
  console.log(`[${ts()}] ${from_session} → send_message → ${targetAlias}: ${message.slice(0, 60)}${canonical.renamed ? ` [renamed from ${alias}]` : ""}`);
2495
+ const isControl = control === "interrupt";
2496
+ const isSteer = steer === true;
2497
+ const meta = isSteer ? JSON.stringify({ delivery: "steer" }) : null;
2488
2498
  const id = uuidv4();
2489
2499
  db.run(
2490
- `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, network_id)
2491
- VALUES (?1, ?2, ?3, 'message', 'normal', ?4, ?5, ?6)`,
2492
- [id, targetAlias, target.session?.node_id ?? null, message, from_session, effectiveNetId ?? null]
2500
+ `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, network_id, meta_json)
2501
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)`,
2502
+ [id, targetAlias, target.session?.node_id ?? null, isControl ? "control" : "message",
2503
+ isControl ? "high" : "normal", isControl ? JSON.stringify({ op: "interrupt" }) : message,
2504
+ from_session, effectiveNetId ?? null, meta]
2493
2505
  );
2494
2506
 
2495
2507
  // 同 send_task:可达性用订阅者注册表判,不用心跳时间戳猜。
2496
- pushEvent(targetAlias, { type: "new_message", inbox_count: pendingInboxCount(targetAlias, effectiveNetId), from: from_session, message_id: id, ...(canonical.renamed ? { renamed_from: alias } : {}) }, effectiveNetId);
2508
+ // #cancel —— control 消息的 SSE 事件必须带上 control 字段:节点侧(cli.ts 的 copresence 分支)
2509
+ // 靠 `ev.control` 决定要不要唤醒工作通道去捞 type=control 的 inbox 行。这里不写,control 行
2510
+ // 会卡在「信息通道只排 type=message、工作通道只在 new_task 时排」两条 lane 之间,节点永远不取。
2511
+ pushEvent(targetAlias, { type: "new_message", inbox_count: pendingInboxCount(targetAlias, effectiveNetId), from: from_session, message_id: id, ...(isControl ? { control: "interrupt" } : {}), ...(canonical.renamed ? { renamed_from: alias } : {}) }, effectiveNetId);
2497
2512
 
2498
2513
  const offlineReply = deliveryTargetReply(target, { message_id: id });
2499
2514
  if (offlineReply) {
@@ -2512,6 +2527,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2512
2527
  text: JSON.stringify({
2513
2528
  ok: true,
2514
2529
  message_id: id,
2530
+ ...(isControl ? { control: "interrupt" as const, accepted: true, result_from: "node_reply" } : {}),
2531
+ ...(isSteer ? { delivery: "steer" as const, accepted: true } : {}),
2515
2532
  ...(canonical.renamed ? { renamed_from: alias, renamed_to: targetAlias } : {}),
2516
2533
  session_status: target.session?.status ?? "unknown",
2517
2534
  }),
@@ -2532,7 +2549,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2532
2549
  // undefined at alias". The target was already knowable from the task,
2533
2550
  // so requiring the caller to pass it was a redundant-param trap.
2534
2551
  alias: z.string().min(1).max(200).optional().describe("Target alias — optional; defaults to in_reply_to's sender"),
2535
- text: z.string().min(1).max(10000).describe("Reply content"),
2552
+ text: z.string().min(1).max(100_000).describe("Reply content"),
2536
2553
  in_reply_to: z.string().max(200).optional().describe("Original task/message ID"),
2537
2554
  status: z.enum(["replied", "failed", "cancelled"]).optional().default("replied").describe("Task outcome"),
2538
2555
  from_session: z.string().max(200).optional(),
@@ -2554,7 +2571,12 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2554
2571
  turn_id: z.string().optional(),
2555
2572
  };
2556
2573
  const handleReply = async (args: any, peerCapabilityRequired: boolean) => {
2557
- const { alias, text, in_reply_to, status: replyStatus = "replied", from_session: _fromIn, network_id: netId, attachments, meta, thread_id: threadId, turn_id: turnId } = args;
2574
+ const { alias, text, in_reply_to: inReplyToArg, status: replyStatus = "replied", from_session: _fromIn, network_id: netId, attachments, meta, thread_id: threadId, turn_id: turnId } = args;
2575
+ // #4315 —— `in_reply_to` 必须是可改写的局部量:某些 runtime 回执时既不带 alias
2576
+ // 也不带 in_reply_to(模型直接裸调 send_reply),于是回执被拒 ⇒ 那笔任务走不完生命周期
2577
+ // ⇒ 每处理一笔 +1 expired ⇒ 攒到 3 条就把整台节点挡成 target_never_consumes。
2578
+ // 下面会在「恰好一条在手的任务」时把它推断出来。
2579
+ let in_reply_to = inReplyToArg as string | undefined;
2558
2580
  const workSignal = parseScheduledWorkOutcome(meta, replyStatus);
2559
2581
  if (!workSignal.ok) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: workSignal.error, reply_queued: false }) }] };
2560
2582
  if (workSignal.outcome && !in_reply_to) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "scheduled_work_outcome_task_required", reply_queued: false }) }] };
@@ -2564,6 +2586,30 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2564
2586
  if (peerCapabilityRequired && !in_reply_to) {
2565
2587
  return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "peer_reply_task_required" }) }] };
2566
2588
  }
2589
+ // #4315 —— 裸回执(既无 alias 也无 in_reply_to)的推断:
2590
+ // 只有当**这台节点手上恰好有一条非终态任务**时才推断(单候选才安全);
2591
+ // 多条并存时保持原来的 reply_target_required —— 宁可拒绝,也不赌错对象。
2592
+ const callerBoundNodeId = callerTokenId
2593
+ ? (db.get<{ bound_node_id: string | null }>("SELECT bound_node_id FROM api_tokens WHERE token_id = ?1", callerTokenId)?.bound_node_id ?? null)
2594
+ : null;
2595
+ if (!in_reply_to && !(typeof alias === "string" && alias.trim()) && callerBoundNodeId) {
2596
+ // 先拿这台节点的 alias(不要在同一条 SQL 里 JOIN nodes:两表都有 network_id,
2597
+ // addScope 追加的裸列名会歧义报 SQLITE_ERROR —— 第一版就是这么挂的)
2598
+ const selfAlias = db.get<{ alias: string | null }>(
2599
+ "SELECT alias FROM nodes WHERE node_id = ?1", callerBoundNodeId)?.alias ?? null;
2600
+ const cands = selfAlias ? (() => {
2601
+ const candParams: any[] = [selfAlias];
2602
+ let candSql = `SELECT task_id, from_name FROM tasks
2603
+ WHERE to_name = ?1 AND status IN ('delivered','acked','running')`;
2604
+ candSql = addScope(candSql, candParams, effectiveNetId);
2605
+ candSql += " ORDER BY created_at DESC LIMIT 2";
2606
+ return db.all<{ task_id: string; from_name: string }>(candSql, ...candParams);
2607
+ })() : [];
2608
+ if (cands.length === 1) {
2609
+ in_reply_to = cands[0].task_id;
2610
+ console.log(`[${ts()}] ${from_session} → send_reply 裸回执,推断 in_reply_to=${cands[0].task_id.slice(0, 8)} (#4315)`);
2611
+ }
2612
+ }
2567
2613
  if ([threadId, turnId].some((v) => v !== undefined && (typeof v !== "string" || v.length < 1 || v.length > 200))) {
2568
2614
  return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "late_reply_context_invalid", message: "thread_id and turn_id must be 1-200 characters" }) }] };
2569
2615
  }
@@ -3188,7 +3234,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3188
3234
  // #3943 —— 服务端水位。调用方不传时间,Hub 用「上次给这个调用者返回的时刻」当下界,
3189
3235
  // 返回后把水位推到本次的 server_time。客户端连时钟都不用记(也就不会因两边差几秒漏活)。
3190
3236
  since_last: z.boolean().optional().default(false)
3191
- .describe("Only tasks created since this caller's previous list_tasks (server-side watermark)."),
3237
+ .describe("Only since this caller's previous list_tasks (watermark)."),
3192
3238
  },
3193
3239
  async ({ alias, status, from_name, from_node_id, network_id: netId, before_created_at, before_task_id, durable_cursor, durable_terminal_cursor, after_terminal_seq, limit, created_since, omit_stats, since_last }) => {
3194
3240
  const readScope = resolveReadScope(netId);
@@ -3383,7 +3429,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3383
3429
  // ── V2: cancel_task (取消任务) ──
3384
3430
  server.tool(
3385
3431
  "cancel_task",
3386
- "Cancel a pending task. Works on delivered/acked/running tasks.",
3432
+ "Cancel a task (user tokens may cancel expired too).",
3387
3433
  {
3388
3434
  task_id: z.string().min(1).max(200).describe("Task ID to cancel"),
3389
3435
  reason: z.string().max(1000).optional().describe("Cancellation reason"),
@@ -3394,9 +3440,16 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3394
3440
  const effectiveNetId = getNetworkId(netId);
3395
3441
  if (!canWrite(effectiveNetId)) return writeDeniedReply(effectiveNetId);
3396
3442
  console.log(`[${ts()}] ${from_session} → cancel_task → ${task_id.slice(0, 8)}`);
3443
+ // #4307 —— `expired` 是终态,节点令牌不得改写;但**用户令牌**必须能清:
3444
+ // target_never_consumes 的判据是「最后一次回复之后仍 expired 且 result 为空」,
3445
+ // 不清这些行,那个节点就永远收不到新消息(实测 4 个节点各 14–46 条)。
3446
+ // 取消时写 result(非空),既保留行做审计,又让它不再被计数。
3447
+ const cancelStatuses = callerTokenIsNetwork
3448
+ ? "('created', 'delivered', 'acked', 'running')"
3449
+ : "('created', 'delivered', 'acked', 'running', 'expired')";
3397
3450
  const updateParams: any[] = [reason || "cancelled by " + from_session, task_id];
3398
3451
  let updateSql = `UPDATE tasks SET status = 'cancelled', result = ?1, completed_at = datetime('now')
3399
- WHERE task_id = ?2 AND status IN ('created', 'delivered', 'acked', 'running')`;
3452
+ WHERE task_id = ?2 AND status IN ${cancelStatuses}`;
3400
3453
  updateSql = addScope(updateSql, updateParams, effectiveNetId);
3401
3454
  const result = db.transaction(() => {
3402
3455
  const updated = db.run(updateSql, updateParams);
@@ -3665,7 +3718,12 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3665
3718
  const { allowed: targets, skipped: inboxSkipped } = filterBroadcastByInbox(allTargets, effectiveNetId, inboxSender(), "mcp:broadcast");
3666
3719
  // #2721 —— 分批入库 + 批间让出(见 broadcast-fanout.ts 顶部:一条广播 384 行曾把 Hub
3667
3720
  // 打成 143.9 秒的 timer 饥饿)。语义不变:仍然逐个收件人一行、仍然 best-effort 跳过非 active。
3668
- const { ids } = await enqueueBroadcast(targets, message, "hub", effectiveNetId, {
3721
+ // #4066 —— 发信人必须是**真的调用者**,不是 'hub'。
3722
+ // 原来这里写死 "hub",于是一条由 TMA客户端欧5号 发出的广播,收件人看到的
3723
+ // from_session 是 hub、正文却是 "[TMA客户端欧5号] …" ⇒ 用户根本分不清谁说的。
3724
+ // 生产 2026-11-13 实测:type=broadcast 且 from_session='hub' 共 3253 行。
3725
+ // 节点令牌调用时 callerAlias 就是该节点 alias;人/API 调用时退化成用户名;都拿不到才回 "hub"。
3726
+ const { ids } = await enqueueBroadcast(targets, message, callerAlias || "hub", effectiveNetId, {
3669
3727
  // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.1 site 6/6).
3670
3728
  isActive: (alias, netId) => assertNodeActive(alias, netId).ok,
3671
3729
  notify: (alias, netId) => pushEvent(alias, { type: "broadcast", inbox_count: pendingInboxCount(alias, netId) }, netId),
@@ -5358,7 +5416,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
5358
5416
  WHERE child_node_id = ?1 AND network_id = ?2 AND status = 'succeeded'
5359
5417
  ORDER BY created_at DESC LIMIT 1`,
5360
5418
  source_node_id, source.network_id || effectiveNetId || "default",
5361
- );
5419
+ ) ?? adoptedCloneSourceRow(source_node_id, source.network_id || effectiveNetId || "default", source.runtime ?? null, source.alias || source.node_name || "");
5362
5420
  const net = source.network_id || effectiveNetId || "default";
5363
5421
  const nameRows = db.all<{ alias: string | null; node_name: string | null }>(
5364
5422
  `SELECT alias, node_name FROM nodes WHERE network_id = ?1`,
@@ -7294,7 +7352,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
7294
7352
  cursor: z.string().max(600).optional().describe("next_cursor from the previous page"),
7295
7353
  view: z.enum(["full", "summary"]).optional().describe("summary (default; no bodies) or full"),
7296
7354
  changes: z.boolean().optional().describe("with updated_since: tasks changed since then, +deleted ids, +server_time (+newer events with include_last_event)"),
7297
- include_last_event: z.boolean().optional().describe("true adds last_event per row (~150 B: type/field/actor/at/summary; null if none)"),
7355
+ include_last_event: z.boolean().optional().describe("true adds last_event per row (~150B)"),
7298
7356
  };
7299
7357
  const reqListKeys = Object.keys(reqListShape);
7300
7358
  server.registerTool(