@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.
@@ -0,0 +1,473 @@
1
+ /**
2
+ * @m-cpy/pi-a2a-inbox 0.5.0 — a2a-inbox/v1(PROTOCOL-v3-inbox)。
3
+ * 信封层 envelope.ts(A2A 标准)+ 语义层 inbox.ts(消息盒子四态)+ 本文件(pi 适配)。
4
+ * 回复是 agent 主动调用 a2a_reply 的动作;Task 只是投递回执。
5
+ *
6
+ * 进程级引擎(globalThis 单例):HTTP/inbox/peer 表全进程唯一。
7
+ * 每会话模块实例:mySessionId/myPi 绑定本会话;7 个工具操作本会话的盒子。
8
+ * 单写者:端口所有者运行 inbox,bind 失败降级纯客户端(envelope.clientOnly)。
9
+ */
10
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
11
+ import { Type } from "typebox";
12
+ import * as crypto from "node:crypto";
13
+ import * as fs from "node:fs";
14
+ import * as os from "node:os";
15
+ import * as path from "node:path";
16
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
17
+ import { loadConfig, saveConfig, configPath, type A2aConfig } from "./config.ts";
18
+ import { Inbox, EXT_URI, effectiveConfigLine } from "./inbox.ts";
19
+ import { Envelope } from "./envelope.ts";
20
+ import { getSession } from "./worker.ts";
21
+
22
+ // ── 进程级引擎单例 ──
23
+ interface Engine {
24
+ config: A2aConfig | null;
25
+ configPath: string | null;
26
+ inbox: Inbox | null;
27
+ envelope: Envelope | null;
28
+ instances: Map<string, { pi: ExtensionAPI; ctx: any }>;
29
+ running: Set<string>;
30
+ watchdog: NodeJS.Timeout | null;
31
+ baseDir: string;
32
+ version?: string;
33
+ }
34
+ const ENGINE_KEY = Symbol.for("cpy.pi-a2a.engine.v3");
35
+ // 引擎代码版本:inbox/envelope 改动须递增;reload 时若版本不符且空闲→重建引擎(避免旧类实例缺新方法)。
36
+ const ENGINE_VERSION = "0.5.0-r50";
37
+ const engine: Engine = ((globalThis as any)[ENGINE_KEY] ??= {
38
+ config: null, configPath: null, inbox: null, envelope: null,
39
+ instances: new Map(), running: new Set(), watchdog: null, baseDir: process.cwd(),
40
+ });
41
+
42
+ // ── 每会话模块实例(pi-web 每会话独立加载模块)──
43
+ let mySessionId: string | null = null;
44
+ let myPi: ExtensionAPI | null = null;
45
+ let myCtx: any = null;
46
+ let widgetTimer: NodeJS.Timeout | null = null;
47
+
48
+ /** 最小 widget:在线 peer + 本会话盒子待处理/挂起计数。 */
49
+ function redrawWidget(): void {
50
+ const ctx = myCtx;
51
+ try {
52
+ if (!ctx?.hasUI) return;
53
+ ctx.ui.setWidget("pi-a2a", (_tui: any, theme: any) => ({
54
+ render(_width: number) {
55
+ if (!engine.config) return [theme.fg("muted", "📨 pi-a2a 未配置")];
56
+ const env = engine.envelope;
57
+ const peers = (env?.getPeers() ?? []).filter(p => p.peerName !== engine.config!.peerName);
58
+ const online = peers.filter(p => env!.isOnline(p.peerName)).map(p => p.peerName);
59
+ const peerTxt = online.length ? online.join(" ") : "(无在线 peer)";
60
+ let boxTxt = "";
61
+ if (mySessionId) {
62
+ const r = widgetCounts;
63
+ boxTxt = ` · 盒 ${r.pendingTotal} 待处理${r.suspendedTotal ? ` / ${r.suspendedTotal} 挂起` : ""}`;
64
+ }
65
+ const co = env?.clientOnly ? " [client-only]" : "";
66
+ return [theme.fg("accent", `📨 a2a${co} `) + theme.fg("muted", peerTxt + boxTxt)];
67
+ },
68
+ }));
69
+ } catch { /* UI 不可用忽略 */ }
70
+ }
71
+
72
+ const log = (...a: unknown[]) => console.log("[pi-a2a]", ...a);
73
+ function textResult(text: string, details: Record<string, unknown> = {}) {
74
+ return { content: [{ type: "text" as const, text }], details };
75
+ }
76
+ function notReady() {
77
+ if (!engine.config) return textResult("⚠️ pi-a2a-inbox not configured. Run /a2a-setup (engine basics + per-peer Bearer rows).");
78
+ return textResult("⏳ pi-a2a engine not ready; retry shortly.");
79
+ }
80
+
81
+ /** 单写者路由:client-only 进程经 RPC 访问端口所有者的唯一盒子;否则本地调用。 */
82
+ async function mbOp(method: string, params: any, local: () => any): Promise<any> {
83
+ if (engine.envelope?.clientOnly) return engine.envelope.callLocalInbox(method, params);
84
+ return local();
85
+ }
86
+ let widgetCounts = { pendingTotal: 0, suspendedTotal: 0 };
87
+ async function refreshWidgetCounts(): Promise<void> {
88
+ if (mySessionId && (engine.inbox || engine.envelope?.clientOnly)) {
89
+ try { widgetCounts = (await mbOp("inbox/counts", { sessionId: mySessionId }, () => engine.inbox!.boxCounts(mySessionId!))) ?? widgetCounts; } catch { /* ignore */ }
90
+ }
91
+ redrawWidget();
92
+ }
93
+
94
+ // ── pi-web wake(未加载会话:认证 + prompt 实例化并投递提醒)──
95
+ async function piWebWake(sessionId: string, text: string): Promise<boolean> {
96
+ const pw = process.env.PI_WEB_PASSWORD;
97
+ const port = process.env.PI_WEB_PORT || "30141";
98
+ if (!pw) { log("wake 失败:无 PI_WEB_PASSWORD"); return false; }
99
+ const base = `http://127.0.0.1:${port}`;
100
+ try {
101
+ const auth = await fetch(`${base}/api/web-auth`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password: pw }) });
102
+ const cookie = auth.headers.get("set-cookie")?.split(";")[0] ?? "";
103
+ const r = await fetch(`${base}/api/agent/${sessionId}`, { method: "POST", headers: { "Content-Type": "application/json", Cookie: cookie }, body: JSON.stringify({ type: "prompt", message: text, streamingBehavior: "followUp" }) });
104
+ const j: any = await r.json().catch(() => ({}));
105
+ const accepted = j?.success === true && j?.accepted !== false;
106
+ if (!accepted) log(`wake 被宿主拒绝(${j?.code ?? r.status})→ 留 queued 交看门狗`);
107
+ return accepted; // 诚实报告送达(#15):拒收不算 delivered
108
+ } catch (e) { log("wake 异常", e); return false; }
109
+ }
110
+
111
+ async function wakeSession(s: string, text: string): Promise<boolean> {
112
+ const inst = engine.instances.get(s);
113
+ if (inst) { try { inst.pi.sendUserMessage(text, { deliverAs: "followUp" }); return true; } catch (e) { log("wake via pi 失败,回退 pi-web", e); } }
114
+ return await piWebWake(s, text);
115
+ }
116
+ // 轮间轻提醒 = steer 注入(r50):当前轮 tool calls 执行完、下次 LLM call 前 drain(agent-loop.js:191),
117
+ // agent 继续跑不中断会话,在当前轮内就看到提醒并取件(DSH 轮间注入体感)。区别于 followUp(整轮结束另起一轮)。
118
+ // 重试间隙 loop 阻塞在 streamAssistantResponse 内,到不了 drain 点 → steer 不反复插入;当前轮内消费不跨轮 spawning 空轮。
119
+ async function steerInject(s: string, text: string): Promise<boolean> {
120
+ const inst = engine.instances.get(s);
121
+ if (!inst) return false; // 未加载 → 降级唤醒
122
+ try {
123
+ inst.pi.sendUserMessage(text, { deliverAs: "steer" });
124
+ return true;
125
+ } catch (e) { log("steer inject 失败", e); return false; }
126
+ }
127
+
128
+ // ── 引擎启动 ──
129
+ async function startEngine(ctx?: any): Promise<void> {
130
+ if (engine.envelope) return;
131
+ const loaded = loadConfig(ctx?.cwd ?? process.cwd()) ?? loadConfig(os.homedir());
132
+ if (!loaded) return;
133
+ engine.config = loaded.config;
134
+ engine.configPath = loaded.path;
135
+ engine.baseDir = path.dirname(path.dirname(fs.realpathSync(loaded.path)));
136
+ const msgFile = path.join(engine.baseDir, ".pi", "a2a-messages.json");
137
+ const inbox = new Inbox(msgFile, {
138
+ now: () => Date.now(),
139
+ isBusy: (s) => engine.running.has(s),
140
+ sessionExists: async (s) => !!(await getSession(s)),
141
+ createSession: async () => {
142
+ const cwd = path.join(engine.baseDir, ".a2a-sessions"); // 工作区根(可写),不用 process.cwd()(npm 安装目录只读→EACCES)
143
+ fs.mkdirSync(cwd, { recursive: true });
144
+ const id = crypto.randomUUID();
145
+ SessionManager.create(cwd, undefined, { id } as any);
146
+ return id;
147
+ },
148
+ wake: wakeSession,
149
+ light: steerInject, // dep 名保留 light(轮间轻提醒通道),实现已是 steer 轮间注入
150
+ log,
151
+ });
152
+ const envelope = new Envelope(engine.config, inbox, log);
153
+ await envelope.start();
154
+ engine.inbox = inbox;
155
+ engine.envelope = envelope;
156
+ engine.version = ENGINE_VERSION;
157
+ // 生效配置显形(qwenpaw 61161d1):任何来源都喊生效值与来源(config/default 或 env),不依赖 env
158
+ log(effectiveConfigLine());
159
+ if (!engine.watchdog && !envelope.clientOnly) engine.watchdog = setInterval(() => void inbox.watchdogTick(), 15_000); // 看门狗仅端口所有者
160
+ log(`引擎启动 port=${envelope.getListenPort()} clientOnly=${envelope.clientOnly}`);
161
+ }
162
+
163
+ async function restartEngine(ctx?: any): Promise<void> {
164
+ if (engine.watchdog) { clearInterval(engine.watchdog); engine.watchdog = null; }
165
+ if (engine.envelope) { await engine.envelope.stop(); engine.envelope = null; }
166
+ engine.inbox = null;
167
+ await startEngine(ctx);
168
+ }
169
+
170
+ // ── 扩展入口 ──
171
+ export default function (pi: ExtensionAPI) {
172
+ if (!engine.envelope) void startEngine();
173
+ else if (engine.version !== ENGINE_VERSION && engine.running.size === 0) void restartEngine(); // reload 加载新 inbox/envelope
174
+
175
+ pi.on("session_start", async (_e, ctx) => {
176
+ myCtx = ctx; myPi = pi;
177
+ mySessionId = ctx.sessionManager?.getSessionId?.() ?? (ctx as any).sessionId ?? null;
178
+ if (mySessionId) engine.instances.set(mySessionId, { pi, ctx });
179
+ if (!engine.envelope) await startEngine(ctx);
180
+ if (ctx.hasUI) {
181
+ void refreshWidgetCounts();
182
+ if (!widgetTimer) widgetTimer = setInterval(() => void refreshWidgetCounts(), 5000);
183
+ }
184
+ });
185
+ pi.on("agent_start", async () => {
186
+ if (!mySessionId) return;
187
+ const sid = mySessionId;
188
+ engine.running.add(sid);
189
+ void mbOp("inbox/markDelivered", { sessionId: sid }, () => engine.inbox?.markDelivered?.(sid)).catch(() => {}); // 提醒投递进轮 = 消费(§5)
190
+ });
191
+ // steer 轮间投递不触发新 agent_start(当前轮内 drain),故 markDelivered 另挂 message_start:
192
+ // 识别 pi-a2a 提醒用户消息("[a2a]" 前缀 + a2a_inbox 工具引导)→ 消费。markDelivered 幂等(if ns.queued),
193
+ // followUp 路径 agent_start 已先标记,此处 no-op,不会重复计 batchCount。
194
+ pi.on("message_start", async (e: any) => {
195
+ if (!mySessionId) return;
196
+ const sid = mySessionId;
197
+ const m = e?.message;
198
+ if (m?.role !== "user") return;
199
+ const text = Array.isArray(m.content) ? m.content.filter((c: any) => c?.type === "text").map((c: any) => c.text).join("") : (typeof m.content === "string" ? m.content : "");
200
+ if (text.startsWith("[a2a]") && text.includes("a2a_inbox")) {
201
+ void mbOp("inbox/markDelivered", { sessionId: sid }, () => engine.inbox?.markDelivered?.(sid)).catch(() => {});
202
+ }
203
+ });
204
+ pi.on("agent_settled", async () => {
205
+ // 轮末收口挂 agent_settled(完全 settled、无自动重试/压缩/续跑后才触发)而非 agent_end:
206
+ // agent_end 每次循环结束都发(含 429 自动重试前),会在重试间隙误回退 consuming→reply 报 fetch first。
207
+ if (!mySessionId) return;
208
+ const sid = mySessionId;
209
+ engine.running.delete(sid);
210
+ await mbOp("inbox/turnEnd", { sessionId: sid }, () => engine.inbox?.turnEnd?.(sid)).catch(() => {}); // 轮末收口(§4.5 + 兜底)
211
+ });
212
+ pi.on("session_shutdown", async () => {
213
+ if (mySessionId) { engine.instances.delete(mySessionId); engine.running.delete(mySessionId); }
214
+ if (widgetTimer) { clearInterval(widgetTimer); widgetTimer = null; }
215
+ // 进程生命周期:不停引擎
216
+ });
217
+
218
+ const sid = () => mySessionId ?? "";
219
+
220
+ // ── a2a_peers ──
221
+ pi.registerTool({
222
+ name: "a2a_peers", label: "A2A Peers",
223
+ description: "List reachable peer agents with online status. Use to find a peer name or check reachability. Lists peers only, not their sessions (use a2a_sessions).",
224
+ parameters: Type.Object({}),
225
+ async execute() {
226
+ if (!engine.envelope) return notReady();
227
+ const peers = engine.envelope.getPeers().map(p => ({ peer: p.peerName, online: engine.envelope!.isOnline(p.peerName) }));
228
+ if (!peers.length) return textResult("No peers configured yet. Add a peer's URL and token in the a2a config.");
229
+ return textResult(JSON.stringify(peers, null, 2));
230
+ },
231
+ });
232
+
233
+ // ── a2a_sessions ──
234
+ pi.registerTool({
235
+ name: "a2a_sessions", label: "A2A Sessions",
236
+ description: "List a peer's sessions (sessionId, title, status, lastActiveAt, pending, suspended) to choose a target. Do NOT guess sessionId: an unknown id returns SESSION_NOT_FOUND, never auto-created. Omit sessionId in a2a_send to start a new session.",
237
+ parameters: Type.Object({
238
+ peer: Type.String({ description: "Peer name (see a2a_peers)" }),
239
+ keyword: Type.Optional(Type.String({ description: "Filter by title" })),
240
+ limit: Type.Optional(Type.Number({ description: "Default 20, max 100" })),
241
+ offset: Type.Optional(Type.Number()),
242
+ }),
243
+ async execute(_id, p) {
244
+ if (!engine.envelope) return notReady();
245
+ try {
246
+ const r = await engine.envelope.callPeerMethod(p.peer, "sessions/list", { keyword: p.keyword, limit: p.limit ?? 20, offset: p.offset ?? 0 });
247
+ if (r?.error) return textResult(`Query failed: ${r.error.message}`);
248
+ return textResult(JSON.stringify(r.result, null, 2));
249
+ } catch (e: any) { return textResult(`PEER_UNREACHABLE: ${e?.message ?? e}`); }
250
+ },
251
+ });
252
+
253
+ // ── a2a_send ──
254
+ pi.registerTool({
255
+ name: "a2a_send", label: "A2A Send",
256
+ description: "Send a new message to a peer session. To continue an existing session pass its sessionId (confirm via a2a_sessions). To start a NEW session you MUST pass newSession:true (omitting sessionId alone is rejected — prevents accidentally spawning sessions). Sending does NOT require a reply by default; set mustReply:true only when you genuinely await an answer. The return is a delivery receipt — not proof the peer read it or will reply. To respond to a message in your inbox use a2a_reply, not this.",
257
+ promptGuidelines: [
258
+ "Find peers with a2a_peers; confirm target sessionId with a2a_sessions. Never guess sessionId.",
259
+ "topic is the only thing shown in the peer's reminder (<=60 chars); write it so they can judge priority.",
260
+ "Set mustReply:true when asking a question, requesting a decision, or awaiting a result. Do not set it for polite acknowledgements.",
261
+ ],
262
+ parameters: Type.Object({
263
+ peer: Type.String({ description: "Peer name" }),
264
+ sessionId: Type.Optional(Type.String({ description: "Target session on peer; confirm via a2a_sessions. Omit only with newSession:true" })),
265
+ newSession: Type.Optional(Type.Boolean({ description: "Required true to start a new session (omit sessionId). Cannot combine with sessionId." })),
266
+ topic: Type.String({ description: "One-line subject (<=60 chars)" }),
267
+ body: Type.String({ description: "Message body (<=32768 chars)" }),
268
+ mustReply: Type.Optional(Type.Boolean({ description: "Default false. Set true only when you need an answer." })),
269
+ }),
270
+ async execute(_id, p, _s, onUpdate) {
271
+ if (!engine.envelope || !engine.inbox) return notReady();
272
+ if (!mySessionId) return textResult("Cannot determine the current session id");
273
+ // 护栏(DSH 5931085 同构,工具层硬要求):省略 sessionId 须显式 newSession:true,防手滑静默新建会话
274
+ const sid = p.sessionId?.trim() || "";
275
+ if (!sid && p.newSession !== true) return textResult("Rejected: omitting sessionId requires newSession:true to start a new session. Pass sessionId to continue an existing one (a2a_sessions), or set newSession:true to deliberately create a new session.");
276
+ if (sid && p.newSession === true) return textResult("Rejected: pass either sessionId (continue existing) or newSession:true (create new), not both.");
277
+ const messageId = `m-${crypto.randomUUID()}`;
278
+ const mustReply = p.mustReply === true;
279
+ onUpdate?.(textResult(`Sending to ${p.peer}…`));
280
+ try {
281
+ const receipt = await engine.envelope.sendMessage(p.peer, {
282
+ messageId, contextId: sid, senderSessionId: mySessionId,
283
+ topic: p.topic, body: p.body, mustReply,
284
+ });
285
+ await mbOp("inbox/recordOut", { sessionId: mySessionId, messageId, peer: p.peer, targetSession: receipt.sessionId, topic: p.topic, body: p.body, mustReply }, () => engine.inbox!.recordOut(mySessionId!, messageId, p.peer, receipt.sessionId, p.topic, p.body, mustReply));
286
+ let text = JSON.stringify({ messageId, sessionId: receipt.sessionId, mode: receipt.mode, peerPending: receipt.queueDepth, mustReply });
287
+ if (!sid) text += `\nNew session created sessionId=${receipt.sessionId}; pass it to continue this topic.`;
288
+ if (mustReply) text += `\nReply requested from the peer.`;
289
+ return textResult(text);
290
+ } catch (e: any) { return textResult(`Send failed (${e?.code ?? ""}): ${e?.message ?? e}\nNext: a2a_peers to check reachability / a2a_sessions to confirm sessionId.`); }
291
+ },
292
+ });
293
+
294
+ // ── a2a_inbox_list ──
295
+ pi.registerTool({
296
+ name: "a2a_inbox_list", label: "A2A Inbox List",
297
+ description: "Overview of THIS session's inbox: pending count, sender, topic, mustReply, attempts. No bodies — use a2a_inbox_fetch to consume. Suspended messages show only a total unless includeSuspended:true. Boxes are per-session.",
298
+ parameters: Type.Object({
299
+ peer: Type.Optional(Type.String()),
300
+ includeSuspended: Type.Optional(Type.Boolean({ description: "Default false; true lists suspended details" })),
301
+ limit: Type.Optional(Type.Number()),
302
+ }),
303
+ async execute(_id, p) {
304
+ if (!engine.envelope) return notReady();
305
+ const r = await mbOp("inbox/list", { sessionId: sid(), peer: p.peer, includeSuspended: p.includeSuspended, limit: p.limit }, () => engine.inbox!.list(sid(), { peer: p.peer, includeSuspended: p.includeSuspended, limit: p.limit }));
306
+ let text = JSON.stringify(r, null, 2);
307
+ if (r.suspendedTotal > 0 && !p.includeSuspended) text += `\n${r.suspendedTotal} suspended message(s) also present: not nudged, not auto-fetched. They require an explicit user instruction to handle (includeSuspended:true for details); do not touch them without instruction.`;
308
+ const mustN = r.pending.filter((m: any) => m.mustReply).length;
309
+ if (mustN) text += `\n${mustN} of these need a reply: after fetching, answer each with a2a_reply; un-replied ones return to the box at turn end.`;
310
+ return textResult(text);
311
+ },
312
+ });
313
+
314
+ // ── a2a_inbox_fetch ──
315
+ pi.registerTool({
316
+ name: "a2a_inbox_fetch", label: "A2A Inbox Fetch",
317
+ description: "Fetch body from THIS session's inbox. Default: earliest pending. Specify messageId/messageIds to pick. Fetching enters consuming: mustReply:false completes on fetch (no reply owed); mustReply:true MUST be answered with a2a_reply or it returns to the box at turn end (3 un-replied fetches → suspended). Suspended messages need fromSuspended:true + messageId (declares user instruction).",
318
+ parameters: Type.Object({
319
+ messageId: Type.Optional(Type.String()),
320
+ messageIds: Type.Optional(Type.Array(Type.String())),
321
+ fromSuspended: Type.Optional(Type.Boolean({ description: "Default false; required to fetch a suspended message" })),
322
+ peer: Type.Optional(Type.String({ description: "Restrict to this peer; required when a messageId exists for several peers" })),
323
+ }),
324
+ async execute(_id, p) {
325
+ if (!engine.envelope) return notReady();
326
+ try {
327
+ const r = await mbOp("inbox/fetch", { sessionId: sid(), messageId: p.messageId, messageIds: p.messageIds, fromSuspended: p.fromSuspended, peer: p.peer }, () => engine.inbox!.fetch(sid(), { messageId: p.messageId, messageIds: p.messageIds, fromSuspended: p.fromSuspended, peer: p.peer }));
328
+ let text = JSON.stringify(r, null, 2);
329
+ const mustIds = r.messages.filter((m: any) => m.mustReply).map((m: any) => m.messageId);
330
+ if (mustIds.length) text += `\nNeeds reply: ${mustIds.join(", ")}. After handling, answer each with a2a_reply({messageId, body}) — even just \"received\"; un-replied ones return to the box at turn end. Set mustReply:true if your reply needs a further answer.`;
331
+ if (p.fromSuspended) text += `\nThis is a suspended message, fetched per your explicit request. After handling per the user's instruction, a2a_reply, or a2a_inbox_drop to delete; do not handle other suspended messages in passing.`;
332
+ return textResult(text);
333
+ } catch (e: any) { return textResult(`Fetch failed (${e?.code ?? ""}): ${e?.message ?? e}`); }
334
+ },
335
+ });
336
+
337
+ // ── a2a_reply ──
338
+ pi.registerTool({
339
+ name: "a2a_reply", label: "A2A Reply",
340
+ description: "Reply to a message you received (only for inbox messages; new topics use a2a_send). Reply does NOT require a further answer by default; set mustReply:true to ask back. Delivered receipt marks it done; failure returns replyFails for you to retry (3 cumulative failures → suspended). Only consuming messages can be replied.",
341
+ parameters: Type.Object({
342
+ messageId: Type.String({ description: "Message id from a2a_inbox_list/fetch" }),
343
+ body: Type.String(),
344
+ topic: Type.Optional(Type.String({ description: "Default: original topic" })),
345
+ mustReply: Type.Optional(Type.Boolean({ description: "Default false" })),
346
+ }),
347
+ async execute(_id, p) {
348
+ if (!engine.envelope) return notReady();
349
+ const env = engine.envelope;
350
+ const r = await mbOp("inbox/reply", { sessionId: sid(), messageId: p.messageId, body: p.body, topic: p.topic, mustReply: p.mustReply === true }, () => engine.inbox!.reply(sid(), p.messageId, p.body, p.topic, p.mustReply === true,
351
+ async (outId, target, peer, payload) => {
352
+ try {
353
+ const receipt = await env.sendMessage(peer, { messageId: outId, contextId: target, senderSessionId: sid(), topic: payload.topic, body: payload.body, mustReply: payload.mustReply, replyToMessageId: payload.replyToMessageId });
354
+ return { delivered: receipt.delivered };
355
+ } catch (e: any) {
356
+ if (e?.code === -32040) {
357
+ // 诊断增强(DSH 裁决:仅 -32040 后确认,不预校验/不兜底):sessions/get 核实对端会话确不存在,升级文案
358
+ let confirmed = "";
359
+ try { const g = await env.callPeerMethod(peer, "sessions/get", { sessionId: target }); if (g?.error) confirmed = ` Peer confirms session '${target}' does not exist (${g.error.message}).`; }
360
+ catch { confirmed = " Peer session lookup also failed."; }
361
+ const err: any = new Error(`Reply target session '${target}' (self-reported by peer) no longer exists on ${peer}.${confirmed} This counts toward replyFails; 3 failures suspend it and notify the user. Ask the peer for a valid session id (a2a_sessions) and resend.`);
362
+ err.code = -32040; throw err;
363
+ }
364
+ throw e;
365
+ }
366
+ }));
367
+ if (r.ok) return textResult(`Delivered.${p.mustReply ? " Reply requested from the peer." : ""}`);
368
+ if (r.state === "suspended") return textResult(`Failed ${r.replyFails} times cumulatively; now suspended. It will not nudge you again; requires a user instruction to handle.`);
369
+ return textResult(`Not delivered (${r.error}). This message stays consuming and returns to the box at turn end; you may retry, 3 cumulative failures suspend it. replyFails=${r.replyFails}, remainingTries=${r.remainingTries}`);
370
+ },
371
+ });
372
+
373
+ // ── a2a_inbox_drop ──
374
+ pi.registerTool({
375
+ name: "a2a_inbox_drop", label: "A2A Inbox Drop",
376
+ description: "Delete suspended messages (destroy; not consumption, not reply). Only when the user explicitly asks to discard. Only suspended can be dropped; pending/consuming/done are rejected.",
377
+ parameters: Type.Object({
378
+ messageIds: Type.Array(Type.String()),
379
+ reason: Type.String({ description: "One-line reason, logged" }),
380
+ }),
381
+ async execute(_id, p) {
382
+ if (!engine.envelope) return notReady();
383
+ const r = await mbOp("inbox/drop", { sessionId: sid(), messageIds: p.messageIds, reason: p.reason }, () => engine.inbox!.drop(sid(), p.messageIds, p.reason));
384
+ let text = `Deleted ${r.dropped.length} message(s); ${r.remainingSuspended} suspended remaining.`;
385
+ if (r.rejected?.length) text += `\nThe following are not suspended and were not deleted: ${r.rejected.map((x: any) => `${x.messageId}:${x.state}`).join(", ")}`;
386
+ return textResult(text);
387
+ },
388
+ });
389
+
390
+ // ── 命令 ──
391
+ pi.registerCommand("a2a-status", {
392
+ description: "Show pi-a2a-inbox engine status",
393
+ async handler(_args, ctx) {
394
+ const env = engine.envelope;
395
+ const lines = [
396
+ `config: ${engine.configPath ?? "(未配置)"}`,
397
+ `engine: ${env ? `port=${env.getListenPort()} clientOnly=${env.clientOnly}` : "未启动"}`,
398
+ `running sessions: ${[...engine.running].join(", ") || "(无)"}`,
399
+ `instances: ${engine.instances.size}`,
400
+ `peers: ${env?.getPeers().map(p => p.peerName).join(", ") || "(无)"}`,
401
+ ];
402
+ ctx.ui?.notify?.(lines.join("\n"), "info");
403
+ },
404
+ });
405
+ pi.registerCommand("a2a-restart", {
406
+ description: "Restart the pi-a2a-inbox engine (guards against busy sessions)",
407
+ async handler(_args, ctx) {
408
+ if (engine.running.size > 0) {
409
+ ctx.ui?.notify?.(`有 ${engine.running.size} 个会话在跑,重启会打断。确认空闲后再试。`, "warning");
410
+ return;
411
+ }
412
+ await restartEngine(ctx);
413
+ ctx.ui?.notify?.("pi-a2a 引擎已重启", "info");
414
+ },
415
+ });
416
+ pi.registerCommand("a2a-setup", {
417
+ description: "Configure pi-a2a-inbox (engine basics + per-peer Bearer rows)",
418
+ async handler(args, ctx) {
419
+ const cwd = ctx.cwd ?? process.cwd();
420
+ const loaded = loadConfig(cwd);
421
+ const cfg: A2aConfig = loaded?.config ?? { workspace: "default", workspaceSecret: "", peerName: "pi", agentId: "", listenPort: 30142 };
422
+ const parts = (args ?? "").trim().split(/\s+/).filter(Boolean);
423
+ const sub = parts[0];
424
+ const notify = (m: string, k: "info" | "warning" | "error" = "info") => ctx.ui?.notify?.(m, k);
425
+ const cfgPath = loaded?.path ?? configPath(cwd);
426
+ // v3 身份=per-peer Bearer:peer 行管理(通信必需,共享密钥只是匿名入口)
427
+ if (sub === "peer") {
428
+ const [, name, url, outToken, inToken] = parts;
429
+ if (!name || !url || !outToken) { notify("用法: /a2a-setup peer <name> <cardUrl> <outToken> [inToken]\noutToken=出站(对方认我的那把);inToken 省略=对称复用 outToken", "warning"); return; }
430
+ if (!cfg.workspaceSecret) { notify("先设引擎基础: /a2a-setup <匿名入口secret> [peerName]", "warning"); return; }
431
+ cfg.peers = cfg.peers ?? [];
432
+ const row = { name, url, bearer: outToken, ...(inToken ? { inboundToken: inToken } : {}) };
433
+ const i = cfg.peers.findIndex(p => p.name === name);
434
+ if (i >= 0) cfg.peers[i] = row; else cfg.peers.push(row);
435
+ let fp: string;
436
+ try { fp = saveConfig(cwd, cfg); } catch (e: any) { notify(`保存拒绝:${e?.message ?? e}`, "error"); return; }
437
+ await restartEngine(ctx);
438
+ notify(`peer ${name} 已${i >= 0 ? "更新" : "新增"}并重启(出站尾${outToken.slice(-4)}${inToken ? `/入站尾${inToken.slice(-4)}` : "/对称"})\n${fp}`, "info");
439
+ return;
440
+ }
441
+ if (sub === "peers") {
442
+ const rows = (cfg.peers ?? []).map(p => `${p.name} → ${p.url}(出站尾${(p.bearer ?? "").slice(-4) || "无"}${p.inboundToken ? `/入站尾${p.inboundToken.slice(-4)}` : "/对称"})`).join("\n");
443
+ notify(`peers (${cfg.peers?.length ?? 0}):\n${rows || "(无,用 /a2a-setup peer 添加)"}\nconfig: ${cfgPath}`, "info");
444
+ return;
445
+ }
446
+ if (sub === "del-peer") {
447
+ const name = parts[1];
448
+ if (!name) { notify("用法: /a2a-setup del-peer <name>", "warning"); return; }
449
+ const before = cfg.peers?.length ?? 0;
450
+ cfg.peers = (cfg.peers ?? []).filter(p => p.name !== name);
451
+ if (cfg.peers.length === before) { notify(`未找到 peer ${name}`, "warning"); return; }
452
+ saveConfig(cwd, cfg); await restartEngine(ctx);
453
+ notify(`peer ${name} 已删除并重启`, "info");
454
+ return;
455
+ }
456
+ // 引擎基础: /a2a-setup <secret> [name];无参显示用法
457
+ if (sub && sub !== "help") { cfg.workspaceSecret = parts[0]; if (parts[1]) cfg.peerName = parts[1]; }
458
+ if (!cfg.workspaceSecret) {
459
+ notify("pi-a2a-inbox 配置(v3 per-peer Bearer):\n" +
460
+ " /a2a-setup <匿名入口secret> [peerName] 设引擎基础(secret 只作匿名入口 _shared,不产生 peer 身份)\n" +
461
+ " /a2a-setup peer <name> <cardUrl> <outToken> [inToken] 加对端行(通信必需;inToken 省略=对称复用)\n" +
462
+ " /a2a-setup peers 列对端行\n" +
463
+ " /a2a-setup del-peer <name> 删对端行\n" +
464
+ `config: ${cfgPath}`, "info");
465
+ return;
466
+ }
467
+ let fp: string;
468
+ try { fp = saveConfig(cwd, cfg); } catch (e: any) { notify(`保存拒绝:${e?.message ?? e}`, "error"); return; }
469
+ await restartEngine(ctx);
470
+ notify(`引擎基础已配置并重启(peerName=${cfg.peerName},匿名入口尾${cfg.workspaceSecret.slice(-4)})\n通信需配 peer 行: /a2a-setup peer <name> <cardUrl> <outToken>\n${fp}`, "info");
471
+ },
472
+ });
473
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * v3 会话发现(只读投影,与 DSH 互通的形状):
3
+ * sessions/list → {sessions:[{id,name,cwd,createdAt,updatedAt}]}(updatedAt 降序,上限 100)
4
+ * sessions/get → 单个会话对象,不存在返回 undefined
5
+ *
6
+ * 实现=读 pi 自身会话存储(SessionManager.listAll 读盘投影),不持有运行时状态。
7
+ * v3 新建会话由 index.ts createSession 直接走 SessionManager.create;
8
+ * 入站落盒 + 提醒唤醒由 inbox.ts 负责。本文件不做会话执行/排队/插话/心跳
9
+ * (v2 的会话执行池 / 运行时状态 / 排队 / 插话已删,无运行时调用方)。
10
+ */
11
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
12
+
13
+ /** sessions/list / sessions/get 返回的会话对象(与 DSH 互通的形状)。 */
14
+ export interface RemoteSessionInfo {
15
+ id: string;
16
+ name?: string; // 会话标题,可缺省
17
+ cwd: string;
18
+ createdAt: number; // epoch ms(与 DSH 对齐)
19
+ updatedAt: number; // epoch ms,最近活跃(会话文件 mtime,缺省回退 createdAt)
20
+ }
21
+
22
+ const SESSION_LIST_LIMIT = 100;
23
+
24
+ function toInfo(s: { id: string; name?: string; cwd: string; created: Date; modified: Date; firstMessage: string }): RemoteSessionInfo {
25
+ const createdAt = s.created.getTime();
26
+ return {
27
+ id: s.id,
28
+ // 标题优先用户命名;缺省回退首条消息摘要(pi-web 同款展示逻辑)
29
+ name: s.name || (s.firstMessage ? s.firstMessage.slice(0, 60) : undefined),
30
+ cwd: s.cwd,
31
+ createdAt,
32
+ updatedAt: s.modified?.getTime() || createdAt,
33
+ };
34
+ }
35
+
36
+ /** sessions/list:全部会话,updatedAt(最近活跃)降序,上限 100。 */
37
+ export async function listSessions(limit = SESSION_LIST_LIMIT): Promise<RemoteSessionInfo[]> {
38
+ const all = await SessionManager.listAll();
39
+ return all
40
+ .map(toInfo)
41
+ .sort((a, b) => b.updatedAt - a.updatedAt)
42
+ .slice(0, Math.max(1, Math.min(limit, SESSION_LIST_LIMIT)));
43
+ }
44
+
45
+ /** sessions/get:按 id 找单个会话;不存在返回 undefined。 */
46
+ export async function getSession(id: string): Promise<RemoteSessionInfo | undefined> {
47
+ const all = await SessionManager.listAll();
48
+ const hit = all.find((s) => s.id === id);
49
+ return hit ? toInfo(hit) : undefined;
50
+ }
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@m-cpy/pi-a2a-inbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.5.0",
4
+ "description": "A2A peer collaboration for pi — standard A2A v1.0 envelope + inbox extension, static URL peers, per-peer Bearer identity, session continuation",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi-extension",
8
+ "pi-skill",
9
+ "agent",
10
+ "agent-to-agent",
11
+ "agent2agent",
12
+ "collaboration",
13
+ "a2a",
14
+ "multi-agent",
15
+ "inbox"
16
+ ],
17
+ "type": "module",
18
+ "license": "Apache-2.0",
19
+ "scripts": {
20
+ "typecheck": "bash scripts/typecheck.sh",
21
+ "test": "bash scripts/run-v3-tests.sh"
22
+ },
23
+ "author": "Mcpy",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/Mcpy/a2a-inbox.git",
27
+ "directory": "pi-a2a-inbox"
28
+ },
29
+ "homepage": "https://github.com/Mcpy/a2a-inbox/tree/main/pi-a2a-inbox#readme",
30
+ "bugs": "https://github.com/Mcpy/a2a-inbox/issues",
31
+ "files": [
32
+ "extensions",
33
+ "skills",
34
+ "config.example.json",
35
+ "LICENSE",
36
+ "NOTICE",
37
+ "README.md",
38
+ "CHANGELOG.md"
39
+ ],
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "pi": {
44
+ "extensions": [
45
+ "./extensions"
46
+ ],
47
+ "skills": [
48
+ "./skills"
49
+ ]
50
+ },
51
+ "dependencies": {},
52
+ "devDependencies": {
53
+ "typescript": "^5.9.3"
54
+ },
55
+ "peerDependencies": {
56
+ "@earendil-works/pi-coding-agent": "*",
57
+ "typebox": "*"
58
+ }
6
59
  }
@@ -0,0 +1,61 @@
1
+ ---
2
+ name: pi-a2a-inbox
3
+ description: A2A peer collaboration for pi — send messages to named peers, reply in their sessions, and discuss code across peer agents. Per-peer Bearer identity, inbox four-state semantics, explicit reply (standard A2A v1.0 envelope, static URL peers).
4
+ ---
5
+
6
+ # pi-a2a-inbox — Agent 间收件箱协作(A2A / per-peer Bearer)
7
+
8
+ 当用户想和**另一个 agent**沟通、协作、讨论代码时,使用 pi-a2a-inbox。每个对端有一个本地名字(如 `reviewer` / `backend`),消息按**对端会话**组织,入站一律先进收件箱(pending),回复是显式动作。
9
+
10
+ **协议**:标准 [A2A v1.0](https://a2aproject.github.io/A2A/) 信封(JSON-RPC over HTTP)+ 私有 inbox 扩展(URI `https://a2a-inbox.local/ext/a2a-inbox/v1`,card 里 `required:true`)。**静态 URL peer 直连**(无 mDNS);身份由 **per-peer Bearer token** 确立(不是共享密钥,自报名字不参与路由)。纯标准 A2A 客户端不带扩展 metadata 会被 `-32009` 拒(设计如此,降级面不开)。
11
+
12
+ ## 何时使用
13
+
14
+ - 用户说"问问另一个 agent"、"让 X 帮忙看看"、"和另一个 agent 讨论一下"
15
+ - 你需要把代码片段、设计决定、问题发给另一个 agent
16
+ - 另一个 agent 问了你问题(widget 显示待处理计数,提醒会唤醒你)
17
+
18
+ ## 工具(7 个)
19
+
20
+ | 工具 | 用途 |
21
+ |------|------|
22
+ | `a2a_peers` | 列出已配置对端 + 在线状态,拿到可用的 `peer` 名字 |
23
+ | `a2a_sessions` | 列某对端的会话(sessionId/title/status/pending),选回复目标;**不要猜 sessionId** |
24
+ | `a2a_send` | 发消息。`peer` 必填;继续已有会话传 `sessionId`,**新建会话必须显式 `newSession:true`**(省略 sessionId 又不带 newSession 会被拒)|
25
+ | `a2a_inbox_list` | 看本会话收件箱概况(pending/suspended 计数、sender、topic、mustReply),**不含正文** |
26
+ | `a2a_inbox_fetch` | 取正文(进入 consuming)。`mustReply:false` 取即完成;`mustReply:true` **必须当轮 `a2a_reply`**,否则轮末回盒,3 次未回复挂起 |
27
+ | `a2a_reply` | 回复 inbox 里的消息(收件人自动取原发送者)。新话题用 `a2a_send`,不要用 reply |
28
+ | `a2a_inbox_drop` | 删除**挂起**消息(销毁,非消费非回复)。**仅用户明确指示时**才 drop |
29
+
30
+ ## 路由铁律(v3)
31
+
32
+ - `contextId` = **对端会话 id**:空→新建;非空但未知→`-32040`,**绝不偷建会话**;错误不回显调用方 id。
33
+ - `metadata.senderSessionId` 必填(完整会话 id,带前缀),回复路由靠它。
34
+ - 身份 = per-peer Bearer:出站必须用「对端会把我认成我的那把」token;入站按 token 反查 peer 名。
35
+ - 披露面 A+:`a2a_sessions` 只列**与该对端有往来**的会话,标签用对方已知的最新 topic;不可见的会话不回显 id。
36
+
37
+ ## 典型流程
38
+
39
+ **发起讨论:**
40
+ 1. `a2a_peers` → 确认对端在线、拿到名字
41
+ 2. `a2a_sessions(peer)` → 选已有会话;新话题 `a2a_send(peer, topic, body, newSession:true)`
42
+ 3. 对方 `a2a_reply` 回来,你被唤醒,`a2a_inbox_fetch` 取正文
43
+
44
+ **回应别人:**
45
+ 1. 提醒唤醒 → `a2a_inbox_list` 看概况 → `a2a_inbox_fetch` 取正文
46
+ 2. `mustReply:true` → **当轮** `a2a_reply(messageId, body)` 回掉(fetch 与 reply 同轮完成)
47
+ 3. `mustReply:false` → 取即完成,按需回复(不强制)
48
+
49
+ ## 代码讨论建议
50
+
51
+ - 完整代码放 `body`(单条上限 **32768 字符**,超限 `-32602`)
52
+ - `topic` 一句话总结(**超 60 字符截断**,不为长标题丢整条消息)
53
+ - 回复引用对方具体问题再给答案
54
+
55
+ ## 约定与护栏
56
+
57
+ - **per-peer 专属 token**,不横跨多 peer;一对专属 peer 可显式对称复用(泄露=双向,UI 明示)。共享 workspaceSecret 进来只算匿名 `_shared`,不产生 peer 身份。
58
+ - 入站一律 pending;同批最多催 3 次真送达即停或转挂起(不无限唤醒)。
59
+ - 挂起 reason:`no-reply-3x` / `reply-failed-3x` / `session-gone` / `expired`。挂起消息须用户指示才 drop。
60
+ - 保留期:pending>24h→`suspended(expired)` 可逆;suspended>72h→删(purged);done>24h→裁(trimmed)。
61
+ - 错误码:`-32040` 未知会话 / `-32041` 鉴权(401) / `-32043` 同 id 异正文 / `-32044` 盒满(cap 1000) / `-32045` 状态冲突 / `-32009` 扩展未激活 / `-32602` 参数。