@sleep2agi/commhub-server 0.9.0-preview.277 → 0.9.0-preview.279

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": "e1ef891a7971a79a90eb3df8d7b42de9dca8db9c",
3
+ "commit": "d45e3b04f79ae33cc3a9d1ff09183124925c47e4",
4
4
  "dirty": false,
5
- "built_at": "2026-11-09T06:53:05.119Z",
5
+ "built_at": "2026-11-09T11:41:59.929Z",
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.277",
3
+ "version": "0.9.0-preview.279",
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",
@@ -0,0 +1,31 @@
1
+ import { beforeEach, expect, test } from "bun:test";
2
+ import { ALL_STATUS_TTL_MS, allStatusCacheKey, cachedAllStatus, clearAllStatusCache } from "./all-status-cache";
3
+
4
+ beforeEach(() => clearAllStatusCache());
5
+
6
+ test("identical scope+filters within TTL reuse one serialized response", () => {
7
+ let builds = 0, t = 1_000;
8
+ const key = allStatusCacheKey({ networkId: "net_a", networkIds: null }, [null, null, null]);
9
+ const build = () => `v${++builds}`;
10
+ expect(cachedAllStatus(key, build, () => t)).toEqual({ text: "v1", hit: false });
11
+ t += ALL_STATUS_TTL_MS - 1;
12
+ expect(cachedAllStatus(key, build, () => t)).toEqual({ text: "v1", hit: true });
13
+ t += 1;
14
+ expect(cachedAllStatus(key, build, () => t)).toEqual({ text: "v2", hit: false });
15
+ });
16
+
17
+ test("different network, scope or filters never share an entry", () => {
18
+ let n = 0; const build = () => `r${++n}`;
19
+ const a = allStatusCacheKey({ networkId: "net_a", networkIds: null }, [null, null, null]);
20
+ const b = allStatusCacheKey({ networkId: "net_b", networkIds: null }, [null, null, null]);
21
+ const c = allStatusCacheKey({ networkId: "net_a", networkIds: null }, ["idle", null, null]);
22
+ const d = allStatusCacheKey({ networkId: "net_a", networkIds: null }, [null, null, "x,y"]);
23
+ expect(new Set([a, b, c, d]).size).toBe(4);
24
+ expect(new Set([a, b, c, d].map(k => cachedAllStatus(k, build).text)).size).toBe(4);
25
+ });
26
+
27
+ test("null key (restricted member scope) always rebuilds", () => {
28
+ let n = 0; const build = () => `r${++n}`;
29
+ expect(cachedAllStatus(null, build).text).toBe("r1");
30
+ expect(cachedAllStatus(null, build).text).toBe("r2");
31
+ });
@@ -0,0 +1,37 @@
1
+ // get_all_status response cache (perf).
2
+ //
3
+ // Production 2026-11-09: ~20 LLM agents each called get_all_status about once a
4
+ // minute (465 calls / 22 min). Every call re-read all ~400 sessions and built a
5
+ // ~580 KB JSON string (then wrapped/escaped again by MCP) — several MB of
6
+ // short-lived garbage per call. The Hub's event loop stalled 2–9 s every few
7
+ // seconds (663 stalls in ~2 h) and phone sends sat at 「发送中」.
8
+ //
9
+ // Identical requests within TTL_MS reuse one serialized response. The key is the
10
+ // caller's full read scope (which already encodes network + per-member
11
+ // restrictions) plus every filter, so two callers share an entry only when the
12
+ // SQL they would run is identical. Status that is ≤10 s stale is fine for a roster.
13
+ export const ALL_STATUS_TTL_MS = 10_000;
14
+ const MAX_ENTRIES = 256;
15
+ const cache = new Map<string, { at: number; text: string }>();
16
+
17
+ export function allStatusCacheKey(scope: unknown, filters: unknown): string {
18
+ return JSON.stringify([scope, filters]);
19
+ }
20
+
21
+ /** Return the cached text for `key`, or build, store and return it. */
22
+ export function cachedAllStatus(key: string | null, build: () => string, now: () => number = Date.now): { text: string; hit: boolean } {
23
+ if (key === null) return { text: build(), hit: false }; // uncacheable scope
24
+ const t = now();
25
+ const hit = cache.get(key);
26
+ if (hit && t - hit.at < ALL_STATUS_TTL_MS) return { text: hit.text, hit: true };
27
+ const text = build();
28
+ if (cache.size >= MAX_ENTRIES) {
29
+ for (const [k, v] of cache) if (t - v.at >= ALL_STATUS_TTL_MS) cache.delete(k);
30
+ if (cache.size >= MAX_ENTRIES) cache.delete(cache.keys().next().value!);
31
+ }
32
+ cache.set(key, { at: t, text });
33
+ return { text, hit: false };
34
+ }
35
+
36
+ /** Tests only. */
37
+ export function clearAllStatusCache(): void { cache.clear(); }
@@ -36,6 +36,8 @@ const publicLifecycleErrors = new Set([
36
36
  // #2012 —— daemon 的 copresence_adopt_v2 拒绝是固定安全码(无路径/无异常文本),
37
37
  // 不放行会让用户投影退化成 lifecycle_error,看不到「为什么被拒绝」。
38
38
  "copresence_adopt_v2",
39
+ // OpenCode V2 co-presence adoption (registration for fork): bridge must be live; start/stop not yet supported.
40
+ "adopt_opencode_bridge_not_running", "adopt_opencode_lifecycle_unsupported",
39
41
  "adopt_proc_invalid", "adopt_proc_unreadable", "adopt_platform_unsupported",
40
42
  "adopt_registry_conflict", "adopt_registry_entry_invalid", "adopt_registry_invalid",
41
43
  "adopt_registry_unsafe", "adopt_config_env_invalid", "adopt_env_file_invalid",
@@ -192,10 +192,13 @@ test("acknowledged adoption is a management relation, not canonical-directory or
192
192
  });
193
193
 
194
194
  test("freshness uses Hub receipt times and currently valid immutable node credentials", () => {
195
- for (const offset of ["-2 minutes", "+2 minutes"]) {
195
+ for (const offset of ["-5 minutes", "+2 minutes"]) {
196
196
  db.run("UPDATE sessions SET last_seen_at=datetime('now',?1) WHERE resume_id='issuer_source'", [offset]);
197
197
  expect(inspect()).toEqual({ ok: false, error: "source_evidence_stale" });
198
198
  }
199
+ // Within one 3-minute status heartbeat: alive (75 s used to call this stale).
200
+ db.run("UPDATE sessions SET last_seen_at=datetime('now','-2 minutes') WHERE resume_id='issuer_source'");
201
+ expect((inspect() as any).error).not.toBe("source_evidence_stale");
199
202
  db.run("UPDATE sessions SET last_seen_at=datetime('now') WHERE resume_id='issuer_source'");
200
203
  for (const tokenId of [sourceToken.token_id!, daemonToken.token_id!]) {
201
204
  db.run("UPDATE api_tokens SET revoked_at=datetime('now') WHERE token_id=?1", [tokenId]);
@@ -18,6 +18,12 @@ export type SourceIssuerCode = "source_selection_invalid" | "source_auth_require
18
18
  | "source_read_forbidden" | "insufficient_role_for_create_node" | "daemon_not_found"
19
19
  | "daemon_cannot_create_nodes" | "source_runtime_unsupported" | "source_daemon_unverified"
20
20
  | "source_daemon_mismatch" | "source_evidence_stale" | "source_evidence_unavailable";
21
+ /** Liveness window for source and daemon Hub receipt times. Nodes and daemons report
22
+ * status every 3 min (STATUS_HEARTBEAT_MS / node-server heartbeat), so the former
23
+ * 75 s window made a healthy pair look stale for ~60% of each cycle and the app's
24
+ * fork returned 403 almost always. One heartbeat + jitter. Still liveness only,
25
+ * not a generation lease (the daemon's live evidence read is the proof). */
26
+ export const SOURCE_LIVENESS_MS = 4 * 60_000;
21
27
  export type SourceIssuerRefusal = { ok: false; error: SourceIssuerCode };
22
28
  export class SourceIssuerError extends Error {
23
29
  constructor(public readonly code: SourceIssuerCode) { super(code); this.name = "SourceIssuerError"; }
@@ -99,7 +105,7 @@ function readEvidence(p: Permissions): SourceEvidenceRead | SourceIssuerRefusal
99
105
  WHERE node_id=?1 AND network_id=?2 ORDER BY last_seen_at DESC LIMIT 1`, nodeId, s.network_id);
100
106
  const time = parseDbTimestampMs(seen?.last_seen_at ?? "");
101
107
  const age = Date.now() - time;
102
- if (!Number.isFinite(time) || age < 0 || age > 75_000) return fail("source_evidence_stale");
108
+ if (!Number.isFinite(time) || age < 0 || age > SOURCE_LIVENESS_MS) return fail("source_evidence_stale");
103
109
  const tokens = db.all<{ token_id: string; user_id: string }>(`SELECT t.token_id,t.user_id FROM api_tokens t JOIN users u ON u.user_id=t.user_id
104
110
  JOIN network_members m ON m.user_id=t.user_id AND m.network_id=t.network_id
105
111
  WHERE t.bound_node_id=?1 AND t.network_id=?2 AND t.scope='network' AND t.revoked_at IS NULL
package/src/tools.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { allStatusCacheKey, cachedAllStatus } from "./all-status-cache.js";
1
2
  import { parseScheduledWorkOutcome, qualifyScheduledWorkOutcome, saveScheduledWorkOutcome } from "./scheduled-work-outcome.js";
2
3
  import { enqueueBroadcast } from "./broadcast-fanout.js";
3
4
  import { selectHumanInboxIds } from "./human-inbox.js";
@@ -1995,10 +1996,13 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1995
1996
  async ({ filter_status, filter_server, filter_alias, network_id: netId }) => {
1996
1997
  const readScope = resolveReadScope(netId);
1997
1998
  if (readScope.denied) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: readScope.denied }) }] };
1998
- console.log(`[${ts()}] hub → get_all_status${filter_status ? ": filter=" + filter_status : ""}${filter_alias ? " alias=" + filter_alias.slice(0, 80) : ""}${readScope.networkId ? " net=" + readScope.networkId.slice(0, 12) : ""}`);
1999
+ const cacheKey = allStatusCacheKey(readScope, [filter_status ?? null, filter_server ?? null, filter_alias ?? null]);
1999
2000
 
2000
2001
  // Round-2/4 review ③: stale-marking moved to startStaleSessionSweeper()
2001
2002
  // (background timer, ~60s cadence). Read path no longer fires UPDATE.
2003
+ // Members restricted to granted agents always read fresh: a grant/revoke must
2004
+ // take effect on the next call, not up to TTL later.
2005
+ const { text, hit } = cachedAllStatus(readScope.agentRestriction ? null : cacheKey, () => {
2002
2006
  let sql = "SELECT * FROM sessions WHERE 1=1";
2003
2007
  const params: any[] = [];
2004
2008
  sql = addAgentNetworkScope(sql, params, readScope, { alias: "alias", nodeId: "node_id" });
@@ -2033,22 +2037,18 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2033
2037
  const summary = db.all(summarySql, ...summaryParams);
2034
2038
 
2035
2039
  const filtered = !!(filter_status || filter_server || aliases.length > 0);
2036
- return {
2037
- content: [
2038
- {
2039
- type: "text" as const,
2040
- text: JSON.stringify({
2041
- ok: true,
2042
- sessions,
2043
- summary,
2044
- summary_scope: filtered
2045
- ? "every session in the read scope — NOT narrowed by the filters applied to `sessions`"
2046
- : "every session in the read scope",
2047
- sessions_returned: sessions.length,
2048
- }),
2049
- },
2050
- ],
2051
- };
2040
+ return JSON.stringify({
2041
+ ok: true,
2042
+ sessions,
2043
+ summary,
2044
+ summary_scope: filtered
2045
+ ? "every session in the read scope — NOT narrowed by the filters applied to `sessions`"
2046
+ : "every session in the read scope",
2047
+ sessions_returned: sessions.length,
2048
+ });
2049
+ });
2050
+ console.log(`[${ts()}] hub → get_all_status${hit ? " (cached)" : ""}${filter_status ? ": filter=" + filter_status : ""}${filter_alias ? " alias=" + filter_alias.slice(0, 80) : ""}${readScope.networkId ? " net=" + readScope.networkId.slice(0, 12) : ""}`);
2051
+ return { content: [{ type: "text" as const, text }] };
2052
2052
  }
2053
2053
  );
2054
2054