@sleep2agi/commhub-server 0.9.0-preview.273 → 0.9.0-preview.274

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build-info.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "commit": "a99bf9c369e357748d6171b68c0a3507e2bbccdc",
3
+ "commit": "a10fa363e362c705a212eb1ad883fdc72dc4499c",
4
4
  "dirty": false,
5
- "built_at": "2026-11-05T14:41:04.990Z",
5
+ "built_at": "2026-11-05T17:33:11.706Z",
6
6
  "source": "git"
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.273",
3
+ "version": "0.9.0-preview.274",
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",
@@ -97,3 +97,32 @@ describe("#3952 节点 Token 审计", () => {
97
97
  expect(norm?.costUsd).toBeNull();
98
98
  });
99
99
  });
100
+
101
+ // #3950 —— 覆盖率分母:让「只有一行」不被读成「只有一个节点在干活」。
102
+ import { reportsTokenUsage, tokenUsageCoverage } from "./node-token-usage";
103
+
104
+ describe("#3950 覆盖率分母", () => {
105
+ test("版本判定:>= .180 会报;旧版本不会;解析不出返回 null(不猜)", () => {
106
+ expect(reportsTokenUsage("2.5.0-preview.181")).toBe(true);
107
+ expect(reportsTokenUsage("2.5.0-preview.180")).toBe(true);
108
+ expect(reportsTokenUsage("2.5.0-preview.164")).toBe(false);
109
+ expect(reportsTokenUsage("2.4.1-preview.9")).toBeNull();
110
+ expect(reportsTokenUsage("")).toBeNull();
111
+ expect(reportsTokenUsage(null)).toBeNull();
112
+ });
113
+
114
+ test("分母三数:reporting / capable / 未知版本各自独立", () => {
115
+ const rows = [
116
+ { version: "2.5.0-preview.181" }, { version: "2.5.0-preview.164" },
117
+ { version: "2.5.0-preview.146" }, { version: "codex-app-server" },
118
+ { version: null },
119
+ ];
120
+ const cov = tokenUsageCoverage("net_x", 1, () => rows);
121
+ expect(cov.reporting_nodes).toBe(1);
122
+ expect(cov.capable_nodes).toBe(1);
123
+ expect(cov.sessions_with_version).toBe(3);
124
+ expect(cov.sessions_without_known_version).toBe(2);
125
+ // 镜像:capable 只统计「能解析且 >= 阈值」,不等于 sessions_with_version
126
+ expect(cov.capable_nodes).toBeLessThan(cov.sessions_with_version);
127
+ });
128
+ });
@@ -143,6 +143,9 @@ export function readTokenUsage(networkId: string, sinceHours = 24): NodeTokenUsa
143
143
  const rows = db.all<{
144
144
  node_id: string; alias: string | null;
145
145
  input_tokens: number; output_tokens: number;
146
+ // #3950 —— SELECT 里已经有 SUM(cache_read_tokens),类型漏了它时
147
+ // `r.cache_read_tokens` 在 TS 上是错的,而运行期是 undefined ⇒ totals 变成 NaN。
148
+ cache_read_tokens: number | null;
146
149
  turns: number; cost_usd: number; models: number;
147
150
  first_hour: string | null; last_hour: string | null;
148
151
  }>(
@@ -176,3 +179,50 @@ export const NODE_TOKEN_USAGE_COLUMNS = [
176
179
  'network_id', 'node_id', 'hour', 'model',
177
180
  'input_tokens', 'output_tokens', 'cache_read_tokens', 'turns', 'cost_usd', 'updated_at',
178
181
  ] as const;
182
+
183
+ // ── 覆盖率:让「只有一行」不被读成「只有一个节点在干活」 ──
184
+ //
185
+ // 生产实测(2026-11-06):203 个 agent-node 里只有 1 个 >= .180(会报 token),
186
+ // 其余停在 .164 / .146。于是 /api/token-usage 只返回 1 行 —— 那不是"系统没工作",
187
+ // 是"几乎没有节点拥有这个能力"。这两个解释在报表上同形,分母必须一起给。
188
+
189
+ /** agent-node 从哪一版开始上报 token(.180 加 claude/codex,.181 加 opencode 增量)。 */
190
+ export const TOKEN_USAGE_MIN_PREVIEW = 180;
191
+
192
+ /** 这个 version 字符串会不会上报 token:true / false / null(解析不出,不猜)。 */
193
+ export function reportsTokenUsage(version: string | null | undefined): boolean | null {
194
+ const raw = typeof version === "string" ? version.trim() : "";
195
+ const m = /^2\.5\.0-preview\.(\d+)$/.exec(raw);
196
+ if (!m) return null; // 换版本线 / 旧格式 ⇒ 不知道,不猜
197
+ return Number(m[1]) >= TOKEN_USAGE_MIN_PREVIEW;
198
+ }
199
+
200
+ export interface TokenUsageCoverage {
201
+ reporting_nodes: number;
202
+ /** 会话里能解析出版本、且版本 >= 阈值的数量(能力分母) */
203
+ capable_nodes: number;
204
+ sessions_with_version: number;
205
+ /** 解析不出版本线的会话数(不含在 capable 里,也不假装它们不能报) */
206
+ sessions_without_known_version: number;
207
+ }
208
+
209
+ export function tokenUsageCoverage(
210
+ networkId: string,
211
+ reportingNodes: number,
212
+ get: (sql: string, ...params: any[]) => Array<{ version: string | null }>,
213
+ ): TokenUsageCoverage {
214
+ const rows = get("SELECT version FROM sessions WHERE network_id = ?1", networkId);
215
+ let capable = 0, known = 0;
216
+ for (const r of rows) {
217
+ const verdict = reportsTokenUsage(r.version);
218
+ if (verdict === null) continue;
219
+ known += 1;
220
+ if (verdict) capable += 1;
221
+ }
222
+ return {
223
+ reporting_nodes: reportingNodes,
224
+ capable_nodes: capable,
225
+ sessions_with_version: known,
226
+ sessions_without_known_version: rows.length - known,
227
+ };
228
+ }
@@ -134,9 +134,11 @@ export function parseScheduleSpec(raw: unknown, timezoneRaw: unknown): { spec: S
134
134
 
135
135
  if (type === "once") {
136
136
  if (typeof obj.run_at !== "string") throw new Error("run_at_required");
137
- const when = new Date(obj.run_at);
138
- if (!Number.isFinite(when.getTime())) throw new Error("invalid_run_at");
139
- return { spec: { type, run_at: iso(when) }, timezone };
137
+ // #3951 —— 用户给的 run_at 走同一个入口:无时区标记的 'YYYY-MM-DDTHH:MM:SS'
138
+ // 若直接 new Date() 会按**本机时区**解释(hub 的列是 UTC 无标记)⇒ 跨时区差 8 小时。
139
+ const whenMs = parseHubTimestamp(obj.run_at);
140
+ if (whenMs === null) throw new Error("invalid_run_at");
141
+ return { spec: { type, run_at: iso(new Date(whenMs)) }, timezone };
140
142
  }
141
143
  if (type === "interval") {
142
144
  const every = Number(obj.every_seconds);
@@ -162,8 +164,11 @@ export function parseScheduleSpec(raw: unknown, timezoneRaw: unknown): { spec: S
162
164
  * platform timezone database instead of a hand-written offset guess. */
163
165
  export function nextOccurrence(spec: ScheduleSpec, timezone: string, after: Date): Date | null {
164
166
  if (spec.type === "once") {
165
- const when = new Date(spec.run_at);
166
- return when.getTime() > after.getTime() ? when : null;
167
+ // spec.run_at 由上面的 normalize 写出(总是带 Z),但仍然走同一个解析入口:
168
+ // 「这一处安全」是上一行写出来的事实,不是这一行能自己保证的。
169
+ const ms = parseHubTimestamp(spec.run_at);
170
+ if (ms === null) return null;
171
+ return ms > after.getTime() ? new Date(ms) : null;
167
172
  }
168
173
  if (spec.type === "interval") return new Date(after.getTime() + spec.every_seconds * 1000);
169
174
 
@@ -327,7 +332,7 @@ export function patchSchedule(row: ScheduledRow, body: Record<string, unknown>,
327
332
  ? null
328
333
  : schedulingChanged || backoffGenerationReset || resumed || !row.next_run_at
329
334
  ? nextOccurrence(parsed.spec, parsed.timezone, new Date())
330
- : new Date(row.next_run_at);
335
+ : new Date(parseHubTimestamp(row.next_run_at) ?? Date.now());
331
336
  if (requestedStatus === "active" && !next) throw new Error("schedule_has_no_future_occurrence");
332
337
  // Runs no longer bump revision, so the scheduler may have advanced
333
338
  // next_run_at after `row` was read. When cadence is preserved, keep the
package/src/server.ts CHANGED
@@ -108,7 +108,7 @@ import { startDueReminderTimer } from "./requirement-due-reminders.js";
108
108
  import { clearNodeFromRequirements, handleRequirementsRequest } from "./requirements.js";
109
109
  import { readHubProviders, putHubProvider, providerWriteStatus } from "./hub-provider-config.js";
110
110
  import { readLastConfigUpdate } from "./node-config-last-update.js";
111
- import { readTokenUsage } from "./node-token-usage.js";
111
+ import { readTokenUsage, tokenUsageCoverage } from "./node-token-usage.js";
112
112
  import { readBuildInfo } from "./build-info.js";
113
113
  import { requestProviderApplication } from "./daemon-provider-snapshots.js";
114
114
  import { requestNodeSecrets, getScopedSecrets } from "./scoped-secrets.js";
@@ -6405,10 +6405,12 @@ return Bun.serve({
6405
6405
  const resolved = token ? resolveToken(token) : null;
6406
6406
  if (!resolved) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
6407
6407
  if (isNodeCredential(resolved)) return withCors(req, Response.json({ ok: false, error: "user_token_required" }, { status: 403 }));
6408
- const netId = getNetworkId(url.searchParams.get("network_id") ?? undefined);
6408
+ // 作用域用 handler 顶部已解析的 restScope —— 它已经做过「是不是这个网络的成员」,
6409
+ // 且 denied 分支在上面统一 return 403。**不要**再在这里自己查一次网络:
6410
+ // 上一版调了一个本文件里不存在的 `getNetworkId()` ⇒ 这个端点自 .273 上线起一直 500,
6411
+ // 而所有人都只会看到「空了」,不会看到「坏了」。(#3951 由 HTTP 测试抓出)
6412
+ const netId = restScope.networkId;
6409
6413
  if (!netId) return withCors(req, Response.json({ ok: false, error: "network_required" }, { status: 400 }));
6410
- const role = resolved.user.role === "admin" ? "admin" : getUserNetworkRole(resolved.user.user_id, netId);
6411
- if (!role) return withCors(req, Response.json({ ok: false, error: "not a member of this network" }, { status: 403 }));
6412
6414
  const raw = Number(url.searchParams.get("since_hours") ?? 24);
6413
6415
  const sinceHours = Number.isFinite(raw) ? Math.max(1, Math.min(24 * 90, Math.floor(raw))) : 24;
6414
6416
  const nodes = readTokenUsage(netId, sinceHours);
@@ -6425,6 +6427,8 @@ return Bun.serve({
6425
6427
  // 空表也要说清口径:0 行可能因为「没人上报」,也可能因为「窗口里没用量」。
6426
6428
  note: nodes.length ? undefined : "这个窗口里没有任何节点上报过 token 用量(不是「用量为 0」)",
6427
6429
  nodes, totals,
6430
+ // #3950 —— 分母。只有 1 行时,读表的人必须能分清「只有 1 台在干活」还是「只有 1 台有这能力」。
6431
+ coverage: tokenUsageCoverage(netId, nodes.length, (sql: string, ...params: any[]) => db.all(sql, ...params)),
6428
6432
  }));
6429
6433
  }
6430
6434
 
@@ -123,7 +123,11 @@ describe("task consumed_at identity and lifecycle", () => {
123
123
  // 游标 :多一个 capability = "list_tasks.immutable-node-cursor.v1"
124
124
  // 只断言 capability 的值时,「顺手把它也加到非游标那条」不会有东西变红。
125
125
  // 实测五键:我按源码读成三键(漏了 count 与 stats)——又一次「按代码读会少」
126
- expect(Object.keys(first).sort()).toEqual(["capability", "count", "next_cursor", "ok", "stats", "tasks"]);
126
+ // 🔴 2026-11-05 再变一次(#3119 since_last 水位):游标出口多了 `server_time`(下一次的入参)
127
+ // 与 `stats_omitted`(节点令牌默认省 stats,于是 `stats` 只是一个**省略**标记而不是读数)。
128
+ // ⇒ 这条断言从「六个键」变成「七个键」,而变的是**语义**不是措辞:
129
+ // 有 server_time ⇒ 调用方可以拿它做增量;有 stats_omitted ⇒ 「没有 stats」不再等于「stats 是空」。
130
+ expect(Object.keys(first).sort()).toEqual(["capability", "count", "next_cursor", "ok", "server_time", "stats_omitted", "tasks"]);
127
131
  expect(first.capability).toBe("list_tasks.immutable-node-cursor.v1");
128
132
  expect(first.tasks).toHaveLength(100);
129
133
  const second = await call(handler, { from_node_id: `id_${NODE_A}`, durable_cursor: true, limit: 100, ...first.next_cursor });
@@ -0,0 +1,146 @@
1
+ // #3952/#3950 —— `GET /api/token-usage` 的 HTTP 面。
2
+ //
3
+ // 这个端点存在的理由是「人能看见节点消耗了多少 token」,所以它必须钉住四条:
4
+ //
5
+ // ① 节点令牌看不到(node 不是人 —— 与 catalog 读接口同一条边界);
6
+ // ② 别的网络的成员看不到本网络的用量(network 隔离);
7
+ // ③ **cache 不进 total**(实测 cache.read 可以是 total 的几百倍,
8
+ // 一旦混算,排行会变成「谁最老」而不是「谁用得最多」);
9
+ // ④ 空窗口要能分清「没人上报」与「用量为 0」—— 两者在表上同形。
10
+ //
11
+ // 另外钉住覆盖率的分母:只有 1 行时,读表的人不该把它读成「只有 1 台在干活」。
12
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
13
+ import { mkdtempSync, rmSync } from "node:fs";
14
+ import { tmpdir } from "node:os";
15
+ import { join } from "node:path";
16
+
17
+ const PRIVATE_DB_DIR = mkdtempSync(join(tmpdir(), "anet-token-usage-"));
18
+ process.env.COMMHUB_DB ||= join(PRIVATE_DB_DIR, "hub.db");
19
+
20
+ let server: ReturnType<typeof Bun.serve>;
21
+ let base = "";
22
+ let ownerToken = "", strangerToken = "", nodeToken = "";
23
+ let ownerNet = "", strangerNet = "";
24
+ // 路径写成字面量常量:`scripts/report-rest-visibility.py` 用「测试里出现带引号的完整路径」
25
+ // 判断这条路由有没有被请求过;模板串里拼参数会让它记成「从未被请求」。
26
+ const TOKEN_USAGE = "/api/token-usage";
27
+
28
+ const get = async (path: string, token?: string) => {
29
+ const headers: Record<string, string> = {};
30
+ if (token) headers.Authorization = `Bearer ${token}`;
31
+ const r = await fetch(`${base}${path}`, { headers });
32
+ const text = await r.text();
33
+ let body: any = null;
34
+ try { body = JSON.parse(text); } catch { body = null; }
35
+ return { status: r.status, body, text };
36
+ };
37
+
38
+ beforeAll(async () => {
39
+ const { db } = await import("./db.js");
40
+ // 建表发生在 node-token-usage 模块被 import 时(刻意的:只要 import 了它,表就一定在)。
41
+ // 不先 import 就直接 INSERT ⇒ "no such table",而那个错误看起来像"迁移没跑"。
42
+ await import("./node-token-usage.js");
43
+ const { register, createNetworkTokenForNode } = await import("./auth.js");
44
+ const stamp = Date.now();
45
+
46
+ const owner = register(`tu_owner_${stamp}`, "TuOwner-Strong-1!");
47
+ const stranger = register(`tu_stranger_${stamp}`, "TuStranger-Strong-1!");
48
+ expect(owner.ok && stranger.ok).toBe(true);
49
+ ownerToken = owner.token!;
50
+ strangerToken = stranger.token!;
51
+ ownerNet = owner.network_id!;
52
+ strangerNet = stranger.network_id!;
53
+
54
+ const ownerUserId = db.get<{ user_id: string }>(
55
+ "SELECT user_id FROM users WHERE username = ?1", `tu_owner_${stamp}`)!.user_id;
56
+ const nodeTok = createNetworkTokenForNode(ownerUserId, ownerNet, "tu-node", "n_tu_test");
57
+ expect(nodeTok.ok).toBe(true);
58
+ nodeToken = nodeTok.token!;
59
+
60
+ // 两行用量:一行大(cache 远大于 body),一行小。
61
+ const now = new Date();
62
+ const hour = `${now.toISOString().slice(0, 13)}`;
63
+ db.run(
64
+ `INSERT INTO node_token_usage (network_id, node_id, hour, model, input_tokens, output_tokens, cache_read_tokens)
65
+ VALUES (?1, 'n_tu_a', ?2, 'm1', 1000, 500, 900000)`,
66
+ [ownerNet, hour],
67
+ );
68
+ db.run(
69
+ `INSERT INTO node_token_usage (network_id, node_id, hour, model, input_tokens, output_tokens, cache_read_tokens)
70
+ VALUES (?1, 'n_tu_b', ?2, 'm2', 10, 5, 100)`,
71
+ [ownerNet, hour],
72
+ );
73
+ // 另一个网络的行:绝不能出现在 owner 的读数里。
74
+ db.run(
75
+ `INSERT INTO node_token_usage (network_id, node_id, hour, model, input_tokens, output_tokens, cache_read_tokens)
76
+ VALUES (?1, 'n_tu_x', ?2, 'mx', 77777, 77777, 77777)`,
77
+ [strangerNet, hour],
78
+ );
79
+
80
+ // 覆盖率分母靠 sessions.version 判定:一台 >= .180(会报),一台旧版(不会报)。
81
+ db.run(
82
+ `INSERT INTO sessions (resume_id, alias, node_id, network_id, status, version)
83
+ VALUES ('tu-s1', 'tu-capable', 'n_tu_a', ?1, 'idle', '2.5.0-preview.181')`,
84
+ [ownerNet],
85
+ );
86
+ db.run(
87
+ `INSERT INTO sessions (resume_id, alias, node_id, network_id, status, version)
88
+ VALUES ('tu-s2', 'tu-old', 'n_tu_b', ?1, 'idle', '2.5.0-preview.164')`,
89
+ [ownerNet],
90
+ );
91
+
92
+ // 用 bootServer 而不是 app.fetch:server.ts 只导出 bootServer(没有默认导出的 handler)。
93
+ const mod: any = await import("./server.js");
94
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
95
+ base = `http://127.0.0.1:${server.port}`;
96
+ });
97
+
98
+ afterAll(() => {
99
+ server?.stop(true);
100
+ rmSync(PRIVATE_DB_DIR, { recursive: true, force: true });
101
+ });
102
+
103
+ describe("#3952 /api/token-usage", () => {
104
+ test("本人网络:拿得到两行,且 total = input + output(cache 不进 total)", async () => {
105
+ const r = await get(`${TOKEN_USAGE}?network_id=${ownerNet}&since_hours=24`, ownerToken);
106
+ expect(r.status).toBe(200);
107
+ const nodes = r.body.nodes as any[];
108
+ expect(nodes.length).toBe(2);
109
+ expect(r.body.totals.input_tokens).toBe(1010);
110
+ expect(r.body.totals.output_tokens).toBe(505);
111
+ expect(r.body.totals.total_tokens).toBe(1515);
112
+ // 镜像:cache 单列存在,且**不等于** total —— 混算的话这里会相等
113
+ expect(r.body.totals.cache_read_tokens).toBe(900100);
114
+ expect(r.body.totals.cache_read_tokens).not.toBe(r.body.totals.total_tokens);
115
+ // 别的网络的行不在里面
116
+ expect(nodes.every((n: any) => n.node_id !== "n_tu_x")).toBe(true);
117
+ });
118
+
119
+ test("节点令牌看不到(user_token_required,不是 404 也不是空表)", async () => {
120
+ const r = await get(`${TOKEN_USAGE}?network_id=${ownerNet}`, nodeToken);
121
+ expect(r.status).toBe(403);
122
+ expect(r.body.error).toBe("user_token_required");
123
+ });
124
+
125
+ test("别的网络的成员看不到(not a member,且不泄漏行数)", async () => {
126
+ const r = await get(`${TOKEN_USAGE}?network_id=${ownerNet}`, strangerToken);
127
+ expect(r.status).toBe(403);
128
+ expect(r.body.nodes).toBeUndefined();
129
+ });
130
+
131
+ test("没令牌:401 而不是空表", async () => {
132
+ const r = await get(`${TOKEN_USAGE}?network_id=${ownerNet}`);
133
+ expect(r.status).toBe(401);
134
+ });
135
+
136
+ test("覆盖率分母:capable 只数 >= .180,不等于会话总数", async () => {
137
+ const r = await get(`${TOKEN_USAGE}?network_id=${ownerNet}&since_hours=24`, ownerToken);
138
+ expect(r.status).toBe(200);
139
+ const cov = r.body.coverage;
140
+ expect(cov.reporting_nodes).toBe(2);
141
+ expect(cov.capable_nodes).toBe(1);
142
+ expect(cov.sessions_with_version).toBe(2);
143
+ // 镜像:分母比分子大 ⇒ 这个字段不是把 reporting_nodes 复制了一遍
144
+ expect(cov.sessions_with_version).toBeGreaterThan(cov.capable_nodes);
145
+ });
146
+ });
package/src/tools.ts CHANGED
@@ -863,18 +863,18 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
863
863
 
864
864
  server.tool(
865
865
  "report_status",
866
- "Report agent status. Returns inbox_count.",
866
+ "Report status; returns inbox_count.",
867
867
  {
868
- resume_id: z.string().min(1).max(200).describe("Claude Code session UUID (unique per session)"),
869
- alias: z.string().min(1).max(200).describe("Human-readable session name for dispatching (e.g. 指挥室/知识哥)"),
868
+ resume_id: z.string().min(1).max(200).describe("Session UUID"),
869
+ alias: z.string().min(1).max(200).describe("Session alias for dispatch"),
870
870
  status: z.enum(["working", "idle", "blocked", "error", "waiting_input", "offline"]),
871
- task: z.string().max(TASK_CONTENT_MAX).optional().describe("Task (session stores 200 chars; full text matches tasks.content)"),
872
- output: z.string().max(50000).optional().describe("Recent output (max 4000 chars stored)"),
871
+ task: z.string().max(TASK_CONTENT_MAX).optional().describe("Task (200 chars stored)"),
872
+ output: z.string().max(50000).optional().describe("Recent output (4k stored)"),
873
873
  score: z.number().min(0).max(10).optional().describe("Self-score 1-10"),
874
874
  progress: z.number().min(0).max(100).optional().describe("Progress 0-100"),
875
875
  server: z.string().max(200).optional().describe("Server identifier"),
876
876
  hostname: z.string().max(200).optional().describe("Agent hostname"),
877
- agent: z.string().max(100).optional().describe("Agent type (claude-code / codex / opencode)"),
877
+ agent: z.string().max(100).optional().describe("Agent type"),
878
878
  project_dir: z.string().max(1000).optional().describe("Agent working directory"),
879
879
  // #1198 — OS account the process runs as (platform identity only; no env fallback).
880
880
  os_user: z.string().min(1).max(256).optional().describe("OS account"),
@@ -896,8 +896,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
896
896
  config_path: z.string().max(1000).optional().describe("Config file path"),
897
897
  channels: z.string().max(2000).optional().describe("JSON array of channels"),
898
898
  model: z.string().max(200).optional().describe("AI model name"),
899
- node_name: z.string().max(200).optional().describe("Stable node display name (may differ from alias)"),
900
- network_id: z.string().max(200).optional().describe("Network this agent belongs to"),
899
+ node_name: z.string().max(200).optional().describe("Node display name"),
900
+ network_id: z.string().max(200).optional().describe("Network id"),
901
901
  // ╭─ 🔴 往 report_status 里加字段之前先读这一段(#1545 实测,zod 4.3.6)─────────╮
902
902
  // │ **这份 schema 的子对象一半严一半松,而后果完全不同。**
903
903
  // │
@@ -939,7 +939,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
939
939
  disk_total_gb: z.number().nullable().optional(),
940
940
  disk_used_gb: z.number().nullable().optional(),
941
941
  disk_avail_gb: z.number().nullable().optional(),
942
- }).optional().describe("Host telemetry reported by agent-node"),
942
+ }).optional().describe("Host telemetry"),
943
943
  process_telemetry: z.object({
944
944
  rss_bytes: z.number().nullable().optional(),
945
945
  rss_mb: z.number().nullable().optional(),
@@ -947,7 +947,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
947
947
  cpu_pct: z.number().nullable().optional(),
948
948
  uptime_seconds: z.number().nullable().optional(),
949
949
  in_flight_count: z.number().nullable().optional(),
950
- }).optional().describe("Per-agent process telemetry reported by agent-node"),
950
+ }).optional().describe("Process telemetry"),
951
951
  external_schedules: z.object({
952
952
  observed_at: z.string().datetime({ offset: true }).max(64),
953
953
  schedules: z.array(z.object({
@@ -967,7 +967,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
967
967
  revision: z.number().int().min(0).optional(),
968
968
  }).strict()).max(64),
969
969
  error: z.enum(["invalid_manifest", "unsafe_manifest", "read_failed"]).optional(),
970
- }).strict().optional().describe("Node-reported schedules; never includes host paths or commands"),
970
+ }).strict().optional().describe("External schedules (no paths)"),
971
971
  // RFC-024 B6 — masked snapshot of the node's effective config
972
972
  // (model + 6 dashboard-editable flags). Secrets ARE NOT in this
973
973
  // shape (env._envRef stays on host); the dashboard reads this
@@ -2071,8 +2071,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2071
2071
  from_session: z.string().max(200).optional(),
2072
2072
  ttl_seconds: z.number().min(1).max(86400).optional().describe("Task TTL in seconds (default: 3600)"),
2073
2073
  network_id: z.string().max(200).optional().describe("Network scope"),
2074
- parent_task_id: z.string().max(200).optional().describe("Parent task this dispatch is on behalf of. The child's reply is auto-chained to the parent's originator, so the user sees the result even if the intermediate session ends."),
2075
- meta: z.any().optional().describe("Optional task metadata, e.g. { attachments: [{ type, path, url, mime, name, size }] }."),
2074
+ parent_task_id: z.string().max(200).optional().describe("Parent task this dispatch serves; the reply auto-chains to its originator."),
2075
+ meta: z.any().optional().describe("Optional task metadata, e.g. { attachments: [{type,path,url,mime,name,size}] }."),
2076
2076
  force: z.boolean().optional().describe("dispatch even if the target is degraded (user tokens only)"),
2077
2077
  },
2078
2078
  async ({ alias, task, priority, context, from_session: _fromIn, ttl_seconds, network_id: netId, parent_task_id: parentIn, meta, force }) => {
@@ -2134,7 +2134,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2134
2134
  recentSql += " ORDER BY created_at DESC LIMIT 5";
2135
2135
  const cands = db.all<{ task_id: string; created_at: string | null }>(recentSql, ...recentParams);
2136
2136
  const verdict = decideParentInference(
2137
- cands.map((c) => ({ task_id: c.task_id, created_at_ms: c.created_at ? Date.parse(c.created_at) : null })),
2137
+ cands.map((c) => ({ task_id: c.task_id, created_at_ms: parseHubTimestamp(c.created_at) })),
2138
2138
  Date.now(),
2139
2139
  );
2140
2140
  if (verdict.ok) {
@@ -3127,17 +3127,17 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3127
3127
  // 是最大的一格:每次轮询都拉全量再自己筛。给它一个「只要这之后创建的」,
3128
3128
  // 空窗口就回极短体,比任何提示词都省(提示词只能劝,改不了接口成本)。
3129
3129
  created_since: z.string().max(64).optional()
3130
- .describe("Only tasks created after this timestamp (ISO 8601 or 'YYYY-MM-DD HH:MM:SS'). Use the previous response's server_time as the next value."),
3130
+ .describe("Only tasks created after this (ISO 8601 or 'YYYY-MM-DD HH:MM:SS'); pass previous server_time."),
3131
3131
  // #3119 —— stats 是全表 GROUP BY:轮询时它比任务列表本身还贵。
3132
3132
  // #3119 —— 不给 `.default(false)`:要能区分「没传」与「显式传 false」。
3133
3133
  // 节点令牌没传时默认省略 stats(它是给「看图的人」用的计数,轮询的节点不读它);
3134
3134
  // 显式传 false 仍然可以要回来。用户令牌保持旧行为(默认返回 stats)。
3135
3135
  omit_stats: z.boolean().optional()
3136
- .describe("Skip the per-status counts (they scan every task in scope). Defaults to true for node tokens, false otherwise."),
3136
+ .describe("Skip per-status counts (they scan every task in scope). Default true for node tokens."),
3137
3137
  // #3943 —— 服务端水位。调用方不传时间,Hub 用「上次给这个调用者返回的时刻」当下界,
3138
3138
  // 返回后把水位推到本次的 server_time。客户端连时钟都不用记(也就不会因两边差几秒漏活)。
3139
3139
  since_last: z.boolean().optional().default(false)
3140
- .describe("Only tasks created since this caller's previous list_tasks call. Server keeps the watermark."),
3140
+ .describe("Only tasks created since this caller's previous list_tasks (watermark kept server-side)."),
3141
3141
  },
3142
3142
  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 }) => {
3143
3143
  const readScope = resolveReadScope(netId);
@@ -3439,7 +3439,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3439
3439
  kind: z.string().min(1).max(80).optional().default("agent_message"),
3440
3440
  meta: z.record(z.string(), z.unknown()).optional(),
3441
3441
  from_session: z.string().max(200).optional(),
3442
- network_id: z.string().max(200).optional().describe("Network scope (auto-resolved for single-network user tokens; ntok stays bound to its network)."),
3442
+ network_id: z.string().max(200).optional().describe("Network scope (auto-resolved for single-network user tokens; ntok stays bound)."),
3443
3443
  },
3444
3444
  async ({ to_user_id, to_username, title, message, severity, kind, meta, from_session: _fromIn, network_id: netId }) => {
3445
3445
  const fromMismatch = fromIdentityMismatchReply(_fromIn);
@@ -3716,7 +3716,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3716
3716
  "Set the per-node config (model + flags) and push a doorbell; the node pulls, validates and applies (hot or restart per field). RFC-024.",
3717
3717
  {
3718
3718
  ...NODE_ID_ALIAS_FIELDS,
3719
- base_revision: z.number().int().min(0).describe("Current revision per the dashboard's last GET — 409 if hub's current revision differs."),
3719
+ base_revision: z.number().int().min(0).describe("Revision from the dashboard's last GET — 409 if the hub's differs."),
3720
3720
  patch: z.object({
3721
3721
  model: z.string().max(200).optional(),
3722
3722
  flags: z.record(z.string(), z.unknown()).optional(),
@@ -4429,7 +4429,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
4429
4429
  lines: z.number().int().min(1).max(LOGS_MAX_LINES).optional().describe("How many of the newest matching lines (default 500, max 2000)."),
4430
4430
  level: z.enum(["info", "warn", "error"]).optional().describe("Only lines of exactly this level."),
4431
4431
  grep: z.string().min(1).max(LOGS_GREP_MAX).optional().describe("Case-insensitive substring, matched after redaction."),
4432
- since_ts: z.number().int().min(0).optional().describe("Only lines at/after this epoch-ms timestamp (follow mode; client de-dupes by line key)."),
4432
+ since_ts: z.number().int().min(0).optional().describe("Only lines at/after this epoch-ms (follow mode; client de-dupes by line key)."),
4433
4433
  network_id: z.string().max(200).optional(),
4434
4434
  },
4435
4435
  async ({ node_id, child_node_id, alias, lines, level, grep, since_ts, network_id }) =>
@@ -7130,9 +7130,9 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
7130
7130
  description: z.string().max(20_000).optional().describe("markdown"),
7131
7131
  checklist: z.array(reqChecklistItem).max(100).optional().describe("replaces the whole list"),
7132
7132
  project_id: z.string().max(200).nullable().optional(),
7133
- owner: reqPerson.nullable().optional().describe("负责人 (a person): {kind:'user', id | username} (ids / usernames from requirements_people; names resolve in the task's network); a node is rejected with owner_must_be_human — use agent_owner"),
7133
+ owner: reqPerson.nullable().optional().describe("Owner (person): {kind:'user', id|username} from requirements_people; a node gets owner_must_be_human — use agent_owner"),
7134
7134
  agent_owner: reqPerson.nullable().optional().describe("负责 Agent: {kind:'node', id | alias}"),
7135
- participants: z.array(reqPerson).max(100).optional().describe("REPLACES the whole list (like owner/agent_owner; omitted people are removed, [] clears). For a few, use participants_add/participants_remove."),
7135
+ participants: z.array(reqPerson).max(100).optional().describe("REPLACES the list (omitted removed; [] clears). For a few use participants_add/_remove."),
7136
7136
  external_url: z.string().max(500).nullable().optional(),
7137
7137
  parent_id: z.string().regex(/^[A-Za-z0-9_-]{1,200}$/).nullable().optional().describe("parent requirement (same network, no cycles, ≤ 5 levels); null detaches"),
7138
7138
  };
@@ -7167,13 +7167,13 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
7167
7167
  parent_id: z.string().max(200).optional().describe("children of this requirement ('none' = top level)"),
7168
7168
  department_id: z.string().max(64).optional().describe("owner (or its Agent's owner) in this department or below"),
7169
7169
  top_level: z.boolean().optional(), q: z.string().max(200).optional(),
7170
- overdue: z.boolean().optional().describe("true = open tasks whose due is past (date-only: before today, Asia/Shanghai); false = rest"),
7170
+ overdue: z.boolean().optional().describe("true = open tasks past due (date-only: before today, Asia/Shanghai); false = rest"),
7171
7171
  due_within_days: z.number().int().min(0).max(365).optional().describe("open tasks not yet overdue, due by the end of today + N days (0 = later today)"),
7172
7172
  limit: z.number().int().min(1).max(1000).optional().describe(`page size, default ${REQ_LIST_MCP_DEFAULT_LIMIT}`),
7173
7173
  cursor: z.string().max(600).optional().describe("next_cursor from the previous page"),
7174
- view: z.enum(["full", "summary"]).optional().describe("default summary (no bodies; has_description/checklist_count instead); full = everything"),
7175
- changes: z.boolean().optional().describe("with updated_since: only tasks changed since then (incl. archived; +deleted ids +server_time; with include_last_event also newer events)"),
7176
- include_last_event: z.boolean().optional().describe("default false; true adds last_event per row (~150 B/row: type, field, actor, at, summary; null if none)"),
7174
+ view: z.enum(["full", "summary"]).optional().describe("default summary (no bodies; has_description/checklist_count); full = everything"),
7175
+ changes: z.boolean().optional().describe("with updated_since: only tasks changed since then (+deleted ids +server_time; with include_last_event also newer events)"),
7176
+ include_last_event: z.boolean().optional().describe("default false; true adds last_event per row (~150 B: type/field/actor/at/summary; null if none)"),
7177
7177
  };
7178
7178
  const reqListKeys = Object.keys(reqListShape);
7179
7179
  server.registerTool(