@m-cpy/pi-a2a-inbox 0.0.0-stage → 0.5.1

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,619 @@
1
+ /**
2
+ * inbox.ts — a2a-inbox/v1 语义层(PROTOCOL-v3-inbox §2/§4/§5/§7)。
3
+ * 消息表 + 四态状态机 + 投递提醒 + 显式回复。与信封(envelope.ts)解耦:
4
+ * 依赖通过 InboxDeps 注入,离线可测(验收 §14)。
5
+ *
6
+ * 关键不变量:
7
+ * - 正文只能 fetch 获得;入站一律 pending(§4.1)。
8
+ * - 必回消息只有 a2a_reply 能到 done;不必回 fetch 即 done(§4.2/3)。
9
+ * - attempts(取走/轮末回退)与 replyFails(回复投递失败)两条独立计数(§4.5/6,二审拆名)。
10
+ * - 提醒消费 = 投递进轮(delivered),不是 fetch(§5)。
11
+ * - 兜底同批 3 次上限,按会话维护,仅 pending 归零重置(二审批定义)。
12
+ * - 单写者:本实例只在端口所有者进程运行(envelope 保证)。
13
+ */
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ import crypto from "node:crypto";
17
+
18
+ export const EXT_URI = "https://a2a-inbox.local/ext/a2a-inbox/v1";
19
+ export const MAX_BODY = 32768;
20
+ export const MAX_TOPIC = 60;
21
+ export const MAX_PENDING = 1000; // 单盒 pending 上限(本地策略,各家可不同;-32044 语义统一,DSH 623dd25 共识)
22
+ export const MAX_ATTEMPTS = 3;
23
+ export const WATCHDOG_MS = Number(process.env.A2A_WATCHDOG_MS) > 0 ? Number(process.env.A2A_WATCHDOG_MS) : 60_000;
24
+ export const WAKE_COOLDOWN_MS = Number(process.env.A2A_WAKE_COOLDOWN_MS) > 0 ? Number(process.env.A2A_WAKE_COOLDOWN_MS) : 30_000; // 兜底/看门狗唤醒冷却:防重试/快速轮次期间 follow-up 唤醒堆积(空盒也排队)
25
+ export const STALL_WINDOWS = Number(process.env.A2A_STALL_WINDOWS) > 0 ? Number(process.env.A2A_STALL_WINDOWS) : 10; // 挂起超 N 个看门狗窗口喊一次 STALLED(qwenpaw c3d4e5a,状态迁移不刷屏)
26
+ export const PARK_MS = Number(process.env.A2A_PARK_MS) > 0 ? Number(process.env.A2A_PARK_MS) : 24 * 3600_000; // pending 超此时长没人取→suspended(expired 可逆)(DSH 两级淘汰)
27
+ export const PURGE_MS = Number(process.env.A2A_PURGE_MS) > 0 ? Number(process.env.A2A_PURGE_MS) : 72 * 3600_000; // suspended 超此时长→删 purged(不可逆,计数+日志)
28
+ export const TRIM_MS = Number(process.env.A2A_TRIM_MS) > 0 ? Number(process.env.A2A_TRIM_MS) : 24 * 3600_000; // done 超此时长→裁 trimmed(pi 去重走独立 dedup 账本不读盒子行,故 done 可激进;DSH 读盒子行故下限=去重窗口)
29
+ export const ORPHAN_GRACE_MS = Number(process.env.A2A_ORPHAN_GRACE_MS) > 0 ? Number(process.env.A2A_ORPHAN_GRACE_MS) : 7 * 24 * 3600_000; // 孤儿回收宽限期(DSH PR#9):会话持久化列表确认缺席超此时长 + 无未读→连参与事实一起删。7 天理由:缺席判定依赖一个可能失败的列表读取,宽限要足以覆盖存储抖动/重启/长期离线
30
+ export const ORPHAN_SCAN_MS = Number(process.env.A2A_ORPHAN_SCAN_MS) > 0 ? Number(process.env.A2A_ORPHAN_SCAN_MS) : 5 * 60_000; // 孤儿扫描周期(DSH 每 5 分钟异步扫一轮,只对已有盒子的会话问存在性,防每 tick I/O 放大)
31
+ // env 覆盖显形(qwenpaw 07dcdbb):有覆盖才喊(带生效值与来源),无覆盖返回 null 不喊(否则告警变噪音)——抽成函数以便负向断言
32
+ export function envOverrideLine(): string | null {
33
+ if (!(process.env.A2A_WATCHDOG_MS || process.env.A2A_WAKE_COOLDOWN_MS || process.env.A2A_STALL_WINDOWS || process.env.A2A_PARK_MS || process.env.A2A_PURGE_MS || process.env.A2A_TRIM_MS)) return null;
34
+ return `config ENV OVERRIDE | watchdogMs=${WATCHDOG_MS} wakeCooldownMs=${WAKE_COOLDOWN_MS} stallWindows=${STALL_WINDOWS} parkMs=${PARK_MS} purgeMs=${PURGE_MS} trimMs=${TRIM_MS} | source=process.env 环境变量重启即丢,验完请清`;
35
+ }
36
+ // 生效配置显形(qwenpaw 61161d1):任何来源的生效值都看得见(config/default 或 env),不依赖 env——「重启三问」③对任何来源成立
37
+ export function effectiveConfigLine(): string {
38
+ const isEnv = !!(process.env.A2A_WATCHDOG_MS || process.env.A2A_WAKE_COOLDOWN_MS || process.env.A2A_STALL_WINDOWS || process.env.A2A_PARK_MS || process.env.A2A_PURGE_MS);
39
+ return `config effective | watchdogMs=${WATCHDOG_MS} wakeCooldownMs=${WAKE_COOLDOWN_MS} stallWindows=${STALL_WINDOWS} parkMs=${PARK_MS} purgeMs=${PURGE_MS} trimMs=${TRIM_MS} | source=${isEnv ? "env" : "config/default"}${isEnv ? " 环境变量重启即丢,验完请清" : ""}`;
40
+ }
41
+ export const DEDUP_TTL_MS = 24 * 3600_000;
42
+
43
+ export type MsgState = "pending" | "consuming" | "done" | "suspended";
44
+
45
+ export interface BoxMessage {
46
+ messageId: string;
47
+ peer: string;
48
+ fromSessionId: string;
49
+ topic: string;
50
+ body: string;
51
+ mustReply: boolean;
52
+ receivedAt: number;
53
+ state: MsgState;
54
+ attempts: number; // 取走/轮末回退次数
55
+ replyFails: number; // 回复投递累计失败次数
56
+ reappeared: boolean;
57
+ direction: "in" | "out";
58
+ outId?: string; // 回复出站 id(一条入站绑定一个,重试复用,§2.2)
59
+ suspendedAt?: number;
60
+ doneAt?: number;
61
+ reason?: string;
62
+ replyToMessageId?: string; // out 消息:回哪条
63
+ }
64
+
65
+ export interface Receipt {
66
+ delivered: boolean;
67
+ sessionId: string;
68
+ queueDepth: number;
69
+ mode: "nudge-wake" | "nudge" | "duplicate";
70
+ duplicate?: boolean;
71
+ }
72
+
73
+ export interface InboxDeps {
74
+ now(): number;
75
+ isBusy(sessionId: string): boolean;
76
+ sessionExists(sessionId: string): Promise<boolean>;
77
+ createSession(): Promise<string>;
78
+ wake(sessionId: string, text: string): Promise<boolean>; // 唤醒+提醒;返回宿主是否接受(诚实送达,#15)
79
+ light(sessionId: string, text: string): Promise<boolean>; // 轮间 steer 注入(当前轮内 drain,不另起轮);投不进返回 false
80
+ log(...a: unknown[]): void;
81
+ }
82
+
83
+ interface DedupEntry { receipt: Receipt; bodyHash: string; at: number }
84
+ interface Counters {
85
+ since: number; recv: number; dup: number; returned: number; wakeQueued: number; wakeFail: number;
86
+ susp: Record<string, number>; lastInbound: number; lastClaim: number; lastWakeOk: number;
87
+ rejects: { noToken: number; unknownToken: number; ambiguousToken: number };
88
+ selfProbes: number; purged: number; trimmed: number; reclaimedOrphan: number;
89
+ }
90
+ interface Persisted { messages: BoxMessage[]; dedup: Record<string, DedupEntry>; nudges: Record<string, NudgeState>; counters?: Counters; participation?: Record<string, Record<string, { topic: string; at: number }>>; orphanSince?: Record<string, number> }
91
+ interface NudgeState {
92
+ queued: boolean; // 提醒已入队未投递
93
+ delivered: boolean; // 本轮已投递(消费)
94
+ text: string;
95
+ injectedAt: number; // 上次尝试时刻(看门狗退避基准,尝试刷新)
96
+ firstQueuedAt: number; // 这批首次挂起时刻(观测“挂了多久”,尝试不刷新,qwenpaw c3d4e5a ④)
97
+ stallReported: boolean; // 挂够久已告警(状态迁移,送达后重新武装)
98
+ batchCount: number; // 同批兜底唤醒次数(pending 归零重置)
99
+ lastActivity: number;
100
+ lastWakeAt: number; // 上次唤醒时刻(冷却去重,防 follow-up 堆积)
101
+ hostQueued: boolean; // 宿主已可靠接受入队(steer/followUp accepted)→ 等 drain,看门狗不升级防重复提醒(r51)
102
+ }
103
+
104
+ export class Inbox {
105
+ private messages: BoxMessage[] = [];
106
+ private dedup: Record<string, DedupEntry> = {};
107
+ private nudges: Record<string, NudgeState> = {};
108
+ // 参与事实(DSH b073169):谁参与过/最后用什么 topic,从消息行拆出独立存——披露面正确性不该依赖留多少历史(trim 不撤回 A+)
109
+ private participation: Record<string, Record<string, { topic: string; at: number }>> = {};
110
+ // 孤儿回收(DSH PR#9):会话首次确认缺席的时刻;会话回来即清。与空盒回收(reclaimed)分开计数——一个是读不到的空壳,一个是主人没了的房子
111
+ private orphanSince: Record<string, number> = {};
112
+ private lastOrphanScan = 0;
113
+ private counters: Counters = { since: 0, recv: 0, dup: 0, returned: 0, wakeQueued: 0, wakeFail: 0, susp: {}, lastInbound: 0, lastClaim: 0, lastWakeOk: 0, rejects: { noToken: 0, unknownToken: 0, ambiguousToken: 0 }, selfProbes: 0, purged: 0, trimmed: 0, reclaimedOrphan: 0 };
114
+ private rejectDirty = false;
115
+ private chains = new Map<string, Promise<unknown>>();
116
+ private loaded = false;
117
+
118
+ constructor(private file: string, private deps: InboxDeps) {}
119
+
120
+ // ---------- 持久化 ----------
121
+ // pi-web 多进程:端口所有者接收写盘,其他进程的工具读盘。按 mtime 刷新保证跨进程可见。
122
+ private lastMtime = 0;
123
+ private load() {
124
+ let mt = 0;
125
+ try { mt = fs.statSync(this.file).mtimeMs; } catch { /* 新文件 */ }
126
+ if (this.loaded && mt === this.lastMtime) return;
127
+ const first = !this.loaded;
128
+ this.loaded = true;
129
+ this.lastMtime = mt;
130
+ try {
131
+ const raw = JSON.parse(fs.readFileSync(this.file, "utf8")) as Persisted;
132
+ this.messages = raw.messages ?? [];
133
+ this.dedup = raw.dedup ?? {};
134
+ this.nudges = raw.nudges ?? {};
135
+ this.participation = raw.participation ?? {};
136
+ this.orphanSince = raw.orphanSince ?? {};
137
+ for (const m of this.messages) if (m.topic) this.noteTraffic(m.peer, this.boxOwner(m), m.topic, m.receivedAt); // 老数据自动迁移
138
+ this.counters = raw.counters ?? { since: this.deps.now(), recv: 0, dup: 0, returned: 0, wakeQueued: 0, wakeFail: 0, susp: {}, lastInbound: 0, lastClaim: 0, lastWakeOk: 0, rejects: { noToken: 0, unknownToken: 0, ambiguousToken: 0 }, selfProbes: 0, purged: 0, trimmed: 0, reclaimedOrphan: 0 };
139
+ if (this.counters.purged === undefined) this.counters.purged = 0; // 旧账本补字段
140
+ if (this.counters.trimmed === undefined) this.counters.trimmed = 0;
141
+ if (this.counters.reclaimedOrphan === undefined) this.counters.reclaimedOrphan = 0; // 旧账本补字段
142
+ if (!this.counters.since) this.counters.since = this.deps.now();
143
+ if (!this.counters.rejects) this.counters.rejects = { noToken: 0, unknownToken: 0, ambiguousToken: 0 };
144
+ if (typeof this.counters.selfProbes !== "number") this.counters.selfProbes = 0;
145
+ } catch { /* 新文件 */ }
146
+ // §4.9 重启:consuming → pending(仅进程首次加载,跨进程刷新不重复回退)
147
+ // P0-B:崩溃计一次未答(attempts++,3 次转 suspended)并持久化,与 DSH 1ca8da0 对齐;防无限崩溃恢复循环
148
+ if (first) {
149
+ let changed = false;
150
+ for (const m of this.messages) if (m.state === "consuming") {
151
+ m.attempts++;
152
+ if (m.attempts >= MAX_ATTEMPTS) { m.state = "suspended"; m.suspendedAt = this.deps.now(); m.reason = "no-reply-3x"; this.suspCount("no-reply-3x"); }
153
+ else { m.state = "pending"; m.reappeared = true; }
154
+ changed = true;
155
+ }
156
+ // ⑦ 重启后失效 reminder 状态重置(qwenpaw d1e92f6):那轮推理已随进程消失,delivered/queued 标记不再有效;
157
+ // 有 pending 才置回 none(防积压永久躺平 + 新入站也救不了的双重断路);保留 batchCount(防烧 token 跨重启)与 firstQueuedAt(首次挂起是事实)
158
+ for (const sid of Object.keys(this.nudges)) {
159
+ const ns = this.nudges[sid];
160
+ if ((ns.delivered || ns.queued) && this.pendingOf(sid).length > 0) {
161
+ ns.delivered = false; ns.queued = false; ns.stallReported = false; ns.hostQueued = false; changed = true;
162
+ }
163
+ }
164
+ if (changed) this.save();
165
+ }
166
+ this.pruneDedup();
167
+ }
168
+ private save() {
169
+ const data: Persisted = { messages: this.messages, dedup: this.dedup, nudges: this.nudges, counters: this.counters, participation: this.participation, orphanSince: this.orphanSince };
170
+ fs.mkdirSync(path.dirname(this.file), { recursive: true });
171
+ const tmp = `${this.file}.tmp-${process.pid}`;
172
+ fs.writeFileSync(tmp, JSON.stringify(data));
173
+ fs.renameSync(tmp, this.file); // 原子写
174
+ try { this.lastMtime = fs.statSync(this.file).mtimeMs; } catch { /* ignore */ }
175
+ }
176
+ private pruneDedup() {
177
+ const now = this.deps.now();
178
+ for (const k of Object.keys(this.dedup)) if (now - this.dedup[k].at > DEDUP_TTL_MS) delete this.dedup[k];
179
+ }
180
+
181
+ // ---------- per-session 串行链(§5 并发) ----------
182
+ private enqueue<T>(sessionId: string, fn: () => Promise<T> | T): Promise<T> {
183
+ const prev = this.chains.get(sessionId) ?? Promise.resolve();
184
+ const next = prev.then(fn, fn);
185
+ this.chains.set(sessionId, next.then(() => undefined, () => undefined));
186
+ return next;
187
+ }
188
+
189
+ private nudge(sessionId: string): NudgeState {
190
+ return (this.nudges[sessionId] ??= { queued: false, delivered: false, text: "", injectedAt: 0, firstQueuedAt: 0, stallReported: false, batchCount: 0, lastActivity: 0, lastWakeAt: 0, hostQueued: false });
191
+ }
192
+ private pendingOf(sessionId: string) {
193
+ return this.messages.filter(m => m.direction === "in" && m.fromSessionId !== undefined && m.state === "pending" && this.boxOwner(m) === sessionId);
194
+ }
195
+ private consumingOf(sessionId: string) {
196
+ return this.messages.filter(m => m.direction === "in" && m.state === "consuming" && this.boxOwner(m) === sessionId);
197
+ }
198
+ private markQueued(ns: NudgeState, now: number) { ns.queued = true; if (!ns.firstQueuedAt) ns.firstQueuedAt = now; } // 首次挂起时刻只记一次
199
+ private resetBatch(ns: NudgeState) { ns.queued = false; ns.delivered = false; ns.batchCount = 0; ns.firstQueuedAt = 0; ns.stallReported = false; ns.hostQueued = false; }
200
+ // 盒子按"我方会话"隔离:入站消息的盒子归属 = 投递目标会话(contextId),存于 boxSession
201
+ private boxOwner(m: BoxMessage): string { return (m as any).boxSession ?? m.fromSessionId; }
202
+
203
+ // ---------- 接收(§5) ----------
204
+ async receive(peer: string, sessionId: string, rawContext: string, fields: {
205
+ messageId: string; senderSessionId: string; topic: string; body: string; mustReply: boolean; replyToMessageId?: string;
206
+ }): Promise<Receipt> {
207
+ this.load();
208
+ if (!fields.senderSessionId) { const e: any = new Error("INVALID_PARAMS: senderSessionId required"); e.code = -32602; throw e; }
209
+ // 目标会话解析:空→新建;非空未知→拒绝(§2,调用方 envelope 已校验,这里再兜底)
210
+ let target = rawContext;
211
+ if (!target) target = await this.deps.createSession();
212
+ else if (!(await this.deps.sessionExists(target))) { const e: any = new Error("Session not found on this side"); e.code = -32040; throw e; } // 不回显调用方给的 id(DSH:减少被当作“确认过此名字”的错觉)
213
+
214
+ return this.enqueue(target, async () => {
215
+ this.pruneDedup();
216
+ const key = `${peer}|${fields.messageId}`;
217
+ const bodyHash = crypto.createHash("sha256").update(`${fields.topic}|${fields.body}|${fields.mustReply}`).digest("hex"); // 全 sha256(DSH 碰撞顾虑:截断 64bit 弱,全 256bit 碰撞实际不可能)
218
+ const dup = this.dedup[key];
219
+ if (dup) {
220
+ if (dup.bodyHash !== bodyHash) { const e: any = new Error("DUPLICATE_MESSAGE: same messageId, different body"); e.code = -32043; throw e; }
221
+ this.counters.dup++;
222
+ return { ...dup.receipt, duplicate: true, mode: "duplicate" as const };
223
+ }
224
+ // 单盒背压(-32044 BOX_FULL):pending 达上限拒新入站,不落盒;消费一条释放一位(非封禁)。duplicate 不受影响(上面已返回)
225
+ const cur = this.pendingOf(target).length;
226
+ if (cur >= MAX_PENDING) { const e: any = new Error(`BOX_FULL: pending cap ${MAX_PENDING} reached (current ${cur})`); e.code = -32044; e.data = { current: cur, cap: MAX_PENDING }; throw e; }
227
+ // 回复关联:把对方回的那条 out 消息标 done(§7)
228
+ if (fields.replyToMessageId) {
229
+ const out = this.messages.find(m => m.direction === "out" && m.messageId === fields.replyToMessageId);
230
+ if (out && out.state !== "done") { out.state = "done"; out.doneAt = this.deps.now(); }
231
+ }
232
+ const m: BoxMessage = {
233
+ messageId: fields.messageId, peer, fromSessionId: fields.senderSessionId,
234
+ topic: fields.topic, body: fields.body, mustReply: fields.mustReply,
235
+ receivedAt: this.deps.now(), state: "pending", attempts: 0, replyFails: 0,
236
+ reappeared: false, direction: "in", replyToMessageId: fields.replyToMessageId,
237
+ };
238
+ (m as any).boxSession = target;
239
+ this.messages.push(m);
240
+ this.noteTraffic(peer, target, fields.topic, m.receivedAt); // 参与事实(入站)
241
+ this.counters.recv++; this.counters.lastInbound = this.deps.now();
242
+ this.event(target, `+1 recv from=${peer} topic=${fields.topic}`);
243
+ const N = this.pendingOf(target).length;
244
+ const ns = this.nudge(target);
245
+ ns.lastActivity = this.deps.now();
246
+ // 批计数:pending 归零才重置(二审);此处 N>=1,若之前归零已重置
247
+ const mode = await this.deliverNudge(target, peer, fields.topic, N);
248
+ const receipt: Receipt = { delivered: true, sessionId: target, queueDepth: N, mode };
249
+ this.dedup[key] = { receipt, bodyHash, at: this.deps.now() };
250
+ this.save();
251
+ return receipt;
252
+ });
253
+ }
254
+
255
+ /** 投递提醒:idle 唤醒(followUp 起新一轮)/ running 轮间 steer 轻提醒;合并去重(§5/§6)。 */
256
+ private async deliverNudge(target: string, peer: string, topic: string, N: number): Promise<"nudge-wake" | "nudge"> {
257
+ const ns = this.nudge(target);
258
+ const mustCount = this.pendingOf(target).filter(m => m.mustReply).length;
259
+ const busy = this.deps.isBusy(target);
260
+ // 起新一轮唤醒(idle/降级 followUp)提醒不变(用户定 r50):带发送方/主题/计数 + fetch
261
+ const wakeText = `[a2a] 来自 ${peer} 的消息 · 主题:${topic}${mustCount ? "(需回复)" : ""}\n消息盒:${N} 条待处理${mustCount ? `(${mustCount} 条需回复)` : ""} → a2a_inbox_fetch`;
262
+ // 轮间 steer 轻提醒(B 通用触发,r50):不写死 peer/计数 → 排队窗口盒子变化永不 stale;指 list 让 agent 看实时全貌自主排序(必回优先)
263
+ const steerText = `[a2a] 消息盒有新消息 → a2a_inbox_list 查看后取件处理`;
264
+ if (ns.queued) { ns.text = busy ? steerText : wakeText; return busy ? "nudge" : "nudge-wake"; } // 合并:更新内部记录不重复入队(已入队文本是快照,B 通用文本无 stale)
265
+ if (busy) {
266
+ const ok = await this.deps.light(target, steerText); // 轮间 steer 注入(当前轮内 drain,不跨轮)
267
+ if (ok) { this.markQueued(ns, this.deps.now()); ns.hostQueued = true; ns.injectedAt = this.deps.now(); ns.text = steerText; this.counters.wakeQueued++; return "nudge"; }
268
+ // 轮间提醒投不进(未加载)→ 降级唤醒
269
+ }
270
+ const ok = await this.deps.wake(target, wakeText);
271
+ this.markQueued(ns, this.deps.now()); ns.hostQueued = ok; ns.text = wakeText;
272
+ if (ok) { ns.injectedAt = this.deps.now(); ns.lastWakeAt = this.deps.now(); this.counters.lastWakeOk = this.deps.now(); }
273
+ else { const past = this.deps.now() - Math.max(WATCHDOG_MS, WAKE_COOLDOWN_MS); ns.injectedAt = past; ns.lastActivity = past; ns.lastWakeAt = past; this.counters.wakeFail++; } // 拒收→回拨计时,看门狗尽快升级
274
+ return "nudge-wake";
275
+ }
276
+
277
+ /** 提醒被投递进轮(agent_start 时调用)→ 消费(§5 定义)。 */
278
+ markDelivered(sessionId: string) {
279
+ this.load();
280
+ const ns = this.nudge(sessionId);
281
+ if (ns.queued) { ns.queued = false; ns.delivered = true; ns.batchCount++; ns.firstQueuedAt = 0; ns.stallReported = false; ns.hostQueued = false; this.save(); } // 预算只计真送达(qwenpaw 6a5335b ①:催过一次=delivered 非调用 wake);送达清挂起观测重新武装
282
+ }
283
+
284
+ // ---------- 轮末收口(§4.5 + §5 兜底,进串行链) ----------
285
+ async turnEnd(sessionId: string): Promise<void> {
286
+ this.load();
287
+ return this.enqueue(sessionId, async () => {
288
+ const ns = this.nudge(sessionId);
289
+ ns.delivered = false;
290
+ // consuming 回退
291
+ for (const m of this.messages) {
292
+ if (this.boxOwner(m) !== sessionId || m.state !== "consuming") continue;
293
+ m.attempts++;
294
+ if (m.attempts >= MAX_ATTEMPTS) { m.state = "suspended"; m.suspendedAt = this.deps.now(); m.reason = "no-reply-3x"; this.suspCount("no-reply-3x"); }
295
+ else { m.state = "pending"; m.reappeared = true; }
296
+ }
297
+ const pending = this.pendingOf(sessionId);
298
+ if (pending.length === 0 && this.consumingOf(sessionId).length === 0) { this.resetBatch(ns); this.save(); return; } // 批重置:既无 pending 也无 consuming(③ consuming≠批结束)
299
+ // 兜底:pending>0 且无 queued 提醒且过冷却 → 唤醒一次(同批 3 次真送达封顶)
300
+ // 冷却基准取 lastWakeAt 与 injectedAt 较大者:light 提醒只设 injectedAt 不设 lastWakeAt,
301
+ // 否则轮末会在 receive 轻提醒后几秒再补一声响 wake(多余触发,投递滞后变 stale 提醒)
302
+ if (!ns.queued && ns.batchCount < MAX_ATTEMPTS && this.deps.now() - Math.max(ns.lastWakeAt, ns.injectedAt) >= WAKE_COOLDOWN_MS) {
303
+ const mustCount = pending.filter(m => m.mustReply).length;
304
+ const text = `[a2a] 消息盒:${pending.length} 条待处理${mustCount ? `(${mustCount} 条需回复)` : ""} → a2a_inbox_fetch`;
305
+ const wok = await this.deps.wake(sessionId, text);
306
+ this.markQueued(ns, this.deps.now()); ns.hostQueued = wok; ns.injectedAt = this.deps.now(); ns.lastWakeAt = this.deps.now(); ns.text = text;
307
+ }
308
+ this.save();
309
+ });
310
+ }
311
+
312
+ // ---------- 看门狗(§5:误判忙/注入丢失 → T 秒升级唤醒) ----------
313
+ async watchdogTick(): Promise<void> {
314
+ this.load();
315
+ this.flushRejects(); // 401 脏标记定期落盘(不每次同步写,防 I/O 放大)
316
+ const now = this.deps.now();
317
+ for (const sessionId of Object.keys(this.nudges)) {
318
+ const ns = this.nudges[sessionId];
319
+ const pending = this.pendingOf(sessionId);
320
+ if (pending.length === 0) {
321
+ if ((ns.queued || ns.delivered) && this.consumingOf(sessionId).length === 0) { this.resetBatch(ns); this.save(); } // ③ consuming 未干完不清账
322
+ continue;
323
+ }
324
+ // 孤儿盒子(DSH 969c7bb 同构):会话已不存在 + 最老 pending 超 5 个看门狗窗口 → 转 suspended(session-gone),可见可删;不新建会话搬消息(防污染)
325
+ if (!(await this.deps.sessionExists(sessionId))) {
326
+ const oldest = Math.min(...pending.map(m => m.receivedAt));
327
+ if (now - oldest > 5 * WATCHDOG_MS) {
328
+ await this.enqueue(sessionId, async () => {
329
+ for (const m of this.pendingOf(sessionId)) { m.state = "suspended"; m.suspendedAt = now; m.reason = "session-gone"; this.suspCount("session-gone"); }
330
+ this.event(sessionId, "session-gone suspended");
331
+ this.resetBatch(ns); this.save();
332
+ });
333
+ }
334
+ continue; // 会话没了不唤醒
335
+ }
336
+ // ④ 挂起观测(qwenpaw c3d4e5a):firstQueuedAt 不被尝试刷新;挂够久喊一次 STALLED(独立于唤醒预算/冷却,状态迁移不刷屏)
337
+ if (ns.queued && !ns.delivered && ns.firstQueuedAt && now - ns.firstQueuedAt > STALL_WINDOWS * WATCHDOG_MS && !ns.stallReported) {
338
+ ns.stallReported = true;
339
+ const c = this.counters;
340
+ const peers = [...new Set(pending.map(m => m.peer))].join(",") || "-";
341
+ const rj = c.rejects; const rjTotal = rj.noToken + rj.unknownToken + rj.ambiguousToken;
342
+ // 告警行五组模板(DSH/qwenpaw):谁/哪/多少/何时/为什么
343
+ this.deps.log(`[a2a] reminder STALLED peers=${peers} session=${sessionId} pending=${pending.length} | firstQueued=${new Date(ns.firstQueuedAt).toISOString()} lastAttempt=${new Date(ns.injectedAt).toISOString()} lastInbound=${c.lastInbound ? new Date(c.lastInbound).toISOString() : "-"} lastWakeOk=${c.lastWakeOk ? new Date(c.lastWakeOk).toISOString() : "-"} | recv=${c.recv} wakeQueued=${c.wakeQueued} wakeFail=${c.wakeFail} rejects=${rjTotal}(no-token ${rj.noToken}/unknown ${rj.unknownToken}/ambiguous ${rj.ambiguousToken}) | queued ${Math.round((now - ns.firstQueuedAt) / 1000)}s never delivered: host may be deaf or rejecting, check reachability`);
344
+ this.save();
345
+ }
346
+ if (ns.batchCount >= MAX_ATTEMPTS) continue;
347
+ if (now - Math.max(ns.lastWakeAt, ns.injectedAt) < WAKE_COOLDOWN_MS) continue; // 冷却防堆积(含 light 提醒的 injectedAt)
348
+ if (ns.queued && !ns.delivered) {
349
+ // queued 提醒未投递:老化后升级(判忙误判场景,不查 isBusy)
350
+ if (ns.hostQueued) continue; // r51:宿主已可靠入队(steer/followUp accepted)→ 等当前轮工具边界 drain,不升级防重复提醒(长工具 >60s 时看门狗误判丢失会补一条 followUp,与 steer 叠成两条);真卡死由 STALLED 告警观测
351
+ if (now - ns.injectedAt < WATCHDOG_MS) continue;
352
+ if (now - ns.lastActivity < WATCHDOG_MS) continue; // 期间有活动则不升级
353
+ } else {
354
+ // 积压但无 queued 提醒(restart 后 idle 积压 / 轻提醒已 delivered 但未消费):仅空闲时兜底唤醒
355
+ if (this.deps.isBusy(sessionId)) continue;
356
+ }
357
+ await this.enqueue(sessionId, async () => {
358
+ const p = this.pendingOf(sessionId);
359
+ if (p.length === 0 && this.consumingOf(sessionId).length === 0) { this.resetBatch(ns); this.save(); return; }
360
+ if (p.length === 0) return; // 有 consuming 无 pending:不催也不清账
361
+ const mustCount = p.filter(m => m.mustReply).length;
362
+ const text = `[a2a] 消息盒:${p.length} 条待处理${mustCount ? `(${mustCount} 条需回复)` : ""} → a2a_inbox_fetch`;
363
+ const wok = await this.deps.wake(sessionId, text);
364
+ this.markQueued(ns, now); ns.hostQueued = wok; ns.delivered = false; ns.injectedAt = now; ns.lastWakeAt = now; ns.text = text;
365
+ this.save();
366
+ });
367
+ }
368
+ await this.retentionSweep(now); // 永久残留两级淘汰(DSH):park 可逆 / purge 不可逆
369
+ await this.reclaimOrphans(now); // 孤儿回收(DSH PR#9):会话持久化确认缺席超宽限 + 无未读→连参与事实一起删
370
+ }
371
+
372
+ // 永久残留淘汰(DSH 两级,语义一致数值可配):pending 超 PARK_MS 没人取→suspended(expired 可逆 fromSuspended 取回);suspended 超 PURGE_MS→删 purged+日志
373
+ private async retentionSweep(now: number): Promise<void> {
374
+ let changed = false;
375
+ const bySession = new Map<string, BoxMessage[]>();
376
+ for (const m of this.messages) if (m.direction === "in" && m.state === "pending") {
377
+ const sid = this.boxOwner(m); const arr = bySession.get(sid) ?? []; arr.push(m); bySession.set(sid, arr);
378
+ }
379
+ for (const [sid, pend] of bySession) {
380
+ const oldest = Math.min(...pend.map(m => m.receivedAt));
381
+ if (now - oldest > PARK_MS) {
382
+ for (const m of pend) { m.state = "suspended"; m.suspendedAt = now; m.reason = "expired"; this.suspCount("expired"); }
383
+ this.event(sid, "expired suspended"); changed = true;
384
+ }
385
+ }
386
+ const purgedBySession = new Map<string, string[]>();
387
+ this.messages = this.messages.filter(m => {
388
+ if (m.state === "suspended" && m.suspendedAt && now - m.suspendedAt > PURGE_MS) {
389
+ const sid = this.boxOwner(m); const arr = purgedBySession.get(sid) ?? []; arr.push(m.messageId); purgedBySession.set(sid, arr); return false;
390
+ }
391
+ return true;
392
+ });
393
+ let purged = 0; for (const ids of purgedBySession.values()) purged += ids.length;
394
+ if (purged > 0) {
395
+ this.counters.purged += purged;
396
+ for (const [sid, ids] of purgedBySession) this.event(sid, `purged ${ids.length} (${ids.join(",")})`); // 删除带 id(审计,DSH/qwenpaw 同构)
397
+ changed = true;
398
+ }
399
+ // done 裁剪(DSH a1c77c7):已处理历史「清灰」,独立 trimmed 计数(非残留是无界增长);一个数说明不了三件事
400
+ const trimmedBySession = new Map<string, string[]>();
401
+ this.messages = this.messages.filter(m => {
402
+ if (m.state === "done" && now - (m.doneAt ?? m.receivedAt) > TRIM_MS) {
403
+ const sid = this.boxOwner(m); const arr = trimmedBySession.get(sid) ?? []; arr.push(m.messageId); trimmedBySession.set(sid, arr); return false;
404
+ }
405
+ return true;
406
+ });
407
+ let trimmed = 0; for (const ids of trimmedBySession.values()) trimmed += ids.length;
408
+ if (trimmed > 0) { this.counters.trimmed += trimmed; for (const [sid, ids] of trimmedBySession) this.event(sid, `trimmed ${ids.length} (${ids.join(",")})`); changed = true; }
409
+ // nudges 清理:会话无任何消息→删 nudge entry(pi 每盒一对象不按次追加,但会话删后 entry 残留,防按盒累积)
410
+ for (const sid of Object.keys(this.nudges)) {
411
+ if (!this.messages.some(m => this.boxOwner(m) === sid)) { delete this.nudges[sid]; changed = true; }
412
+ }
413
+ // 空盒回收(DSH dda93a5 同构,适配 pi 结构):participation[peer] 为空 {}(无任何参与会话)→删该 peer 键。
414
+ // 核心约束「参与事实非空就不删」:participation[peer][session] 条目是 sessions/list 的披露面载体(PROTOCOL §9.5.2 解耦),
415
+ // 消息裁剪光也绝不回收——删了等于让「留多少历史」静默决定「对端还能看到哪些会话」。pi 只回收两边都空的残渣(空 peer 键 / 无消息的 nudge)。
416
+ for (const peer of Object.keys(this.participation)) {
417
+ if (Object.keys(this.participation[peer] ?? {}).length === 0) { delete this.participation[peer]; changed = true; }
418
+ }
419
+ if (changed) this.save();
420
+ }
421
+
422
+ // 孤儿回收(DSH PR#9 同构,适配 pi 结构):会话在宿主持久化列表确认不存在 + 连续缺席超宽限期 + 无未读 → 连参与事实一起删。
423
+ // 两条硬约束(比删除逻辑更重要,写进协议文本):
424
+ // ① 存在性读持久化列表(pi getSession→SessionManager.listAll 读盘投影),不读活跃注册表——空闲会话不是被删会话(2026-12-02 “空闲会话被误判已删除”代价)。
425
+ // ② “查不到”≠“不存在”:listAll 失败/抖动/锁/超时/启动中 → unknown,no-op 不推进计时(把失败当缺席=让一次存储异常删掉真实数据)。
426
+ private async reclaimOrphans(now: number): Promise<void> {
427
+ if (now - this.lastOrphanScan < ORPHAN_SCAN_MS) return; // 每 5 分钟扫一轮(DSH),防每 tick 对每会话 listAll 的 I/O 放大
428
+ this.lastOrphanScan = now;
429
+ const boxSessions = new Set<string>();
430
+ for (const peer of Object.keys(this.participation)) for (const sid of Object.keys(this.participation[peer] ?? {})) boxSessions.add(sid);
431
+ for (const sid of Object.keys(this.nudges)) boxSessions.add(sid);
432
+ for (const m of this.messages) boxSessions.add(this.boxOwner(m));
433
+ let changed = false;
434
+ for (const sid of boxSessions) {
435
+ let presence: "exists" | "absent" | "unknown";
436
+ try { presence = (await this.deps.sessionExists(sid)) ? "exists" : "absent"; }
437
+ catch { presence = "unknown"; } // 硬约束②:失败按未知,不推进计时
438
+ if (presence === "unknown") continue; // no-op
439
+ if (presence === "exists") { if (this.orphanSince[sid] !== undefined) { delete this.orphanSince[sid]; changed = true; } continue; } // 会话回来即清标记
440
+ // absent:推进缺席计时(首次发现缺席的时刻)
441
+ if (this.orphanSince[sid] === undefined) { this.orphanSince[sid] = now; changed = true; }
442
+ const unread = this.messages.some(m => this.boxOwner(m) === sid && (m.state === "pending" || m.state === "suspended"));
443
+ if (unread) continue; // 有未读就永不删(三条同时成立才删)
444
+ if (now - this.orphanSince[sid] > ORPHAN_GRACE_MS) {
445
+ // 连参与事实一起删(用户明确要求:会话都没了,那个“关系”已经没有另一头)
446
+ for (const peer of Object.keys(this.participation)) { if (this.participation[peer]?.[sid]) delete this.participation[peer][sid]; }
447
+ delete this.nudges[sid];
448
+ this.messages = this.messages.filter(m => this.boxOwner(m) !== sid);
449
+ delete this.orphanSince[sid];
450
+ this.counters.reclaimedOrphan++;
451
+ this.event(sid, `reclaimedOrphan (session absent > ${Math.round(ORPHAN_GRACE_MS / 86400000)}d, no unread)`);
452
+ changed = true;
453
+ }
454
+ }
455
+ if (changed) this.save();
456
+ }
457
+
458
+ // ---------- 工具面 ----------
459
+ /** 同步盒子计数(widget 用,不走串行链)。 */
460
+ boxCounts(sessionId: string): { pendingTotal: number; suspendedTotal: number } {
461
+ this.load();
462
+ const mine = this.messages.filter(m => this.boxOwner(m) === sessionId && m.direction === "in");
463
+ return { pendingTotal: mine.filter(m => m.state === "pending").length, suspendedTotal: mine.filter(m => m.state === "suspended").length };
464
+ }
465
+ // 可观测性(qwenpaw 5bba8cb 同名):累计计数+since+最后动作时间戳,落盘重启不丢;日切从日志重算不进账本
466
+ countersView(): Counters { this.load(); return { ...this.counters, susp: { ...this.counters.susp } }; }
467
+ reminderState(sessionId: string) { this.load(); const ns = this.nudges[sessionId]; return ns ? { queued: ns.queued, delivered: ns.delivered, batchCount: ns.batchCount, firstQueuedAt: ns.firstQueuedAt, stallReported: ns.stallReported, hostQueued: ns.hostQueued } : { queued: false, delivered: false, batchCount: 0, firstQueuedAt: 0, stallReported: false, hostQueued: false }; }
468
+ private suspCount(reason: string) { this.counters.susp[reason] = (this.counters.susp[reason] ?? 0) + 1; }
469
+ // authReject 服务级计数(qwenpaw 同类):401 故意不每次同步写盘,只置脏标记(防端口扫描 I/O 放大),看门狗/下次 save flush
470
+ noteReject(kind: "noToken" | "unknownToken" | "ambiguousToken") { this.load(); this.counters.rejects[kind]++; this.rejectDirty = true; }
471
+ noteSelfProbe() { this.load(); this.counters.selfProbes++; this.rejectDirty = true; } // 自探针独立计数,不污染 authReject(qwenpaw cfb65c2)
472
+ flushRejects() { if (this.rejectDirty) { this.rejectDirty = false; this.save(); } }
473
+ private event(session: string, action: string) {
474
+ const c = this.counters;
475
+ const susp = Object.entries(c.susp).map(([k, v]) => `${k}=${v}`).join(",") || "0";
476
+ this.deps.log(`[a2a] box session=${session}: ${action} | since=${c.since} recv=${c.recv} dup=${c.dup} returned=${c.returned} wakeQueued=${c.wakeQueued} wakeFail=${c.wakeFail} susp=${susp}`);
477
+ }
478
+ /** 会话是否正在推理(sessions/list 真实 status 用)。 */
479
+ isSessionBusy(sessionId: string): boolean { return this.deps.isBusy(sessionId); }
480
+ // 与某 peer 有过消息往来(in/out 任意)的会话集——sessions/list 标题可见性用(A 关系型可见性,DSH §9.4)
481
+ exchangedSessions(peer: string): Set<string> {
482
+ this.load();
483
+ return new Set(Object.keys(this.participation[peer] ?? {})); // 读参与事实,不读消息行(trim 后仍在)
484
+ }
485
+ // A+(DSH db27084 / qwenpaw d0dc228):可见集=与该 peer 有往来的会话,标签=该 peer 已知最新 topic(in/out 任一,对方本来就知道);零新增泄露
486
+ visibleSessions(peer: string): Map<string, string> {
487
+ this.load();
488
+ const out = new Map<string, string>();
489
+ const p = this.participation[peer]; // 读参与事实(load 已从消息行迁移老数据),trim 消息行不撤回披露面
490
+ if (p) for (const [s, v] of Object.entries(p)) out.set(s, v.topic);
491
+ return out;
492
+ }
493
+ // 参与事实写入(in/out 各一次):只保留最新 topic
494
+ private noteTraffic(peer: string, session: string, topic: string, at: number) {
495
+ if (!topic) return;
496
+ const p = this.participation[peer] ?? (this.participation[peer] = {});
497
+ const cur = p[session];
498
+ if (!cur || at >= cur.at) p[session] = { topic, at };
499
+ }
500
+
501
+ async list(sessionId: string, opts: { peer?: string; includeSuspended?: boolean; limit?: number }) {
502
+ this.load();
503
+ const mine = this.messages.filter(m => this.boxOwner(m) === sessionId && m.direction === "in");
504
+ const pending = mine.filter(m => m.state === "pending" && (!opts.peer || m.peer === opts.peer));
505
+ const suspended = mine.filter(m => m.state === "suspended");
506
+ const view = (m: BoxMessage) => ({ messageId: m.messageId, from: m.peer, fromSessionId: m.fromSessionId, topic: m.topic, mustReply: m.mustReply, receivedAt: m.receivedAt, attempts: m.attempts, reappeared: m.reappeared });
507
+ return {
508
+ pending: pending.slice(0, opts.limit ?? 20).map(view),
509
+ pendingTotal: pending.length,
510
+ suspendedTotal: suspended.length,
511
+ ...(opts.includeSuspended ? { suspended: suspended.map(m => ({ messageId: m.messageId, from: m.peer, topic: m.topic, suspendedAt: m.suspendedAt, reason: m.reason })) } : {}),
512
+ };
513
+ }
514
+
515
+ async fetch(sessionId: string, opts: { messageId?: string; messageIds?: string[]; fromSuspended?: boolean; peer?: string }) {
516
+ this.load();
517
+ return this.enqueue(sessionId, async () => {
518
+ const mine = this.messages.filter(m => this.boxOwner(m) === sessionId && m.direction === "in");
519
+ let picked: BoxMessage[];
520
+ if (opts.fromSuspended) {
521
+ if (!opts.messageId) { const e: any = new Error("fromSuspended requires messageId"); e.code = -32602; throw e; }
522
+ const m = mine.find(x => x.messageId === opts.messageId);
523
+ if (!m || m.state !== "suspended") { const e: any = new Error("MESSAGE_NOT_PENDING"); e.code = -32045; throw e; }
524
+ m.attempts = 0; m.replyFails = 0; m.reappeared = false; // §4.11 用户指示重置
525
+ picked = [m];
526
+ } else if (opts.messageIds?.length || opts.messageId) {
527
+ const ids = opts.messageIds ?? [opts.messageId!];
528
+ picked = [];
529
+ for (const id of ids) {
530
+ // 三级规则(qwenpaw f2bec03 同构):①有 peer 只在该 peer 找;②无 peer 跨 peer 多条 pending 报错点名不猜;③同 peer 多条按状态优先 pending→consuming→suspended,同级到达序
531
+ let cands = mine.filter(x => x.messageId === id);
532
+ if (opts.peer) cands = cands.filter(x => x.peer === opts.peer);
533
+ const pendPeers = [...new Set(cands.filter(x => x.state === "pending").map(x => x.peer))];
534
+ if (!opts.peer && pendPeers.length > 1) { const e: any = new Error(`messageId ${id} exists for several peers (${pendPeers.join(", ")}); pass peer=<name>`); e.code = -32602; throw e; }
535
+ const order: Record<string, number> = { pending: 0, consuming: 1, suspended: 2, done: 3 };
536
+ cands.sort((a, b) => (order[a.state] - order[b.state]) || (a.receivedAt - b.receivedAt));
537
+ const m = cands[0];
538
+ if (!m || m.state !== "pending") { const e: any = new Error(`MESSAGE_NOT_PENDING: ${id}`); e.code = -32045; throw e; }
539
+ picked.push(m);
540
+ }
541
+ } else {
542
+ const earliest = mine.filter(m => m.state === "pending").sort((a, b) => a.receivedAt - b.receivedAt)[0];
543
+ picked = earliest ? [earliest] : [];
544
+ }
545
+ const out = [];
546
+ for (const m of picked) {
547
+ if (m.mustReply) m.state = "consuming";
548
+ else { m.state = "done"; m.doneAt = this.deps.now(); } // 不必回 fetch 即 done
549
+ out.push({ messageId: m.messageId, from: m.peer, fromSessionId: m.fromSessionId, topic: m.topic, mustReply: m.mustReply, body: m.body, receivedAt: m.receivedAt, attempts: m.attempts, reappeared: m.reappeared });
550
+ this.counters.returned++; this.counters.lastClaim = this.deps.now();
551
+ this.event(sessionId, `returned ${m.messageId} from=${m.peer}`);
552
+ }
553
+ this.save();
554
+ return { messages: out, remainingPending: this.pendingOf(sessionId).length };
555
+ });
556
+ }
557
+
558
+ /** 回复(§7)。sendFn 执行实际 RPC,返回 {delivered} 或抛错。 */
559
+ async reply(sessionId: string, messageId: string, body: string, topic: string | undefined, mustReply: boolean,
560
+ sendFn: (outId: string, target: string, peer: string, payload: { body: string; topic: string; mustReply: boolean; replyToMessageId: string }) => Promise<{ delivered: boolean }>): Promise<any> {
561
+ this.load();
562
+ return this.enqueue(sessionId, async () => {
563
+ const m = this.messages.find(x => x.messageId === messageId && this.boxOwner(x) === sessionId && x.direction === "in");
564
+ if (!m) { const e: any = new Error("MESSAGE_NOT_PENDING"); e.code = -32045; throw e; }
565
+ if (m.state === "pending") { const e: any = new Error("MESSAGE_NOT_PENDING: fetch first"); e.code = -32045; throw e; }
566
+ if (m.state === "done") { const e: any = new Error("MESSAGE_ALREADY_DONE: use a2a_send"); e.code = -32047; throw e; }
567
+ if (m.state === "suspended") { const e: any = new Error("MESSAGE_SUSPENDED: needs user instruction"); e.code = -32046; throw e; }
568
+ // consuming:绑定固定出站 id(§2.2)
569
+ if (!m.outId) m.outId = `r-${crypto.randomUUID()}`;
570
+ const outId = m.outId;
571
+ try {
572
+ const r = await sendFn(outId, m.fromSessionId, m.peer, { body, topic: topic ?? m.topic, mustReply, replyToMessageId: messageId });
573
+ if (!r.delivered) throw new Error("not delivered");
574
+ m.state = "done"; m.doneAt = this.deps.now();
575
+ // 记录 out 消息(供 a2a_pending 未来视图)
576
+ this.messages.push({ messageId: outId, peer: m.peer, fromSessionId: sessionId, topic: topic ?? m.topic, body, mustReply, receivedAt: this.deps.now(), doneAt: this.deps.now(), state: mustReply ? "pending" : "done", attempts: 0, replyFails: 0, reappeared: false, direction: "out", replyToMessageId: messageId });
577
+ this.noteTraffic(m.peer, sessionId, topic ?? m.topic, this.deps.now()); // 参与事实(回复出站)
578
+ this.save();
579
+ return { ok: true, state: "done" };
580
+ } catch (err: any) {
581
+ m.replyFails++;
582
+ if (m.replyFails >= MAX_ATTEMPTS) {
583
+ m.state = "suspended"; m.suspendedAt = this.deps.now(); m.reason = "reply-failed-3x"; this.suspCount("reply-failed-3x");
584
+ this.event(sessionId, `reply-failed-3x ${messageId}`);
585
+ this.save();
586
+ return { ok: false, state: "suspended", replyFails: m.replyFails, error: String(err?.message ?? err) };
587
+ }
588
+ this.save();
589
+ return { ok: false, state: "consuming", replyFails: m.replyFails, remainingTries: MAX_ATTEMPTS - m.replyFails, error: String(err?.message ?? err) };
590
+ }
591
+ });
592
+ }
593
+
594
+ async drop(sessionId: string, messageIds: string[], reason: string) {
595
+ this.load();
596
+ return this.enqueue(sessionId, async () => {
597
+ const dropped: string[] = []; const rejected: { messageId: string; state: string }[] = [];
598
+ for (const id of messageIds) {
599
+ let m = this.messages.find(x => x.messageId === id && this.boxOwner(x) === sessionId);
600
+ // 孤儿出口(DSH 永久残留):session-gone 挂起(owner 会话已删)任何会话可按用户指示删——否则没人能取也没人能删,永久残留
601
+ if (!m) m = this.messages.find(x => x.messageId === id && x.state === "suspended" && x.reason === "session-gone");
602
+ if (!m || m.state !== "suspended") { rejected.push({ messageId: id, state: m?.state ?? "absent" }); continue; }
603
+ this.messages = this.messages.filter(x => x !== m);
604
+ dropped.push(id);
605
+ }
606
+ this.save();
607
+ return { dropped, remainingSuspended: this.messages.filter(m => this.boxOwner(m) === sessionId && m.state === "suspended").length, rejected };
608
+ });
609
+ }
610
+
611
+ /** 发送方记录 out 消息(a2a_send 成功后调用,供回复关联与未来 pending 视图)。 */
612
+ recordOut(sessionId: string, messageId: string, peer: string, targetSession: string, topic: string, body: string, mustReply: boolean) {
613
+ this.load();
614
+ this.messages.push({ messageId, peer, fromSessionId: targetSession, topic, body, mustReply, receivedAt: this.deps.now(), doneAt: this.deps.now(), state: mustReply ? "pending" : "done", attempts: 0, replyFails: 0, reappeared: false, direction: "out" });
615
+ (this.messages[this.messages.length - 1] as any).boxSession = sessionId;
616
+ this.noteTraffic(peer, sessionId, topic, this.deps.now()); // 参与事实(出站)
617
+ this.save();
618
+ }
619
+ }