@sleep2agi/commhub-server 0.9.0-preview.81 → 0.9.0-preview.83
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 +1 -1
- package/src/agent-access.ts +5 -0
- package/src/mcp-projects-events-http.test.ts +162 -0
- package/src/server.ts +17 -5
- package/src/status-alias-resolver-http.test.ts +163 -0
- package/src/status-alias-resolver.ts +19 -0
- package/src/tools.ts +58 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/commhub-server",
|
|
3
|
-
"version": "0.9.0-preview.
|
|
3
|
+
"version": "0.9.0-preview.83",
|
|
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/agent-access.ts
CHANGED
|
@@ -475,4 +475,9 @@ export const RESTRICTED_MEMBER_TOOLS: ReadonlySet<string> = new Set([
|
|
|
475
475
|
"requirements_checklist_toggle",
|
|
476
476
|
"requirements_upsert_by_external_ref",
|
|
477
477
|
"projects_list",
|
|
478
|
+
// 2026-10-02(app 任务页审计 M3):和 app「管理项目」/「动态」同一个 REST 处理,权限也同一套 —— 项目管理对仅相关任务的
|
|
479
|
+
// 成员和 viewer 一律 403;动态按任务可见性过滤,受限成员看不见的节点在里面隐去(listEvents 的 hiddenNodeFilter)。
|
|
480
|
+
"projects_create",
|
|
481
|
+
"projects_update",
|
|
482
|
+
"requirements_events",
|
|
478
483
|
]);
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// MCP projects_create / projects_update / requirements_events(app 任务页审计 2026-10-02 M3:Agent 能做人能做的)。
|
|
2
|
+
// HTTP 集成测试(真实 Bun.serve,私有端口,临时库)。三个工具都走 app 用的同一套 REST 处理(handleRequirementsRequest),
|
|
3
|
+
// 所以这里不另抄一份权限规则:对每类调用者(网络 owner、全部任务成员、仅相关任务成员、viewer、节点令牌)都同时调
|
|
4
|
+
// MCP 和 REST,断言状态码 / 结果逐项一致。再钉住正向行为(建 / 改名 / 归档 / 取消归档、读流水、"#N")和工具出现在 tools/list 里。
|
|
5
|
+
|
|
6
|
+
import { describe, expect, test, beforeAll, afterAll } from "bun:test";
|
|
7
|
+
import { mkdtempSync, rmSync } from "fs";
|
|
8
|
+
import { join } from "path";
|
|
9
|
+
import { tmpdir } from "os";
|
|
10
|
+
import { register, createNetworkTokenForNode } from "./auth.js";
|
|
11
|
+
import { db } from "./db.js";
|
|
12
|
+
|
|
13
|
+
const DIR = mkdtempSync(join(tmpdir(), "anet-mcp-projects-events-"));
|
|
14
|
+
let BASE = "";
|
|
15
|
+
let hub: any = null;
|
|
16
|
+
const PW = "McpProjectsEventsPassw0rd!x";
|
|
17
|
+
let NET = "";
|
|
18
|
+
const U: Record<string, { token: string; id: string }> = {};
|
|
19
|
+
|
|
20
|
+
async function rest(token: string, method: string, path: string, body?: unknown) {
|
|
21
|
+
const res = await fetch(`${BASE}${path}`, { method, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
22
|
+
const text = await res.text();
|
|
23
|
+
let json: any = null;
|
|
24
|
+
try { json = JSON.parse(text); } catch {}
|
|
25
|
+
return { status: res.status, body: json };
|
|
26
|
+
}
|
|
27
|
+
async function rpc(token: string, method: string, params?: unknown): Promise<any> {
|
|
28
|
+
const res = await fetch(`${BASE}/mcp`, {
|
|
29
|
+
method: "POST",
|
|
30
|
+
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26" },
|
|
31
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, ...(params === undefined ? {} : { params }) }),
|
|
32
|
+
});
|
|
33
|
+
const raw = await res.text();
|
|
34
|
+
const lines = raw.split("\n").filter(x => x.startsWith("data:"));
|
|
35
|
+
return lines.length ? JSON.parse(lines.at(-1)!.slice(5).trim()) : JSON.parse(raw);
|
|
36
|
+
}
|
|
37
|
+
async function mcp(token: string, name: string, args: Record<string, unknown>): Promise<any> {
|
|
38
|
+
const out = await rpc(token, "tools/call", { name, arguments: args });
|
|
39
|
+
return JSON.parse(out.result.content[0].text);
|
|
40
|
+
}
|
|
41
|
+
// MCP error bodies from the REST handler carry its status (requirementsCall). Anything else that isn't ok (e.g. a tool-level
|
|
42
|
+
// gate) is NOT a success — a body without `status` must never be read as the 2xx (that hid a gate in the first draft).
|
|
43
|
+
const mcpStatus = (r: any, okStatus: number) => (r?.ok === true || (r && r.ok === undefined && (r.project || r.events)) ? okStatus : typeof r?.status === "number" ? r.status : -1);
|
|
44
|
+
|
|
45
|
+
beforeAll(async () => {
|
|
46
|
+
process.env.COMMHUB_DB ||= join(DIR, "hub.db");
|
|
47
|
+
process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
|
|
48
|
+
process.env.HOST = "127.0.0.1";
|
|
49
|
+
const a = register(`mpe_owner_${Date.now()}`, PW, undefined, "Owner");
|
|
50
|
+
expect(a.ok).toBe(true);
|
|
51
|
+
U.owner = { token: a.token!, id: a.user!.user_id };
|
|
52
|
+
NET = a.network_id!;
|
|
53
|
+
db.run("UPDATE users SET role = 'admin' WHERE user_id = ?1", [U.owner.id]);
|
|
54
|
+
const mod: any = await import("./server.js");
|
|
55
|
+
hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
56
|
+
BASE = `http://127.0.0.1:${hub.port}`;
|
|
57
|
+
const mk = async (username: string, role: string) => {
|
|
58
|
+
expect((await rest(U.owner.token, "POST", "/api/admin/users", { username, password: PW, network_id: NET, role })).status).toBe(200);
|
|
59
|
+
const login = await rest("", "POST", "/api/auth/login", { username, password: PW });
|
|
60
|
+
expect(login.status).toBe(200);
|
|
61
|
+
return { token: login.body.token as string, id: login.body.user.user_id as string };
|
|
62
|
+
};
|
|
63
|
+
const stamp = Date.now();
|
|
64
|
+
U.member = await mk(`mpe_member_${stamp}`, "member");
|
|
65
|
+
U.scoped = await mk(`mpe_scoped_${stamp}`, "member");
|
|
66
|
+
U.viewer = await mk(`mpe_viewer_${stamp}`, "viewer");
|
|
67
|
+
db.run("UPDATE network_members SET task_access = 'all' WHERE network_id = ?1 AND user_id = ?2", [NET, U.member.id]);
|
|
68
|
+
expect((await rest(U.owner.token, "PUT", `/api/networks/${NET}/members/${U.scoped.id}/task-grants`, { task_access: "scoped", project_grants: [] })).status).toBe(200);
|
|
69
|
+
const node = createNetworkTokenForNode(U.owner.id, NET, "mpe-node", "node_mpe");
|
|
70
|
+
U.node = { token: node.token!, id: "node_mpe" };
|
|
71
|
+
}, 30_000);
|
|
72
|
+
|
|
73
|
+
afterAll(() => {
|
|
74
|
+
try { hub?.stop?.(true); } catch {}
|
|
75
|
+
try { rmSync(DIR, { recursive: true, force: true }); } catch {}
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe("discoverable", () => {
|
|
79
|
+
test("tools/list carries the three tools with descriptions", async () => {
|
|
80
|
+
const list = await rpc(U.owner.token, "tools/list");
|
|
81
|
+
const byName = new Map((list.result.tools as any[]).map(t => [t.name, t]));
|
|
82
|
+
for (const n of ["projects_create", "projects_update", "requirements_events"]) {
|
|
83
|
+
expect(byName.has(n)).toBe(true);
|
|
84
|
+
expect(String(byName.get(n).description).length).toBeGreaterThan(40);
|
|
85
|
+
}
|
|
86
|
+
expect(String(byName.get("projects_list").description)).toContain("projects_create");
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
describe("projects_create / projects_update", () => {
|
|
91
|
+
test("owner: create, rename, recolour, archive, unarchive — same rows the app sees", async () => {
|
|
92
|
+
const created = await mcp(U.owner.token, "projects_create", { network_id: NET, name: "mpe-项目甲" });
|
|
93
|
+
expect(created.ok).toBe(true);
|
|
94
|
+
const id = created.project.id as string;
|
|
95
|
+
expect(created.project.name).toBe("mpe-项目甲");
|
|
96
|
+
const renamed = await mcp(U.owner.token, "projects_update", { network_id: NET, id, name: "mpe-项目乙", color: "#16a34a" });
|
|
97
|
+
expect(renamed.project.name).toBe("mpe-项目乙");
|
|
98
|
+
expect(renamed.project.color).toBe("#16a34a");
|
|
99
|
+
expect((await mcp(U.owner.token, "projects_update", { network_id: NET, id, archived: true })).project.archived).toBe(true);
|
|
100
|
+
const seen = await rest(U.owner.token, "GET", `/api/requirements/projects?network_id=${NET}`);
|
|
101
|
+
expect(seen.body.projects.find((p: any) => p.id === id).archived).toBe(true);
|
|
102
|
+
expect((await mcp(U.owner.token, "projects_update", { network_id: NET, id, archived: false })).project.archived).toBe(false);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test("validation comes from the REST handler: duplicate name 409, unknown id 404", async () => {
|
|
106
|
+
await mcp(U.owner.token, "projects_create", { network_id: NET, name: "mpe-重名" });
|
|
107
|
+
const dup = await mcp(U.owner.token, "projects_create", { network_id: NET, name: "mpe-重名" });
|
|
108
|
+
expect(dup.ok).toBe(false);
|
|
109
|
+
expect(dup.status).toBe(409);
|
|
110
|
+
const missing = await mcp(U.owner.token, "projects_update", { network_id: NET, id: "proj_nobody", name: "x" });
|
|
111
|
+
expect(missing.status).toBe(404);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("permission parity with the app's REST path, for every kind of caller", async () => {
|
|
115
|
+
const results: Record<string, { mcp: number; rest: number }> = {};
|
|
116
|
+
for (const who of ["owner", "member", "scoped", "viewer", "node"]) {
|
|
117
|
+
const name = `mpe-parity-${who}`;
|
|
118
|
+
const viaMcp = await mcp(U[who].token, "projects_create", { network_id: NET, name: `${name}-mcp` });
|
|
119
|
+
const viaRest = await rest(U[who].token, "POST", `/api/requirements/projects?network_id=${NET}`, { name: `${name}-rest` });
|
|
120
|
+
results[who] = { mcp: mcpStatus(viaMcp, 201), rest: viaRest.status };
|
|
121
|
+
}
|
|
122
|
+
for (const r of Object.values(results)) expect(r.mcp).toBe(r.rest);
|
|
123
|
+
// the rule itself (RFC-038 §9): task-scoped members and viewers can't manage projects; the others can
|
|
124
|
+
expect(results.owner.rest).toBe(201);
|
|
125
|
+
expect(results.member.rest).toBe(201);
|
|
126
|
+
expect(results.scoped.rest).toBe(403);
|
|
127
|
+
expect(results.viewer.rest).toBe(403);
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
describe("requirements_events", () => {
|
|
132
|
+
test("one task's timeline by id and by #N, same rows as GET /api/requirements/events", async () => {
|
|
133
|
+
const card = await rest(U.owner.token, "POST", "/api/requirements", { network_id: NET, name: "mpe-流水示例" });
|
|
134
|
+
expect(card.status).toBe(201);
|
|
135
|
+
const id = card.body.requirement.id as string, seq = card.body.requirement.seq as number;
|
|
136
|
+
expect((await rest(U.owner.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { priority: "high" })).status).toBe(200);
|
|
137
|
+
const viaMcp = await mcp(U.owner.token, "requirements_events", { network_id: NET, requirement_id: id });
|
|
138
|
+
const viaRest = await rest(U.owner.token, "GET", `/api/requirements/events?network_id=${NET}&requirement_id=${id}`);
|
|
139
|
+
expect(viaMcp.ok).toBe(true);
|
|
140
|
+
expect(viaMcp.events.length).toBeGreaterThan(0);
|
|
141
|
+
expect(viaMcp.events.map((e: any) => e.id)).toEqual(viaRest.body.events.map((e: any) => e.id));
|
|
142
|
+
expect(viaMcp.events.every((e: any) => e.requirement_id === id)).toBe(true);
|
|
143
|
+
const bySeq = await mcp(U.owner.token, "requirements_events", { network_id: NET, requirement_id: `#${seq}` });
|
|
144
|
+
expect(bySeq.events.map((e: any) => e.id)).toEqual(viaMcp.events.map((e: any) => e.id));
|
|
145
|
+
// paging / bad input come from the REST handler too
|
|
146
|
+
expect((await mcp(U.owner.token, "requirements_events", { network_id: NET, since: "not-a-date" })).status).toBe(400);
|
|
147
|
+
expect((await mcp(U.owner.token, "requirements_events", { network_id: NET, requirement_id: "#999999" })).status).toBe(404);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test("visibility parity: a task-scoped member doesn't get events for a task they can't see", async () => {
|
|
151
|
+
const hidden = await rest(U.owner.token, "POST", "/api/requirements", { network_id: NET, name: "mpe-看不见的" });
|
|
152
|
+
const id = hidden.body.requirement.id as string;
|
|
153
|
+
await rest(U.owner.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { priority: "low" });
|
|
154
|
+
for (const who of ["scoped", "member", "node"]) {
|
|
155
|
+
const viaMcp = await mcp(U[who].token, "requirements_events", { network_id: NET, requirement_id: id });
|
|
156
|
+
const viaRest = await rest(U[who].token, "GET", `/api/requirements/events?network_id=${NET}&requirement_id=${id}`);
|
|
157
|
+
expect((viaMcp.events ?? []).map((e: any) => e.id)).toEqual((viaRest.body?.events ?? []).map((e: any) => e.id));
|
|
158
|
+
}
|
|
159
|
+
expect((await mcp(U.scoped.token, "requirements_events", { network_id: NET, requirement_id: id })).events ?? []).toHaveLength(0);
|
|
160
|
+
expect((await mcp(U.member.token, "requirements_events", { network_id: NET, requirement_id: id })).events.length).toBeGreaterThan(0);
|
|
161
|
+
});
|
|
162
|
+
});
|
package/src/server.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { buildServeErrorResponse } from "./serve-error.js";
|
|
2
2
|
import { maybeGzipResponse, trimLightTask } from "./http-gzip";
|
|
3
|
+
import { statusAliasResolverRead } from "./status-alias-resolver.js";
|
|
3
4
|
import { redactMessageRow } from "./redact-tokens.js";
|
|
4
5
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
5
6
|
import { parseDbTimestampMs } from "./db-timestamp.js";
|
|
@@ -2207,11 +2208,19 @@ return Bun.serve({
|
|
|
2207
2208
|
// take 12s+ on flaky cellular (Vincent tg, #220 PWA). Default response
|
|
2208
2209
|
// is unchanged so the dashboard / scripts that read full telemetry are
|
|
2209
2210
|
// unaffected.
|
|
2210
|
-
const isLight = url.searchParams.get("light") === "1";
|
|
2211
2211
|
const nodeIdFilter = url.searchParams.get("node_id")?.trim();
|
|
2212
|
+
// agent-node < 2.5.0-preview.93 resolves its own alias every 30 s with the WHOLE network's full projection
|
|
2213
|
+
// (~93 KB gzip on production) and reads only sessions[].node_id / .alias — under a hard 2.5 s abort. Over the
|
|
2214
|
+
// RELAY frp tunnel to a China-side machine (~50 KB/s per connection) the body often isn't done in 2.5 s: the
|
|
2215
|
+
// node aborts, the Hub has already pushed the body into the tunnel and frps drops it (~60% of the tunnel,
|
|
2216
|
+
// 2026-10-01). That caller has an exact signature no other client sends (statusAliasResolverRead): give it
|
|
2217
|
+
// the light projection + node_id (~28 KB gzip), which is all it reads. `?full=1` always gets the full body.
|
|
2218
|
+
const aliasResolverRead = statusAliasResolverRead(url.searchParams, requestToken(req), req.headers.get("accept"));
|
|
2219
|
+
const isLight = url.searchParams.get("light") === "1" || aliasResolverRead;
|
|
2220
|
+
const withNodeId = !!nodeIdFilter || aliasResolverRead;
|
|
2212
2221
|
const params: any[] = [];
|
|
2213
2222
|
let sql = isLight
|
|
2214
|
-
? `SELECT alias, status, agent, task, server, updated_at, network_id${
|
|
2223
|
+
? `SELECT alias, status, agent, task, server, updated_at, network_id${withNodeId ? ", node_id" : ""} FROM sessions WHERE 1=1`
|
|
2215
2224
|
: `SELECT ${SESSION_REST_SELECT} FROM sessions WHERE 1=1`;
|
|
2216
2225
|
sql = addAgentNetworkScope(sql, params, restScope, { alias: "alias", nodeId: "node_id" });
|
|
2217
2226
|
// `?alias=<name>` narrows to that one agent's rows (same projection, same scope). The app's
|
|
@@ -2249,8 +2258,9 @@ return Bun.serve({
|
|
|
2249
2258
|
updated_at: s.updated_at ?? null,
|
|
2250
2259
|
runtime: normalizeRuntime(s.agent),
|
|
2251
2260
|
network_id: s.network_id ?? null,
|
|
2252
|
-
// Only when filtering by node_id, so the unfiltered light response
|
|
2253
|
-
|
|
2261
|
+
// Only when filtering by node_id (or for the old alias resolver), so the unfiltered light response
|
|
2262
|
+
// keeps its exact bytes.
|
|
2263
|
+
...(withNodeId ? { node_id: s.node_id ?? null } : {}),
|
|
2254
2264
|
};
|
|
2255
2265
|
}
|
|
2256
2266
|
const externalSchedules = (() => {
|
|
@@ -2296,7 +2306,9 @@ return Bun.serve({
|
|
|
2296
2306
|
else acc.idle++;
|
|
2297
2307
|
return acc;
|
|
2298
2308
|
}, { idle: 0, working: 0, offline: 0, total: sessions.length });
|
|
2299
|
-
|
|
2309
|
+
const res = Response.json({ ok: true, sessions, summary });
|
|
2310
|
+
if (aliasResolverRead) res.headers.set("X-Status-Projection", "alias-resolver");
|
|
2311
|
+
return withCors(req, res);
|
|
2300
2312
|
}
|
|
2301
2313
|
|
|
2302
2314
|
// ── REST: aggregate agents by physical server ──
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// 旧版 agent-node(< 2.5.0-preview.93)找自己别名的全量 /api/status 读法 → light 投影 + node_id。
|
|
2
|
+
//
|
|
3
|
+
// 背景(2026-10-01,app「连接较慢」#431):生产上约 2.3 次/秒的全量状态读(~93 KB gzip)几乎都来自旧节点的
|
|
4
|
+
// CurrentAliasResolver,它只读 sessions[].node_id / .alias,且 2.5 s 硬超时。经 RELAY frp 隧道到国内机器时常常
|
|
5
|
+
// 读不完就中止,Hub 已经推进隧道的字节被丢掉(约占隧道 60%)。这里钉住:
|
|
6
|
+
// - 签名只认「节点令牌 + Accept 恰好 application/json + 只有 network_id」(statusAliasResolverRead);
|
|
7
|
+
// - 命中时回 light + node_id,旧解析器照旧解析出别名(含改名之后);
|
|
8
|
+
// - 不命中的(用户令牌 / CLI 不带 Accept / 浏览器 */* / light / node_id / alias / full=1 / 多值 Accept)字节不变;
|
|
9
|
+
// - 量体积:同一批行,完整投影 vs 这条读法的 gzip 字节。
|
|
10
|
+
|
|
11
|
+
import { describe, expect, test, beforeAll, afterAll } from "bun:test";
|
|
12
|
+
import { mkdtempSync, rmSync } from "fs";
|
|
13
|
+
import { join } from "path";
|
|
14
|
+
import { tmpdir } from "os";
|
|
15
|
+
import { gzipSync } from "zlib";
|
|
16
|
+
import { register, createNetworkTokenForNode } from "./auth.js";
|
|
17
|
+
import { db } from "./db.js";
|
|
18
|
+
import { statusAliasResolverRead } from "./status-alias-resolver.js";
|
|
19
|
+
|
|
20
|
+
const DIR = mkdtempSync(join(tmpdir(), "anet-status-alias-resolver-"));
|
|
21
|
+
let BASE = "";
|
|
22
|
+
let hub: any = null;
|
|
23
|
+
const PW = "StatusAliasResolverPassw0rd!";
|
|
24
|
+
let userToken = "", userId = "", NET = "";
|
|
25
|
+
let nodeToken = "";
|
|
26
|
+
const ROWS = 120;
|
|
27
|
+
|
|
28
|
+
function seed(i: number) {
|
|
29
|
+
const node = `node_sar_${i}`, alias = `sar-${i}`;
|
|
30
|
+
db.run(`INSERT INTO nodes (node_id, node_name, alias, network_id, owner_user_id) VALUES (?1, ?2, ?2, ?3, ?4)`, [node, alias, NET, userId]);
|
|
31
|
+
db.run(
|
|
32
|
+
`INSERT INTO sessions (resume_id, alias, node_id, status, network_id, task, output, project_dir, config_path, hostname, ip, server, agent, version,
|
|
33
|
+
cpu_load_1min, cpu_cores, mem_total_gb, mem_used_gb, mem_avail_gb, disk_total_gb, disk_used_gb, disk_avail_gb,
|
|
34
|
+
process_rss_bytes, process_rss_mb, process_cpu_pct, process_uptime_seconds, process_in_flight_count, updated_at, last_seen_at, registered_at)
|
|
35
|
+
VALUES (?1, ?2, ?3, 'idle', ?4, ?5, ?6, ?7, ?8, ?9, '10.0.0.' || ?10, ?9, 'agent-node:codex-app-server', '2.5.0-preview.88',
|
|
36
|
+
'1.5', '8', '61.4', '26.9', '34.5', '491.8', '442.2', '29.4', 121868288, 116.2, 0.2, 292866, 0,
|
|
37
|
+
datetime('now', '-' || ?10 || ' seconds'), datetime('now'), datetime('now', '-30 days'))`,
|
|
38
|
+
[`r_${node}`, alias, node, NET, `示例任务 ${i}:`.repeat(12), `示例输出 ${i} `.repeat(20), `/home/user/project-${i}`,
|
|
39
|
+
`/home/user/project-${i}/.anet/nodes/${alias}/config.json`, `sample-host-${i % 4}`, i],
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function req(path: string, headers: Record<string, string>) {
|
|
44
|
+
const res = await fetch(`${BASE}${path}`, { headers: { "Accept-Encoding": "gzip", ...headers } });
|
|
45
|
+
const text = await res.text();
|
|
46
|
+
return { status: res.status, text, body: JSON.parse(text) as any, projection: res.headers.get("x-status-projection") };
|
|
47
|
+
}
|
|
48
|
+
const asNode = (accept?: string) => ({ Authorization: `Bearer ${nodeToken}`, ...(accept !== undefined ? { Accept: accept } : {}) });
|
|
49
|
+
const gz = (s: string) => gzipSync(Buffer.from(s)).length;
|
|
50
|
+
|
|
51
|
+
// The exact call agent-node 2.5.0-preview.32 … .90 makes (dist/cli.js CurrentAliasResolver.fetchCanonicalAlias).
|
|
52
|
+
async function oldResolver(nodeId: string, token: string, networkId: string): Promise<string | null> {
|
|
53
|
+
try {
|
|
54
|
+
const headers: Record<string, string> = { Accept: "application/json" };
|
|
55
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
56
|
+
const url = `${BASE}/api/status${networkId ? `?network_id=${encodeURIComponent(networkId)}` : ""}`;
|
|
57
|
+
const ctl = new AbortController();
|
|
58
|
+
const timer = setTimeout(() => ctl.abort(), 2500);
|
|
59
|
+
try {
|
|
60
|
+
const res = await fetch(url, { headers, signal: ctl.signal });
|
|
61
|
+
if (!res.ok) return null;
|
|
62
|
+
const body = (await res.json()) as { sessions?: Array<{ node_id?: string; alias?: string }> };
|
|
63
|
+
return body.sessions?.find((s) => s.node_id === nodeId)?.alias ?? null;
|
|
64
|
+
} finally { clearTimeout(timer); }
|
|
65
|
+
} catch { return null; }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
beforeAll(async () => {
|
|
69
|
+
process.env.COMMHUB_DB ||= join(DIR, "hub.db");
|
|
70
|
+
process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
|
|
71
|
+
process.env.HOST = "127.0.0.1";
|
|
72
|
+
const a = register(`sar_owner_${Date.now()}`, PW);
|
|
73
|
+
userToken = a.token!; userId = a.user!.user_id; NET = a.network_id!;
|
|
74
|
+
for (let i = 0; i < ROWS; i++) seed(i);
|
|
75
|
+
nodeToken = createNetworkTokenForNode(userId, NET, "sar-7", "node_sar_7").token!;
|
|
76
|
+
const mod: any = await import("./server.js");
|
|
77
|
+
hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
78
|
+
BASE = `http://127.0.0.1:${hub.port}`;
|
|
79
|
+
}, 30_000);
|
|
80
|
+
|
|
81
|
+
afterAll(() => {
|
|
82
|
+
try { hub?.stop?.(true); } catch {}
|
|
83
|
+
try { rmSync(DIR, { recursive: true, force: true }); } catch {}
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
describe("statusAliasResolverRead (signature)", () => {
|
|
87
|
+
const p = (q: string) => new URLSearchParams(q);
|
|
88
|
+
test("matches only node token + Accept exactly application/json + at most network_id", () => {
|
|
89
|
+
expect(statusAliasResolverRead(p(""), "ntok_x", "application/json")).toBe(true);
|
|
90
|
+
expect(statusAliasResolverRead(p("network_id=net_1"), "ntok_x", "application/json")).toBe(true);
|
|
91
|
+
expect(statusAliasResolverRead(p("network_id=net_1"), "ntok_x", " Application/JSON ")).toBe(true);
|
|
92
|
+
expect(statusAliasResolverRead(p("network_id=net_1"), "utok_x", "application/json")).toBe(false);
|
|
93
|
+
expect(statusAliasResolverRead(p("network_id=net_1"), "legacy-global-token", "application/json")).toBe(false);
|
|
94
|
+
expect(statusAliasResolverRead(p("network_id=net_1"), "ntok_x", null)).toBe(false);
|
|
95
|
+
expect(statusAliasResolverRead(p("network_id=net_1"), "ntok_x", "*/*")).toBe(false);
|
|
96
|
+
expect(statusAliasResolverRead(p("network_id=net_1"), "ntok_x", "application/json, text/plain, */*")).toBe(false);
|
|
97
|
+
for (const q of ["light=1", "node_id=n", "alias=a", "full=1", "network_id=n&full=1", "network_id=n&light=0"]) {
|
|
98
|
+
expect(statusAliasResolverRead(p(q), "ntok_x", "application/json")).toBe(false);
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
describe("GET /api/status for the old alias resolver", () => {
|
|
104
|
+
test("old resolver still resolves its alias from the light body", async () => {
|
|
105
|
+
expect(await oldResolver("node_sar_7", nodeToken, NET)).toBe("sar-7");
|
|
106
|
+
expect(await oldResolver("node_sar_7", nodeToken, "")).toBe("sar-7");
|
|
107
|
+
// other rows are resolvable too (the resolver can be asked about a renamed peer id) and an unknown id is null
|
|
108
|
+
expect(await oldResolver("node_sar_42", nodeToken, NET)).toBe("sar-42");
|
|
109
|
+
expect(await oldResolver("node_nobody", nodeToken, NET)).toBeNull();
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test("…and follows a rename (the reason the resolver exists)", async () => {
|
|
113
|
+
db.run("UPDATE sessions SET alias = 'sar-7-renamed' WHERE node_id = 'node_sar_7'");
|
|
114
|
+
try {
|
|
115
|
+
expect(await oldResolver("node_sar_7", nodeToken, NET)).toBe("sar-7-renamed");
|
|
116
|
+
} finally {
|
|
117
|
+
db.run("UPDATE sessions SET alias = 'sar-7' WHERE node_id = 'node_sar_7'");
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test("the body is the light projection plus node_id, marked by a header", async () => {
|
|
122
|
+
const r = await req(`/api/status?network_id=${NET}`, asNode("application/json"));
|
|
123
|
+
expect(r.status).toBe(200);
|
|
124
|
+
expect(r.projection).toBe("alias-resolver");
|
|
125
|
+
expect(r.body.sessions).toHaveLength(ROWS);
|
|
126
|
+
expect(Object.keys(r.body.sessions[0]).sort()).toEqual(["agent", "alias", "network_id", "node_id", "runtime", "server", "status", "task", "updated_at"]);
|
|
127
|
+
expect(r.body.summary.total).toBe(ROWS);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test("everything else is byte-identical to the full projection", async () => {
|
|
131
|
+
const full = await req(`/api/status?network_id=${NET}&full=1`, asNode("application/json"));
|
|
132
|
+
expect(full.projection).toBeNull();
|
|
133
|
+
expect(full.body.sessions[0].host).toBeDefined();
|
|
134
|
+
const same = [
|
|
135
|
+
await req(`/api/status?network_id=${NET}`, { Authorization: `Bearer ${userToken}`, Accept: "application/json" }), // user token (app / dashboard)
|
|
136
|
+
await req(`/api/status?network_id=${NET}`, asNode()), // anet CLI: authHeaders() only
|
|
137
|
+
await req(`/api/status?network_id=${NET}`, asNode("*/*")), // browser / undici / bun default
|
|
138
|
+
await req(`/api/status?network_id=${NET}`, asNode("application/json, text/plain, */*")),
|
|
139
|
+
];
|
|
140
|
+
for (const r of same) {
|
|
141
|
+
expect(r.projection).toBeNull();
|
|
142
|
+
expect(r.body.sessions[0].host).toBeDefined();
|
|
143
|
+
expect(r.text).toBe(full.text);
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test("light / node_id reads keep their own exact shape", async () => {
|
|
148
|
+
const light = await req(`/api/status?network_id=${NET}&light=1`, asNode("application/json"));
|
|
149
|
+
expect(light.projection).toBeNull();
|
|
150
|
+
expect(light.body.sessions[0].node_id).toBeUndefined();
|
|
151
|
+
const one = await req(`/api/status?network_id=${NET}&node_id=node_sar_7&light=1`, asNode("application/json"));
|
|
152
|
+
expect(one.body.sessions).toHaveLength(1);
|
|
153
|
+
expect(one.body.sessions[0].node_id).toBe("node_sar_7");
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test("size: full projection vs the alias-resolver body (gzip)", async () => {
|
|
157
|
+
const full = await req(`/api/status?network_id=${NET}&full=1`, asNode("application/json"));
|
|
158
|
+
const slim = await req(`/api/status?network_id=${NET}`, asNode("application/json"));
|
|
159
|
+
const f = gz(full.text), s = gz(slim.text);
|
|
160
|
+
console.log(`[size] ${ROWS} rows: full ${full.text.length} B raw / ${f} B gzip → alias-resolver ${slim.text.length} B raw / ${s} B gzip (${Math.round(100 - (100 * s) / f)}% smaller)`);
|
|
161
|
+
expect(s).toBeLessThan(f / 2);
|
|
162
|
+
});
|
|
163
|
+
});
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// GET /api/status 的「旧版 agent-node 找自己别名」读法识别(纯函数,可单测)。
|
|
2
|
+
//
|
|
3
|
+
// agent-node < 2.5.0-preview.93 的 CurrentAliasResolver 每 30 s 读一次全网完整 /api/status,只用
|
|
4
|
+
// sessions[].node_id / .alias,并且 2.5 s 硬超时。它的请求有一个别的客户端都不发的签名(2026-10-01 逐个核过
|
|
5
|
+
// 线上在用的 agent-node .32–.93 包、agent-network CLI 2.2.21 / 2.3.0-preview.76–.120 源码、dashboard、
|
|
6
|
+
// claude-code 节点的 .anet/node-server.js):
|
|
7
|
+
// - 节点令牌(ntok_);
|
|
8
|
+
// - Accept 恰好是 `application/json`(CLI 的 authHeaders 只带 Authorization;浏览器 / undici / bun 默认 `*/*`);
|
|
9
|
+
// - 查询串里除了 network_id 什么都没有(不带 light / node_id / alias / full)。
|
|
10
|
+
// 命中 ⇒ 回 light 投影 + node_id(它读的就这两列)。`?full=1` 永远拿完整投影。
|
|
11
|
+
|
|
12
|
+
const ALLOWED_PARAMS = new Set(["network_id"]);
|
|
13
|
+
|
|
14
|
+
export function statusAliasResolverRead(params: URLSearchParams, token: string, accept: string | null): boolean {
|
|
15
|
+
if (!token.startsWith("ntok_")) return false;
|
|
16
|
+
if ((accept ?? "").trim().toLowerCase() !== "application/json") return false;
|
|
17
|
+
for (const key of params.keys()) if (!ALLOWED_PARAMS.has(key)) return false;
|
|
18
|
+
return true;
|
|
19
|
+
}
|
package/src/tools.ts
CHANGED
|
@@ -5888,10 +5888,67 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
5888
5888
|
|
|
5889
5889
|
server.tool(
|
|
5890
5890
|
"projects_list",
|
|
5891
|
-
"List requirement projects in your network (id, name, color, sort, archived).",
|
|
5891
|
+
"List requirement projects in your network (id, name, color, sort, archived). Manage them with projects_create / projects_update.",
|
|
5892
5892
|
{ network_id: z.string().max(200).optional() },
|
|
5893
5893
|
async ({ network_id }) => requirementsCall("GET", "/api/requirements/projects", network_id),
|
|
5894
5894
|
);
|
|
5895
|
+
|
|
5896
|
+
// Agent parity (app task audit 2026-10-02 M3): what people do under 管理项目 and the task 动态 timeline. Both go
|
|
5897
|
+
// through the same REST handlers as the app, so every permission check is the app's own: project management needs
|
|
5898
|
+
// write access and is refused to 「仅相关任务」(task-scoped) members; events use the task list's visibility.
|
|
5899
|
+
server.tool(
|
|
5900
|
+
"projects_create",
|
|
5901
|
+
"Create a requirement project in your network (same as 管理项目 → 新建 in the app). name 1–40 characters, unique in the network; color #RRGGBB (default: next palette colour); sort integer. Returns { project }. Refused (403) for task-scoped members and read-only roles.",
|
|
5902
|
+
{
|
|
5903
|
+
network_id: z.string().max(200).optional(),
|
|
5904
|
+
name: z.string().min(1).max(40),
|
|
5905
|
+
color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),
|
|
5906
|
+
sort: z.number().int().optional(),
|
|
5907
|
+
},
|
|
5908
|
+
async (args) => requirementsCall("POST", "/api/requirements/projects", args.network_id, pick(args, ["name", "color", "sort"])),
|
|
5909
|
+
);
|
|
5910
|
+
|
|
5911
|
+
server.tool(
|
|
5912
|
+
"projects_update",
|
|
5913
|
+
"Rename, recolour, reorder, archive or unarchive a requirement project (same as 管理项目 in the app). Only the fields you pass change. archived=true hides it from pickers (its tasks keep project_id); archived=false brings it back. Returns { project }. Refused (403) for task-scoped members and read-only roles.",
|
|
5914
|
+
{
|
|
5915
|
+
network_id: z.string().max(200).optional(),
|
|
5916
|
+
id: z.string().min(1).max(200).describe("project id (proj_…), from projects_list"),
|
|
5917
|
+
name: z.string().min(1).max(40).optional(),
|
|
5918
|
+
color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),
|
|
5919
|
+
sort: z.number().int().optional(),
|
|
5920
|
+
archived: z.boolean().optional(),
|
|
5921
|
+
},
|
|
5922
|
+
async (args) => requirementsCall("PATCH", `/api/requirements/projects/${encodeURIComponent(args.id)}`, args.network_id, pick(args, ["name", "color", "sort", "archived"])),
|
|
5923
|
+
);
|
|
5924
|
+
|
|
5925
|
+
server.tool(
|
|
5926
|
+
"requirements_events",
|
|
5927
|
+
"Read the task activity timeline (the app's 动态): field-level changes — who, when, old → new — newest first. Pass requirement_id (req_… or \"#N\") for one task, or omit it for the whole network. since (ISO) = only changes after it; limit 1–500 (default 200); next_cursor → pass as cursor for the next page; server_time → use as the next since. Same visibility as requirements_list: tasks you can't see (and hidden Agents) are left out.",
|
|
5928
|
+
{
|
|
5929
|
+
network_id: z.string().max(200).optional(),
|
|
5930
|
+
requirement_id: z.string().min(1).max(200).optional(),
|
|
5931
|
+
since: z.string().max(40).optional(),
|
|
5932
|
+
limit: z.number().int().min(1).max(500).optional(),
|
|
5933
|
+
cursor: z.string().max(20).optional(),
|
|
5934
|
+
},
|
|
5935
|
+
async (args) => {
|
|
5936
|
+
let card = args.requirement_id;
|
|
5937
|
+
// "#N" → the card's id, resolved exactly like requirements_get (same scope; a card you can't see is a 404 here too).
|
|
5938
|
+
if (card && /^#\d+$/.test(card)) {
|
|
5939
|
+
const got = await requirementsCall("GET", `/api/requirements/${encodeURIComponent(card)}`, args.network_id);
|
|
5940
|
+
const parsed = JSON.parse(got.content[0].text) as { requirement?: { id?: string } };
|
|
5941
|
+
if (!parsed.requirement?.id) return got;
|
|
5942
|
+
card = parsed.requirement.id;
|
|
5943
|
+
}
|
|
5944
|
+
const q = new URLSearchParams();
|
|
5945
|
+
if (card) q.set("requirement_id", card);
|
|
5946
|
+
if (args.since) q.set("since", args.since);
|
|
5947
|
+
if (args.limit !== undefined) q.set("limit", String(args.limit));
|
|
5948
|
+
if (args.cursor) q.set("cursor", args.cursor);
|
|
5949
|
+
return requirementsCall("GET", `/api/requirements/events${q.size ? `?${q}` : ""}`, args.network_id);
|
|
5950
|
+
},
|
|
5951
|
+
);
|
|
5895
5952
|
}
|
|
5896
5953
|
|
|
5897
5954
|
// ────────────────────────────────────────────────────────────────────
|