@m-cpy/pi-a2a-inbox 0.0.0-stage → 0.5.0
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/CHANGELOG.md +22 -0
- package/LICENSE +201 -0
- package/NOTICE +27 -0
- package/README.md +170 -2
- package/config.example.json +20 -0
- package/extensions/config.ts +150 -0
- package/extensions/envelope.ts +489 -0
- package/extensions/inbox.ts +617 -0
- package/extensions/index.ts +473 -0
- package/extensions/worker.ts +50 -0
- package/package.json +56 -3
- package/skills/pi-a2a-inbox/SKILL.md +61 -0
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* envelope.ts — a2a-inbox/v1 信封层(L1,PROTOCOL-v3 §9)。
|
|
3
|
+
* 保留 v2 验证过的资产:HTTP/AgentCard/Bearer 鉴权/静态 peer/sessions 读投影。
|
|
4
|
+
* 删除 v2 语义:双类型消息、任务转发、三档投递、排队 RPC、反向结果、同步等待(均无运行时调用方)。
|
|
5
|
+
* SendMessage → inbox.receive(投递回执);Task 降级为回执(§1)。
|
|
6
|
+
* 单写者(§4.12):bind 失败 → clientOnly,不开 inbox。
|
|
7
|
+
*/
|
|
8
|
+
import http from "node:http";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
import crypto from "node:crypto";
|
|
11
|
+
import { A2aConfig, StaticPeerConfig } from "./config";
|
|
12
|
+
import { Inbox, EXT_URI, MAX_BODY, MAX_TOPIC, Receipt } from "./inbox";
|
|
13
|
+
import { listSessions, getSession } from "./worker";
|
|
14
|
+
import fs from "node:fs";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
|
|
17
|
+
const A2AVER = "1.0";
|
|
18
|
+
// 卡片版本跟随 package.json(单一来源,防 hardcoded 与线上代码漂移;DSH 0872ac1 同口径)
|
|
19
|
+
const PKG_VERSION = (() => { try { return JSON.parse(fs.readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8")).version ?? "0.0.0"; } catch { return "0.0.0"; } })();
|
|
20
|
+
const POST_TIMEOUT_MS = 30_000;
|
|
21
|
+
const REFRESH_INTERVAL_MS = 60_000;
|
|
22
|
+
const PEER_TTL_MS = 600_000;
|
|
23
|
+
const SELF_PROBE_INTERVAL_MS = 120_000; // 周期自探针:启动只测一次测不出后来聋(qwenpaw deaf→RECOVERED)
|
|
24
|
+
|
|
25
|
+
const ERR_PARSE = -32700;
|
|
26
|
+
const ERR_INVALID_REQ = -32600;
|
|
27
|
+
const ERR_METHOD_NOT_FOUND = -32601;
|
|
28
|
+
const ERR_INVALID_PARAMS = -32602;
|
|
29
|
+
const ERR_INTERNAL = -32603;
|
|
30
|
+
const ERR_SESSION_NOT_FOUND = -32040;
|
|
31
|
+
const ERR_UNAUTHORIZED = -32041;
|
|
32
|
+
const ERR_PEER_UNREACHABLE = -32042;
|
|
33
|
+
const ERR_DUPLICATE = -32043;
|
|
34
|
+
const ERR_BOX_FULL = -32044;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The wire error codes, as one machine-readable table.
|
|
38
|
+
*
|
|
39
|
+
* Exported so tests assert uniqueness on **this**, not on a copy typed into
|
|
40
|
+
* the test file: a copy can stay self-consistent while the implementation
|
|
41
|
+
* drifts, which is how a duplicate value reaches production and shows up as
|
|
42
|
+
* "the client took the wrong action" instead of a failure.
|
|
43
|
+
*/
|
|
44
|
+
export const ERROR_CODES = {
|
|
45
|
+
ERR_PARSE,
|
|
46
|
+
ERR_INVALID_REQ,
|
|
47
|
+
ERR_METHOD_NOT_FOUND,
|
|
48
|
+
ERR_INVALID_PARAMS,
|
|
49
|
+
ERR_INTERNAL,
|
|
50
|
+
ERR_SESSION_NOT_FOUND,
|
|
51
|
+
ERR_UNAUTHORIZED,
|
|
52
|
+
ERR_PEER_UNREACHABLE,
|
|
53
|
+
ERR_DUPLICATE,
|
|
54
|
+
ERR_BOX_FULL,
|
|
55
|
+
} as const;
|
|
56
|
+
|
|
57
|
+
export interface Peer {
|
|
58
|
+
peerName: string; host: string; port: number; lastSeen: number;
|
|
59
|
+
static?: boolean; gossip?: boolean; bearer?: string; inboundToken?: string; rpcUrl?: string; cardUrl?: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function genId(p: string) { return p + "_" + crypto.randomBytes(5).toString("hex"); }
|
|
63
|
+
function isoNow() { return new Date().toISOString(); }
|
|
64
|
+
function rpcResult(id: any, result: unknown) { return { jsonrpc: "2.0", id, result }; }
|
|
65
|
+
function rpcError(id: any, code: number, message: string, data?: unknown) {
|
|
66
|
+
const err: any = { code, message }; if (data !== undefined) err.data = data;
|
|
67
|
+
return { jsonrpc: "2.0", id, error: err };
|
|
68
|
+
}
|
|
69
|
+
function extractText(parts: any[]): string {
|
|
70
|
+
if (!Array.isArray(parts)) return "";
|
|
71
|
+
return parts.map(p => typeof p?.text === "string" ? p.text : "").filter(Boolean).join("\n");
|
|
72
|
+
}
|
|
73
|
+
const VIRTUAL_IFACE_RE = /^(docker|br-|veth|vEthernet|WSL|Hyper-V|VMware|VMnet|VirtualBox|TAP|tun|utun|llw|awdl|bridge|tap|p2p|anpi)/i;
|
|
74
|
+
function getLocalLanIp(): string {
|
|
75
|
+
try {
|
|
76
|
+
let fb = "";
|
|
77
|
+
for (const [name, list] of Object.entries(os.networkInterfaces())) {
|
|
78
|
+
for (const i of list ?? []) {
|
|
79
|
+
if (i.internal || i.family !== "IPv4") continue;
|
|
80
|
+
if (VIRTUAL_IFACE_RE.test(name)) { if (!fb) fb = i.address; continue; }
|
|
81
|
+
return i.address;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (fb) return fb;
|
|
85
|
+
} catch { /* ignore */ }
|
|
86
|
+
return "127.0.0.1";
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export class Envelope {
|
|
90
|
+
private server: http.Server | null = null;
|
|
91
|
+
private listenPort = 0;
|
|
92
|
+
private lanIp = "127.0.0.1";
|
|
93
|
+
private peers = new Map<string, Peer>();
|
|
94
|
+
private selfNonce = crypto.randomBytes(16).toString("hex"); // 进程内随机 nonce,自探针带它→仍 401 但记 selfProbes 不污染 authReject(qwenpaw cfb65c2)
|
|
95
|
+
private reqId = 0;
|
|
96
|
+
private refreshTimer: NodeJS.Timeout | null = null;
|
|
97
|
+
private receipts = new Map<string, { receipt: Receipt; contextId: string }>();
|
|
98
|
+
clientOnly = false; // bind 失败降级(§4.12)
|
|
99
|
+
|
|
100
|
+
constructor(private config: A2aConfig, private inbox: Inbox, private log: (...a: unknown[]) => void) {}
|
|
101
|
+
|
|
102
|
+
getListenPort() { return this.listenPort; }
|
|
103
|
+
private get rpcPath() { return this.config.rpcPath ?? "/rpc"; }
|
|
104
|
+
private get cardPath() { return this.config.agentCardPath ?? "/.well-known/agent-card.json"; }
|
|
105
|
+
|
|
106
|
+
async start(): Promise<void> {
|
|
107
|
+
this.lanIp = this.config.advertiseHost?.trim() || getLocalLanIp();
|
|
108
|
+
try {
|
|
109
|
+
await this.startHttp();
|
|
110
|
+
} catch (e: any) {
|
|
111
|
+
if (e?.code === "EADDRINUSE") {
|
|
112
|
+
// 单写者:端口被占 → 降级纯客户端,不开 inbox(§4.12 / 验收 25)
|
|
113
|
+
this.clientOnly = true;
|
|
114
|
+
this.log(`端口 ${this.config.listenPort} 被占 → 降级纯客户端(inbox 由端口所有者运行)`);
|
|
115
|
+
} else throw e;
|
|
116
|
+
}
|
|
117
|
+
await this.loadStaticPeers();
|
|
118
|
+
this.refreshTimer = setInterval(() => void this.refreshPeers(), REFRESH_INTERVAL_MS);
|
|
119
|
+
if (!this.clientOnly) { void this.probeOnce(true); this.selfProbeTimer = setInterval(() => void this.probeOnce(false), SELF_PROBE_INTERVAL_MS); } // 启动自检 + 周期探活
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async stop(): Promise<void> {
|
|
123
|
+
if (this.refreshTimer) { clearInterval(this.refreshTimer); this.refreshTimer = null; }
|
|
124
|
+
if (this.selfProbeTimer) { clearInterval(this.selfProbeTimer); this.selfProbeTimer = null; }
|
|
125
|
+
if (this.server) { const s = this.server; this.server = null; await new Promise<void>(r => s.close(() => r())); }
|
|
126
|
+
this.peers.clear();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// 启动自检 + 周期自探针(qwenpaw 三次 sidecar 聋掉教训:启动只测一次测不出后来聋):带 nonce 打自己 RPC,nonce 记 selfProbes 不污染 authReject
|
|
130
|
+
private probeDeaf = false;
|
|
131
|
+
private selfProbeTimer: ReturnType<typeof setInterval> | null = null;
|
|
132
|
+
private async probeOnce(startup = false): Promise<void> {
|
|
133
|
+
const ctrl = new AbortController(); const t = setTimeout(() => ctrl.abort(), 5000);
|
|
134
|
+
let status: "ok" | "deaf" | "warn" = "ok";
|
|
135
|
+
try {
|
|
136
|
+
const resp = await fetch(`http://127.0.0.1:${this.listenPort}${this.rpcPath}`, { method: "POST", signal: ctrl.signal, headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.selfNonce}` }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "peers/list", params: {} }) });
|
|
137
|
+
const body: any = await resp.json().catch(() => null);
|
|
138
|
+
if (resp.status === 401 && body?.error?.code === ERR_UNAUTHORIZED) status = "ok"; else status = "warn";
|
|
139
|
+
} catch { status = "deaf"; }
|
|
140
|
+
finally { clearTimeout(t); }
|
|
141
|
+
if (startup) {
|
|
142
|
+
if (status === "ok") this.log(`[a2a] self-probe OK: RPC accepts connections (401 shape correct, counted as selfProbes not authReject)`);
|
|
143
|
+
else if (status === "deaf") this.log(`[a2a] self-probe FAIL: RPC no response within 5s — sidecar may be deaf (binds port but not accepting); restart the plugin`);
|
|
144
|
+
else this.log(`[a2a] self-probe WARN: unexpected response (门禁回退?)`);
|
|
145
|
+
this.probeDeaf = status === "deaf";
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
// 周期:状态迁移才喊(防刷屏,同 qwenpaw idle 哨兵状态位)
|
|
149
|
+
if (status === "deaf" && !this.probeDeaf) { this.probeDeaf = true; this.log(`[a2a] sidecar probe deaf | ReadTimeout | fix: unload -> install (restart plugin)`); }
|
|
150
|
+
else if (status === "ok" && this.probeDeaf) { this.probeDeaf = false; this.log(`[a2a] sidecar probe RECOVERED (was deaf)`); }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// ── peer 表 ──
|
|
154
|
+
getPeers(): Peer[] { return [...this.peers.values()]; }
|
|
155
|
+
getPeer(name: string) { return this.peers.get(name); }
|
|
156
|
+
isOnline(name: string) { const p = this.peers.get(name); return !!p && (p.static || p.gossip || p.lastSeen >= Date.now() - PEER_TTL_MS); }
|
|
157
|
+
|
|
158
|
+
private async loadStaticPeers() { for (const sp of this.config.peers ?? []) if (sp?.name && sp?.url) await this.refreshStaticPeer(sp); this.auditPeerConflicts(); }
|
|
159
|
+
/** 加载时告警(B 规则三层之二):重复入站凭据指名冲突两对端;I4 重复 cardUrl 地址(ADDRESS_TAKEN)。面板/日志可见。 */
|
|
160
|
+
private auditPeerConflicts() {
|
|
161
|
+
const peers = this.config.peers ?? [];
|
|
162
|
+
const byTok = new Map<string, string[]>(); const byUrl = new Map<string, string[]>();
|
|
163
|
+
for (const p of peers) {
|
|
164
|
+
if (!p?.name) continue;
|
|
165
|
+
const tok = p.inboundToken ?? p.bearer;
|
|
166
|
+
if (tok) { const a = byTok.get(tok) ?? []; a.push(p.name); byTok.set(tok, a); }
|
|
167
|
+
if (p.url) { const u = p.url.trim(); const a = byUrl.get(u) ?? []; a.push(p.name); byUrl.set(u, a); }
|
|
168
|
+
}
|
|
169
|
+
for (const [tok, names] of byTok) if (names.length > 1) this.log(`[a2a] ⚠️ 入站凭据冲突(B规则/I6):尾${tok.slice(-4)} 同时映射 ${names.join(", ")} → 该凭据请求一律 401;请给每个 peer 专属 inboundToken`);
|
|
170
|
+
for (const [url, names] of byUrl) if (names.length > 1) this.log(`[a2a] ⚠️ 地址冲突(I4 ADDRESS_TAKEN):${url} 同时被 ${names.join(", ")} 使用 → 一个 cardUrl 只能对应一个 peer 名`);
|
|
171
|
+
}
|
|
172
|
+
async addStaticPeer(sp: StaticPeerConfig) { await this.refreshStaticPeer(sp); }
|
|
173
|
+
private async refreshPeers() { for (const sp of this.config.peers ?? []) if (sp?.name && sp?.url) await this.refreshStaticPeer(sp); }
|
|
174
|
+
|
|
175
|
+
private async refreshStaticPeer(sp: StaticPeerConfig) {
|
|
176
|
+
const card = await this.fetchCard(sp.url, sp.bearer?.trim() || undefined);
|
|
177
|
+
let rpcUrl = card ? this.cardRpcUrl(card) : undefined;
|
|
178
|
+
if (rpcUrl) { try { const u = new URL(rpcUrl); if (["0.0.0.0", "::", "[::]"].includes(u.hostname)) { u.hostname = new URL(sp.url).hostname; rpcUrl = u.toString(); } } catch { /* keep */ } }
|
|
179
|
+
const ex = this.peers.get(sp.name);
|
|
180
|
+
let host = ex?.host ?? "", port = ex?.port ?? 0;
|
|
181
|
+
try { const u = new URL(rpcUrl ?? sp.url); host = u.hostname; port = Number(u.port || (u.protocol === "https:" ? 443 : 80)); } catch { /* keep */ }
|
|
182
|
+
this.peers.set(sp.name, {
|
|
183
|
+
peerName: sp.name, host, port, lastSeen: card ? Date.now() : (ex?.lastSeen ?? 0),
|
|
184
|
+
static: true, bearer: sp.bearer?.trim() || undefined, inboundToken: sp.inboundToken?.trim() || undefined, rpcUrl: rpcUrl ?? ex?.rpcUrl, cardUrl: sp.url,
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
private async fetchCard(url: string, bearer?: string): Promise<any | null> {
|
|
189
|
+
const ctrl = new AbortController(); const t = setTimeout(() => ctrl.abort(), POST_TIMEOUT_MS);
|
|
190
|
+
try { const r = await fetch(url, { signal: ctrl.signal, headers: bearer ? { Authorization: `Bearer ${bearer}` } : undefined }); return r.ok ? await r.json() : null; }
|
|
191
|
+
catch { return null; } finally { clearTimeout(t); }
|
|
192
|
+
}
|
|
193
|
+
private cardRpcUrl(card: any): string | undefined {
|
|
194
|
+
const ifaces = Array.isArray(card?.supportedInterfaces) ? card.supportedInterfaces : [];
|
|
195
|
+
const i = ifaces.find((x: any) => String(x?.protocolBinding ?? "").toUpperCase() === "JSONRPC") ?? ifaces[0];
|
|
196
|
+
const u = i?.url ?? card?.url;
|
|
197
|
+
return typeof u === "string" && /^https?:\/\//.test(u) ? u : undefined;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ── HTTP ──
|
|
201
|
+
private startHttp(): Promise<void> {
|
|
202
|
+
return new Promise((resolve, reject) => {
|
|
203
|
+
this.server = http.createServer((req, res) => void this.handle(req, res));
|
|
204
|
+
const port = this.config.listenPort ?? 0;
|
|
205
|
+
this.server.once("error", reject);
|
|
206
|
+
this.server.listen(port, "0.0.0.0", () => {
|
|
207
|
+
const a = this.server!.address(); this.listenPort = typeof a === "object" && a ? a.port : port;
|
|
208
|
+
this.log(`A2A HTTP 监听 0.0.0.0:${this.listenPort} (lanIp=${this.lanIp})`);
|
|
209
|
+
resolve();
|
|
210
|
+
});
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private async handle(req: http.IncomingMessage, res: http.ServerResponse) {
|
|
215
|
+
const url = req.url ?? "";
|
|
216
|
+
try {
|
|
217
|
+
if (req.method === "GET" && url === this.cardPath) return this.json(res, 200, this.agentCard(), { "Cache-Control": "max-age=60" });
|
|
218
|
+
if (req.method === "GET" && url === "/health") return this.json(res, 200, { status: "ok", peer: this.config.peerName, proto: "a2a-inbox/v1", clientOnly: this.clientOnly });
|
|
219
|
+
if (req.method === "POST" && url === this.rpcPath) return this.handleRpc(req, res);
|
|
220
|
+
this.json(res, 404, { error: "Not found" });
|
|
221
|
+
} catch (e) { this.log(`handle 异常: ${e instanceof Error ? e.message : String(e)}`); try { this.json(res, 500, { error: "internal" }); } catch { /* ignore */ } }
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
private bearerSecret(req: http.IncomingMessage): string {
|
|
225
|
+
const a = req.headers["authorization"];
|
|
226
|
+
return typeof a === "string" && a.startsWith("Bearer ") ? a.slice(7).trim() : "";
|
|
227
|
+
}
|
|
228
|
+
private checkAuth(req: http.IncomingMessage): boolean {
|
|
229
|
+
const secret = this.bearerSecret(req);
|
|
230
|
+
if (secret === "") return false;
|
|
231
|
+
// B 规则(I6/Q4,跨端统一):一枚入站凭据指向 >1 对端=哪边都不算 → 一律 401,不 first-wins、不记一笔照收
|
|
232
|
+
let n = 0;
|
|
233
|
+
for (const p of this.peers.values()) { const tok = p.inboundToken ?? p.bearer; if (tok && tok === secret) n++; }
|
|
234
|
+
if (n > 1) return false;
|
|
235
|
+
if (n === 1) return true; // per-peer 入站 token 放行
|
|
236
|
+
return secret === this.config.workspaceSecret; // 匿名入口 _shared(不产生 peer 身份)
|
|
237
|
+
}
|
|
238
|
+
/** 由 Bearer 匹配出站 peer 名(metadata.from 已删,peer 身份靠 token)。 */
|
|
239
|
+
private peerByAuth(req: http.IncomingMessage): string {
|
|
240
|
+
const secret = this.bearerSecret(req);
|
|
241
|
+
let matched = ""; let n = 0;
|
|
242
|
+
for (const p of this.peers.values()) { const tok = p.inboundToken ?? p.bearer; if (tok && tok === secret) { matched = p.peerName; n++; } }
|
|
243
|
+
if (n > 1) { this.inbox?.noteReject("ambiguousToken"); return "_shared"; } // checkAuth 已 401;防御:歧义凭据不返回任何 peer 身份
|
|
244
|
+
return matched || "_shared"; // P0-A:共享 workspaceSecret 不产生 peer 身份(记匿名);未知 token 已被 checkAuth 拒,不回落 _default
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
private async handleRpc(req: http.IncomingMessage, res: http.ServerResponse) {
|
|
248
|
+
let body: any;
|
|
249
|
+
try { body = await this.readBody(req); } catch { return this.rpcJson(res, null, rpcError(null, ERR_PARSE, "Invalid JSON")); }
|
|
250
|
+
const id = body?.id ?? null;
|
|
251
|
+
if (!this.checkAuth(req)) {
|
|
252
|
+
const sec = this.bearerSecret(req);
|
|
253
|
+
let n = 0; for (const p of this.peers.values()) { const tok = p.inboundToken ?? p.bearer; if (tok && tok === sec) n++; }
|
|
254
|
+
if (sec === this.selfNonce) this.inbox?.noteSelfProbe();
|
|
255
|
+
else this.inbox?.noteReject(sec === "" ? "noToken" : n > 1 ? "ambiguousToken" : "unknownToken");
|
|
256
|
+
const hint = n > 1
|
|
257
|
+
? "this inbound token maps to multiple peers; each peer must have a unique inbound token (B rule / I6: one credential -> one identity)"
|
|
258
|
+
: "Inbound accepts workspaceSecret or any peer's inboundToken/bearer; outbound must use the token the peer issued for you (the one that identifies you as you).";
|
|
259
|
+
return this.json(res, 401, rpcError(id, ERR_UNAUTHORIZED, "Unauthorized: check the bearer token (is it registered in the peer's inbound list?)", { hint }), { "WWW-Authenticate": "Bearer" });
|
|
260
|
+
}
|
|
261
|
+
const method = String(body?.method ?? ""); const params = (body?.params ?? {}) as any;
|
|
262
|
+
switch (method) {
|
|
263
|
+
case "SendMessage": return this.handleSendMessage(req, params, res, id);
|
|
264
|
+
case "GetTask": return this.handleGetTask(params, res, id);
|
|
265
|
+
case "sessions/list": return this.handleSessionsList(params, res, id, this.peerByAuth(req));
|
|
266
|
+
case "sessions/get": return this.handleSessionsGet(params, res, id, this.peerByAuth(req));
|
|
267
|
+
case "peers/list": return this.rpcJson(res, id, rpcResult(id, { peers: this.getPeers().map(p => ({ peer: p.peerName, online: this.isOnline(p.peerName), host: p.host, port: p.port })) }));
|
|
268
|
+
case "peers/announce": return this.handlePeersAnnounce(params, res, id);
|
|
269
|
+
// 内部 inbox RPC(单写者):client-only 进程的工具路由到端口所有者
|
|
270
|
+
case "inbox/list": case "inbox/fetch": case "inbox/reply": case "inbox/drop":
|
|
271
|
+
case "inbox/counts": case "inbox/turnEnd": case "inbox/markDelivered": case "inbox/recordOut":
|
|
272
|
+
return this.handleInboxOp(method, params, res, id);
|
|
273
|
+
default: return this.rpcJson(res, id, rpcError(id, ERR_METHOD_NOT_FOUND, `Method not found: ${method}`));
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** SendMessage → inbox.receive → 投递回执(§9.2)。 */
|
|
278
|
+
private async handleSendMessage(req: http.IncomingMessage, params: any, res: http.ServerResponse, id: any) {
|
|
279
|
+
if (this.clientOnly) return this.rpcJson(res, id, rpcError(id, ERR_INTERNAL, "inbox owned by another process (client-only)"));
|
|
280
|
+
const msg = params?.message;
|
|
281
|
+
if (!msg || !Array.isArray(msg.parts) || !msg.parts.length) return this.rpcJson(res, id, rpcError(id, ERR_INVALID_PARAMS, "message.parts required"));
|
|
282
|
+
const meta = msg.metadata ?? {};
|
|
283
|
+
const extRaw = meta[EXT_URI];
|
|
284
|
+
// 诊断性(#18):扩展元数据完全缺失 = 两端 URI 不一致(部署/迁移),报 -32009 而非字段缺失,避免误导查实现 bug
|
|
285
|
+
if (extRaw === undefined || extRaw === null) {
|
|
286
|
+
return this.rpcJson(res, id, rpcError(id, -32009, "extension not activated: no metadata under " + EXT_URI, { hint: "两端 extension URI 必须逐字符一致;检查对端是否旧 URI/旧构建", expectedUri: EXT_URI }));
|
|
287
|
+
}
|
|
288
|
+
const ext = extRaw;
|
|
289
|
+
const senderSessionId = String(ext.senderSessionId ?? "");
|
|
290
|
+
if (!senderSessionId) return this.rpcJson(res, id, rpcError(id, ERR_INVALID_PARAMS, "senderSessionId required (extension activated but field missing)", { hint: "extension " + EXT_URI }));
|
|
291
|
+
const topic = String(ext.topic ?? "").slice(0, MAX_TOPIC); // 超 60 截断(对齐 DSH a13574f:主题只喂一行提醒,不为长标题丢整条消息)
|
|
292
|
+
const body = extractText(msg.parts);
|
|
293
|
+
if (body.length > MAX_BODY) return this.rpcJson(res, id, rpcError(id, ERR_INVALID_PARAMS, `body exceeds limit: got ${body.length} / max ${MAX_BODY}`));
|
|
294
|
+
const peer = this.peerByAuth(req);
|
|
295
|
+
const rawContext = String(msg.contextId ?? "");
|
|
296
|
+
try {
|
|
297
|
+
const receipt = await this.inbox.receive(peer, rawContext, rawContext, {
|
|
298
|
+
messageId: String(msg.messageId ?? genId("msg")), senderSessionId, topic, body,
|
|
299
|
+
mustReply: ext.mustReply === true, replyToMessageId: ext.replyToMessageId ? String(ext.replyToMessageId) : undefined,
|
|
300
|
+
});
|
|
301
|
+
const taskId = genId("task");
|
|
302
|
+
this.receipts.set(taskId, { receipt, contextId: receipt.sessionId });
|
|
303
|
+
const task = {
|
|
304
|
+
id: taskId, contextId: receipt.sessionId,
|
|
305
|
+
status: { state: "TASK_STATE_COMPLETED", timestamp: isoNow() },
|
|
306
|
+
artifacts: [{ artifactId: "ack", parts: [{ kind: "data", data: receipt }] }],
|
|
307
|
+
metadata: receipt.duplicate ? { deduplicated: true } : undefined,
|
|
308
|
+
};
|
|
309
|
+
return this.rpcJson(res, id, rpcResult(id, { task }));
|
|
310
|
+
} catch (e: any) {
|
|
311
|
+
const code = e?.code ?? ERR_INTERNAL;
|
|
312
|
+
const data = e?.data ?? (code === ERR_SESSION_NOT_FOUND ? { hint: "a2a_sessions 取有效 id,或省略 sessionId 新建" } : undefined);
|
|
313
|
+
return this.rpcJson(res, id, rpcError(id, code, String(e?.message ?? e), data));
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
private handleGetTask(params: any, res: http.ServerResponse, id: any) {
|
|
318
|
+
const t = this.receipts.get(String(params?.id ?? ""));
|
|
319
|
+
if (!t) return this.rpcJson(res, id, rpcError(id, -32001, "Task not found"));
|
|
320
|
+
return this.rpcJson(res, id, rpcResult(id, { id: params.id, contextId: t.contextId, status: { state: "TASK_STATE_COMPLETED", timestamp: isoNow() }, artifacts: [{ artifactId: "ack", parts: [{ kind: "data", data: t.receipt }] }] }));
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
private async handleSessionsList(params: any, res: http.ServerResponse, id: any, peer: string) {
|
|
324
|
+
try {
|
|
325
|
+
const limit = Math.max(1, Math.min(Number(params?.limit) || 20, 100));
|
|
326
|
+
const offset = Number(params?.offset) || 0;
|
|
327
|
+
const keyword = String(params?.keyword ?? "").toLowerCase();
|
|
328
|
+
let all = await listSessions(100);
|
|
329
|
+
// A+(DSH db27084 / qwenpaw d0dc228):可见集只含与该 peer 有往来的会话,其余不列不可搜;标签=对方已知最新 topic(零新增泄露,不暴露作息表)
|
|
330
|
+
const visible = this.inbox?.visibleSessions(peer) ?? new Map<string, string>();
|
|
331
|
+
all = all.filter(s => visible.has(s.id));
|
|
332
|
+
if (keyword) all = all.filter(s => (visible.get(s.id) ?? "").toLowerCase().includes(keyword));
|
|
333
|
+
const total = all.length;
|
|
334
|
+
const sessions = all.slice(offset, offset + limit).map(s => {
|
|
335
|
+
const c = this.inbox?.boxCounts(s.id) ?? { pendingTotal: 0, suspendedTotal: 0 };
|
|
336
|
+
const busy = this.inbox?.isSessionBusy(s.id) ?? false;
|
|
337
|
+
return { sessionId: s.id, title: visible.get(s.id) ?? "<session>", status: busy ? "working" : "idle", lastActiveAt: s.updatedAt, pending: c.pendingTotal, suspended: c.suspendedTotal };
|
|
338
|
+
});
|
|
339
|
+
return this.rpcJson(res, id, rpcResult(id, { sessions, total }));
|
|
340
|
+
} catch (e) { return this.rpcJson(res, id, rpcError(id, ERR_INTERNAL, `sessions/list failed: ${e instanceof Error ? e.message : String(e)}`)); }
|
|
341
|
+
}
|
|
342
|
+
private async handleSessionsGet(params: any, res: http.ServerResponse, id: any, peer: string) {
|
|
343
|
+
const sid = String(params?.sessionId ?? params?.id ?? "");
|
|
344
|
+
if (!sid) return this.rpcJson(res, id, rpcError(id, ERR_INVALID_PARAMS, "sessionId required"));
|
|
345
|
+
// A+ 同口径:不可见即 -32040 不回显 id(防 get 绕过可见集);标签用对方已知 topic
|
|
346
|
+
const visible = this.inbox?.visibleSessions(peer) ?? new Map<string, string>();
|
|
347
|
+
if (!visible.has(sid)) return this.rpcJson(res, id, rpcError(id, ERR_SESSION_NOT_FOUND, "Session not found on this side"));
|
|
348
|
+
const s = await getSession(sid);
|
|
349
|
+
if (!s) return this.rpcJson(res, id, rpcError(id, ERR_SESSION_NOT_FOUND, "Session not found on this side"));
|
|
350
|
+
return this.rpcJson(res, id, rpcResult(id, { sessionId: s.id, title: visible.get(sid) ?? "<session>", status: "idle", lastActiveAt: s.updatedAt }));
|
|
351
|
+
}
|
|
352
|
+
private handlePeersAnnounce(params: any, res: http.ServerResponse, id: any) {
|
|
353
|
+
const name = String(params?.peerName ?? ""); const cardUrl = String(params?.cardUrl ?? "");
|
|
354
|
+
if (!name || !cardUrl) return this.rpcJson(res, id, rpcError(id, ERR_INVALID_PARAMS, "peerName + cardUrl required"));
|
|
355
|
+
if (!this.peers.has(name)) this.peers.set(name, { peerName: name, host: "", port: 0, lastSeen: Date.now(), gossip: true, cardUrl });
|
|
356
|
+
else { const p = this.peers.get(name)!; p.lastSeen = Date.now(); p.gossip = true; }
|
|
357
|
+
return this.rpcJson(res, id, rpcResult(id, { ok: true }));
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** 内部 inbox RPC(端口所有者单写者)。client-only 进程经此访问唯一盒子。 */
|
|
361
|
+
private async handleInboxOp(method: string, params: any, res: http.ServerResponse, id: any) {
|
|
362
|
+
if (this.clientOnly || !this.inbox) return this.rpcJson(res, id, rpcError(id, ERR_INTERNAL, "inbox not owned by this process"));
|
|
363
|
+
const sid = String(params?.sessionId ?? "");
|
|
364
|
+
try {
|
|
365
|
+
let result: any;
|
|
366
|
+
switch (method) {
|
|
367
|
+
case "inbox/list": result = await this.inbox.list(sid, { peer: params.peer, includeSuspended: params.includeSuspended, limit: params.limit }); break;
|
|
368
|
+
case "inbox/fetch": result = await this.inbox.fetch(sid, { messageId: params.messageId, messageIds: params.messageIds, fromSuspended: params.fromSuspended, peer: params.peer }); break;
|
|
369
|
+
case "inbox/drop": result = await this.inbox.drop(sid, params.messageIds ?? [], String(params.reason ?? "")); break;
|
|
370
|
+
case "inbox/counts": result = this.inbox.boxCounts(sid); break;
|
|
371
|
+
case "inbox/turnEnd": await this.inbox.turnEnd(sid); result = { ok: true }; break;
|
|
372
|
+
case "inbox/markDelivered": this.inbox.markDelivered(sid); result = { ok: true }; break;
|
|
373
|
+
case "inbox/recordOut": this.inbox.recordOut(sid, params.messageId, params.peer, params.targetSession, params.topic, params.body, params.mustReply === true); result = { ok: true }; break;
|
|
374
|
+
case "inbox/reply": {
|
|
375
|
+
const env = this;
|
|
376
|
+
result = await this.inbox.reply(sid, params.messageId, params.body, params.topic, params.mustReply === true,
|
|
377
|
+
async (outId, target, peer, payload) => {
|
|
378
|
+
const r = await env.sendMessage(peer, { messageId: outId, contextId: target, senderSessionId: sid, topic: payload.topic, body: payload.body, mustReply: payload.mustReply, replyToMessageId: payload.replyToMessageId });
|
|
379
|
+
return { delivered: r.delivered };
|
|
380
|
+
});
|
|
381
|
+
break;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
return this.rpcJson(res, id, rpcResult(id, result));
|
|
385
|
+
} catch (e: any) {
|
|
386
|
+
return this.rpcJson(res, id, rpcError(id, e?.code ?? ERR_INTERNAL, String(e?.message ?? e)));
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** client-only 进程:把 inbox 操作路由到端口所有者(127.0.0.1:listenPort)。 */
|
|
391
|
+
async callLocalInbox(method: string, params: any): Promise<any> {
|
|
392
|
+
const port = this.config.listenPort || 30142;
|
|
393
|
+
const ctrl = new AbortController(); const t = setTimeout(() => ctrl.abort(), 15_000);
|
|
394
|
+
try {
|
|
395
|
+
const resp = await fetch(`http://127.0.0.1:${port}${this.rpcPath}`, {
|
|
396
|
+
method: "POST", signal: ctrl.signal,
|
|
397
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.config.workspaceSecret}` },
|
|
398
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: ++this.reqId, method, params }),
|
|
399
|
+
});
|
|
400
|
+
const r = await resp.json();
|
|
401
|
+
if (r?.error) { const e: any = new Error(r.error.message); e.code = r.error.code; throw e; }
|
|
402
|
+
return r?.result;
|
|
403
|
+
} finally { clearTimeout(t); }
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// ── client 侧 ──
|
|
407
|
+
async callPeerMethod(peerName: string, method: string, params: any): Promise<any> {
|
|
408
|
+
const peer = this.getPeer(peerName);
|
|
409
|
+
if (!peer) { const e: any = new Error(`peer not found: ${peerName}`); e.code = ERR_PEER_UNREACHABLE; throw e; }
|
|
410
|
+
return this.rpcCall(peer, method, params, 15_000);
|
|
411
|
+
}
|
|
412
|
+
/** 发送一条 inbox 消息(a2a_send / a2a_reply 用)。返回回执 artifact data。 */
|
|
413
|
+
async sendMessage(peerName: string, msg: { messageId: string; contextId: string; senderSessionId: string; topic: string; body: string; mustReply: boolean; replyToMessageId?: string }): Promise<Receipt> {
|
|
414
|
+
const peer = this.getPeer(peerName);
|
|
415
|
+
if (!peer) { const e: any = new Error(`peer not found: ${peerName}`); e.code = ERR_PEER_UNREACHABLE; throw e; }
|
|
416
|
+
const params = {
|
|
417
|
+
message: {
|
|
418
|
+
messageId: msg.messageId, role: "ROLE_USER", contextId: msg.contextId || undefined,
|
|
419
|
+
parts: [{ kind: "text", text: msg.body }],
|
|
420
|
+
metadata: { [EXT_URI]: { senderSessionId: msg.senderSessionId, topic: msg.topic, mustReply: msg.mustReply, ...(msg.replyToMessageId ? { replyToMessageId: msg.replyToMessageId } : {}) } },
|
|
421
|
+
},
|
|
422
|
+
};
|
|
423
|
+
const r = await this.rpcCall(peer, "SendMessage", params, POST_TIMEOUT_MS);
|
|
424
|
+
if (r?.error) { const e: any = new Error(r.error.message); e.code = r.error.code; throw e; }
|
|
425
|
+
const data = r?.result?.task?.artifacts?.[0]?.parts?.[0]?.data;
|
|
426
|
+
// 兼容对端回执:spec 要求 delivered:true;部分实现(如 DSH)只给 sessionId+mode 不给 delivered,
|
|
427
|
+
// 以“COMPLETED 回执 + sessionId”推断已投递(联调容错,同时要求对端补齐 delivered 字段)。
|
|
428
|
+
const delivered = data?.delivered === true || (typeof data?.sessionId === "string" && !!data?.mode);
|
|
429
|
+
if (!delivered) { const e: any = new Error("no delivery receipt"); e.code = ERR_PEER_UNREACHABLE; throw e; }
|
|
430
|
+
return { ...data, delivered: true } as Receipt;
|
|
431
|
+
}
|
|
432
|
+
private async rpcCall(peer: Peer, method: string, params: any, timeoutMs: number): Promise<any> {
|
|
433
|
+
const url = peer.rpcUrl ?? `http://${peer.host}:${peer.port}${this.rpcPath}`;
|
|
434
|
+
const ctrl = new AbortController(); const t = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
435
|
+
try {
|
|
436
|
+
const resp = await fetch(url, {
|
|
437
|
+
method: "POST", signal: ctrl.signal,
|
|
438
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${peer.bearer ?? this.config.workspaceSecret}` },
|
|
439
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: ++this.reqId, method, params }),
|
|
440
|
+
});
|
|
441
|
+
const data = await resp.json().catch(() => null);
|
|
442
|
+
if (resp.status === 401) {
|
|
443
|
+
// 读 body 的 code/message/data(不只映射 HTTP 状态):以后区分 token 错/过期/peer 删靠机器可读码,不靠文本匹配
|
|
444
|
+
const err: any = new Error(data?.error?.message ?? "peer rejected bearer (HTTP 401): check the outbound token is one the peer recognizes as me");
|
|
445
|
+
err.code = data?.error?.code ?? ERR_UNAUTHORIZED; err.data = data?.error?.data; throw err;
|
|
446
|
+
}
|
|
447
|
+
return data;
|
|
448
|
+
} catch (e: any) {
|
|
449
|
+
if (e?.code === ERR_UNAUTHORIZED) throw e; // 认证失败不是传输失败:保留专用码,不误判为 unreachable 触发重试风暴
|
|
450
|
+
const err: any = new Error(`PEER_UNREACHABLE: ${e?.message ?? e}`); err.code = ERR_PEER_UNREACHABLE; throw err;
|
|
451
|
+
}
|
|
452
|
+
finally { clearTimeout(t); }
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
private agentCard(): any {
|
|
456
|
+
return {
|
|
457
|
+
name: this.config.peerName, description: this.config.role || "pi agent", version: PKG_VERSION,
|
|
458
|
+
supportedInterfaces: [{ url: `http://${this.lanIp}:${this.listenPort}${this.rpcPath}`, protocolBinding: "JSONRPC", protocolVersion: A2AVER }],
|
|
459
|
+
capabilities: {
|
|
460
|
+
streaming: false, pushNotifications: false, extendedAgentCard: false,
|
|
461
|
+
extensions: [{
|
|
462
|
+
uri: EXT_URI,
|
|
463
|
+
description: "Session-addressed inbox; SendMessage returns a delivery receipt, bodies are fetched by tool, replies are explicit.",
|
|
464
|
+
required: true,
|
|
465
|
+
params: { topics: true, maxBodyChars: MAX_BODY, maxAttempts: 3 },
|
|
466
|
+
}],
|
|
467
|
+
},
|
|
468
|
+
securitySchemes: { ws: { httpAuthSecurityScheme: { scheme: "Bearer", description: "per-peer Bearer token (workspaceSecret is an anonymous entry only, no peer identity)" } } },
|
|
469
|
+
securityRequirements: [{ ws: [] }],
|
|
470
|
+
defaultInputModes: ["text/plain"], defaultOutputModes: ["text/plain"],
|
|
471
|
+
skills: [{ id: "pi-a2a-inbox", name: this.config.peerName, description: this.config.role || "pi agent", tags: ["pi", "agent", "a2a", "inbox"] }],
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
private readBody(req: http.IncomingMessage): Promise<any> {
|
|
476
|
+
return new Promise((resolve, reject) => {
|
|
477
|
+
const chunks: Buffer[] = []; let size = 0;
|
|
478
|
+
req.on("data", c => { size += c.length; if (size > 4 * 1024 * 1024) { reject(new Error("too large")); req.destroy(); } else chunks.push(c); });
|
|
479
|
+
req.on("end", () => { try { resolve(JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}")); } catch (e) { reject(e); } });
|
|
480
|
+
req.on("error", reject);
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
private json(res: http.ServerResponse, status: number, data: unknown, extra?: Record<string, string>) {
|
|
484
|
+
const body = JSON.stringify(data);
|
|
485
|
+
res.writeHead(status, { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body), ...(extra ?? {}) });
|
|
486
|
+
res.end(body);
|
|
487
|
+
}
|
|
488
|
+
private rpcJson(res: http.ServerResponse, id: any, payload: unknown) { this.json(res, 200, payload); }
|
|
489
|
+
}
|