@sleep2agi/commhub-server 0.9.0-preview.267 → 0.9.0-preview.269

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": "54d87dd2c5a1d5261b5953a6fc1204e34024c0cb",
3
+ "commit": "5ab2d97f46837423a72c1270c2bc6750cdad898b",
4
4
  "dirty": false,
5
- "built_at": "2026-11-05T12:41:26.525Z",
5
+ "built_at": "2026-11-05T13:02:38.695Z",
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.267",
3
+ "version": "0.9.0-preview.269",
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",
package/src/db.ts CHANGED
@@ -1222,6 +1222,19 @@ db.exec(`
1222
1222
  // ── #3432(admin 2026-11-05) 部门维度授权:把「人的组织架构」当成授权单位 ──
1223
1223
  // 与组授权同构(每次现算展开),差别只在展开源是 departments 子树 + nodes.department_id。
1224
1224
  // 单独一张表:组那张表的主键/语义都是 Agent 侧的,部门是人的树,混在一张表里以后分不清。
1225
+ // ── #3943 list_tasks 的轮询水位(每个调用者一条)──
1226
+ // 「自上次调用以来新增」比「每次拉全量再自己筛」便宜一个数量级,而提示词那一招
1227
+ // 对本项无效(实测 19.1% → 50.3%)。水位由服务端给、服务端存:
1228
+ // 客户端连时间都不用记,也就不会因为两边时钟差几秒而漏活。
1229
+ db.exec(`
1230
+ CREATE TABLE IF NOT EXISTS list_tasks_watermarks (
1231
+ network_id TEXT NOT NULL,
1232
+ caller_key TEXT NOT NULL,
1233
+ watermark TEXT NOT NULL,
1234
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
1235
+ PRIMARY KEY (network_id, caller_key)
1236
+ );
1237
+ `);
1225
1238
  db.exec(`
1226
1239
  CREATE TABLE IF NOT EXISTS network_member_department_grants (
1227
1240
  network_id TEXT NOT NULL,
@@ -0,0 +1,100 @@
1
+ // #3943 —— since_last:服务端水位,让「自上次以来新增」不需要客户端记时间。
2
+ //
3
+ // 为什么在服务端存而不是让调用方传:提示词那一招对本项无效(实测占比 19.1% → 50.3%),
4
+ // 而「记住上次返回的 server_time」是个状态,让每个调用方各自记,就必然有人记错或忘。
5
+ //
6
+ // 判据五格:
7
+ // ① 首次调用无水位 ⇒ 全量,且 since_from=null(不假装有水位)
8
+ // ② 再调一次 + 中间插入一条 ⇒ 只回那一条
9
+ // ③ 镜像:不传 since_last ⇒ 行为与 .268 逐字一致,且**不写**水位
10
+ // ④ 水位按 (network, caller) 隔离:A 调用者的水位不影响 B
11
+ // ⑤ since_last 与 created_since 同时给 ⇒ 明确报错(两个下界不混用)
12
+ import './require-explicit-test-db';
13
+ import { afterAll, beforeEach, describe, expect, test } from 'bun:test';
14
+ import { db } from './db';
15
+ import { registerTools } from './tools';
16
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
17
+
18
+ const net = 'net_wm';
19
+ const userA = 'u_wm_a';
20
+ const userB = 'u_wm_b';
21
+
22
+ function client(username: string) {
23
+ const handlers: Record<string, any> = {};
24
+ const server = new McpServer({ name: 't-wm', version: '0' }) as any;
25
+ const tool = server.tool.bind(server);
26
+ server.tool = (name: string, desc: any, shape: any, handler: any) => { handlers[name] = handler; return tool(name, desc, shape, handler); };
27
+ registerTools(server, undefined, null, username, username, false, null);
28
+ return async (name: string, args: any = {}) => JSON.parse((await handlers[name](args)).content[0].text);
29
+ }
30
+
31
+ const insertTask = (id: string, toName: string, createdAt: string) => db.run(
32
+ `INSERT INTO tasks(task_id, from_name, to_name, status, content, created_at, network_id)
33
+ VALUES (?1, 'peer', ?2, 'delivered', 'work', ?3, ?4)`, [id, toName, createdAt, net]);
34
+
35
+ function cleanup() {
36
+ db.run("DELETE FROM tasks WHERE task_id LIKE 't_wm_%'");
37
+ db.run('DELETE FROM list_tasks_watermarks WHERE network_id=?1', [net]);
38
+ db.run('DELETE FROM nodes WHERE network_id=?1', [net]);
39
+ db.run('DELETE FROM network_members WHERE network_id=?1', [net]);
40
+ db.run('DELETE FROM networks WHERE network_id=?1', [net]);
41
+ db.run('DELETE FROM users WHERE user_id IN (?1, ?2)', [userA, userB]);
42
+ }
43
+
44
+ beforeEach(() => {
45
+ cleanup();
46
+ for (const u of [userA, userB]) {
47
+ db.run("INSERT INTO users(user_id,username,password_hash,role) VALUES(?1,?1,'x','user')", [u]);
48
+ db.run("INSERT INTO network_members(user_id,network_id,role) VALUES(?1,?2,'owner')", [u, net]);
49
+ // username 必须等于某 nodes/sessions 的 alias,否则受限成员过滤会把任务全挡掉
50
+ db.run('INSERT INTO nodes(node_id,node_name,alias,network_id) VALUES(?1,?2,?2,?3)', [`n_${u}`, u, net]);
51
+ }
52
+ db.run('INSERT INTO networks(network_id,network_name,owner_id) VALUES(?1,?1,?2)', [net, userA]);
53
+ insertTask('t_wm_1', userA, '2026-11-05 01:00:00');
54
+ insertTask('t_wm_2', userB, '2026-11-05 01:00:00');
55
+ });
56
+ afterAll(cleanup);
57
+
58
+ describe("#3943 list_tasks since_last(服务端水位)", () => {
59
+ test("① 首次调用无水位 ⇒ 全量,且 since_from=null", async () => {
60
+ const call = client(userA);
61
+ const r = await call('list_tasks', { alias: userA, network_id: net, since_last: true, omit_stats: true, limit: 20 });
62
+ expect(r.ok).toBe(true);
63
+ expect(r.tasks.map((t: any) => t.task_id)).toEqual(['t_wm_1']);
64
+ expect(r.since_from).toBeNull();
65
+ expect(typeof r.since_to).toBe('string');
66
+ });
67
+
68
+ test("② 中间插入一条 ⇒ 第二次只回它(旧的不再出现)", async () => {
69
+ const call = client(userA);
70
+ await call('list_tasks', { alias: userA, network_id: net, since_last: true, omit_stats: true, limit: 20 });
71
+ insertTask('t_wm_new', userA, '2099-01-01 00:00:00');
72
+ const r = await call('list_tasks', { alias: userA, network_id: net, since_last: true, omit_stats: true, limit: 20 });
73
+ expect(r.tasks.map((t: any) => t.task_id)).toEqual(['t_wm_new']);
74
+ expect(typeof r.since_from).toBe('string');
75
+ });
76
+
77
+ test("③ 镜像:不传 since_last ⇒ 全量、且**不写**水位", async () => {
78
+ const call = client(userA);
79
+ const r = await call('list_tasks', { alias: userA, network_id: net, omit_stats: true, limit: 20 });
80
+ expect(r.since_from).toBeUndefined();
81
+ const rows = db.all("SELECT network_id FROM list_tasks_watermarks WHERE network_id=?1", [net]);
82
+ expect(rows.length).toBe(0);
83
+ });
84
+
85
+ test("④ 水位按 (network, caller) 隔离:B 的水位不影响 A", async () => {
86
+ const a = client(userA), b = client(userB);
87
+ await a('list_tasks', { alias: userA, network_id: net, since_last: true, omit_stats: true, limit: 20 });
88
+ const rb = await b('list_tasks', { alias: userB, network_id: net, since_last: true, omit_stats: true, limit: 20 });
89
+ // B 是首次 ⇒ 全量(自己的任务),不能因为 A 已经有了水位就变成空
90
+ expect(rb.tasks.map((t: any) => t.task_id)).toEqual(['t_wm_2']);
91
+ expect(rb.since_from).toBeNull();
92
+ });
93
+
94
+ test("⑤ since_last 与 created_since 同时给 ⇒ 明确报错(两个下界不混用)", async () => {
95
+ const call = client(userA);
96
+ const r = await call('list_tasks', { alias: userA, network_id: net, since_last: true, created_since: '2026-11-05 00:00:00', omit_stats: true, limit: 20 });
97
+ expect(r.ok).toBe(false);
98
+ expect(r.error).toBe('created_since_and_since_last_are_exclusive');
99
+ });
100
+ });
@@ -63,6 +63,14 @@ describe("#3119 list_tasks 的增量与水印", () => {
63
63
  expect(r.tasks.map((t: any) => t.task_id)).toEqual(['t_since_new']);
64
64
  });
65
65
 
66
+ test("①b ISO 带 T/Z 传参也必须生效(字符串比较会在第 11 个字符判错)", async () => {
67
+ const call = client();
68
+ // 同一天的午夜:用 ISO 传,库里是 'YYYY-MM-DD HH:MM:SS'(空格)。
69
+ // 直接字符串比较 ⇒ ' ' < 'T' ⇒ 库里那条被判成"更早" ⇒ 返回空。
70
+ const r = await call('list_tasks', { alias, network_id: net, created_since: '2026-11-05T00:00:00Z', omit_stats: true, limit: 20 });
71
+ expect(r.tasks.map((t: any) => t.task_id).sort()).toEqual(['t_since_new', 't_since_old']);
72
+ });
73
+
66
74
  test("② 镜像:不传 created_since ⇒ 两条都在(旧调用方零影响)", async () => {
67
75
  const call = client();
68
76
  const r = await call('list_tasks', { alias, network_id: net, limit: 20 });
package/src/tools.ts CHANGED
@@ -3130,8 +3130,12 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3130
3130
  // #3119 —— stats 是全表 GROUP BY:轮询时它比任务列表本身还贵。
3131
3131
  omit_stats: z.boolean().optional().default(false)
3132
3132
  .describe("Skip the per-status counts (they scan every task in scope). Pollers should set true."),
3133
+ // #3943 —— 服务端水位。调用方不传时间,Hub 用「上次给这个调用者返回的时刻」当下界,
3134
+ // 返回后把水位推到本次的 server_time。客户端连时钟都不用记(也就不会因两边差几秒漏活)。
3135
+ since_last: z.boolean().optional().default(false)
3136
+ .describe("Only tasks created since this caller's previous list_tasks call. Server keeps the watermark."),
3133
3137
  },
3134
- 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 }) => {
3138
+ 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 }) => {
3135
3139
  const readScope = resolveReadScope(netId);
3136
3140
  if (readScope.denied) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: readScope.denied }) }] };
3137
3141
  if (durable_cursor) {
@@ -3181,6 +3185,31 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3181
3185
  has_more: tasks.length === limit,
3182
3186
  }) }] };
3183
3187
  }
3188
+ // #3943 —— 两种下界不许同时给:一个来自调用方,一个来自服务端,混用说不清以谁为准。
3189
+ if (since_last && created_since) {
3190
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "created_since_and_since_last_are_exclusive" }) }] };
3191
+ }
3192
+ const effectiveNetIdForWatermark = enforceNetworkId ?? getNetworkId(netId);
3193
+ const watermarkKey = (() => {
3194
+ if (callerTokenIsNetwork && callerTokenId && enforceNetworkId) {
3195
+ const bound = db.get<{ bound_node_id: string | null }>(
3196
+ "SELECT bound_node_id FROM api_tokens WHERE token_id = ?1 AND network_id = ?2",
3197
+ callerTokenId, enforceNetworkId,
3198
+ )?.bound_node_id ?? null;
3199
+ if (bound) return `n:${bound}`;
3200
+ }
3201
+ return `a:${callerAlias ?? ""}`;
3202
+ })();
3203
+ const readWatermark = (): string | null => {
3204
+ if (!since_last || !effectiveNetIdForWatermark) return null;
3205
+ return db.get<{ watermark: string }>(
3206
+ "SELECT watermark FROM list_tasks_watermarks WHERE network_id = ?1 AND caller_key = ?2",
3207
+ effectiveNetIdForWatermark, watermarkKey,
3208
+ )?.watermark ?? null;
3209
+ };
3210
+ const previousWatermark = readWatermark();
3211
+ const sinceBound = previousWatermark ?? created_since ?? null;
3212
+
3184
3213
  let sql = "SELECT task_id, from_node_id, from_name, to_node_id, to_name, priority, status, content, result, created_at, runtime_submitted_at, consumed_at, thread_id, turn_id, completed_at FROM tasks WHERE 1=1";
3185
3214
  const params: any[] = [];
3186
3215
  sql = addAgentTimelineScope(sql, params, readScope, { from: "from_name", to: "to_name", fromNodeId: "from_node_id", toNodeId: "to_node_id" });
@@ -3188,7 +3217,12 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3188
3217
  if (status) { sql += ` AND status = ?${params.length + 1}`; params.push(status); }
3189
3218
  if (from_name) { sql += ` AND from_name = ?${params.length + 1}`; params.push(from_name); }
3190
3219
  if (from_node_id) { sql += ` AND from_node_id = ?${params.length + 1}`; params.push(from_node_id); }
3191
- if (created_since) { sql += ` AND created_at > ?${params.length + 1}`; params.push(created_since); }
3220
+ // #3119 —— 必须用 julianday 比,不能直接拿字符串比:
3221
+ // tasks.created_at 存的是 'YYYY-MM-DD HH:MM:SS'(空格),而客户端传 ISO 带 'T' 与 'Z'。
3222
+ // 字符串比较在第 11 个字符就分高低(' ' 0x20 < 'T' 0x54)⇒ **同一天的记录会被判成"更早"**
3223
+ // ⇒ 用 ISO 传参几乎永远返回空列表。上线后发现(生产实测:传 2026-11-05T00:00:00Z 返回 0 条,
3224
+ // 而库里当天明明有记录)。julianday 两种格式都认。
3225
+ if (sinceBound) { sql += ` AND julianday(created_at) > julianday(?${params.length + 1})`; params.push(sinceBound); }
3192
3226
  if (before_created_at && before_task_id) {
3193
3227
  sql += ` AND (created_at < ?${params.length + 1} OR (created_at = ?${params.length + 1} AND task_id < ?${params.length + 2}))`;
3194
3228
  params.push(before_created_at, before_task_id);
@@ -3196,6 +3230,18 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3196
3230
  sql += ` ORDER BY created_at DESC, task_id DESC LIMIT ?${params.length + 1}`;
3197
3231
  params.push(limit);
3198
3232
  const tasks = db.all(sql, ...params);
3233
+ // 水位在**查询之后**推进:这样「两次调用之间创建」的任务不会因为并发被跳过。
3234
+ // 用本次响应里的 server_time 作为下一次的下界;首次调用没有水位 ⇒ 全量,且 since_from=null
3235
+ // (不假装有水位,否则调用方会以为「之前那些已经看过了」)。
3236
+ const serverTime = new Date().toISOString();
3237
+ if (since_last && effectiveNetIdForWatermark) {
3238
+ db.run(
3239
+ `INSERT INTO list_tasks_watermarks(network_id, caller_key, watermark, updated_at)
3240
+ VALUES(?1, ?2, ?3, datetime('now'))
3241
+ ON CONFLICT(network_id, caller_key) DO UPDATE SET watermark=excluded.watermark, updated_at=excluded.updated_at`,
3242
+ [effectiveNetIdForWatermark, watermarkKey, serverTime],
3243
+ );
3244
+ }
3199
3245
 
3200
3246
  // Stats(#3119:轮询时默认仍然返回,调用方可用 omit_stats 显式关掉)
3201
3247
  if (omit_stats) {
@@ -3209,7 +3255,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3209
3255
  before_task_id: tasks[tasks.length - 1]?.task_id,
3210
3256
  } : null,
3211
3257
  // 客户端把这个值原样当下一轮的 created_since,避免两边时钟不一致。
3212
- server_time: new Date().toISOString(),
3258
+ server_time: serverTime,
3259
+ ...(since_last ? { since_from: previousWatermark, since_to: serverTime } : {}),
3213
3260
  stats_omitted: true,
3214
3261
  }) }] };
3215
3262
  }
@@ -3232,7 +3279,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3232
3279
  before_task_id: tasks[tasks.length - 1]?.task_id,
3233
3280
  } : null,
3234
3281
  // #3119 —— 轮询水位由服务端给,客户端别用本地时钟(两边差几秒就会漏活或重复)。
3235
- server_time: new Date().toISOString(),
3282
+ server_time: serverTime,
3283
+ ...(since_last ? { since_from: previousWatermark, since_to: serverTime } : {}),
3236
3284
  stats,
3237
3285
  }),
3238
3286
  }],