@sleep2agi/commhub-server 0.9.0-preview.197 → 0.9.0-preview.199

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.197",
3
+ "version": "0.9.0-preview.199",
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",
@@ -127,6 +127,41 @@ describe("Agent 显式归属部门", () => {
127
127
  expect((await setDept(U.owner.token, NODE_OUTSIDE, D.tmai)).status).toBe(404);
128
128
  });
129
129
 
130
+ // #2965 —— 同 alias 多 node 行必须在通讯录里折叠成一行,并给出「历史注册」计数。
131
+ // 现场:一组同名里只有一个挂过会话,其余是重复注册留下的空行;页面看起来就是「重复的 Agent」。
132
+ // 折叠不能只看 updated_at —— 实测那 3 个 node 的 updated_at 完全相同,必须优先保留有会话的那条。
133
+ test("同 alias 多 node:不删行,但其余行带 duplicate_of 指向首选(有会话者优先)", async () => {
134
+ const now = Date.now();
135
+ const dupAlias = `重复-Agent-${now}`;
136
+ const live = `n_live_${now}`;
137
+ const dead1 = `n_dead1_${now}`;
138
+ const dead2 = `n_dead2_${now}`;
139
+ // 三条 updated_at 完全一样(现场就是这样),只有 live 有会话行
140
+ for (const id of [dead2, live, dead1]) {
141
+ db.run(
142
+ "INSERT INTO nodes (node_id, node_name, alias, network_id, created_at, updated_at) VALUES (?1, ?2, ?2, ?3, datetime('now'), '2026-10-26 12:26:22')",
143
+ [id, dupAlias, NET],
144
+ );
145
+ }
146
+ db.run(
147
+ "INSERT INTO sessions (resume_id, alias, status, network_id, node_id, updated_at) VALUES (?1, ?2, 'offline', ?3, ?4, datetime('now'))",
148
+ [`s_${live}`, dupAlias, NET, live],
149
+ );
150
+
151
+ const dir = await send(U.owner.token, "GET", `/api/requirements/people/directory?network_id=${NET}`);
152
+ expect(dir.status).toBe(200);
153
+ const agents = [...(dir.body.people ?? []).flatMap((p: any) => p.agents ?? []), ...(dir.body.agents_without_owner ?? [])];
154
+ const rows = agents.filter((a: any) => a.alias === dupAlias);
155
+ // 契约不变:三条都还在(客户端照旧可按 updated_at 去重)
156
+ expect(rows).toHaveLength(3);
157
+ // 新增:其余两条都指向首选,而首选必须是**有会话**的那条(三条 updated_at 完全相同)
158
+ const liveRow = rows.find((a: any) => a.node_id === live);
159
+ expect(liveRow.duplicate_of).toBeUndefined();
160
+ for (const dead of [dead1, dead2]) {
161
+ expect(rows.find((a: any) => a.node_id === dead)?.duplicate_of).toBe(live);
162
+ }
163
+ });
164
+
130
165
  test("普通成员改不了(403)", async () => {
131
166
  const r = await setDept(U.member.token, NODE_A, D.tmai);
132
167
  expect(r.status).toBe(403);
package/src/db.ts CHANGED
@@ -1123,16 +1123,11 @@ db.exec(`
1123
1123
  );
1124
1124
  `);
1125
1125
 
1126
- // Auto-create trial license on first run
1127
- const existingLicense = db.get<any>("SELECT id FROM licenses LIMIT 1");
1128
- if (!existingLicense) {
1129
- const trialId = crypto.randomUUID().replace(/-/g, "").slice(0, 12);
1130
- db.run(
1131
- "INSERT INTO licenses (id, license_key, type, expires_at) VALUES (?1, ?2, 'trial', datetime('now', '+14 days'))",
1132
- [`lic_${trialId}`, `trial-${trialId}`]
1133
- );
1134
- console.log("[commhub] 🎉 14-day free trial started!");
1135
- }
1126
+ // license 功能已移除(2026-10-29 admin 决定)。
1127
+ // 这里原来会在首次启动时插一条 14 天 trial —— 现在没有任何代码读它,
1128
+ // 继续插只会让每个新库凭空多一行死数据。
1129
+ // `licenses` 表本身保留(CREATE TABLE 不动):已有实例里可能还有历史行,
1130
+ // 删表的迁移代价大于留着;表从此不再被读写。
1136
1131
 
1137
1132
  // ── V3.13: network_members table (user ↔ network many-to-many) ──
1138
1133
  db.exec(`
@@ -6,7 +6,7 @@ import { join } from "path";
6
6
  import { tmpdir } from "os";
7
7
  import { register } from "./auth.js";
8
8
  import { db } from "./db.js";
9
- import { scanNodeFailureAlerts, classifyDeterministicFailure, NODE_FAILURE_ALERT_KIND } from "./node-failure-alert.js";
9
+ import { scanNodeFailureAlerts, scanModelAuthBlockedNodes, classifyDeterministicFailure, NODE_FAILURE_ALERT_KIND, MODEL_AUTH_BLOCKED_CATEGORY } from "./node-failure-alert.js";
10
10
 
11
11
  const DIR = mkdtempSync(join(tmpdir(), "anet-nfa-"));
12
12
  let NET = "", UID = "", NODE = "";
@@ -97,3 +97,54 @@ describe("#2840 节点连续确定性失败告警", () => {
97
97
  expect(r.nodes).not.toContain(reset);
98
98
  });
99
99
  });
100
+
101
+ // #2964 后半 —— 节点「在线但干不了活」:状态是 error、原因是登录失效,
102
+ // 但它一条任务都不接,所以「连续失败」那条告警路径永远不会触发。
103
+ describe("#2964 登录失效节点(不接活)", () => {
104
+ const session = (alias: string, status: string, task: string | null) => {
105
+ db.run(
106
+ `INSERT OR REPLACE INTO sessions (resume_id, alias, status, task, network_id, updated_at)
107
+ VALUES (?1, ?2, ?3, ?4, ?5, datetime('now'))`,
108
+ [`s_${alias}`, alias, status, task, NET],
109
+ );
110
+ db.run(
111
+ `INSERT OR IGNORE INTO nodes (node_id, node_name, alias, runtime, network_id, owner_user_id)
112
+ VALUES (?1, ?2, ?2, 'codex', ?3, ?4)`,
113
+ [`n_${alias}`, alias, NET, UID],
114
+ );
115
+ };
116
+
117
+ test("status=error 且原因是登录失效 → 告警一次;同一天再扫不重复", () => {
118
+ const alias = `nfa-auth-${Date.now()}`;
119
+ session(alias, "error", "model login expired: this node's CODEX_HOME needs a fresh login — log in again there");
120
+ const before = alerts().length;
121
+ expect(scanModelAuthBlockedNodes().nodes).toContain(alias);
122
+ expect(alerts().length).toBe(before + 1);
123
+ // 每节点每天一条:再扫一次不应新增
124
+ expect(scanModelAuthBlockedNodes().alerts).toBe(0);
125
+ });
126
+
127
+ test("idle 的节点不告警(没坏就别吵)", () => {
128
+ const alias = `nfa-auth-idle-${Date.now()}`;
129
+ session(alias, "idle", "model login expired: needs a fresh login");
130
+ expect(scanModelAuthBlockedNodes().nodes).not.toContain(alias);
131
+ });
132
+
133
+ test("error 但原因不是登录类(例如代码异常)不告警", () => {
134
+ const alias = `nfa-auth-other-${Date.now()}`;
135
+ session(alias, "error", "TypeError: cannot read properties of undefined (reading 'x')");
136
+ expect(scanModelAuthBlockedNodes().nodes).not.toContain(alias);
137
+ });
138
+
139
+ test("告警里带类别与当天日期(去重键)", () => {
140
+ const row = db.get<{ cat: string; day: string }>(
141
+ `SELECT json_extract(meta_json,'$.node_failure_alert.category') AS cat,
142
+ json_extract(meta_json,'$.node_failure_alert.first_seen') AS day
143
+ FROM user_inbox WHERE kind = ?1
144
+ AND json_extract(meta_json,'$.node_failure_alert.category') = ?2 LIMIT 1`,
145
+ NODE_FAILURE_ALERT_KIND, MODEL_AUTH_BLOCKED_CATEGORY,
146
+ );
147
+ expect(row?.cat).toBe(MODEL_AUTH_BLOCKED_CATEGORY);
148
+ expect(row?.day).toMatch(/^\d{4}-\d{2}-\d{2}$/);
149
+ });
150
+ });
@@ -49,6 +49,61 @@ const PATTERNS: Array<{ category: Category; re: RegExp; label: string; hint: str
49
49
  hint: "该节点的上游额度已用完:换 key / 充值 / 换 provider 后重启节点;限流(rate limit)不属此类,会自愈" },
50
50
  ];
51
51
 
52
+ /** #2964 后半 —— 节点完全不接活时的告警类别(与「连续失败」区分开)。 */
53
+ export const MODEL_AUTH_BLOCKED_CATEGORY = "login_expired";
54
+
55
+ /**
56
+ * #2964 后半 —— 扫「在线但干不了活」的节点。
57
+ *
58
+ * 前一半(分类器认得出登录文案)只覆盖「节点产生了失败」的情况。
59
+ * 还有一种更安静的状态:节点启动后登录已失效,**一条任务都不接**,
60
+ * 于是 `#2840` 的「连续失败」永远不会触发 —— 但它同样干不了活。
61
+ *
62
+ * hub 侧的事实来源:agent-node 的 `gateStatusOnModelAuth` 会把这种节点的状态报成
63
+ * `error`,并把原因写进 `sessions.task`。这里直接读它,不做任何推断。
64
+ *
65
+ * 去重粒度:每节点每天最多一条(`first_seen` 用日期),因为这不是「某一次失败」,
66
+ * 而是一个需要人处理的状态;每隔 5 分钟提醒一次只会变成噪音。
67
+ */
68
+ export function scanModelAuthBlockedNodes(now = new Date()): AlertScanResult {
69
+ const day = now.toISOString().slice(0, 10);
70
+ const rows = db.all<{ alias: string | null; network_id: string | null; task: string | null }>(
71
+ `SELECT alias, network_id, task FROM sessions WHERE status = 'error' AND task IS NOT NULL`,
72
+ );
73
+ const out: string[] = [];
74
+ for (const r of rows) {
75
+ const node = r.alias;
76
+ if (!node || !r.network_id) continue;
77
+ if (classifyDeterministicFailure(r.task) !== "login_required") continue;
78
+ const dup = db.get<{ n: number }>(
79
+ `SELECT COUNT(*) AS n FROM user_inbox WHERE kind = ?1 AND from_session = ?2
80
+ AND json_extract(meta_json, '$.node_failure_alert.category') = ?3
81
+ AND json_extract(meta_json, '$.node_failure_alert.first_seen') = ?4`,
82
+ NODE_FAILURE_ALERT_KIND, node, MODEL_AUTH_BLOCKED_CATEGORY, day,
83
+ )?.n ?? 0;
84
+ if (dup > 0) continue;
85
+ const owner = db.get<{ owner_user_id: string | null }>(
86
+ "SELECT owner_user_id FROM nodes WHERE alias = ?1 AND network_id = ?2", node, r.network_id,
87
+ )?.owner_user_id;
88
+ if (!owner) continue;
89
+ const sent = sendAgentNotice({
90
+ networkId: r.network_id,
91
+ userId: owner,
92
+ fromAlias: node,
93
+ kind: NODE_FAILURE_ALERT_KIND,
94
+ title: "节点在线但不会接活:登录失效",
95
+ text: `${node} 当前状态是 error,原因是登录失效。它不会接任何任务(不是慢,是干不了)。\n\n`
96
+ + `节点自述:\n${String(r.task).slice(0, 300)}\n\n`
97
+ + `处理建议:在该节点自己的 CODEX_HOME 里重新登录(不要拷贝别的节点的 auth.json),然后重启节点。`,
98
+ severity: "error",
99
+ meta: { node_failure_alert: { node, category: MODEL_AUTH_BLOCKED_CATEGORY, first_seen: day } },
100
+ idPrefix: "dm_nfa_",
101
+ });
102
+ if (sent) out.push(node);
103
+ }
104
+ return { alerts: out.length, nodes: out };
105
+ }
106
+
52
107
  /** 只认确定性错误;timeout / 任务内容错误一律返回 null(那类会自愈或与节点无关)。 */
53
108
  export function classifyDeterministicFailure(result: string | null | undefined): Category | null {
54
109
  if (!result) return null;
@@ -83,6 +83,36 @@ export function peopleDirectory(networkId: string, hidden: HiddenNode, query: {
83
83
  "SELECT node_id, alias, node_name, owner_user_id, department_id, updated_at, lifecycle_state FROM nodes WHERE network_id = ?1 ORDER BY COALESCE(alias, node_name), node_id",
84
84
  networkId,
85
85
  ).filter(n => !hidden?.(n.node_id));
86
+ // #2965 —— 同 alias 多 node 行时**不删行**(保持既有契约:重复项照样列出,客户端去重),
87
+ // 只额外给一个确定性的「该保留哪条」:其余行带 `duplicate_of = <首选 node_id>`。
88
+ //
89
+ // 为什么必须由 hub 判:客户端只看得到 updated_at,而重复注册常发生在同一秒 ——
90
+ // 实测 TM客户端基建牛 三条 updated_at 完全相同(2026-10-26 12:26:22),
91
+ // 按「保留最新」会随机留一条,而真正在跑的是**有会话**的那条(客户端看不到会话)。
92
+ //
93
+ // 规则:有会话 > updated_at 新 > node_id 字典序(最后一条只为让结果稳定)。
94
+ const liveNodeIds = new Set(
95
+ db.all<{ node_id: string | null }>("SELECT DISTINCT node_id FROM sessions WHERE network_id = ?1", networkId)
96
+ .map(r => r.node_id).filter((x): x is string => !!x),
97
+ );
98
+ const byAliasForRank = new Map<string, typeof nodes>();
99
+ for (const n of nodes) {
100
+ const key = n.alias || n.node_name;
101
+ const bucket = byAliasForRank.get(key);
102
+ if (bucket) bucket.push(n); else byAliasForRank.set(key, [n]);
103
+ }
104
+ const preferredByAlias = new Map<string, string>();
105
+ for (const [key, bucket] of byAliasForRank) {
106
+ if (bucket.length < 2) continue;
107
+ const ranked = [...bucket].sort((a, b) => {
108
+ const alive = Number(liveNodeIds.has(b.node_id)) - Number(liveNodeIds.has(a.node_id));
109
+ if (alive !== 0) return alive;
110
+ const t = String(b.updated_at ?? "").localeCompare(String(a.updated_at ?? ""));
111
+ if (t !== 0) return t;
112
+ return a.node_id.localeCompare(b.node_id);
113
+ });
114
+ preferredByAlias.set(key, ranked[0].node_id);
115
+ }
86
116
  const memberIds = new Set(members.map(m => m.user_id));
87
117
  const byOwner = new Map<string, DirectoryAgent[]>();
88
118
  const unowned: DirectoryAgent[] = [];
@@ -97,6 +127,12 @@ export function peopleDirectory(networkId: string, hidden: HiddenNode, query: {
97
127
  // #2596 —— 客户端据此做「按 alias 去重(保留最新)」与「默认只看近 7 天」。
98
128
  updated_at: n.updated_at ?? null,
99
129
  lifecycle_state: n.lifecycle_state ?? null,
130
+ // #2965 —— 同 alias 的重复行:这一格指向「首选 node_id」,没有重复时不出现。
131
+ // 客户端可以据此只显示首选那条;也可以像以前一样自己按 updated_at 去重(行为不变)。
132
+ ...(() => {
133
+ const pref = preferredByAlias.get(n.alias || n.node_name);
134
+ return pref && pref !== n.node_id ? { duplicate_of: pref } : {};
135
+ })(),
100
136
  };
101
137
  if (n.owner_user_id && memberIds.has(n.owner_user_id)) {
102
138
  const list = byOwner.get(n.owner_user_id) ?? [];
package/src/server.ts CHANGED
@@ -85,7 +85,7 @@ import { startRetentionSweeper } from "./retention.js";
85
85
  import { sweepEmptyNodeRows } from "./empty-node-sweeper.js";
86
86
  import { versionStats } from "./version-stats.js";
87
87
  import { startStaleSessionSweeper } from "./stale-sweeper.js";
88
- import { scanNodeFailureAlerts } from "./node-failure-alert.js";
88
+ import { scanNodeFailureAlerts, scanModelAuthBlockedNodes } from "./node-failure-alert.js";
89
89
  import { scanStarvedSchedules } from "./schedule-starved.js";
90
90
  import { scanNodeBusyCircuit } from "./node-serviceability.js";
91
91
  import {
@@ -1401,49 +1401,12 @@ return Bun.serve({
1401
1401
  }
1402
1402
 
1403
1403
  // ── V3: License endpoints ──
1404
- if (url.pathname === "/api/license" && req.method === "GET") {
1405
- const license = db.get<any>(
1406
- "SELECT type, expires_at, max_agents, max_networks, max_tasks_day FROM licenses ORDER BY created_at LIMIT 1",
1407
- );
1408
- if (!license) return withCors(req, Response.json({ ok: true, status: "no_license" }));
1409
- const now = new Date().toISOString().replace("T", " ").slice(0, 19);
1410
- const expired = license.expires_at && license.expires_at < now;
1411
- // #1650 — licenses.expires_at 是 TEXT(datetime('now') 家族),UTC 但不带时区
1412
- // 标记;`new Date()` 会按本机时区解析,边界上差一天。parse 失败时返回 null
1413
- // 而不是 NaN —— JSON.stringify(NaN) 本来也序列化成 null,线上字节不变。
1414
- const expiresMs = parseHubTimestamp(license.expires_at);
1415
- const daysLeft = expiresMs === null
1416
- ? null
1417
- : Math.max(0, Math.ceil((expiresMs - Date.now()) / 86400000));
1418
- return withCors(req, Response.json({
1419
- ok: true,
1420
- license: { type: license.type, expires_at: license.expires_at, days_left: daysLeft, expired },
1421
- limits: { max_agents: license.max_agents, max_networks: license.max_networks, max_tasks_day: license.max_tasks_day },
1422
- }));
1423
- }
1424
-
1425
- if (url.pathname === "/api/license/activate" && req.method === "POST") {
1426
- try {
1427
- const body = await req.json() as any;
1428
- const key = body.key;
1429
- if (!key) return withCors(req, Response.json({ ok: false, error: "key required" }, { status: 400 }));
1430
- // For now: accept any key starting with "anet-" as valid pro license
1431
- if (!key.startsWith("anet-") || key.length < 16) {
1432
- return withCors(req, Response.json({ ok: false, error: "invalid license key" }, { status: 400 }));
1433
- }
1434
- // Upgrade existing license or create new
1435
- db.run("DELETE FROM licenses");
1436
- const licId = `lic_${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`;
1437
- db.run(
1438
- "INSERT INTO licenses (id, license_key, type, max_agents, max_networks, max_tasks_day, activated_at, expires_at) VALUES (?1, ?2, 'pro', 50, 10, 10000, datetime('now'), datetime('now', '+365 days'))",
1439
- [licId, key]
1440
- );
1441
- return withCors(req, Response.json({ ok: true, type: "pro", expires_in_days: 365 }));
1442
- } catch (e: any) {
1443
- return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
1444
- }
1445
- }
1446
-
1404
+ // 🔴 2026-10-29 admin:「license 删掉吧」。
1405
+ // 这两个端点原本是 v0.6 试用/激活码体系的遗留路径,开源后没有任何真实用途:
1406
+ // GET /api/license —— 读 licenses 表第一行(trial/pro + 剩余天数)
1407
+ // POST /api/license/activate —— 收一个 "anet-" 前缀的串,先 DELETE FROM licenses 再写一条
1408
+ // (而且**完全没有鉴权**,见 #3199)
1409
+ // 现已移除;命中时按未知路径处理(404),不再保留兼容壳。
1447
1410
  // ── V3: Auth endpoints (public) ──
1448
1411
  if (url.pathname === "/api/auth/register" && req.method === "POST") {
1449
1412
  const clientIP = req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || "unknown";
@@ -5823,6 +5786,13 @@ export function startHub(opts?: { port?: number; hostname?: string }): ReturnTyp
5823
5786
  } catch (e: any) {
5824
5787
  console.log(`[commhub node-failure-alert] failed: ${e?.message ?? e}`);
5825
5788
  }
5789
+ // #2964 —— 「在线但干不了活」:登录失效的节点一条任务都不会接,连续失败那条路不会触发。
5790
+ try {
5791
+ const b = scanModelAuthBlockedNodes();
5792
+ if (b.alerts > 0) console.log(`[commhub node-auth-blocked-alert] sent ${b.alerts} alert(s): ${b.nodes.join(", ")}`);
5793
+ } catch (e: any) {
5794
+ console.log(`[commhub node-auth-blocked-alert] failed: ${e?.message ?? e}`);
5795
+ }
5826
5796
  }, nodeFailureAlertMs);
5827
5797
  (nodeFailureAlertTimer as any).unref?.();
5828
5798
 
package/src/tools.ts CHANGED
@@ -2128,17 +2128,13 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2128
2128
  }
2129
2129
  }
2130
2130
 
2131
- // License check
2132
- const license = db.get<any>("SELECT type, expires_at FROM licenses ORDER BY created_at LIMIT 1");
2133
- if (license?.expires_at) {
2134
- const now = new Date().toISOString().replace("T", " ").slice(0, 19);
2135
- if (license.expires_at < now) {
2136
- return { content: [{ type: "text" as const, text: JSON.stringify({
2137
- ok: false, error: "license_expired",
2138
- message: "Trial expired. Activate a license: anet activate <key>",
2139
- }) }] };
2140
- }
2141
- }
2131
+ // 🔴 2026-10-29 —— license 检查已删除(纯开源,没有许可概念)。
2132
+ // 原来是:licenses 表第一行的 expires_at 过了就拒派活(error: license_expired)。
2133
+ // 这在一个自部署的开源 Hub 上是纯粹的故障源:
2134
+ // · 首次启动会自动插一条 14 天 trial(那一行在 db.ts,已一并删除)
2135
+ // · 端点 /api/license/activate 又没有鉴权,谁都能换掉这一行
2136
+ // · 一旦过期,整台 Hub 的 send_task 全部失败,而界面上只看到「Trial expired」
2137
+ // 现在不读 licenses 表,也不再产生 license_expired。
2142
2138
 
2143
2139
  const canonical = resolveCanonicalAlias(effectiveNetId, alias);
2144
2140
  const targetAlias = canonical.alias;