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

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 (43) hide show
  1. package/build-info.json +2 -2
  2. package/package.json +1 -1
  3. package/src/agent-acl-slice3-http.test.ts +3 -2
  4. package/src/api-host-supervisors-source-capabilities.test.ts +107 -0
  5. package/src/auth_login_guard.test.ts +15 -0
  6. package/src/auth_login_guard.ts +20 -1
  7. package/src/board-grants.test.ts +134 -0
  8. package/src/broadcast-attribution.test.ts +93 -0
  9. package/src/build-commit-report-http.test.ts +10 -0
  10. package/src/clone-node-adopted-db.test.ts +78 -0
  11. package/src/clone-node.ts +5 -1
  12. package/src/create-node-department.test.ts +145 -0
  13. package/src/create-node.ts +35 -0
  14. package/src/db.ts +11 -0
  15. package/src/department-heads.ts +3 -0
  16. package/src/expiry-counters.test.ts +50 -1
  17. package/src/expiry-counters.ts +31 -9
  18. package/src/mcp-write-network-resolution.test.ts +36 -0
  19. package/src/node-attrs-validate.ts +34 -0
  20. package/src/node-attrs.test.ts +32 -0
  21. package/src/node-config-last-update.test.ts +103 -1
  22. package/src/node-config-last-update.ts +70 -5
  23. package/src/node-daemon-bindings.ts +9 -0
  24. package/src/node-description-http.test.ts +121 -0
  25. package/src/node-description.test.ts +34 -0
  26. package/src/node-grants-http.test.ts +239 -0
  27. package/src/node-grants.ts +234 -0
  28. package/src/node-inbox-allowlist-http.test.ts +35 -0
  29. package/src/node-permissions.ts +37 -2
  30. package/src/opencode-v2-catalog.test.ts +22 -1
  31. package/src/opencode-v2-catalog.ts +36 -3
  32. package/src/peer-allowlist.test.ts +29 -0
  33. package/src/registration-switch-http.test.ts +60 -0
  34. package/src/reply-bare-infer-4315.test.ts +86 -0
  35. package/src/requirements.ts +29 -4
  36. package/src/schedule-agent.ts +45 -10
  37. package/src/scheduled-tasks-http.test.ts +25 -0
  38. package/src/scheduled-tasks.ts +46 -2
  39. package/src/server.ts +132 -11
  40. package/src/steer-send-message.test.ts +121 -0
  41. package/src/task-access.ts +21 -1
  42. package/src/tool-audience-http.test.ts +5 -0
  43. package/src/tools.ts +147 -42
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";
@@ -8,7 +9,7 @@ import { markTaskActivity } from "./task-activity.js";
8
9
  import { requestProviderSnapshot, requestProviderWrite, requestProviderCollection, requestProviderApplication, requestProviderLogin, getProviderSnapshot, pullProviderSnapshots, ackProviderSnapshot } from "./daemon-provider-snapshots.js";
9
10
  import { readHubProviders, putHubProvider, bindHubProvider } from './hub-provider-config.js';
10
11
  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";
12
+ import { adoptedCloneSourceRow, requestAdopt, getAdopt, ackAdopt, unadopt, resolveManagedDaemon, activeBinding, createdDaemon } from "./node-daemon-bindings.js";
12
13
  import { runtimeReadinessSchema } from "./runtime-readiness.js";
13
14
  import { adoptionCandidatesReportSchema } from "./adoption-candidates.js";
14
15
  import { forkRecoveryRequestSchema, forkRecoveryResultSchema, publicForkResult } from "./codex-fork-contract.js";
@@ -1008,6 +1009,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1008
1009
  // (#3294 的 build_commit 就是同一个坑)。`.catch(undefined)` 与邻居一致:
1009
1010
  // 形状不对只丢这一格,绝不拒掉整份心跳。
1010
1011
  opencode_catalog_seen_at: z.string().max(40).optional().catch(undefined),
1012
+ // 每个模型的思考档位:`provider/model=none,low,high,max`(只有 id)。不写进 schema 会被静默剥掉。
1013
+ opencode_catalog_variants: z.array(z.string().max(600)).optional().catch(undefined),
1011
1014
  // #4150-Build —— 这台节点的 OpenCode V2 暴露的 agent 列表(`build`/`plan`…)。
1012
1015
  // 🔴 与上面 catalog 同一个陷阱:不写进这个 schema,daemon 报上来也**会被静默剥掉**,
1013
1016
  // `/api/nodes` 的投影读到的永远是 null。空数组合法 =「确实没有 agent」。
@@ -1559,6 +1562,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1559
1562
  // A copied node_id must not relabel the row. The heartbeat itself still
1560
1563
  // succeeds: only a token rejected as impersonation fails the whole call.
1561
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;
1562
1567
  if (node_id) {
1563
1568
  try {
1564
1569
  const nodeRuntime = ag?.includes(":") ? ag.split(":")[1] + "-sdk" : ag ?? null;
@@ -1599,6 +1604,10 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1599
1604
  alias: effectiveAlias,
1600
1605
  ...(canonical.renamed ? { renamed_from: alias } : {}),
1601
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)" } : {}),
1602
1611
  inbox_count: row?.cnt ?? 0,
1603
1612
  }),
1604
1613
  },
@@ -1999,9 +2008,23 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1999
2008
  // Hub Tools (5)
2000
2009
  // ═══════════════════════════════════════════
2001
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
+
2002
2025
  server.tool(
2003
2026
  "get_all_status",
2004
- "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.",
2005
2028
  {
2006
2029
  filter_status: z.string().max(50).optional(),
2007
2030
  filter_server: z.string().max(200).optional(),
@@ -2041,7 +2064,13 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2041
2064
  // #500 step 2 — queue_depth = open tasks on that node (task-queue-ahead.ts); one GROUP BY, not one query per row.
2042
2065
  const rows = db.all<any>(sql, ...params);
2043
2066
  const depth = queueDepthByNode(rows.map((r: any) => r.alias));
2044
- const sessions = rows.map((s: any) => ({ ...s, queue_depth: depth.get(queueDepthKey(s.network_id, s.alias)) ?? 0 }));
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
+ });
2045
2074
 
2046
2075
  // `summary` has always counted every session in the read scope, ignoring
2047
2076
  // filter_status / filter_server — and now filter_alias. That is fine for
@@ -2074,7 +2103,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2074
2103
 
2075
2104
  server.tool(
2076
2105
  "get_session_status",
2077
- "Get detailed status of a specific session by alias.",
2106
+ "Get detailed status of a specific session by alias; profile.description = its role.",
2078
2107
  { alias: z.string().min(1).max(200).describe("Session alias") },
2079
2108
  async ({ alias }) => {
2080
2109
  const readScope = resolveReadScope(null);
@@ -2096,11 +2125,22 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2096
2125
  recentSql += " ORDER BY completed_at DESC LIMIT 5";
2097
2126
  const recent = db.all(recentSql, ...recentParams);
2098
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;
2099
2139
  return {
2100
2140
  content: [
2101
2141
  {
2102
2142
  type: "text" as const,
2103
- 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 }),
2104
2144
  },
2105
2145
  ],
2106
2146
  };
@@ -2119,7 +2159,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2119
2159
  ttl_seconds: z.number().min(1).max(86400).optional().describe("Task TTL in seconds (default: 3600)"),
2120
2160
  network_id: z.string().max(200).optional().describe("Network scope"),
2121
2161
  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}] }."),
2162
+ meta: z.any().optional().describe("Optional task metadata (e.g. attachments)."),
2123
2163
  force: z.boolean().optional().describe("dispatch even if the target is degraded (user tokens only)"),
2124
2164
  },
2125
2165
  async ({ alias, task, priority, context, from_session: _fromIn, ttl_seconds, network_id: netId, parent_task_id: parentIn, meta, force }) => {
@@ -2464,14 +2504,19 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2464
2504
 
2465
2505
  server.tool(
2466
2506
  "send_message",
2467
- "Send a message to a session (no task lifecycle, just chat). Use for replies, status updates, or casual communication.",
2507
+ "Send a chat message (no task lifecycle). control=interrupt stops the running turn.",
2468
2508
  {
2469
2509
  alias: z.string().min(1).max(200).describe("Target session alias"),
2470
- message: z.string().min(1).max(10000).describe("Message content"),
2510
+ message: z.string().min(1).max(100_000).describe("Message"),
2511
+ control: z.enum(["interrupt"]).optional().describe("Interrupt turn"),
2512
+ steer: z.boolean().optional().describe("Inject into running turn"),
2471
2513
  from_session: z.string().max(200).optional(),
2472
- network_id: z.string().max(200).optional().describe("Network; auto-resolved for single-network user tokens"),
2514
+ network_id: z.string().max(200).optional().describe("Network (auto for single-network)"),
2473
2515
  },
2474
- async ({ alias, message, from_session: _fromIn, network_id: netId }) => { const fromMismatch = fromIdentityMismatchReply(_fromIn); if (fromMismatch) return fromMismatch; const from_session = defaultFrom(_fromIn);
2516
+ async ({ alias, message, control, steer, from_session: _fromIn, network_id: netId }) => { const fromMismatch = fromIdentityMismatchReply(_fromIn); if (fromMismatch) return fromMismatch; const from_session = defaultFrom(_fromIn);
2517
+ if (control !== undefined && steer !== undefined) {
2518
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "steer_conflicts_with_control", message: "control 与 steer 互斥:一次只能要一样" }) }] };
2519
+ }
2475
2520
  const effectiveNetId = getNetworkId(netId);
2476
2521
  { const sendDenied = agentSendDenied(effectiveNetId, alias, _fromIn, "write"); if (sendDenied) return sendDenied; }
2477
2522
  const canonical = resolveCanonicalAlias(effectiveNetId, alias);
@@ -2485,15 +2530,23 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2485
2530
  if (!lc.ok) return { content: [{ type: "text" as const, text: JSON.stringify(lc) }] };
2486
2531
  }
2487
2532
  console.log(`[${ts()}] ${from_session} → send_message → ${targetAlias}: ${message.slice(0, 60)}${canonical.renamed ? ` [renamed from ${alias}]` : ""}`);
2533
+ const isControl = control === "interrupt";
2534
+ const isSteer = steer === true;
2535
+ const meta = isSteer ? JSON.stringify({ delivery: "steer" }) : null;
2488
2536
  const id = uuidv4();
2489
2537
  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]
2538
+ `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, network_id, meta_json)
2539
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)`,
2540
+ [id, targetAlias, target.session?.node_id ?? null, isControl ? "control" : "message",
2541
+ isControl ? "high" : "normal", isControl ? JSON.stringify({ op: "interrupt" }) : message,
2542
+ from_session, effectiveNetId ?? null, meta]
2493
2543
  );
2494
2544
 
2495
2545
  // 同 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);
2546
+ // #cancel —— control 消息的 SSE 事件必须带上 control 字段:节点侧(cli.ts 的 copresence 分支)
2547
+ // 靠 `ev.control` 决定要不要唤醒工作通道去捞 type=control 的 inbox 行。这里不写,control 行
2548
+ // 会卡在「信息通道只排 type=message、工作通道只在 new_task 时排」两条 lane 之间,节点永远不取。
2549
+ 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
2550
 
2498
2551
  const offlineReply = deliveryTargetReply(target, { message_id: id });
2499
2552
  if (offlineReply) {
@@ -2512,6 +2565,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2512
2565
  text: JSON.stringify({
2513
2566
  ok: true,
2514
2567
  message_id: id,
2568
+ ...(isControl ? { control: "interrupt" as const, accepted: true, result_from: "node_reply" } : {}),
2569
+ ...(isSteer ? { delivery: "steer" as const, accepted: true } : {}),
2515
2570
  ...(canonical.renamed ? { renamed_from: alias, renamed_to: targetAlias } : {}),
2516
2571
  session_status: target.session?.status ?? "unknown",
2517
2572
  }),
@@ -2532,7 +2587,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2532
2587
  // undefined at alias". The target was already knowable from the task,
2533
2588
  // so requiring the caller to pass it was a redundant-param trap.
2534
2589
  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"),
2590
+ text: z.string().min(1).max(100_000).describe("Reply content"),
2536
2591
  in_reply_to: z.string().max(200).optional().describe("Original task/message ID"),
2537
2592
  status: z.enum(["replied", "failed", "cancelled"]).optional().default("replied").describe("Task outcome"),
2538
2593
  from_session: z.string().max(200).optional(),
@@ -2554,7 +2609,12 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2554
2609
  turn_id: z.string().optional(),
2555
2610
  };
2556
2611
  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;
2612
+ 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;
2613
+ // #4315 —— `in_reply_to` 必须是可改写的局部量:某些 runtime 回执时既不带 alias
2614
+ // 也不带 in_reply_to(模型直接裸调 send_reply),于是回执被拒 ⇒ 那笔任务走不完生命周期
2615
+ // ⇒ 每处理一笔 +1 expired ⇒ 攒到 3 条就把整台节点挡成 target_never_consumes。
2616
+ // 下面会在「恰好一条在手的任务」时把它推断出来。
2617
+ let in_reply_to = inReplyToArg as string | undefined;
2558
2618
  const workSignal = parseScheduledWorkOutcome(meta, replyStatus);
2559
2619
  if (!workSignal.ok) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: workSignal.error, reply_queued: false }) }] };
2560
2620
  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 +2624,30 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2564
2624
  if (peerCapabilityRequired && !in_reply_to) {
2565
2625
  return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "peer_reply_task_required" }) }] };
2566
2626
  }
2627
+ // #4315 —— 裸回执(既无 alias 也无 in_reply_to)的推断:
2628
+ // 只有当**这台节点手上恰好有一条非终态任务**时才推断(单候选才安全);
2629
+ // 多条并存时保持原来的 reply_target_required —— 宁可拒绝,也不赌错对象。
2630
+ const callerBoundNodeId = callerTokenId
2631
+ ? (db.get<{ bound_node_id: string | null }>("SELECT bound_node_id FROM api_tokens WHERE token_id = ?1", callerTokenId)?.bound_node_id ?? null)
2632
+ : null;
2633
+ if (!in_reply_to && !(typeof alias === "string" && alias.trim()) && callerBoundNodeId) {
2634
+ // 先拿这台节点的 alias(不要在同一条 SQL 里 JOIN nodes:两表都有 network_id,
2635
+ // addScope 追加的裸列名会歧义报 SQLITE_ERROR —— 第一版就是这么挂的)
2636
+ const selfAlias = db.get<{ alias: string | null }>(
2637
+ "SELECT alias FROM nodes WHERE node_id = ?1", callerBoundNodeId)?.alias ?? null;
2638
+ const cands = selfAlias ? (() => {
2639
+ const candParams: any[] = [selfAlias];
2640
+ let candSql = `SELECT task_id, from_name FROM tasks
2641
+ WHERE to_name = ?1 AND status IN ('delivered','acked','running')`;
2642
+ candSql = addScope(candSql, candParams, effectiveNetId);
2643
+ candSql += " ORDER BY created_at DESC LIMIT 2";
2644
+ return db.all<{ task_id: string; from_name: string }>(candSql, ...candParams);
2645
+ })() : [];
2646
+ if (cands.length === 1) {
2647
+ in_reply_to = cands[0].task_id;
2648
+ console.log(`[${ts()}] ${from_session} → send_reply 裸回执,推断 in_reply_to=${cands[0].task_id.slice(0, 8)} (#4315)`);
2649
+ }
2650
+ }
2567
2651
  if ([threadId, turnId].some((v) => v !== undefined && (typeof v !== "string" || v.length < 1 || v.length > 200))) {
2568
2652
  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
2653
  }
@@ -3188,7 +3272,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3188
3272
  // #3943 —— 服务端水位。调用方不传时间,Hub 用「上次给这个调用者返回的时刻」当下界,
3189
3273
  // 返回后把水位推到本次的 server_time。客户端连时钟都不用记(也就不会因两边差几秒漏活)。
3190
3274
  since_last: z.boolean().optional().default(false)
3191
- .describe("Only tasks created since this caller's previous list_tasks (server-side watermark)."),
3275
+ .describe("Only since this caller's previous list_tasks (watermark)."),
3192
3276
  },
3193
3277
  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
3278
  const readScope = resolveReadScope(netId);
@@ -3383,7 +3467,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3383
3467
  // ── V2: cancel_task (取消任务) ──
3384
3468
  server.tool(
3385
3469
  "cancel_task",
3386
- "Cancel a pending task. Works on delivered/acked/running tasks.",
3470
+ "Cancel a task (user tokens may cancel expired too).",
3387
3471
  {
3388
3472
  task_id: z.string().min(1).max(200).describe("Task ID to cancel"),
3389
3473
  reason: z.string().max(1000).optional().describe("Cancellation reason"),
@@ -3394,9 +3478,16 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3394
3478
  const effectiveNetId = getNetworkId(netId);
3395
3479
  if (!canWrite(effectiveNetId)) return writeDeniedReply(effectiveNetId);
3396
3480
  console.log(`[${ts()}] ${from_session} → cancel_task → ${task_id.slice(0, 8)}`);
3481
+ // #4307 —— `expired` 是终态,节点令牌不得改写;但**用户令牌**必须能清:
3482
+ // target_never_consumes 的判据是「最后一次回复之后仍 expired 且 result 为空」,
3483
+ // 不清这些行,那个节点就永远收不到新消息(实测 4 个节点各 14–46 条)。
3484
+ // 取消时写 result(非空),既保留行做审计,又让它不再被计数。
3485
+ const cancelStatuses = callerTokenIsNetwork
3486
+ ? "('created', 'delivered', 'acked', 'running')"
3487
+ : "('created', 'delivered', 'acked', 'running', 'expired')";
3397
3488
  const updateParams: any[] = [reason || "cancelled by " + from_session, task_id];
3398
3489
  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')`;
3490
+ WHERE task_id = ?2 AND status IN ${cancelStatuses}`;
3400
3491
  updateSql = addScope(updateSql, updateParams, effectiveNetId);
3401
3492
  const result = db.transaction(() => {
3402
3493
  const updated = db.run(updateSql, updateParams);
@@ -3665,7 +3756,12 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3665
3756
  const { allowed: targets, skipped: inboxSkipped } = filterBroadcastByInbox(allTargets, effectiveNetId, inboxSender(), "mcp:broadcast");
3666
3757
  // #2721 —— 分批入库 + 批间让出(见 broadcast-fanout.ts 顶部:一条广播 384 行曾把 Hub
3667
3758
  // 打成 143.9 秒的 timer 饥饿)。语义不变:仍然逐个收件人一行、仍然 best-effort 跳过非 active。
3668
- const { ids } = await enqueueBroadcast(targets, message, "hub", effectiveNetId, {
3759
+ // #4066 —— 发信人必须是**真的调用者**,不是 'hub'。
3760
+ // 原来这里写死 "hub",于是一条由 TMA客户端欧5号 发出的广播,收件人看到的
3761
+ // from_session 是 hub、正文却是 "[TMA客户端欧5号] …" ⇒ 用户根本分不清谁说的。
3762
+ // 生产 2026-11-13 实测:type=broadcast 且 from_session='hub' 共 3253 行。
3763
+ // 节点令牌调用时 callerAlias 就是该节点 alias;人/API 调用时退化成用户名;都拿不到才回 "hub"。
3764
+ const { ids } = await enqueueBroadcast(targets, message, callerAlias || "hub", effectiveNetId, {
3669
3765
  // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.1 site 6/6).
3670
3766
  isActive: (alias, netId) => assertNodeActive(alias, netId).ok,
3671
3767
  notify: (alias, netId) => pushEvent(alias, { type: "broadcast", inbox_count: pendingInboxCount(alias, netId) }, netId),
@@ -3766,7 +3862,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3766
3862
 
3767
3863
  server.tool(
3768
3864
  "update_node_config",
3769
- "Set the per-node config (model + flags) and push a doorbell; the node pulls, validates and applies (hot or restart per field). RFC-024.",
3865
+ "Set the per-node config (model + flags) and push a doorbell; the node pulls, validates and applies (hot or restart per field).",
3770
3866
  {
3771
3867
  ...NODE_ID_ALIAS_FIELDS,
3772
3868
  base_revision: z.number().int().min(0).describe("Revision from the dashboard's last GET — 409 if the hub's differs."),
@@ -4133,7 +4229,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
4133
4229
 
4134
4230
  server.tool(
4135
4231
  "get_config_update",
4136
- "Node pulls its pending config update (called from agent-node when SSE config_update doorbell arrives). RFC-024.",
4232
+ "Node pulls its pending config update (called from agent-node when SSE config_update doorbell arrives).",
4137
4233
  {},
4138
4234
  async () => {
4139
4235
  // F-A (CHANGE_REQ): require ntok_ + non-null enforceNetworkId.
@@ -4188,7 +4284,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
4188
4284
 
4189
4285
  server.tool(
4190
4286
  "ack_config_update",
4191
- "Node acknowledges a config update — applied / rejected / restarting / timeout. RFC-024.",
4287
+ "Node acknowledges a config update — applied / rejected / restarting / timeout.",
4192
4288
  {
4193
4289
  update_id: z.string().min(1).max(200),
4194
4290
  status: z.enum(["applied", "rejected", "restarting", "timeout"]),
@@ -4443,7 +4539,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
4443
4539
 
4444
4540
  server.tool(
4445
4541
  "read_node_rules_file",
4446
- "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. app#225.",
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.",
4447
4543
  {
4448
4544
  ...NODE_ID_ALIAS_FIELDS,
4449
4545
  alias: z.string().min(1).max(200).optional().describe("Instead of node_id: node or rules_file_capable session alias."),
@@ -4529,7 +4625,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
4529
4625
 
4530
4626
  server.tool(
4531
4627
  "get_rules_file_request",
4532
- "Node pulls its oldest pending rules-file request (called from agent-node when the SSE rules_file doorbell arrives). app#225.",
4628
+ "Node pulls its oldest pending rules-file request (called from agent-node when the SSE rules_file doorbell arrives).",
4533
4629
  {},
4534
4630
  async () => {
4535
4631
  // 同 get_config_update 的 F-A 闸:必须是网络 token + alias。
@@ -4574,7 +4670,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
4574
4670
 
4575
4671
  server.tool(
4576
4672
  "ack_rules_file_request",
4577
- "Node reports the outcome of a rules-file request — done (with content for reads) or failed (with error). app#225.",
4673
+ "Node reports the outcome of a rules-file request — done (with content for reads) or failed (with error).",
4578
4674
  {
4579
4675
  request_id: z.string().min(1).max(200),
4580
4676
  status: z.enum(["done", "failed"]),
@@ -4626,7 +4722,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
4626
4722
 
4627
4723
  server.tool(
4628
4724
  "get_rules_file_result",
4629
- "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. app#225.",
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.",
4630
4726
  { request_id: z.string().min(1).max(200), network_id: z.string().max(200).optional() },
4631
4727
  async ({ request_id: requestId, network_id: clientNetId }) => {
4632
4728
  const effectiveNetId = getNetworkId(clientNetId);
@@ -5032,8 +5128,11 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
5032
5128
  workdir: z.string().max(1024).optional().nullable(),
5033
5129
  }),
5034
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(),
5035
5134
  },
5036
- async ({ daemon_node_id, node_spec, network_id: clientNetId }) => {
5135
+ async ({ daemon_node_id, node_spec, network_id: clientNetId, department_id: requestedDepartment }) => {
5037
5136
  const effectiveNetId = getNetworkId(clientNetId);
5038
5137
  if (!canWrite(effectiveNetId)) return writeDeniedReply(effectiveNetId, "write");
5039
5138
 
@@ -5257,6 +5356,11 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
5257
5356
  const childToken = generateNetworkToken();
5258
5357
  const childTokenId = generateId("tok");
5259
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
+ }
5260
5364
  const requestId = newRequestId();
5261
5365
  // Use the dashboard caller's user_id as the token's user_id so
5262
5366
  // resolveToken returns sane role / network on the child's side
@@ -5282,13 +5386,13 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
5282
5386
  const envKeys = Object.keys(envBlob);
5283
5387
  db.run(
5284
5388
  `INSERT INTO node_create_requests
5285
- (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)
5286
- 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)`,
5287
5391
  [
5288
5392
  requestId, daemon_node_id, node_spec.name, networkIdForChild,
5289
5393
  node_spec.runtime, node_spec.model ?? null, JSON.stringify(node_spec.flags || {}),
5290
5394
  JSON.stringify(envKeys), childTokenId, Date.now(), callerTokenId || "unknown",
5291
- requestedWorkdir,
5395
+ requestedWorkdir, departmentForChild,
5292
5396
  ],
5293
5397
  );
5294
5398
 
@@ -5312,11 +5416,12 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
5312
5416
  flag_keys: Object.keys(node_spec.flags || {}),
5313
5417
  env_keys: envKeys,
5314
5418
  workdir: requestedWorkdir,
5419
+ department_id: departmentForChild,
5315
5420
  },
5316
5421
  });
5317
5422
 
5318
5423
  return {
5319
- 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 } : {}) }) }],
5320
5425
  };
5321
5426
  },
5322
5427
  );
@@ -5327,7 +5432,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
5327
5432
  // the policy and the runtime's session capability (see clone-node.ts).
5328
5433
  server.tool(
5329
5434
  "clone_node",
5330
- "Clone a daemon child into a new node on the same daemon: new name + token. copy_session defaults true; workdir_policy new_empty (default) or share_source. Hub #938.",
5435
+ "Clone a daemon child to a new node (new name + token). copy_session default true; workdir_policy new_empty (default) or share_source.",
5331
5436
  {
5332
5437
  source_node_id: z.string().min(1).max(200),
5333
5438
  name: z.string().min(1).max(256),
@@ -5358,7 +5463,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
5358
5463
  WHERE child_node_id = ?1 AND network_id = ?2 AND status = 'succeeded'
5359
5464
  ORDER BY created_at DESC LIMIT 1`,
5360
5465
  source_node_id, source.network_id || effectiveNetId || "default",
5361
- );
5466
+ ) ?? adoptedCloneSourceRow(source_node_id, source.network_id || effectiveNetId || "default", source.runtime ?? null, source.alias || source.node_name || "");
5362
5467
  const net = source.network_id || effectiveNetId || "default";
5363
5468
  const nameRows = db.all<{ alias: string | null; node_name: string | null }>(
5364
5469
  `SELECT alias, node_name FROM nodes WHERE network_id = ?1`,
@@ -5668,7 +5773,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
5668
5773
  // record fork-side info.
5669
5774
  server.tool(
5670
5775
  "ack_create_request",
5671
- "Daemon acks a create-node request (called after fork). status='started' | 'failed' | 'rejected' | 'runtime_capability_check_failed'. RFC-026 §9.3 D2.",
5776
+ "Daemon acks a create-node request (called after fork). status='started' | 'failed' | 'rejected' | 'runtime_capability_check_failed'.",
5672
5777
  {
5673
5778
  request_id: z.string().min(1).max(200),
5674
5779
  // RFC-026 §9.3 D2 — runtime_capability_check_failed signals the
@@ -6117,7 +6222,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
6117
6222
 
6118
6223
  server.tool(
6119
6224
  "delete_node",
6120
- "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. RFC-027 §2.2.",
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.",
6121
6226
  {
6122
6227
  ...NODE_ID_ALIAS_FIELDS,
6123
6228
  daemon_node_id: z.string().min(1).max(200).regex(/^node_[a-z0-9_-]+$/).optional(),
@@ -6147,7 +6252,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
6147
6252
 
6148
6253
  server.tool(
6149
6254
  "get_stop_request",
6150
- "Daemon pulls a pending stop/delete request (called when SSE stop_node doorbell arrives). RFC-027 §2.4.",
6255
+ "Daemon pulls a pending stop/delete request (called when SSE stop_node doorbell arrives).",
6151
6256
  {
6152
6257
  request_id: z.string().min(1).max(200),
6153
6258
  },
@@ -6191,7 +6296,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
6191
6296
 
6192
6297
  server.tool(
6193
6298
  "ack_stop_request",
6194
- "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. RFC-027 §2.3 + §4.5.",
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.",
6195
6300
  {
6196
6301
  request_id: z.string().min(1).max(200),
6197
6302
  status: z.enum(["stopped", "stop_failed", "noop_not_my_child"]),
@@ -6618,7 +6723,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
6618
6723
  // §2.3.4 — upsert_network_secret (OWNER-ONLY; vault write).
6619
6724
  server.tool(
6620
6725
  "upsert_network_secret",
6621
- "Create or replace one vault secret by key (value never read back). RFC-028.",
6726
+ "Create or replace one vault secret by key (value never read back).",
6622
6727
  {
6623
6728
  key: z.string().min(1).max(64).regex(/^[A-Z][A-Z0-9_]{0,63}$/),
6624
6729
  value: z.string().min(1).max(16 * 1024),
@@ -6650,7 +6755,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
6650
6755
  // §2.3.4b — list_network_secrets (key names only; viewer+).
6651
6756
  server.tool(
6652
6757
  "list_network_secrets",
6653
- "List vault key NAMES (NEVER values) for a network. RFC-028.",
6758
+ "List vault key NAMES (NEVER values) for a network.",
6654
6759
  { network_id: z.string().max(200).optional() },
6655
6760
  async ({ network_id: clientNetId }) => {
6656
6761
  const effectiveNetId = getNetworkId(clientNetId);
@@ -6667,7 +6772,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
6667
6772
  // §2.3.1 — upsert_provider (admin+).
6668
6773
  server.tool(
6669
6774
  "upsert_provider",
6670
- "Create or update a provider (vendor + base_url + secret_key_ref + initial models). Admin+. RFC-028.",
6775
+ "Create or update a provider (vendor + base_url + secret_key_ref + initial models). Admin+.",
6671
6776
  {
6672
6777
  name: z.string().min(1).max(100),
6673
6778
  vendor: z.string().min(1).max(64),
@@ -7294,7 +7399,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
7294
7399
  cursor: z.string().max(600).optional().describe("next_cursor from the previous page"),
7295
7400
  view: z.enum(["full", "summary"]).optional().describe("summary (default; no bodies) or full"),
7296
7401
  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)"),
7402
+ include_last_event: z.boolean().optional().describe("true adds last_event per row (~150B)"),
7298
7403
  };
7299
7404
  const reqListKeys = Object.keys(reqListShape);
7300
7405
  server.registerTool(