@sleep2agi/commhub-server 0.9.0-preview.271 → 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": "00f6a6f5fc79688f5242eb71cb1b5322bfd93f4c",
3
+ "commit": "a10fa363e362c705a212eb1ad883fdc72dc4499c",
4
4
  "dirty": false,
5
- "built_at": "2026-11-05T14:24:34.049Z",
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.271",
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",
@@ -64,6 +64,15 @@ describe("#3952 节点 Token 审计", () => {
64
64
  expect(rows[0].total_tokens).toBe(2);
65
65
  });
66
66
 
67
+ test("cache 单列:报进去不进 total(它是 input 的几百倍,混算会把排行变成「谁最老」)", () => {
68
+ cleanup();
69
+ const hour = currentHourUtc();
70
+ reportTokenUsage({ networkId: net, nodeId: nodeA, hour, model: 'm', inputTokens: 100, outputTokens: 10, cacheReadTokens: 50_000 });
71
+ const rows = readTokenUsage(net, 24);
72
+ expect(rows[0].total_tokens).toBe(110);
73
+ expect(rows[0].cache_read_tokens).toBe(50_000);
74
+ });
75
+
67
76
  test("④ 形状:表里没有任何内容列(prompt / message / credential 一律不存在)", () => {
68
77
  const shape = [...NODE_TOKEN_USAGE_COLUMNS].join(",");
69
78
  expect(shape).not.toMatch(/prompt|message|content|credential|secret|token_value/i);
@@ -88,3 +97,32 @@ describe("#3952 节点 Token 审计", () => {
88
97
  expect(norm?.costUsd).toBeNull();
89
98
  });
90
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
+ });
@@ -29,6 +29,7 @@ db.exec(`
29
29
  model TEXT NOT NULL DEFAULT 'unknown',
30
30
  input_tokens INTEGER NOT NULL DEFAULT 0,
31
31
  output_tokens INTEGER NOT NULL DEFAULT 0,
32
+ cache_read_tokens INTEGER NOT NULL DEFAULT 0,
32
33
  turns INTEGER NOT NULL DEFAULT 0,
33
34
  cost_usd REAL NOT NULL DEFAULT 0,
34
35
  updated_at TEXT NOT NULL DEFAULT (datetime('now')),
@@ -36,6 +37,8 @@ db.exec(`
36
37
  );
37
38
  CREATE INDEX IF NOT EXISTS idx_node_token_usage_hour ON node_token_usage(network_id, hour);
38
39
  `);
40
+ // 已存在的库补列(SQLite 没有 IF NOT EXISTS for ADD COLUMN)
41
+ try { db.exec("ALTER TABLE node_token_usage ADD COLUMN cache_read_tokens INTEGER NOT NULL DEFAULT 0"); } catch {}
39
42
 
40
43
  export interface TokenUsageInput {
41
44
  networkId: string;
@@ -46,6 +49,9 @@ export interface TokenUsageInput {
46
49
  model?: string | null;
47
50
  inputTokens?: number | null;
48
51
  outputTokens?: number | null;
52
+ /** 缓存命中的读入量。**必须单列**:opencode 实测 cache.read 是 input+output 的 289 倍,
53
+ * 混进去算会让「谁用得多」变成「谁用得久」。 */
54
+ cacheReadTokens?: number | null;
49
55
  /** 有的运行时只给总轮数/费用;没有就留空,**不填 0**(0 与"不知道"是两件事) */
50
56
  turns?: number | null;
51
57
  costUsd?: number | null;
@@ -67,7 +73,7 @@ function nonNegativeInt(value: unknown): number | null {
67
73
  /** 校验 + 归一。返回 null 表示「这一份上报不合规」——调用方负责拒绝,不静默丢。 */
68
74
  export function normalizeUsage(input: TokenUsageInput): {
69
75
  hour: string; model: string;
70
- inputTokens: number; outputTokens: number;
76
+ inputTokens: number; outputTokens: number; cacheReadTokens: number;
71
77
  turns: number | null; costUsd: number | null;
72
78
  } | null {
73
79
  const hour = typeof input.hour === 'string' && input.hour ? input.hour : currentHourUtc();
@@ -77,14 +83,15 @@ export function normalizeUsage(input: TokenUsageInput): {
77
83
  const model = rawModel || 'unknown';
78
84
  const inputTokens = nonNegativeInt(input.inputTokens) ?? 0;
79
85
  const outputTokens = nonNegativeInt(input.outputTokens) ?? 0;
80
- if (inputTokens === 0 && outputTokens === 0 && input.turns == null && input.costUsd == null) {
86
+ const cacheReadTokens = nonNegativeInt(input.cacheReadTokens) ?? 0;
87
+ if (inputTokens === 0 && outputTokens === 0 && cacheReadTokens === 0 && input.turns == null && input.costUsd == null) {
81
88
  // 什么都没报:不写一行全 0 的记录(那会让"没有用量"和"没上报"在报表上同形)。
82
89
  return null;
83
90
  }
84
91
  const turns = nonNegativeInt(input.turns);
85
92
  const costRaw = input.costUsd;
86
93
  const costUsd = typeof costRaw === 'number' && Number.isFinite(costRaw) && costRaw >= 0 ? costRaw : null;
87
- return { hour, model, inputTokens, outputTokens, turns, costUsd };
94
+ return { hour, model, inputTokens, outputTokens, cacheReadTokens, turns, costUsd };
88
95
  }
89
96
 
90
97
  /** 记账:同一 (network, node, hour, model) 累加。turns/cost 可空,空则保持原值。 */
@@ -92,17 +99,19 @@ export function reportTokenUsage(input: TokenUsageInput): { ok: true; hour: stri
92
99
  const norm = normalizeUsage(input);
93
100
  if (!norm) return { ok: false, error: 'invalid_token_usage' };
94
101
  db.run(
95
- `INSERT INTO node_token_usage(network_id, node_id, hour, model, input_tokens, output_tokens, turns, cost_usd, updated_at)
96
- VALUES(?1, ?2, ?3, ?4, ?5, ?6, COALESCE(?7, 0), COALESCE(?8, 0), datetime('now'))
102
+ `INSERT INTO node_token_usage(network_id, node_id, hour, model, input_tokens, output_tokens, cache_read_tokens, turns, cost_usd, updated_at)
103
+ VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, COALESCE(?8, 0), COALESCE(?9, 0), datetime('now'))
97
104
  ON CONFLICT(network_id, node_id, hour, model) DO UPDATE SET
98
105
  input_tokens = input_tokens + excluded.input_tokens,
99
106
  output_tokens = output_tokens + excluded.output_tokens,
107
+ cache_read_tokens = cache_read_tokens + excluded.cache_read_tokens,
100
108
  turns = COALESCE(turns, 0) + COALESCE(excluded.turns, 0),
101
109
  cost_usd = COALESCE(cost_usd, 0) + COALESCE(excluded.cost_usd, 0),
102
110
  updated_at = datetime('now')`,
103
111
  // turns / cost_usd 这里存 0 = 「没有这一项」。**存储层不区分「0 轮」与「没报轮数」**,
104
112
  // 这是已知偏差(见文件头「已知边界」);要区分得加一列 has_turns,成本不值。
105
- [input.networkId, input.nodeId, norm.hour, norm.model, norm.inputTokens, norm.outputTokens, norm.turns, norm.costUsd],
113
+ [input.networkId, input.nodeId, norm.hour, norm.model, norm.inputTokens, norm.outputTokens,
114
+ norm.cacheReadTokens, norm.turns, norm.costUsd],
106
115
  );
107
116
  return { ok: true, hour: norm.hour, model: norm.model };
108
117
  }
@@ -112,7 +121,10 @@ export interface NodeTokenUsageRow {
112
121
  alias: string | null;
113
122
  input_tokens: number;
114
123
  output_tokens: number;
124
+ /** input+output(**不含 cache**)—— 报表默认看这个 */
115
125
  total_tokens: number;
126
+ /** 单列;opencode 上它可能是 total 的几百倍 */
127
+ cache_read_tokens: number;
116
128
  turns: number;
117
129
  cost_usd: number;
118
130
  models: number;
@@ -131,6 +143,9 @@ export function readTokenUsage(networkId: string, sinceHours = 24): NodeTokenUsa
131
143
  const rows = db.all<{
132
144
  node_id: string; alias: string | null;
133
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;
134
149
  turns: number; cost_usd: number; models: number;
135
150
  first_hour: string | null; last_hour: string | null;
136
151
  }>(
@@ -138,6 +153,7 @@ export function readTokenUsage(networkId: string, sinceHours = 24): NodeTokenUsa
138
153
  COALESCE(n.alias, s.alias) AS alias,
139
154
  SUM(u.input_tokens) AS input_tokens,
140
155
  SUM(u.output_tokens) AS output_tokens,
156
+ SUM(u.cache_read_tokens) AS cache_read_tokens,
141
157
  SUM(u.turns) AS turns,
142
158
  SUM(u.cost_usd) AS cost_usd,
143
159
  COUNT(DISTINCT u.model) AS models,
@@ -153,6 +169,7 @@ export function readTokenUsage(networkId: string, sinceHours = 24): NodeTokenUsa
153
169
  );
154
170
  return rows.map((r) => ({
155
171
  ...r,
172
+ cache_read_tokens: r.cache_read_tokens ?? 0,
156
173
  total_tokens: (r.input_tokens ?? 0) + (r.output_tokens ?? 0),
157
174
  }));
158
175
  }
@@ -160,5 +177,52 @@ export function readTokenUsage(networkId: string, sinceHours = 24): NodeTokenUsa
160
177
  /** 记账表与读账口径都只认这几个列 —— 形状就是「不收内容」的保证。 */
161
178
  export const NODE_TOKEN_USAGE_COLUMNS = [
162
179
  'network_id', 'node_id', 'hour', 'model',
163
- 'input_tokens', 'output_tokens', 'turns', 'cost_usd', 'updated_at',
180
+ 'input_tokens', 'output_tokens', 'cache_read_tokens', 'turns', 'cost_usd', 'updated_at',
164
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";
@@ -6394,22 +6394,7 @@ return Bun.serve({
6394
6394
  // {model, flags, config_revision} the node last posted via
6395
6395
  // report_status (B6). NEVER reads per-node files. Network-scoped
6396
6396
  // via addNetworkScope so a netA viewer can't read a netB node.
6397
- const nodeConfigMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)\/config$/);
6398
- if (nodeConfigMatch && req.method === "GET") {
6399
- const nodeId = decodeURIComponent(nodeConfigMatch[1] ?? "");
6400
- const params: any[] = [nodeId];
6401
- let sql = "SELECT node_id, alias, network_id, config_revision, config_snapshot FROM nodes WHERE node_id = ?1";
6402
- sql = addNetworkScope(sql, params, restScope);
6403
- sql += " LIMIT 1";
6404
- const node = db.get<any>(sql, ...params);
6405
- if (!node) {
6406
- return withCors(req, Response.json({ ok: false, error: "node_not_found", node_id: nodeId }, { status: 404 }));
6407
- }
6408
- let snapshot: any = {};
6409
- if (node.config_snapshot) {
6410
- try { snapshot = JSON.parse(node.config_snapshot); } catch { snapshot = {}; }
6411
- }
6412
- // ── #3952 Token 审计(admin 2026-11-05)──
6397
+ // ── #3952 Token 审计(admin 2026-11-05)──
6413
6398
  // GET /api/token-usage?network_id=…&since_hours=24
6414
6399
  // 人(成员/owner/admin)读本网络各节点的 LLM token 计数聚合;节点令牌不给(user_token_required)。
6415
6400
  // 为什么走 REST 而不是 MCP 工具:tools/list 的 user 预算只剩 ~500 B,
@@ -6420,28 +6405,49 @@ return Bun.serve({
6420
6405
  const resolved = token ? resolveToken(token) : null;
6421
6406
  if (!resolved) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
6422
6407
  if (isNodeCredential(resolved)) return withCors(req, Response.json({ ok: false, error: "user_token_required" }, { status: 403 }));
6423
- 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;
6424
6413
  if (!netId) return withCors(req, Response.json({ ok: false, error: "network_required" }, { status: 400 }));
6425
- const role = resolved.user.role === "admin" ? "admin" : getUserNetworkRole(resolved.user.user_id, netId);
6426
- if (!role) return withCors(req, Response.json({ ok: false, error: "not a member of this network" }, { status: 403 }));
6427
6414
  const raw = Number(url.searchParams.get("since_hours") ?? 24);
6428
6415
  const sinceHours = Number.isFinite(raw) ? Math.max(1, Math.min(24 * 90, Math.floor(raw))) : 24;
6429
6416
  const nodes = readTokenUsage(netId, sinceHours);
6430
6417
  const totals = nodes.reduce((acc, r) => ({
6431
6418
  input_tokens: acc.input_tokens + r.input_tokens,
6432
6419
  output_tokens: acc.output_tokens + r.output_tokens,
6420
+ // cache 单列:它可能是 total 的几百倍,绝不能加进 total
6421
+ cache_read_tokens: acc.cache_read_tokens + r.cache_read_tokens,
6433
6422
  total_tokens: acc.total_tokens + r.total_tokens,
6434
6423
  cost_usd: Number((acc.cost_usd + r.cost_usd).toFixed(6)),
6435
- }), { input_tokens: 0, output_tokens: 0, total_tokens: 0, cost_usd: 0 });
6424
+ }), { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, total_tokens: 0, cost_usd: 0 });
6436
6425
  return withCors(req, Response.json({
6437
6426
  ok: true, network_id: netId, since_hours: sinceHours,
6438
6427
  // 空表也要说清口径:0 行可能因为「没人上报」,也可能因为「窗口里没用量」。
6439
6428
  note: nodes.length ? undefined : "这个窗口里没有任何节点上报过 token 用量(不是「用量为 0」)",
6440
6429
  nodes, totals,
6430
+ // #3950 —— 分母。只有 1 行时,读表的人必须能分清「只有 1 台在干活」还是「只有 1 台有这能力」。
6431
+ coverage: tokenUsageCoverage(netId, nodes.length, (sql: string, ...params: any[]) => db.all(sql, ...params)),
6441
6432
  }));
6442
6433
  }
6443
6434
 
6444
- // #3146 —— 上一次下发的**结局**。没有这一格时,客户端只能靠
6435
+ const nodeConfigMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)\/config$/);
6436
+ if (nodeConfigMatch && req.method === "GET") {
6437
+ const nodeId = decodeURIComponent(nodeConfigMatch[1] ?? "");
6438
+ const params: any[] = [nodeId];
6439
+ let sql = "SELECT node_id, alias, network_id, config_revision, config_snapshot FROM nodes WHERE node_id = ?1";
6440
+ sql = addNetworkScope(sql, params, restScope);
6441
+ sql += " LIMIT 1";
6442
+ const node = db.get<any>(sql, ...params);
6443
+ if (!node) {
6444
+ return withCors(req, Response.json({ ok: false, error: "node_not_found", node_id: nodeId }, { status: 404 }));
6445
+ }
6446
+ let snapshot: any = {};
6447
+ if (node.config_snapshot) {
6448
+ try { snapshot = JSON.parse(node.config_snapshot); } catch { snapshot = {}; }
6449
+ }
6450
+ // #3146 —— 上一次下发的**结局**。没有这一格时,客户端只能靠
6445
6451
  // 「config_revision 有没有涨」推断,涨不了就一律显示成 timeout(「90s 内没回来,去看日志」),
6446
6452
  // 而生产上真实结局是 rejected,原因(OpenCode V2 session is not running)就写在本库里。
6447
6453
  // ⇒ 读者拿不到答案,于是被指去机器上看日志 —— 一句话把人送错了层。
@@ -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);
@@ -3308,10 +3308,11 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3308
3308
  model: z.string().max(100).optional(),
3309
3309
  input_tokens: z.number().int().min(0).optional(),
3310
3310
  output_tokens: z.number().int().min(0).optional(),
3311
+ cache_read_tokens: z.number().int().min(0).optional(),
3311
3312
  turns: z.number().int().min(0).optional(),
3312
3313
  cost_usd: z.number().min(0).optional(),
3313
3314
  },
3314
- async ({ hour, model, input_tokens, output_tokens, turns, cost_usd }) => {
3315
+ async ({ hour, model, input_tokens, output_tokens, cache_read_tokens, turns, cost_usd }) => {
3315
3316
  if (!callerTokenIsNetwork || !enforceNetworkId || !callerAlias) {
3316
3317
  return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "network_token_required" }) }] };
3317
3318
  }
@@ -3321,6 +3322,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3321
3322
  networkId: enforceNetworkId, nodeId: node.node_id,
3322
3323
  hour: hour ?? null, model: model ?? null,
3323
3324
  inputTokens: input_tokens ?? null, outputTokens: output_tokens ?? null,
3325
+ cacheReadTokens: cache_read_tokens ?? null,
3324
3326
  turns: turns ?? null, costUsd: cost_usd ?? null,
3325
3327
  });
3326
3328
  return { content: [{ type: "text" as const, text: JSON.stringify(r) }] };
@@ -3437,7 +3439,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3437
3439
  kind: z.string().min(1).max(80).optional().default("agent_message"),
3438
3440
  meta: z.record(z.string(), z.unknown()).optional(),
3439
3441
  from_session: z.string().max(200).optional(),
3440
- 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)."),
3441
3443
  },
3442
3444
  async ({ to_user_id, to_username, title, message, severity, kind, meta, from_session: _fromIn, network_id: netId }) => {
3443
3445
  const fromMismatch = fromIdentityMismatchReply(_fromIn);
@@ -3714,7 +3716,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3714
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.",
3715
3717
  {
3716
3718
  ...NODE_ID_ALIAS_FIELDS,
3717
- 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."),
3718
3720
  patch: z.object({
3719
3721
  model: z.string().max(200).optional(),
3720
3722
  flags: z.record(z.string(), z.unknown()).optional(),
@@ -4427,7 +4429,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
4427
4429
  lines: z.number().int().min(1).max(LOGS_MAX_LINES).optional().describe("How many of the newest matching lines (default 500, max 2000)."),
4428
4430
  level: z.enum(["info", "warn", "error"]).optional().describe("Only lines of exactly this level."),
4429
4431
  grep: z.string().min(1).max(LOGS_GREP_MAX).optional().describe("Case-insensitive substring, matched after redaction."),
4430
- 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)."),
4431
4433
  network_id: z.string().max(200).optional(),
4432
4434
  },
4433
4435
  async ({ node_id, child_node_id, alias, lines, level, grep, since_ts, network_id }) =>
@@ -7128,9 +7130,9 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
7128
7130
  description: z.string().max(20_000).optional().describe("markdown"),
7129
7131
  checklist: z.array(reqChecklistItem).max(100).optional().describe("replaces the whole list"),
7130
7132
  project_id: z.string().max(200).nullable().optional(),
7131
- 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"),
7132
7134
  agent_owner: reqPerson.nullable().optional().describe("负责 Agent: {kind:'node', id | alias}"),
7133
- 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."),
7134
7136
  external_url: z.string().max(500).nullable().optional(),
7135
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"),
7136
7138
  };
@@ -7165,13 +7167,13 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
7165
7167
  parent_id: z.string().max(200).optional().describe("children of this requirement ('none' = top level)"),
7166
7168
  department_id: z.string().max(64).optional().describe("owner (or its Agent's owner) in this department or below"),
7167
7169
  top_level: z.boolean().optional(), q: z.string().max(200).optional(),
7168
- 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"),
7169
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)"),
7170
7172
  limit: z.number().int().min(1).max(1000).optional().describe(`page size, default ${REQ_LIST_MCP_DEFAULT_LIMIT}`),
7171
7173
  cursor: z.string().max(600).optional().describe("next_cursor from the previous page"),
7172
- view: z.enum(["full", "summary"]).optional().describe("default summary (no bodies; has_description/checklist_count instead); full = everything"),
7173
- 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)"),
7174
- 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)"),
7175
7177
  };
7176
7178
  const reqListKeys = Object.keys(reqListShape);
7177
7179
  server.registerTool(