@vessel-agent/agent 0.0.0-stage → 2.3.0-beta.2

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/src/inbox.ts ADDED
@@ -0,0 +1,2335 @@
1
+ /**
2
+ * 按 agent_id 的持久化收件箱(0.32 切片 A,契约 v2)。
3
+ *
4
+ * 路径:`<dataDir>/inbox/<encodeURIComponent(agentId)>.json`(0.49 T2 根布局),
5
+ * 形状为
6
+ * `{ v: 1, messages: [{ id, ts, source, summary, text, status, consumed_by_session?,
7
+ * session_id?, refs? }] }`。
8
+ *
9
+ * - 每 agent 懒加载;缺失 = 空,损坏 = available=false(只记日志,不覆盖文件,读返回 []);
10
+ * - 有界:最多 `maxMessages`(缺省 200)条,append / load 时裁掉最旧的(append 腾位置时
11
+ * 两级淘汰:先裁非 human 源,再裁 human 源,见 `evictForWrite`);
12
+ * - `summary` 在写入时算好(trim、空白折叠、前 160 字),永不调用模型;
13
+ * - 旧文件里多余的 `important` 字段解析时忽略,不迁移、不报错;
14
+ * - `atomicWrite` 0600,单写者串行写链;append 立即入写链(写前日志,不 debounce);
15
+ * - `hold` 只存在内存(message id → 持有它的 body id),崩溃 / 重启后未读重新可读。
16
+ *
17
+ * **消息状态机(I1–I4,与 `AgentService` 共守)**:
18
+ * `append(unread)` → `hold(被某个 body 的 mailbox 接管)` → `consumed + unhold`
19
+ * (消费口两个,都走同一个 `consume`:`markConsumed` 在消息真正成为一轮 run input 时调用;
20
+ * `claim` 是「我拿到了正文、从队列里拿走」那一步,见下)。
21
+ * 侧出口只有两个:`unhold`(失败 / 退役 / 预算回退 → 回到 unread)与 `discard`(明确
22
+ * 投递失败 → 移除)。`hold` 记录持有者 bodyId,`releaseHeldFor` 只放一个 body 的队列。
23
+ *
24
+ * 模型侧不再自动注入正文:`createInboxNoticeHook` 只发一条 `vessel:notice` 计数行
25
+ * (无消息 / 计数没变就不发),正文由模型调用 `createInboxTool` 的 `inbox` 工具按需读取。
26
+ *
27
+ * **模型契约(0.55 起):`list` 是唯一的廉价偷看,`read` 就等于拿走。**
28
+ * - `list` 只给 id + 来源 + **前 40 字符**前缀 + 「还有 N 字符」,永不吐正文;
29
+ * - `read` = 取正文 + 消费,`unread` 与 `held` **一视同仁**:held 的那几条先走
30
+ * `AgentService.claim` 的同一条前置收口(取消 queued run + 从 mailbox 出队),再
31
+ * `consume`。不可逆:读过的不会再投、不再出现在 list / read 里。
32
+ * 为什么把两个动作并成一个:0.51 的 `claim` 让模型必须先 peek(`read includeHeld:true`)
33
+ * 再 claim,同一条消息因此有「看过但没拿走」这个中间态 —— 两套消费语义、两句提示、两次
34
+ * 决策,模型漏一步就变成同一段正文进两次上下文。现在只有一条口子:想留着别读。
35
+ *
36
+ * **兼容(只在这一层,不改语义)**:老会话仍可能发 `action:'claim'`(0.51 的工具面)。
37
+ * 工具把它当 `read` 的**别名**执行(取正文 + 消费 + 取消 queued run),并在结果里附一行
38
+ * `note` 说明「claim 已并入 read」。不报错、不静默 —— 老会话的意图与新语义本来就一致。
39
+ *
40
+ * **本层只管状态,拦不住已排程的那次投递**:held 的条目已经排进了 scheduler 的一次 run,
41
+ * 执行侧不看 inbox 状态 ⇒ 只在这里标 consumed,那次 run 照样把它当 run input 投出去。
42
+ * 「拿了就真的不再投」靠 `AgentService.claim` 的前置收口(取消 queued run + 出队),
43
+ * 与本层同一个 `consume` 落状态。工具的 `read` 因此对 held 条目先调本层的 `claim`
44
+ * (构造时注入的 `beforeClaim` → `withdrawQueuedRuns`),再返回正文。
45
+ * `agents.claim` RPC 与 web 条带仍走 service 那条路(模型侧不再有 `claim` 动作)。
46
+ *
47
+ * **投递模式**(`AgentInboxDelivery`,模式属于 inbox 自己,不是入口开关):
48
+ * `input` = 本体作为下一轮 run input 送达;`wake` = 到达时只落 inbox(目标忙时不打断、
49
+ * 不灌内容),等它空下来由 service 从**队头**把正文直投成下一轮 run input;
50
+ * `quiet` = 只落 inbox,不唤醒也不进 run。状态机(I1–I4)只描述 `input` 那条路。
51
+ *
52
+ * **归属字段 `session_id`(0.53,additive)**:一句话 —— 「这条消息是哪个会话的下一轮
53
+ * 输入」,**只在 `input` 投递上写**(唯一写入点 `AgentService.trackInbox`)。它一箭三雕:
54
+ * 条带按会话过滤、进程重启后知道往哪个 session 重投、展示时可做身份前缀。
55
+ *
56
+ * `wake` / `quiet` 条目**不写** `session_id`:它们本来就不该变成 run input(`quiet` 的
57
+ * 典型场景是「投递失败后只留档给模型 read」),写了会让恢复路径把它们重投一次。
58
+ * 于是「投递意图」被编码进「字段是否存在」,不引入新的 enum / 不新增条目种类。
59
+ * 缺字段 = 归属未知:条带永不显示、恢复永不碰、`session_id` 过滤永不命中(宁可隐藏
60
+ * 也不串台),但 list / read / delete 一切照旧。
61
+ *
62
+ * **`refs`(附件引用,additive)**:只有路径与元信息,随 `input` 投递一并落盘,恢复重投
63
+ * 时带上,附件不丢。旧文件缺该字段照常加载(按「无引用」降级)。
64
+ *
65
+ * **`quiet` / `conversation_id`(0.51 队头直投,additive)**:idle 直投要从队列里把**队头
66
+ * 那条的正文**原样当下一轮 run input 送,所以队列本身得记住两件此前只存在于内存投递侧的
67
+ * 事实 —— 「这条是不是留档(quiet,永不当 run input)」与「它属于哪个 conversation」。
68
+ * 不记的话,直投要么把 quiet 自述当成用户输入再执行一遍,要么丢掉会话归属(预算 /
69
+ * 事件回放对不上)。两者都只在**首次 append** 时写:`quiet` 由该次投递模式派生,
70
+ * `conversation_id` 由调用方传;后续升级成 input 投递不改写它们(模式不属于消息本体)。
71
+ * **`from_name`(发送者显示名,additive)**:入队那一刻发送方的名字是已知的
72
+ * (`AgentMessage.from_name`,由 `AgentService.admit` 从 registry 取),存下来是因为
73
+ * **读者在渲染时需要「谁」**:待处理条带的身份行只有 `from`(地址)时只能显示一串
74
+ * UUID,读不出来。它只用于展示,不参与任何投递 / 权限 / 归属判定 —— 所以缺字段照常
75
+ * 加载(旧条目按「没有名字」退化),也不回填、不做迁移:没有名字是**可接受的状态**,
76
+ * 不是需要修复的损坏。
77
+ *
78
+ * @module @vessel-agent/agent
79
+ */
80
+
81
+ import { randomUUID } from 'node:crypto';
82
+ import { readFileSync, statSync } from 'node:fs';
83
+ import { readFile, stat } from 'node:fs/promises';
84
+ import { join } from 'node:path';
85
+ import {
86
+ atomicWrite,
87
+ findPiiHandles,
88
+ getPiiVault,
89
+ type Hook,
90
+ HookType,
91
+ type Logger,
92
+ type Message,
93
+ type MessageRef,
94
+ maskPii,
95
+ noopLogger,
96
+ type RunTrigger,
97
+ readSidecar,
98
+ readSidecarSync,
99
+ type SidecarStamp,
100
+ type ToolContext,
101
+ type ToolDefinition,
102
+ writeSidecar,
103
+ } from '@vessel-agent/core';
104
+ import { errorText } from './error-text.js';
105
+ import { normalizeRefs } from './refs.js';
106
+ import { HUMAN_PRINCIPAL } from './team-address.js';
107
+
108
+ export const AGENT_INBOX_VERSION = 1;
109
+ export const DEFAULT_MAX_INBOX_MESSAGES = 200;
110
+ /**
111
+ * read 未给 ids 时的缺省条数(用户裁定:免 list 直读)。
112
+ *
113
+ * 3 而不是 20:无 ids 的 read 定位是「直接拿走最新到达的几条」,省掉先 list 再挑 id
114
+ * 的一轮工具往返;一次吞 20 条正文既撑上下文,也让模型来不及逐条处理。要更多就显式
115
+ * 传 limit,要精确挑就传 ids。
116
+ */
117
+ export const INBOX_READ_DEFAULT_LIMIT = 3;
118
+
119
+ /** summary 的最大字符数(截断时另加 `…`)。 */
120
+ const INBOX_SUMMARY_MAX = 160;
121
+
122
+ /**
123
+ * inbox 的投递模式(一等概念,0.50 切片):模式属于 **inbox**,不是某个入口的开关。
124
+ *
125
+ * - `input`(缺省):消息进 inbox,且**其本体**作为下一轮 run input 送达(同时可被 read);
126
+ * - `wake`:消息进 inbox;目标正忙时**只落盘不打断**(这一轮继续跑),等它空下来 service
127
+ * 再把**队头**那条的正文直投成新一轮输入;只有投不进去时才发一条摘要唤醒;
128
+ * - `quiet`:只进 inbox:不唤醒、不作为 run input,等模型自己 read
129
+ * (自述 `insert` / rotate 窗口 / 投递失败后的恢复)。
130
+ *
131
+ * 只有 `input` 会被 body mailbox 接管(`hold`)并在开始执行时 consumed;
132
+ * `wake` / `quiet` 落盘时不 hold。既有消息被显式升级成 input 投递(urgent 指定
133
+ * `message_id`)时才由 `trackInbox` 接管 —— 模式是**本次投递**的意图,不是消息的永久属性。
134
+ */
135
+ export type AgentInboxDelivery = 'input' | 'wake' | 'quiet';
136
+
137
+ /** 缺省投递模式:消息本体就是下一轮 run input。 */
138
+ export const DEFAULT_INBOX_DELIVERY: AgentInboxDelivery = 'input';
139
+
140
+ /**
141
+ * wire → 投递模式:外部契约里的 `notify: true` 只是 **wake 模式**的别名(0.41 三档),
142
+ * 内部一律用投递模式表达。`notify` 缺省 / false 即 `input`(消息本体作为 run input)。
143
+ */
144
+ export function deliveryFromNotify(notify: boolean | undefined): AgentInboxDelivery {
145
+ return notify === true ? 'wake' : 'input';
146
+ }
147
+
148
+ /**
149
+ * 异步作业的**通用**占位回调元数据(q-async-bash-viz,additive;机制层 kind 无关)。
150
+ *
151
+ * 灵魂出窍复原:起作业时往 inbox 插一条**占位卡**(`status:'running'`),作业完成时
152
+ * **按 job_id 原位更新同一条目**(running→done/failed + 填结果正文 + 转可消费),不是另插
153
+ * 一条。结果正文只存这一条 inbox 条目(单一真相源),模型经 inbox read 取走 —— 杜绝
154
+ * 「工具返回一次 + inbox 又插一次」的双份。
155
+ *
156
+ * `running` 占位**不可被 read 消费 / 弹出**(readable/visible/inputHead 都跳过它),
157
+ * 在 list 里**沉底**(pinned-bottom);done/failed 后回到正常可读队列(仍可 read 消费)。
158
+ * q-inbox-admit-restore 起占位卡**只管卡片视觉**(quiet 留档,永不当 run input);
159
+ * 结果投递是**另一条独立正常条目**(completeAsyncJob 落盘,走队头直投成正文 run)。
160
+ *
161
+ * **通用解耦**:占位行为(不可消费 / 沉底 / 原位复原 / 防双真相 / 不计 unread)全部
162
+ * **kind 无关**。`kind` 是消费者类别扩展点 —— `'bash'` 首个消费者,`'ask'` 未来消费者
163
+ * 复用同一机制,无需再改 inbox 核心。kind 专属细节放 `payload`(机制层不解释,只透传 /
164
+ * 合并):bash = {command, pid, exit_code, log_path};ask = {question, options, ...}。
165
+ *
166
+ * 缺省(老条目 / 非异步作业)= 无此字段,照常加载、照常消费,零回归。
167
+ */
168
+ export interface InboxAsyncJobMeta {
169
+ /** 作业 id(消费者侧 job id 同源;原位更新的定位键)。 */
170
+ job_id: string;
171
+ /**
172
+ * 消费者类别(扩展点,机制层不解释):`'bash'` 首个消费者;`'ask'` 未来;其余字符串
173
+ * 预留。渲染层按 kind 分派专属卡(AsyncJobCard),inbox 核心只认 status。
174
+ */
175
+ kind: string;
176
+ /** 生命周期状态:running 占位不可消费;done/failed 转可消费(kind 无关)。 */
177
+ status: 'running' | 'done' | 'failed';
178
+ /**
179
+ * kind 专属载荷(机制层只当不透明 record 透传 / 合并,不校验内部形状 —— 那是消费者
180
+ * 与渲染层的契约):bash = {command, pid, exit_code, log_path};ask = {question, ...}。
181
+ */
182
+ payload?: Record<string, unknown>;
183
+ /** 起作业时刻(ms)。 */
184
+ started_at: number;
185
+ /** 收口时刻(ms;done/failed 时填)。 */
186
+ ended_at?: number;
187
+ /** 发起会话(会话绑定;展示 / 归属关联用)。 */
188
+ session_id?: string;
189
+ }
190
+
191
+ /** 一条 inbox 条目是否是**仍在跑**的异步作业占位(不可消费 / 沉底;kind 无关)。 */
192
+ export function isRunningAsyncJob(message: { async_job?: InboxAsyncJobMeta }): boolean {
193
+ return message.async_job?.status === 'running';
194
+ }
195
+
196
+ export interface StoredInboxMessage {
197
+ id: string;
198
+ ts: number;
199
+ /**
200
+ * 来源 enum(创建源头赋值,渲染侧读它判显示):固定标签 `human` / `system` /
201
+ * `ask` / `bash`(见 `service.ts` 的 `InboxSourceLabel`)+ principal 地址(本机成员
202
+ * UUID / `federation:` 地址)。旧条目可能是加标签前的成员 id(如 bash 作业曾写
203
+ * 收件人自己)——不迁移,渲染按既有 agent 身份 / 短 id 降级。
204
+ */
205
+ source: string;
206
+ summary: string;
207
+ text: string;
208
+ status: 'unread' | 'consumed';
209
+ consumed_by_session?: string;
210
+ /**
211
+ * 归属:这条消息是哪个会话(body)的下一轮输入。**只有 `input` 投递会写**(见模块
212
+ * 头注释)。缺省 = 归属未知(老文件 / 非 input 投递)⇒ 条带不显示、恢复不碰。
213
+ */
214
+ session_id?: string;
215
+ /** 附件引用:只有路径 + 元信息,恢复重投时原样带回(不丢附件)。 */
216
+ refs?: MessageRef[];
217
+ /**
218
+ * true:这条是 **quiet 投递**(只留档,永不当 run input)。0.51 起随条目落盘,因为
219
+ * idle 直投要按队列取正文 —— 没有这个位,模型 `insert` 的自述 / 投递失败的留档
220
+ * 会被当成用户输入再执行一遍(quiet 的语义正是「不要执行」)。
221
+ */
222
+ quiet?: true;
223
+ /**
224
+ * 会话归属(conversation_id):idle 直投据此把消息送进它原本的会话,否则每条直投
225
+ * 都会新开一个 conversation(预算记账与事件回放对不上)。
226
+ */
227
+ conversation_id?: string;
228
+ /**
229
+ * 来源 Team 日志条目的 message_id(additive):只有 `TeamService.post` 的 @ 投递
230
+ * 会写。team 日志与 inbox 副本是两个 id,这份关联让「编辑 / 删除一条 team 消息」
231
+ * 能定位到成员收件箱里的那一份并级联消费。旧条目 / 非 team 投递缺省 = 无关联
232
+ * (照常加载,级联按 not_found 跳过,不迁移、不报错)。
233
+ */
234
+ team_message_id?: string;
235
+ /**
236
+ * 发送者显示名(additive,0.51):入队时已知的 `AgentMessage.from_name`。
237
+ *
238
+ * 只给展示用(条带身份行),不参与投递判定。缺省 = 老条目 / 发送方没有本机成员名
239
+ * (人类 / 系统 / 联邦地址)⇒ 渲染侧退化成短 id。
240
+ */
241
+ from_name?: string;
242
+ /**
243
+ * 异步作业占位回调元数据(q-async-bash-viz,additive,kind 无关):有它 = 这是一条异步
244
+ * 作业卡(running 占位不可消费 / 沉底;done/failed 转可消费)。缺省 = 普通消息。
245
+ */
246
+ async_job?: InboxAsyncJobMeta;
247
+ /**
248
+ * q-distress-message:这条是 node 以遇难 agent 身份代发的求救消息(additive)。
249
+ * 落盘是为了让防循环判定在重投 / 重启恢复后仍然认得它;也用于「最近发送者」
250
+ * 解析时跳过自身难保的求救者。缺省 = 普通消息 / 老条目。
251
+ */
252
+ distress?: true;
253
+ /**
254
+ * 投递来源语义(q-inbox-admit-restore,additive):`AdmitInput.origin` 随条目落盘。
255
+ * 作业结果以正常条目排队(wake 模式)等队头直投,直投时原样带回 admit ——
256
+ * `bash_job` 据此跳过 canView(成员自己的作业回报它自己,private 成员也收得到)。
257
+ * 缺省 = 普通消息 / 老条目(照常加载,直投不带 origin)。
258
+ */
259
+ origin?: 'ask_answer' | 'bash_job';
260
+ /**
261
+ * RPC 触发的 run correlation(q-error-e2 §3.7,additive):随条目落盘,重启恢复
262
+ * (recoverPendingInputs)与队头直投(dispatchInbox)重投 admit 时原样带回,
263
+ * `run.started.triggered_by` 跨重启不丢。缺省 = 内部触发(team @ / distress / bash)
264
+ * / 老条目(照常加载,重投不带 correlation)。不上 wire(inbox 快照不投影)。
265
+ */
266
+ triggered_by?: RunTrigger;
267
+ }
268
+
269
+ /**
270
+ * 元数据投影(q-inbox-metadata-seam):`StoredInboxMessage` 减 `text` / `refs`,加写侧
271
+ * 派生镜像键 `chars = text.length`。侧车内容与 full 档即时投影共用这一份口径 ——
272
+ * list / counts / reconcile / recover / drain / distress 各取所需,一次投影覆盖全部
273
+ * 元数据消费点。`refs` 是附件路径 + 元信息、仅重放真需,归正文侧。
274
+ *
275
+ * 用 `Omit` 而不是手抄键表:主文件 additive 新键自动流入投影,不造第二份键清单。
276
+ */
277
+ export type InboxMessageMeta = Omit<StoredInboxMessage, 'text' | 'refs'> & {
278
+ /** 正文总字符数(写侧派生镜像,与 session `message_count` 同一信任模型)。 */
279
+ chars: number;
280
+ };
281
+
282
+ export interface AgentInboxEntryInput {
283
+ id: string;
284
+ ts: number;
285
+ source: string;
286
+ text: string;
287
+ /** 归属会话;**只有 `input` 投递该传**(见模块头的 `session_id` 分界)。 */
288
+ session_id?: string;
289
+ /** 附件引用(可缺省);写入前按 `normalizeRefs` 再归一一次。 */
290
+ refs?: MessageRef[];
291
+ /** 会话归属(conversation_id);idle 直投据此把这条送进它原本的会话。 */
292
+ conversation_id?: string;
293
+ /** 来源 Team 日志条目 id(可缺省);随条目落盘,供 team 消息编辑 / 删除级联定位。 */
294
+ team_message_id?: string;
295
+ /**
296
+ * 发送者显示名(可缺省,additive 0.51):入队时发送方已知的 `from_name`。
297
+ *
298
+ * 只有 `admit` 那条路知道它(`AgentService.trackInbox` 从消息原样带过来);不带 =
299
+ * 没有名字(人类 / 系统 / 联邦地址 / 老调用方),条带渲染时退化成短 id。
300
+ */
301
+ from_name?: string;
302
+ /** 异步作业占位元数据(可缺省);起作业时随占位卡写入。 */
303
+ async_job?: InboxAsyncJobMeta;
304
+ /** q-distress-message:求救消息标记(可缺省,additive);随条目落盘。 */
305
+ distress?: true;
306
+ /** 投递来源语义(可缺省,additive):`AdmitInput.origin`;队头直投原样带回 admit。 */
307
+ origin?: 'ask_answer' | 'bash_job';
308
+ /** RPC correlation(可缺省,additive):`AdmitInput.triggered_by`;随条目落盘,重投原样带回。 */
309
+ triggered_by?: RunTrigger;
310
+ }
311
+
312
+ export interface AgentInboxListEntry {
313
+ id: string;
314
+ ts: number;
315
+ source: string;
316
+ summary: string;
317
+ /**
318
+ * 正文总字符数(0.55 additive):工具 `list` 用它算「还有 N 字符」。
319
+ *
320
+ * 为什么不能从 `summary` 推:`summary` 在写入时就被裁到 160 字,一条 5000 字的消息
321
+ * 与一条 200 字的消息在 summary 上看不出差别 —— 而「还差多少」正是模型决定要不要
322
+ * `read` 的唯一依据。只给长度,不给正文。
323
+ */
324
+ chars: number;
325
+ /** 当前被某个 body 的 mailbox 持有(尚未成为 run input)。 */
326
+ held: boolean;
327
+ /** 归属会话(只读视图透传,条带 / 恢复据此按会话定位);缺省 = 归属未知。 */
328
+ session_id?: string;
329
+ /**
330
+ * 发送者显示名(只读透传,additive 0.51):缺省 = 老条目 / 发送方没有本机成员名。
331
+ *
332
+ * 条带的身份行靠它把 `agent:<name>` 读成人能认的名字;缺省时那条带退回短 id
333
+ * (8 位 + `…`),**绝不把完整 UUID 摆到卡头**。
334
+ */
335
+ from_name?: string;
336
+ /** 异步作业占位元数据(只读透传):渲染侧据此画作业卡(running/done/failed)。 */
337
+ async_job?: InboxAsyncJobMeta;
338
+ /** q-distress-message:求救消息标记(只读透传,additive);缺省 = 普通消息。 */
339
+ distress?: true;
340
+ }
341
+
342
+ export interface AgentInboxReadSelection {
343
+ /** read:指定 id(按给定顺序返回);缺省时取**最新**的 limit 条(按时间序返回)。 */
344
+ ids?: readonly string[];
345
+ /** read:未给 ids 时的条数上限,缺省 `INBOX_READ_DEFAULT_LIMIT`。 */
346
+ limit?: number;
347
+ /**
348
+ * read:true 时连 held(已排进某次 run、尚未成为 run input)的消息一起取。
349
+ *
350
+ * **这是存储层的低层开关,不是模型契约**(0.55 起工具的 `read` 恒为 true 并且对 held
351
+ * 条目走 `claim` 收口)。留着它是因为插件端口 `MemberInboxPort.read` 仍然需要「只读
352
+ * peek held」那条路;held 条目在本层只读出正文,**不消费、不取消投递**。
353
+ */
354
+ includeHeld?: boolean;
355
+ }
356
+
357
+ /** read 的一条结果:正文 + 当前是否仍被某个 body 持有。 */
358
+ export interface AgentInboxReadEntry extends StoredInboxMessage {
359
+ /**
360
+ * true:这条还没成为 run input(已排进某次 run)。
361
+ *
362
+ * 存储层 `read` 不消费它;工具的 `read` 会紧接着走 `claim`(取消 queued run + 消费),
363
+ * 所以工具结果里不会再出现这个字段 —— 见到 held:true 的只有插件端口那条路。
364
+ */
365
+ held: boolean;
366
+ }
367
+
368
+ export interface AgentInboxAppendOptions {
369
+ /**
370
+ * 本次投递的模式(见 `AgentInboxDelivery`);缺省 `input`。
371
+ *
372
+ * 只影响本次 append 的裁剪策略与调用方的后续动作(要不要 hold / 起 wake run)。
373
+ *
374
+ * **模式本身仍不落盘**,但 0.53 起有一个**受控的部分推翻**:`input` 投递的条目会带
375
+ * `session_id`(归属 + 重启恢复的唯一判据),而 `wake` / `quiet` 条目**不带** —— 于是
376
+ * 「这条消息该不该在重启后被重投成 run input」完全由「有没有 `session_id`」决定,
377
+ * 不需要第二个字段。**不要**给 `wake` / `quiet` 传 `session_id`:那等于把「只留档」的
378
+ * 消息交给启动恢复重新执行一次。
379
+ */
380
+ delivery?: AgentInboxDelivery;
381
+ /**
382
+ * true:先裁 consumed,仍满则返回 `full`(不裁 unread)。缺省按模式派生:
383
+ * `wake` 缺省 true(它不产生 run input,无权驱逐将要送达的 unread),
384
+ * `input` / `quiet` 缺省 false(先裁 consumed,仍满时继续裁最旧 unread)。
385
+ */
386
+ rejectWhenFull?: boolean;
387
+ /**
388
+ * 落盘遮蔽的 vault 作用域(q-pii-redaction-unify,**不落盘**):条目自身没有
389
+ * 归属字段(`session_id` / `conversation_id` / `async_job.session_id`)时由调用方
390
+ * 显式传入消费会话(inbox insert 传工具 ctx.session_id;异步作业结果卡传起作业
391
+ * 的会话)。缺省按条目归属字段派生;都没有 ⇒ 直掩码(fail-closed)。
392
+ */
393
+ piiScope?: string;
394
+ }
395
+
396
+ export interface AgentInboxAppendResult {
397
+ accepted: boolean;
398
+ reason?: 'unavailable' | 'full';
399
+ }
400
+
401
+ export interface AgentInboxListOptions {
402
+ /** true:messages 同时返回 held 的消息;unread 仍只计可读,pending 计 held ∩ unread。 */
403
+ includeHeld?: boolean;
404
+ }
405
+
406
+ export interface AgentInboxDiscardOptions {
407
+ /** true:只删 unread 且未被持有的消息;held / consumed / 未知 id 进 skipped。 */
408
+ onlyUnheld?: boolean;
409
+ }
410
+
411
+ /**
412
+ * `claim` 的单条跳过原因(与 `discard` 同形,但没有 `held` —— 认领**可以**作用在 held
413
+ * 条目上,它本来就是「已经排进队列、别真的投给我」的那一步)。
414
+ */
415
+ export interface AgentInboxClaimSkip {
416
+ id: string;
417
+ /**
418
+ * `not_found`:id 不在库里(含损坏的收件箱);`consumed`:这条早就被拿走了;
419
+ * `pending`:仍在跑的 异步作业占位(还没结果,不可认领)。
420
+ */
421
+ reason: 'not_found' | 'consumed' | 'pending';
422
+ }
423
+
424
+ /**
425
+ * `claim` 的结果:这批正文。
426
+ *
427
+ * `messages` 只含**真的被拿走**的条目(与 `read` 同形,正文在 `text`);跳过的永远在
428
+ * `skipped` 里,不在 `messages` 里 —— 调用方不需要再按 id 反查一遍谁成谁败。
429
+ *
430
+ * 这里**不带计数**:`unread` / `pending` / `held` 只有一个口径源(`list()`),调用方在
431
+ * 拿完之后读一次即可 —— 两处各算一遍迟早点出「claim 说 3、list 说 2」的账。
432
+ */
433
+ export interface AgentInboxClaimResult {
434
+ claimed: string[];
435
+ skipped: AgentInboxClaimSkip[];
436
+ messages: AgentInboxReadEntry[];
437
+ }
438
+
439
+ export interface AgentInboxDiscardSkip {
440
+ id: string;
441
+ reason: 'held' | 'not_found' | 'consumed';
442
+ }
443
+
444
+ export interface AgentInboxDiscardResult {
445
+ deleted: string[];
446
+ skipped: AgentInboxDiscardSkip[];
447
+ }
448
+
449
+ export interface AgentInboxPort {
450
+ /**
451
+ * I1(唯一写入点):落盘并计算 summary;重复 id 忽略。先裁 consumed,再按 options
452
+ * 决定是否裁 unread。
453
+ *
454
+ * `options.delivery` 是 inbox 的投递模式(缺省 `input`):`input` 由调用方随后
455
+ * `hold` 并提交成 run input;`wake` / `quiet` 只落盘,等被唤醒的 agent 自己 read。
456
+ *
457
+ * `message.session_id` 是**归属会话**,只有 `input` 投递该传(见模块头的分界);
458
+ * `message.refs` 是附件引用,随条目落盘以便恢复重投时带上;`message.from_name` 是
459
+ * 发送者显示名(只给条带身份行看,缺省 = 没有名字)。
460
+ *
461
+ * 写前日志语义:append 先于 scheduler 接管,所以被接管但尚未成为 run input 的消息
462
+ * 一定在库里;`consumed_by_session` 只在 `markConsumed` 时写。
463
+ */
464
+ append(
465
+ agentId: string,
466
+ message: AgentInboxEntryInput,
467
+ options?: AgentInboxAppendOptions,
468
+ ): AgentInboxAppendResult;
469
+ /**
470
+ * I4(held ⊆ 被引用):标记该消息已被**某个 body 的 mailbox 接管**、尚未成为 run input。
471
+ *
472
+ * `bodyId`(= session id)是持有者身份:`releaseHeldFor` 只释放它自己持有的消息,
473
+ * 多 live body 时不会误放别的 body 在途队列。`held` 只存在内存,崩溃即全部失效 →
474
+ * 未消费消息回到 unread 可读。
475
+ */
476
+ hold(agentId: string, id: string, bodyId: string): void;
477
+ /** 单条解除持有(投递因 rotate/close 失败时保留未读)。 */
478
+ unhold(agentId: string, ids: readonly string[]): void;
479
+ /** rotate / retire / close:只释放**这一个 body** 持有的消息,其队列重新可读。 */
480
+ releaseHeldFor(agentId: string, bodyId: string): void;
481
+ /**
482
+ * unread 且未被持有,按插入顺序;不改状态。`includeHeld:true` 时 messages 同时
483
+ * 包含 held 的消息(`summary` 仍是 160 字摘要,另带正文长度 `chars`),并返回 `pending`。
484
+ *
485
+ * 模型看得到的只是工具 `list` 的前 40 字前缀:本方法是**数据源**(RPC 条带、notice
486
+ * 计数、插件端口都用它),前缀裁剪在工具层做,别在这里改口径。
487
+ *
488
+ * `unread` / `pending` 由 `counts()` 统一派生,与 read / notice 同一口径:
489
+ * `unread` 只计可读,`pending` 只计 `unread ∩ held`。
490
+ */
491
+ list(
492
+ agentId: string,
493
+ options?: AgentInboxListOptions,
494
+ ): { unread: number; pending: number; messages: AgentInboxListEntry[] };
495
+ /**
496
+ * 取正文。缺省只取 `unread 且未被持有`;`includeHeld:true` 时连 held 一起取。
497
+ *
498
+ * 消费语义(I2):只有**未被持有**的条目会被标 consumed —— held 的正文已经排进
499
+ * 某次 run,本方法不取消投递、不改变它的状态,只在结果里带 `held:true`。
500
+ *
501
+ * 模型契约(0.55)不直接用它:工具的 `read` 用 `includeHeld:true` 取正文,再对结果里
502
+ * `held:true` 的那几条调 `claim`(取消 queued run + 消费)。插件端口仍走本方法。
503
+ */
504
+ read(
505
+ agentId: string,
506
+ selection: AgentInboxReadSelection,
507
+ sessionId?: string,
508
+ ): Promise<AgentInboxReadEntry[]>;
509
+ /**
510
+ * 认领(「这几条我已经拿到正文了,从队列里拿走、别再投给我」):
511
+ * 任何 `unread`(**包括 held**)→ `consumed` + 解 hold,返回这批正文。
512
+ *
513
+ * **不可逆**:没有 unclaim。进了 consumed 就不再投递、也不再出现在 list / read 里,
514
+ * 下一次 `append` 裁剪时清掉。
515
+ *
516
+ * 0.55 起这是**内部/服务层口子**,不再是模型动作:模型的 `read` 就等于拿走(它取到
517
+ * held 条目后会调本方法收口)。两个入口仍然共用同一段实现,只是模型只看见一个。
518
+ * `agents.claim` RPC 与 web 条带也走 service 那条路(`AgentService.claim`)。
519
+ * 已经 consumed / 找不到的 id 进 `skipped`,不报错。
520
+ *
521
+ * **本方法只改 inbox 状态**:held 条目对应的那次 queued run 仍在 scheduler 里,要真的
522
+ * 「不再投递」必须走 `AgentService.claim`(先取消 queued run 再调这里)。工具的 `read`
523
+ * 用的是同一条前置收口(`beforeClaim`),不是自己另写一套。
524
+ */
525
+ claim(
526
+ agentId: string,
527
+ ids: readonly string[],
528
+ sessionId?: string,
529
+ ): Promise<AgentInboxClaimResult>;
530
+ /**
531
+ * I2(run 侧的消费口):已排程的 run 真正开始时,把消息标 consumed 并解 hold。
532
+ * 这是「消息成为本轮 run input」的唯一收口;`claim`(模型显式认领)走同一段实现。
533
+ */
534
+ markConsumed(agentId: string, ids: readonly string[], sessionId: string): Promise<void>;
535
+ /**
536
+ * 按 job_id **原位更新**异步作业占位(q-async-bash-viz,kind 无关):
537
+ * running→done/failed,填结果正文(重算 summary)+ 合并 kind 专属 payload + ended_at。
538
+ * 本方法只改占位这一条;结果投递由 service.completeAsyncJob 另落独立条目,并在投递
539
+ * 成功后把占位 markConsumed 退场(q-bash-job-dup-notify,单路单卡)。
540
+ * 返回三态(q-bash-async-duplicate-fix F2,区分「无占位」与「幂等拒绝」):
541
+ * - 'updated':原位更新成功;
542
+ * - 'already_final':占位存在但已终态(done/failed/已消费)——幂等拒绝,结果已投递过,
543
+ * 调用方不得据此退回旧投递路径(否则第二源事件穿透成重复投递);
544
+ * - 'absent':找不到对应占位(未起过 / 已被裁 / 无 inbox)——调用方退回旧路径,不丢结果。
545
+ * 更新后条目离开 running 排除集,发 `updated` 变更帧。`payload` 浅合并进既有 payload
546
+ * (机制层不解释)。
547
+ */
548
+ updateAsyncJob(
549
+ agentId: string,
550
+ jobId: string,
551
+ patch: {
552
+ status: 'done' | 'failed';
553
+ text?: string;
554
+ payload?: Record<string, unknown>;
555
+ ended_at?: number;
556
+ },
557
+ ): 'updated' | 'already_final' | 'absent';
558
+ /** 不做 status / hold 过滤、不改状态(0.32-D 打断按 id 定位)。 */
559
+ findByIds(agentId: string, ids: readonly string[]): StoredInboxMessage[];
560
+ /**
561
+ * 按来源 Team 日志条目 id 找 inbox 副本(team 消息编辑 / 删除的级联定位)。
562
+ *
563
+ * 只读、不改状态;返回全部命中(同一 team 消息对同一成员至多一条,防御性返回数组)。
564
+ * 旧条目 / 非 team 投递没有关联字段 ⇒ 空数组,调用方按 not_found 处理。
565
+ */
566
+ findByTeamMessage(agentId: string, teamMessageId: string): StoredInboxMessage[];
567
+ /**
568
+ * 显式投递失败:从队列移除。缺省删除所有命中 id(含 held / consumed);
569
+ * `onlyUnheld:true` 只删 unread 且未持有的消息,其余进 skipped。
570
+ */
571
+ discard(
572
+ agentId: string,
573
+ ids: readonly string[],
574
+ options?: AgentInboxDiscardOptions,
575
+ ): AgentInboxDiscardResult;
576
+ /**
577
+ * **队头**:队列里第一条能当 run input 送的未读条目(正文 + 引用 + 会话归属),只读,
578
+ * 不 hold / 不 consume;没有可直投的条目时返回 undefined。
579
+ *
580
+ * 顺序只来自**队列本身**(`messages` 的入队序),不做任何排序 —— 尤其**不按 `ts`**:
581
+ * 插队 / 优先级 / interrupt 之后队列序不再等于时间序,`ts` 只是写入时刻的旁证,
582
+ * 不是队列语义的代理。后续加优先级时改的是入队位置,这条方法不用改。
583
+ *
584
+ * 跳过(不是「没有队头」):`quiet` 留档条目(模型自述 / 投递失败留档 —— 语义就是
585
+ * 「不要执行」)与空正文条目(不可能成为 run input,`admit` 会按 invalid_input 拒绝)。
586
+ */
587
+ inputHead(agentId: string): StoredInboxMessage | undefined;
588
+ /**
589
+ * q-distress-message:只读历史视图(**含 consumed**),按入队序** newest-first**。
590
+ *
591
+ * 与 list / read 的区别:不做 status / hold 过滤、不消费、不改状态 —— 用途是
592
+ * 「最近一个给该 agent 发过消息的 agent」解析(求救收件人 fallback),那条消息
593
+ * 往往早已 consumed。`limit` 缺省 = 全部;返回克隆,调用方改不动库里状态。
594
+ */
595
+ history(agentId: string, limit?: number): StoredInboxMessage[];
596
+ flush(): Promise<void>;
597
+ }
598
+
599
+ export interface AgentInboxStoreOptions {
600
+ dataDir: string;
601
+ tenantId: string;
602
+ logger?: Logger;
603
+ /** 消息条数上限;缺省 `DEFAULT_MAX_INBOX_MESSAGES`。 */
604
+ maxMessages?: number;
605
+ /**
606
+ * `claim` 的**执行侧前置收口**(装配层注入);缺省 = 没有执行侧(纯 store)。
607
+ *
608
+ * 为什么由外面注入:只有 service 知道 scheduler / body mailbox 的存在(`held` 的条目
609
+ * 已经排进一次 run,光在 store 里标 consumed 拦不住那次投递)。store 只管状态机,
610
+ * 这一步在 `consume` 之前执行,注入方负责「取消 queued run + 出队」。
611
+ */
612
+ beforeClaim?: (agentId: string, ids: readonly string[]) => Promise<void> | void;
613
+ /**
614
+ * 状态机变更钩子(inbox 统一批 §6.2,与 `beforeClaim` 同一注入先例);缺省 = 无观察方。
615
+ *
616
+ * 每个 mutation 口(append / hold / unhold / releaseHeldFor / claim / markConsumed /
617
+ * discard / consume)**落状态后**同步调用一次,装配层据此发 `agent.inbox.changed` 帧。
618
+ * 纯读(list / read 的挑选 / findByIds / inputHead)不调;no-op mutation(重复 id 准入、
619
+ * 已 consumed 再消费、未持有再 unhold)也不调 —— 计数不变不发。
620
+ *
621
+ * 钩子抛错不影响状态机(store 已落状态,观察方失败只记日志);回调里不做重活。
622
+ */
623
+ onChange?: (agentId: string, change: AgentInboxChange) => void;
624
+ }
625
+
626
+ /** `agent.inbox.changed` 的变更理由(store 状态机的出口词汇,§6.2 payload.reason)。 */
627
+ export type AgentInboxChangeReason =
628
+ | 'appended'
629
+ | 'held'
630
+ | 'unheld'
631
+ | 'released'
632
+ | 'consumed'
633
+ | 'claimed'
634
+ | 'discarded'
635
+ /** 异步作业占位原位更新(running→done/failed + 填结果正文;q-async-bash-viz)。 */
636
+ | 'updated';
637
+
638
+ /** 一次 mutation 的变更摘要(触发器不读它,数据永远来自那次 RPC;诊断 / 未来细粒度 UI 用)。 */
639
+ export interface AgentInboxChange {
640
+ reason: AgentInboxChangeReason;
641
+ /** 本次变更的条目 id。 */
642
+ messageIds: readonly string[];
643
+ /** 条目归属会话:变更条目共享同一已知归属时给出;wake/quiet / 混合归属缺省。 */
644
+ sessionId?: string;
645
+ /** 投递模式:仅 `appended`。 */
646
+ delivery?: AgentInboxDelivery;
647
+ }
648
+
649
+ interface InboxFile {
650
+ v: 1;
651
+ messages: StoredInboxMessage[];
652
+ }
653
+
654
+ interface AgentInboxState {
655
+ path: string;
656
+ messages: StoredInboxMessage[];
657
+ /**
658
+ * 仅内存:message id → 持有它的 body id(session id)。
659
+ *
660
+ * 记 body 而不是布尔,是为了 `releaseHeldFor(agentId, bodyId)` 能只释放一个 body
661
+ * 的在途队列:多 live body 的成员里,A 退役不得放出 B 还在排队的消息。
662
+ */
663
+ held: Map<string, string>;
664
+ /**
665
+ * 加载水位(q-inbox-metadata-seam,替代 boolean loaded;private 内部态,无对外契约):
666
+ * `none` = 未读盘;`meta` = 仅元数据投影(侧车命中,`messages` 为空、正文未载);
667
+ * `full` = 整份主文件已载。**水位不降级**:mutation / 正文读恒走 full(stateFor)。
668
+ */
669
+ level: 'none' | 'meta' | 'full';
670
+ /** meta 档投影数组(侧车命中);full 档 meta 视图从 messages 即时投影,不另存。 */
671
+ meta?: InboxMessageMeta[];
672
+ /** 损坏 / 不可读时为 false:不覆盖文件,读返回 [] */
673
+ available: boolean;
674
+ }
675
+
676
+ export function inboxPath(dataDir: string, _tenantId: string, agentId: string): string {
677
+ // 0.49 T2(C13/R4):单公司 inbox 位于数据根;只改路径推导,业务语义不变。
678
+ return join(dataDir, 'inbox', `${encodeURIComponent(agentId)}.json`);
679
+ }
680
+
681
+ /** 写入时计算摘要:trim、空白折叠、前 160 字,截断加 `…`。 */
682
+ function summaryOf(text: string): string {
683
+ const collapsed = text.trim().replace(/\s+/g, ' ');
684
+ return collapsed.length > INBOX_SUMMARY_MAX
685
+ ? `${collapsed.slice(0, INBOX_SUMMARY_MAX)}…`
686
+ : collapsed;
687
+ }
688
+
689
+ // ---------------------------------------------------------------------------
690
+ // PII 单源(q-pii-redaction-unify):inbox 磁盘副本不含真值
691
+ // (message-invariants「把真值写盘禁止」;此前 append 原文落盘是现态违反)
692
+ // ---------------------------------------------------------------------------
693
+
694
+ /**
695
+ * 条目的 vault 作用域 = 「这条正文将来被哪个会话消费」:input 投递带 `session_id`,
696
+ * wake 带 `conversation_id`,异步作业占位带 `async_job.session_id`。
697
+ * 都缺(老形状 / 自述 quiet)⇒ undefined,落盘降级直掩码(fail-closed)。
698
+ */
699
+ export function inboxStorageScopeOf(message: {
700
+ session_id?: string;
701
+ conversation_id?: string;
702
+ async_job?: { session_id?: string };
703
+ }): string | undefined {
704
+ return message.session_id ?? message.conversation_id ?? message.async_job?.session_id;
705
+ }
706
+
707
+ /**
708
+ * 落盘前唯一遮蔽点(I1 append 与 updateAsyncJob 共用):与 append 闸同一个
709
+ * 进程级 vault(getPiiVault)⇒ 同 session 同值同 handle(三通道一致)。
710
+ * 作用域缺失时降级 core 直掩码(无句柄):宁可不可恢复,也不把真值写盘。
711
+ */
712
+ function protectInboxText(text: string, scope: string | undefined): string {
713
+ const vault = getPiiVault();
714
+ if (!vault.isEnabled || text.length === 0) return text;
715
+ if (scope !== undefined && scope !== '') return vault.protect(text, scope).text;
716
+ return maskPii(text).text;
717
+ }
718
+
719
+ /**
720
+ * 跨会话消费翻译:磁盘副本里的句柄属于**存储作用域**;消费会话不同(rotate 后
721
+ * 队头直投 / 新 body read)时,把真值从存储作用域的 vault 解出,交给消费会话的
722
+ * append 闸重新句柄化 —— 同值在新会话拿新 handle(硬约束 #2:跨 session 不共享)。
723
+ * 死句柄(TTL 过期 / 进程重启)原样保留:下游按既有口径中和 / 报 expired,绝不猜。
724
+ * **真值只出现在内存返回值里**:调用方只许把它送进 append 闸(admit / 工具结果),
725
+ * 绝不许再写盘。
726
+ */
727
+ export function rescopeInboxText(
728
+ text: string,
729
+ fromScope: string | undefined,
730
+ toSession: string | undefined,
731
+ ): string {
732
+ if (fromScope === undefined || toSession === undefined || fromScope === toSession) return text;
733
+ if (!text.includes('«pii:')) return text;
734
+ const vault = getPiiVault();
735
+ if (!vault.isEnabled) return text;
736
+ let out = '';
737
+ let cursor = 0;
738
+ for (const occurrence of findPiiHandles(text)) {
739
+ const resolved = vault.resolve(fromScope, occurrence.id);
740
+ if (!resolved.ok) continue;
741
+ out += text.slice(cursor, occurrence.start) + resolved.value;
742
+ cursor = occurrence.end;
743
+ }
744
+ if (cursor === 0) return text;
745
+ return out + text.slice(cursor);
746
+ }
747
+
748
+ /**
749
+ * 显示名归一:空串 / 只有空白 / 非字符串一律当「没有名字」(旧条目与手改文件都走这一条)。
750
+ *
751
+ * 与 `summary` 的差别:这里**不做截断** —— 名字来自 registry(成员名已在创建时约束),
752
+ * 截断会让「显示名」与 roster 里的名字对不上,反而更难认。
753
+ */
754
+ function senderNameOf(value: unknown): string | undefined {
755
+ if (typeof value !== 'string') return undefined;
756
+ const trimmed = value.trim();
757
+ return trimmed === '' ? undefined : trimmed;
758
+ }
759
+
760
+ function isRecord(value: unknown): value is Record<string, unknown> {
761
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
762
+ }
763
+
764
+ /**
765
+ * 异步作业占位元数据的加载校验(additive,kind 无关):缺省合法(普通消息);有它就必须是
766
+ * 合法形状(job_id 非空串 + kind 非空串 + status 三态之一 + started_at 有限数)。`payload`
767
+ * 只校验「是 record」(kind 专属内部形状是消费者 / 渲染层的契约,机制层不解释)。其余字段
768
+ * 类型不符按损坏处理。与其余字段同口径:不猜类型、不做半新半旧的内存。
769
+ */
770
+ function isInboxAsyncJobMeta(value: unknown): value is InboxAsyncJobMeta {
771
+ if (!isRecord(value)) return false;
772
+ if (typeof value.job_id !== 'string' || value.job_id === '') return false;
773
+ if (typeof value.kind !== 'string' || value.kind === '') return false;
774
+ if (value.status !== 'running' && value.status !== 'done' && value.status !== 'failed') {
775
+ return false;
776
+ }
777
+ if (typeof value.started_at !== 'number' || !Number.isFinite(value.started_at)) return false;
778
+ if (value.payload !== undefined && !isRecord(value.payload)) return false;
779
+ if (
780
+ value.ended_at !== undefined &&
781
+ (typeof value.ended_at !== 'number' || !Number.isFinite(value.ended_at))
782
+ ) {
783
+ return false;
784
+ }
785
+ if (value.session_id !== undefined && typeof value.session_id !== 'string') return false;
786
+ return true;
787
+ }
788
+
789
+ /** 归一为内存形状:只保留合法字段;payload 当不透明 record 浅拷贝(机制层不解释内部)。 */
790
+ function cloneAsyncJob(meta: InboxAsyncJobMeta): InboxAsyncJobMeta {
791
+ return {
792
+ job_id: meta.job_id,
793
+ kind: meta.kind,
794
+ status: meta.status,
795
+ started_at: meta.started_at,
796
+ ...(isRecord(meta.payload) ? { payload: { ...meta.payload } } : {}),
797
+ ...(typeof meta.ended_at === 'number' && Number.isFinite(meta.ended_at)
798
+ ? { ended_at: meta.ended_at }
799
+ : {}),
800
+ ...(typeof meta.session_id === 'string' ? { session_id: meta.session_id } : {}),
801
+ };
802
+ }
803
+
804
+ /**
805
+ * 加载放宽:`summary` 可缺失(从 text 派生);0.53 新增的 `session_id` / `refs` 与 0.51 的
806
+ * `from_name` 也可缺失(缺失 = 归属未知 / 无引用 / 无显示名,老文件照常加载)。其余字段
807
+ * 严格;任何类型不符都按损坏处理(不覆盖、不做半新半旧的内存)。未知字段(如旧版
808
+ * `important`)忽略。
809
+ */
810
+ function isStoredInboxMessage(value: unknown): value is StoredInboxMessage {
811
+ if (!isRecord(value)) return false;
812
+ if (typeof value.text !== 'string') return false;
813
+ // refs 只校验「是数组」,条目形状在 cloneMessage 里过 `normalizeRefs`(逐条丢弃坏条目,
814
+ // 不因为一条坏引用把整个收件箱判成损坏)。
815
+ if (value.refs !== undefined && !Array.isArray(value.refs)) return false;
816
+ return isInboxMetaFields(value);
817
+ }
818
+
819
+ /**
820
+ * 元数据键形状校验(主文件与侧车共用单源:侧车 = 主文件减 text/refs 加 chars)。
821
+ * `summary` 在主文件可缺失(加载时派生);侧车侧另要求它在场(写侧已派生,见
822
+ * `validateInboxMetaSidecar`)。其余口径与主文件逐条一致:不猜类型、缺字段当脏数据。
823
+ */
824
+ function isInboxMetaFields(value: Record<string, unknown>): boolean {
825
+ if (typeof value.id !== 'string' || value.id === '') return false;
826
+ if (typeof value.ts !== 'number' || !Number.isFinite(value.ts)) return false;
827
+ if (typeof value.source !== 'string') return false;
828
+ if (value.status !== 'unread' && value.status !== 'consumed') return false;
829
+ if (value.consumed_by_session !== undefined && typeof value.consumed_by_session !== 'string') {
830
+ return false;
831
+ }
832
+ // additive:缺省合法,存在则必须是 string(与其它字段同口径:类型不符按损坏处理)。
833
+ if (value.session_id !== undefined && typeof value.session_id !== 'string') return false;
834
+ if (value.conversation_id !== undefined && typeof value.conversation_id !== 'string') {
835
+ return false;
836
+ }
837
+ // `quiet` 只有 true 一种写值(缺省 = 不是留档条目);写成 false 属于手改跑偏。
838
+ if (value.quiet !== undefined && value.quiet !== true) return false;
839
+ // 显示名同理 additive:老文件没有它照常加载,有它就必须是字符串(不猜类型)。
840
+ if (value.from_name !== undefined && typeof value.from_name !== 'string') return false;
841
+ // team 关联同理 additive:缺省 = 非 team 投递 / 老条目;有它就必须是字符串(不猜类型)。
842
+ if (value.team_message_id !== undefined && typeof value.team_message_id !== 'string') {
843
+ return false;
844
+ }
845
+ if (value.summary !== undefined && typeof value.summary !== 'string') return false;
846
+ // 异步作业占位元数据 additive:缺省 = 普通消息;有它就必须是合法形状。
847
+ if (value.async_job !== undefined && !isInboxAsyncJobMeta(value.async_job)) return false;
848
+ // distress 与 quiet 同口径:只有 true 一种写值(缺省 = 普通消息 / 老条目)。
849
+ if (value.distress !== undefined && value.distress !== true) return false;
850
+ // RPC correlation 同理 additive:缺省 = 内部触发 / 老条目;有它就必须是合法形状
851
+ // (request_id + rpc_method 字符串、agent_id 可选字符串,与 service 的 readRunTrigger 同口径)。
852
+ if (value.triggered_by !== undefined) {
853
+ if (!isRecord(value.triggered_by)) return false;
854
+ if (
855
+ typeof value.triggered_by.request_id !== 'string' ||
856
+ typeof value.triggered_by.rpc_method !== 'string'
857
+ ) {
858
+ return false;
859
+ }
860
+ if (
861
+ value.triggered_by.agent_id !== undefined &&
862
+ typeof value.triggered_by.agent_id !== 'string'
863
+ ) {
864
+ return false;
865
+ }
866
+ }
867
+ return true;
868
+ }
869
+
870
+ function isInboxFile(value: unknown): value is InboxFile {
871
+ if (!isRecord(value)) return false;
872
+ if (value.v !== AGENT_INBOX_VERSION) return false;
873
+ if (!Array.isArray(value.messages)) return false;
874
+ return value.messages.every(isStoredInboxMessage);
875
+ }
876
+
877
+ /** 规范化为内存形状:summary 缺失时派生。 */
878
+ function cloneMessage(message: StoredInboxMessage): StoredInboxMessage {
879
+ // refs 逐条归一(写入侧已经归一过;这层只防手改文件带进半成品形状)。
880
+ const refs = message.refs === undefined ? [] : normalizeRefs(message.refs);
881
+ // 显示名同样归一一次:手改文件里的空串 / 纯空白不该变成「有名字但是空的」。
882
+ const fromName = senderNameOf(message.from_name);
883
+ return {
884
+ id: message.id,
885
+ ts: message.ts,
886
+ source: message.source,
887
+ summary: typeof message.summary === 'string' ? message.summary : summaryOf(message.text),
888
+ text: message.text,
889
+ status: message.status,
890
+ ...(message.consumed_by_session !== undefined
891
+ ? { consumed_by_session: message.consumed_by_session }
892
+ : {}),
893
+ ...(message.session_id !== undefined ? { session_id: message.session_id } : {}),
894
+ ...(message.conversation_id !== undefined ? { conversation_id: message.conversation_id } : {}),
895
+ // team 关联:空串按「无关联」落盘(与显示名同口径:缺字段,不是空字符串)。
896
+ ...(typeof message.team_message_id === 'string' && message.team_message_id !== ''
897
+ ? { team_message_id: message.team_message_id }
898
+ : {}),
899
+ ...(message.quiet === true ? { quiet: true as const } : {}),
900
+ ...(message.distress === true ? { distress: true as const } : {}),
901
+ ...(message.origin !== undefined ? { origin: message.origin } : {}),
902
+ ...(fromName !== undefined ? { from_name: fromName } : {}),
903
+ ...(refs.length > 0 ? { refs } : {}),
904
+ ...(message.async_job !== undefined ? { async_job: cloneAsyncJob(message.async_job) } : {}),
905
+ // RPC correlation 只拷已知字段(加载校验已把形状;克隆不夹带未知键)。
906
+ ...(message.triggered_by !== undefined
907
+ ? {
908
+ triggered_by: {
909
+ request_id: message.triggered_by.request_id,
910
+ rpc_method: message.triggered_by.rpc_method,
911
+ ...(message.triggered_by.agent_id !== undefined
912
+ ? { agent_id: message.triggered_by.agent_id }
913
+ : {}),
914
+ },
915
+ }
916
+ : {}),
917
+ };
918
+ }
919
+
920
+ /**
921
+ * 元数据投影(写侧 / full 档即时视图共用):浅拷贝减 text/refs,加 chars 镜像键。
922
+ * 入参是**已归一的内存形状**(cloneMessage / append 产物),投影不再二次归一。
923
+ */
924
+ function metaOf(message: StoredInboxMessage): InboxMessageMeta {
925
+ const meta: Partial<StoredInboxMessage> & { chars: number } = {
926
+ ...message,
927
+ chars: message.text.length,
928
+ };
929
+ delete meta.text;
930
+ delete meta.refs;
931
+ return meta as InboxMessageMeta;
932
+ }
933
+
934
+ /**
935
+ * 侧车条目归一(与 `cloneMessage` 的非正文键逐条同口径):显示名 / team 关联 / async_job /
936
+ * triggered_by 的归一规则单源复用,保证 meta 路与 full 路投影等值(F3)。不猜、不编字段。
937
+ */
938
+ function normalizeMeta(entry: InboxMessageMeta): InboxMessageMeta {
939
+ const meta: InboxMessageMeta = { ...entry };
940
+ const fromName = senderNameOf(entry.from_name);
941
+ if (fromName === undefined) delete meta.from_name;
942
+ else meta.from_name = fromName;
943
+ if (typeof entry.team_message_id !== 'string' || entry.team_message_id === '') {
944
+ delete meta.team_message_id;
945
+ }
946
+ if (entry.async_job !== undefined) meta.async_job = cloneAsyncJob(entry.async_job);
947
+ if (entry.triggered_by !== undefined) {
948
+ meta.triggered_by = {
949
+ request_id: entry.triggered_by.request_id,
950
+ rpc_method: entry.triggered_by.rpc_method,
951
+ ...(entry.triggered_by.agent_id !== undefined
952
+ ? { agent_id: entry.triggered_by.agent_id }
953
+ : {}),
954
+ };
955
+ }
956
+ return meta;
957
+ }
958
+
959
+ /**
960
+ * inbox 侧车磁盘信封(agent 域内容;机制三段见 core `storage/metadata-sidecar.ts` 单源)。
961
+ * 失效键 = 主文件 (size, mtimeMs);messages 与主文件同序同长的元数据投影。
962
+ * 主文件形状零改动(chars 镜像只落侧车,旧读者 / CLI 离线视图 / 手改文件全不受影响)。
963
+ */
964
+ interface InboxMetaSidecarFile {
965
+ v: 1;
966
+ inbox_size: number;
967
+ inbox_mtime_ms: number;
968
+ messages: InboxMessageMeta[];
969
+ }
970
+
971
+ /**
972
+ * 侧车内容形状校验(agent 域,注入机制叶 `readSidecar`):版本 / 失效键 / 逐条形状
973
+ * 任一不认 ⇒ `undefined`(回退整份 loadSync,主文件仍是事实源)。缺字段当脏数据 ——
974
+ * 宁可多读一次整份,不许编一条假消息(与 session 侧车同口径)。
975
+ */
976
+ function validateInboxMetaSidecar(
977
+ raw: Record<string, unknown>,
978
+ stamp: SidecarStamp,
979
+ ): InboxMessageMeta[] | undefined {
980
+ const file = raw as Partial<InboxMetaSidecarFile>;
981
+ if (file.v !== 1) return undefined;
982
+ if (file.inbox_size !== stamp.size || file.inbox_mtime_ms !== stamp.mtimeMs) return undefined;
983
+ if (!Array.isArray(file.messages)) return undefined;
984
+ const out: InboxMessageMeta[] = [];
985
+ for (const entry of file.messages) {
986
+ if (!isRecord(entry)) return undefined;
987
+ if (!isInboxMetaFields(entry)) return undefined;
988
+ // 侧车的 summary 恒在场(写侧派生镜像);chars 是非负有限数。缺 / 错 ⇒ 脏数据回退。
989
+ if (typeof entry.summary !== 'string') return undefined;
990
+ if (typeof entry.chars !== 'number' || !Number.isFinite(entry.chars) || entry.chars < 0) {
991
+ return undefined;
992
+ }
993
+ out.push(normalizeMeta(entry as unknown as InboxMessageMeta));
994
+ }
995
+ return out;
996
+ }
997
+
998
+ export class AgentInboxStore implements AgentInboxPort {
999
+ private readonly dataDir: string;
1000
+ private readonly tenantId: string;
1001
+ private readonly logger: Logger;
1002
+ private readonly maxMessages: number;
1003
+ private readonly agents = new Map<string, AgentInboxState>();
1004
+ /** 见 `AgentInboxStoreOptions.beforeClaim`;缺省 = 没有执行侧可收口。 */
1005
+ private readonly beforeClaim?: (agentId: string, ids: readonly string[]) => Promise<void> | void;
1006
+ /** 见 `AgentInboxStoreOptions.onChange`;缺省 = 无观察方(纯 store)。 */
1007
+ private readonly onChange?: (agentId: string, change: AgentInboxChange) => void;
1008
+ /** 永不 reject 的串行写链(单写者) */
1009
+ private writeChain: Promise<void> = Promise.resolve();
1010
+
1011
+ constructor(options: AgentInboxStoreOptions) {
1012
+ if (typeof options.dataDir !== 'string' || options.dataDir === '') {
1013
+ throw new Error('AgentInboxStore requires a non-empty dataDir');
1014
+ }
1015
+ if (typeof options.tenantId !== 'string' || options.tenantId === '') {
1016
+ throw new Error('AgentInboxStore requires a non-empty tenantId');
1017
+ }
1018
+ this.dataDir = options.dataDir;
1019
+ this.tenantId = options.tenantId;
1020
+ this.logger = options.logger ?? noopLogger;
1021
+ // 直接 API 调用也做一次防御:非法上限退回默认值,避免 0 条静默吞掉所有消息。
1022
+ const max = options.maxMessages;
1023
+ this.maxMessages =
1024
+ typeof max === 'number' && Number.isInteger(max) && max > 0
1025
+ ? max
1026
+ : DEFAULT_MAX_INBOX_MESSAGES;
1027
+ this.beforeClaim = options.beforeClaim;
1028
+ this.onChange = options.onChange;
1029
+ }
1030
+
1031
+ append(
1032
+ agentId: string,
1033
+ message: AgentInboxEntryInput,
1034
+ options?: AgentInboxAppendOptions,
1035
+ ): AgentInboxAppendResult {
1036
+ const state = this.stateFor(agentId);
1037
+ if (!state.available) return { accepted: false, reason: 'unavailable' };
1038
+ // 投递模式:只有 input 会被随后的 hold / submit 变成 run input;wake 只唤醒,
1039
+ // quiet 连唤醒都没有。模式不落盘,只决定本次写入的裁剪口径。
1040
+ const delivery = options?.delivery ?? DEFAULT_INBOX_DELIVERY;
1041
+ const rejectWhenFull = options?.rejectWhenFull ?? delivery === 'wake';
1042
+ // 所有路径先裁 consumed;consumed 不占 cap。拒绝 / 重复 id 路径也要把裁剪落盘。
1043
+ const prunedConsumed = this.pruneConsumed(state);
1044
+ // 同一 id 只保留一条(重试 / 重复准入不制造重复消息);裁剪仍需落盘。
1045
+ if (state.messages.some((existing) => existing.id === message.id)) {
1046
+ if (prunedConsumed) void this.enqueueWrite(state);
1047
+ return { accepted: true };
1048
+ }
1049
+ if (state.messages.length >= this.maxMessages) {
1050
+ if (rejectWhenFull) {
1051
+ // 不裁 unread:显式拒绝,调用方返回 inbox_full 而不是静默丢消息。
1052
+ if (prunedConsumed) void this.enqueueWrite(state);
1053
+ return { accepted: false, reason: 'full' };
1054
+ }
1055
+ // input / quiet 的既有行为:consumed 裁完仍满时继续裁最旧 —— 0.53 起分两级:
1056
+ // 先裁「非 human 源」最旧条目,再裁 human 源。一条人写的待处理输入不该被成员之间
1057
+ // 的投递挤掉(`splice` 无差别裁头是最容易踩到这个的地方)。
1058
+ this.evictForWrite(state, state.messages.length - this.maxMessages + 1);
1059
+ }
1060
+ const sessionId = message.session_id;
1061
+ const refs = message.refs === undefined ? [] : normalizeRefs(message.refs);
1062
+ // q-pii-redaction-unify:落盘前过同一 vault(真值禁写盘)。summary 从遮蔽后
1063
+ // 正文派生 ⇒ list 预览 / 条带 / 侧车全链都不带真值。
1064
+ const maskedText = protectInboxText(
1065
+ message.text,
1066
+ options?.piiScope ?? inboxStorageScopeOf(message),
1067
+ );
1068
+ // 显示名只有展示用途:空串 / 纯空白按「没有名字」落盘(缺字段,不是空字符串),
1069
+ // 这样渲染侧只需要看「有没有」这一个判据。
1070
+ const fromName = senderNameOf(message.from_name);
1071
+ state.messages.push({
1072
+ id: message.id,
1073
+ ts: message.ts,
1074
+ source: message.source,
1075
+ summary: summaryOf(maskedText),
1076
+ text: maskedText,
1077
+ status: 'unread',
1078
+ ...(sessionId !== undefined ? { session_id: sessionId } : {}),
1079
+ ...(message.conversation_id !== undefined
1080
+ ? { conversation_id: message.conversation_id }
1081
+ : {}),
1082
+ // team 关联随条目落盘:编辑 / 删除 team 消息时按它定位收件箱里的那一份。
1083
+ ...(typeof message.team_message_id === 'string' && message.team_message_id !== ''
1084
+ ? { team_message_id: message.team_message_id }
1085
+ : {}),
1086
+ // quiet 由**本次投递模式**派生(不另开参数):它落盘后只有一个含义
1087
+ // 「这条永不作为 run input」,idle 直投据此跳过它。
1088
+ ...(delivery === 'quiet' ? { quiet: true as const } : {}),
1089
+ // 求救标记随条目落盘:防循环判定在重投 / 重启恢复后仍然认得它。
1090
+ ...(message.distress === true ? { distress: true as const } : {}),
1091
+ // 投递来源语义随条目落盘:队头直投据此还原 origin(bash_job 跳 canView)。
1092
+ ...(message.origin !== undefined ? { origin: message.origin } : {}),
1093
+ ...(fromName !== undefined ? { from_name: fromName } : {}),
1094
+ ...(refs.length > 0 ? { refs } : {}),
1095
+ // 异步作业占位元数据随条目落盘(running 占位不可消费 / 沉底;完成时原位更新)。
1096
+ ...(message.async_job !== undefined ? { async_job: cloneAsyncJob(message.async_job) } : {}),
1097
+ // RPC correlation 随条目落盘:重启恢复 / 队头直投重投时原样带回(跨重启不丢)。
1098
+ ...(message.triggered_by !== undefined
1099
+ ? {
1100
+ triggered_by: {
1101
+ request_id: message.triggered_by.request_id,
1102
+ rpc_method: message.triggered_by.rpc_method,
1103
+ ...(message.triggered_by.agent_id !== undefined
1104
+ ? { agent_id: message.triggered_by.agent_id }
1105
+ : {}),
1106
+ },
1107
+ }
1108
+ : {}),
1109
+ });
1110
+ this.prune(state);
1111
+ void this.enqueueWrite(state);
1112
+ this.notifyChange(agentId, {
1113
+ reason: 'appended',
1114
+ messageIds: [message.id],
1115
+ ...(sessionId !== undefined ? { sessionId } : {}),
1116
+ delivery,
1117
+ });
1118
+ return { accepted: true };
1119
+ }
1120
+
1121
+ hold(agentId: string, id: string, bodyId: string): void {
1122
+ const state = this.stateFor(agentId);
1123
+ const previous = state.held.get(id);
1124
+ state.held.set(id, bodyId);
1125
+ // 计数不变不发:同 body 重 hold / 未知 id / 已 consumed 条目都不改 unread/pending。
1126
+ if (previous === bodyId) return;
1127
+ const message = state.messages.find((entry) => entry.id === id);
1128
+ if (message === undefined || message.status !== 'unread') return;
1129
+ this.notifyChange(agentId, {
1130
+ reason: 'held',
1131
+ messageIds: [id],
1132
+ ...(message.session_id !== undefined ? { sessionId: message.session_id } : {}),
1133
+ });
1134
+ }
1135
+
1136
+ /** I4:只释放 `bodyId` 自己持有的消息;其它 live body 的在途队列不受影响。 */
1137
+ releaseHeldFor(agentId: string, bodyId: string): void {
1138
+ const state = this.stateFor(agentId);
1139
+ const released: string[] = [];
1140
+ for (const [id, owner] of state.held) {
1141
+ if (owner === bodyId) {
1142
+ state.held.delete(id);
1143
+ released.push(id);
1144
+ }
1145
+ }
1146
+ if (released.length === 0) return;
1147
+ const sessionId = this.changeSessionId(state, released);
1148
+ this.notifyChange(agentId, {
1149
+ reason: 'released',
1150
+ messageIds: released,
1151
+ ...(sessionId !== undefined ? { sessionId } : {}),
1152
+ });
1153
+ }
1154
+
1155
+ unhold(agentId: string, ids: readonly string[]): void {
1156
+ const state = this.stateFor(agentId);
1157
+ const unheld: string[] = [];
1158
+ for (const id of ids) {
1159
+ if (state.held.delete(id)) unheld.push(id);
1160
+ }
1161
+ if (unheld.length === 0) return;
1162
+ const sessionId = this.changeSessionId(state, unheld);
1163
+ this.notifyChange(agentId, {
1164
+ reason: 'unheld',
1165
+ messageIds: unheld,
1166
+ ...(sessionId !== undefined ? { sessionId } : {}),
1167
+ });
1168
+ }
1169
+
1170
+ list(
1171
+ agentId: string,
1172
+ options?: AgentInboxListOptions,
1173
+ ): { unread: number; pending: number; messages: AgentInboxListEntry[] } {
1174
+ // 元数据读路径(q-inbox-metadata-seam):侧车命中即 meta 档,零整份读;held 从内存
1175
+ // Map overlay(冷态 held=空,与今天一致 —— held 本不落盘,侧车不承载)。
1176
+ const state = this.stateForMeta(agentId);
1177
+ if (!state.available) return { unread: 0, pending: 0, messages: [] };
1178
+ const meta = this.metaView(state);
1179
+ const includeHeld = options?.includeHeld === true;
1180
+ const selected = this.visible(state, meta, includeHeld);
1181
+ const toEntry = (message: InboxMessageMeta): AgentInboxListEntry => ({
1182
+ id: message.id,
1183
+ ts: message.ts,
1184
+ source: message.source,
1185
+ summary: message.summary,
1186
+ // chars 用写侧派生镜像键(侧车命中即免读正文);full 档由 metaOf 从 text.length 投影。
1187
+ chars: message.chars,
1188
+ held: state.held.has(message.id),
1189
+ // 归属只读透传:条带按会话过滤、启动恢复按会话重投都要它。
1190
+ ...(message.session_id !== undefined ? { session_id: message.session_id } : {}),
1191
+ // 显示名同属只读透传:条带身份行据此显示 `agent:<name>` 而不是一串 UUID。
1192
+ ...(message.from_name !== undefined ? { from_name: message.from_name } : {}),
1193
+ // 异步作业占位元数据只读透传:渲染侧据此画作业卡(running/done/failed)。
1194
+ ...(message.async_job !== undefined ? { async_job: cloneAsyncJob(message.async_job) } : {}),
1195
+ // 求救标记只读透传:工具 list / Web 条带据此在读取前就能认出求救消息。
1196
+ ...(message.distress === true ? { distress: true as const } : {}),
1197
+ });
1198
+ const messages = selected.map(toEntry);
1199
+ // running 异步作业占位**沉底**(pinned-bottom):不计 unread(模型还读不到),但要在
1200
+ // 列表里可见(科技蓝占位卡)。done/failed 后回到上面的正常队列(按插入序)。
1201
+ for (const message of meta) {
1202
+ if (message.status === 'unread' && isRunningAsyncJob(message))
1203
+ messages.push(toEntry(message));
1204
+ }
1205
+ return { ...this.counts(state, meta), messages };
1206
+ }
1207
+
1208
+ async read(
1209
+ agentId: string,
1210
+ selection: AgentInboxReadSelection,
1211
+ sessionId?: string,
1212
+ ): Promise<AgentInboxReadEntry[]> {
1213
+ const state = this.stateFor(agentId);
1214
+ if (!state.available) return [];
1215
+ // 缺省只取可读;includeHeld 时连 held 一起取(见下面的消费语义)。
1216
+ const candidates = this.visible(state, state.messages, selection.includeHeld === true);
1217
+ let picked: StoredInboxMessage[];
1218
+ if (selection.ids !== undefined) {
1219
+ const byId = new Map(candidates.map((message) => [message.id, message]));
1220
+ const seen = new Set<string>();
1221
+ picked = [];
1222
+ for (const id of selection.ids) {
1223
+ if (seen.has(id)) continue;
1224
+ seen.add(id);
1225
+ const message = byId.get(id);
1226
+ if (message !== undefined) picked.push(message);
1227
+ }
1228
+ } else {
1229
+ const limit = selection.limit ?? INBOX_READ_DEFAULT_LIMIT;
1230
+ // 免 list 直读(用户裁定):无 ids 时取**最新**的 limit 条,返回仍按时间序
1231
+ // (candidates 是插入序,slice(-limit) 取尾部 = 最近到达的几条)。较旧的留在
1232
+ // 队列里,下次 read 或显式 ids 再取。
1233
+ picked = limit > 0 ? candidates.slice(-limit) : [];
1234
+ }
1235
+ if (picked.length === 0) return [];
1236
+ // I2:只消费未被持有的条目。held 的正文已经排进某次 run —— read 不取消投递、
1237
+ // 不改变它的状态,否则「读过的正文」与「稍后到达的 run input」会变成两次执行。
1238
+ const consumable = picked
1239
+ .filter((message) => !state.held.has(message.id))
1240
+ .map((message) => message.id);
1241
+ if (consumable.length > 0) {
1242
+ // 先标 consumed 并落盘,再返回:at-most-once 对工具结果成立。
1243
+ await this.consume(agentId, consumable, sessionId);
1244
+ }
1245
+ return picked.map((message) => ({
1246
+ ...cloneMessage(message),
1247
+ held: state.held.has(message.id),
1248
+ }));
1249
+ }
1250
+
1251
+ async markConsumed(agentId: string, ids: readonly string[], sessionId: string): Promise<void> {
1252
+ await this.consume(agentId, ids, sessionId);
1253
+ }
1254
+
1255
+ /**
1256
+ * 显式认领(见 `AgentInboxPort.claim`):`unread`(含 held)→ `consumed` + 解 hold。
1257
+ *
1258
+ * 判定与写入都在这一个函数里完成:先按**同一份快照**分出「能拿的」与「跳过的」,再走
1259
+ * 现有的 `consume`(唯一消费点的同一套实现:标 consumed、删 hold、入写链),不为认领
1260
+ * 另开一条写路径。跳过判定在 consume 之前取快照,所以「本来就是 consumed」与「这条被
1261
+ * 自己拿走了」不会混在同一个 reason 里。
1262
+ */
1263
+ async claim(
1264
+ agentId: string,
1265
+ ids: readonly string[],
1266
+ sessionId?: string,
1267
+ ): Promise<AgentInboxClaimResult> {
1268
+ const state = this.stateFor(agentId);
1269
+ const byId = new Map(state.messages.map((message) => [message.id, message]));
1270
+ const claimed: string[] = [];
1271
+ const skipped: AgentInboxClaimSkip[] = [];
1272
+ for (const id of new Set(ids)) {
1273
+ const message = byId.get(id);
1274
+ if (message === undefined) {
1275
+ skipped.push({ id, reason: 'not_found' });
1276
+ continue;
1277
+ }
1278
+ if (message.status === 'consumed') {
1279
+ skipped.push({ id, reason: 'consumed' });
1280
+ continue;
1281
+ }
1282
+ // running 异步作业占位还没结果,不可认领(与 read 跳过同口径)。
1283
+ if (isRunningAsyncJob(message)) {
1284
+ skipped.push({ id, reason: 'pending' });
1285
+ continue;
1286
+ }
1287
+ claimed.push(id);
1288
+ }
1289
+ if (claimed.length > 0) {
1290
+ // 执行侧收口必须在标 consumed **之前**:held 的条目已经排进了 scheduler 的一次
1291
+ // run,先消费再撤 run 会留一个「消息已不在队列、run 却还在跑」的窗口。
1292
+ await this.beforeClaim?.(agentId, claimed);
1293
+ // `sessionId` 缺省(`agents.claim` RPC 那条路)= 没有任何 body 把它当 run input
1294
+ // 消费过,`consumed_by_session` 就不写:那个字段的含义是「哪具 body 执行的」,
1295
+ // 认领不是执行。模型侧工具会传自己的 session(它就是那个想「收下」的 body)。
1296
+ // 帧理由走 `claimed`(与 read/markConsumed 的 `consumed` 区分,§6.2);
1297
+ // 发帧在 consume 里统一做,这里不另发(一次 mutation 一条帧)。
1298
+ await this.consume(agentId, claimed, sessionId, 'claimed');
1299
+ }
1300
+ return {
1301
+ claimed,
1302
+ skipped,
1303
+ // 正文取自上面那份快照:`consume` 只改 status / 删 hold,不碰 text。
1304
+ messages: claimed.map((id) => ({
1305
+ ...cloneMessage(byId.get(id) as StoredInboxMessage),
1306
+ held: false,
1307
+ })),
1308
+ };
1309
+ }
1310
+
1311
+ updateAsyncJob(
1312
+ agentId: string,
1313
+ jobId: string,
1314
+ patch: {
1315
+ status: 'done' | 'failed';
1316
+ text?: string;
1317
+ payload?: Record<string, unknown>;
1318
+ ended_at?: number;
1319
+ },
1320
+ ): 'updated' | 'already_final' | 'absent' {
1321
+ const state = this.stateFor(agentId);
1322
+ if (!state.available) return 'absent';
1323
+ const message = state.messages.find((entry) => entry.async_job?.job_id === jobId);
1324
+ // 只更新仍在跑的占位(幂等)。三态区分(F2):「无占位」与「已终态幂等拒绝」语义不同 ——
1325
+ // 前者调用方退回旧投递路径,后者结果已投递过,绝不重投。
1326
+ if (message === undefined || message.async_job === undefined) return 'absent';
1327
+ if (message.async_job.status !== 'running') return 'already_final';
1328
+ message.async_job = {
1329
+ ...message.async_job,
1330
+ status: patch.status,
1331
+ // kind 专属 payload 浅合并(机制层不解释内部字段;bash 填 exit_code 等)。
1332
+ ...(patch.payload !== undefined
1333
+ ? { payload: { ...message.async_job.payload, ...patch.payload } }
1334
+ : {}),
1335
+ ...(patch.ended_at !== undefined ? { ended_at: patch.ended_at } : {}),
1336
+ };
1337
+ // 填结果正文(留档):重算 summary,条目离开 running 排除集。可见投递由
1338
+ // service.completeAsyncJob 的结果条目承担,占位随后 markConsumed 退场(单路单卡)。
1339
+ // q-pii-redaction-unify:原位回写同样过闸(占位的归属 = async_job.session_id)。
1340
+ if (patch.text !== undefined) {
1341
+ const maskedText = protectInboxText(patch.text, inboxStorageScopeOf(message));
1342
+ message.text = maskedText;
1343
+ message.summary = summaryOf(maskedText);
1344
+ }
1345
+ void this.enqueueWrite(state);
1346
+ this.notifyChange(agentId, {
1347
+ reason: 'updated',
1348
+ messageIds: [message.id],
1349
+ ...(message.session_id !== undefined ? { sessionId: message.session_id } : {}),
1350
+ });
1351
+ return 'updated';
1352
+ }
1353
+
1354
+ findByIds(agentId: string, ids: readonly string[]): StoredInboxMessage[] {
1355
+ const state = this.stateFor(agentId);
1356
+ if (!state.available) return [];
1357
+ const byId = new Map(state.messages.map((message) => [message.id, message]));
1358
+ const found: StoredInboxMessage[] = [];
1359
+ for (const id of ids) {
1360
+ const message = byId.get(id);
1361
+ if (message !== undefined) found.push(cloneMessage(message));
1362
+ }
1363
+ return found;
1364
+ }
1365
+
1366
+ findByTeamMessage(agentId: string, teamMessageId: string): StoredInboxMessage[] {
1367
+ const state = this.stateFor(agentId);
1368
+ if (!state.available || teamMessageId === '') return [];
1369
+ return state.messages
1370
+ .filter((message) => message.team_message_id === teamMessageId)
1371
+ .map(cloneMessage);
1372
+ }
1373
+
1374
+ inputHead(agentId: string): StoredInboxMessage | undefined {
1375
+ const state = this.stateFor(agentId);
1376
+ if (!state.available) return undefined;
1377
+ // `readable()` 已经是「unread 且未被持有」的**入队序**数组(它只做 filter,不排序)。
1378
+ // 这里再跳过留档 / 空正文:它们的语义不是「等一轮 run」,直投只会把它们执行一遍。
1379
+ const head = this.readable(state, state.messages).find(
1380
+ (message) => message.quiet !== true && message.text.trim() !== '',
1381
+ );
1382
+ return head === undefined ? undefined : cloneMessage(head);
1383
+ }
1384
+
1385
+ history(agentId: string, limit?: number): StoredInboxMessage[] {
1386
+ const state = this.stateFor(agentId);
1387
+ if (!state.available) return [];
1388
+ const all = state.messages;
1389
+ const take =
1390
+ typeof limit === 'number' && Number.isInteger(limit) && limit > 0 ? limit : all.length;
1391
+ // 入队序尾部 = 最近到达;reverse 成 newest-first。克隆交出,调用方改不动库。
1392
+ return all.slice(-take).reverse().map(cloneMessage);
1393
+ }
1394
+
1395
+ /**
1396
+ * 元数据版 history(q-inbox-metadata-seam,additive):返回 meta 投影(newest-first),
1397
+ * 供 reconcileAsyncJobs / distress 扫描等**只读元数据**的消费点用 —— 侧车命中即免整份
1398
+ * 读正文。`history` 旧契约(含 text 的完整克隆)保留不删;正文真需仍走 history / read。
1399
+ * 投影口径与 list 共用 metaView(meta 档侧车数组 / full 档即时投影),判据单源。
1400
+ */
1401
+ historyMeta(agentId: string, limit?: number): InboxMessageMeta[] {
1402
+ const state = this.stateForMeta(agentId);
1403
+ if (!state.available) return [];
1404
+ const all = this.metaView(state);
1405
+ const take =
1406
+ typeof limit === 'number' && Number.isInteger(limit) && limit > 0 ? limit : all.length;
1407
+ // 入队序尾部 = 最近到达;reverse 成 newest-first。浅拷贝交出(嵌套 async_job 克隆防改)。
1408
+ return all
1409
+ .slice(-take)
1410
+ .reverse()
1411
+ .map((message) => ({
1412
+ ...message,
1413
+ ...(message.async_job !== undefined ? { async_job: cloneAsyncJob(message.async_job) } : {}),
1414
+ }));
1415
+ }
1416
+
1417
+ discard(
1418
+ agentId: string,
1419
+ ids: readonly string[],
1420
+ options?: AgentInboxDiscardOptions,
1421
+ ): AgentInboxDiscardResult {
1422
+ const state = this.stateFor(agentId);
1423
+ const unique = [...new Set(ids)];
1424
+ if (unique.length === 0) return { deleted: [], skipped: [] };
1425
+ if (!state.available) {
1426
+ return {
1427
+ deleted: [],
1428
+ skipped: unique.map((id) => ({ id, reason: 'not_found' as const })),
1429
+ };
1430
+ }
1431
+ const wanted = new Set(unique);
1432
+ const matched = new Map<string, StoredInboxMessage>();
1433
+ for (const message of state.messages) {
1434
+ if (wanted.has(message.id)) matched.set(message.id, message);
1435
+ }
1436
+ const onlyUnheld = options?.onlyUnheld === true;
1437
+ const deleted: string[] = [];
1438
+ const skipped: AgentInboxDiscardSkip[] = [];
1439
+ for (const id of unique) {
1440
+ const message = matched.get(id);
1441
+ if (message === undefined) {
1442
+ skipped.push({ id, reason: 'not_found' });
1443
+ continue;
1444
+ }
1445
+ if (onlyUnheld) {
1446
+ if (message.status === 'consumed') {
1447
+ skipped.push({ id, reason: 'consumed' });
1448
+ continue;
1449
+ }
1450
+ if (state.held.has(id)) {
1451
+ skipped.push({ id, reason: 'held' });
1452
+ continue;
1453
+ }
1454
+ }
1455
+ deleted.push(id);
1456
+ state.held.delete(id);
1457
+ }
1458
+ if (deleted.length > 0) {
1459
+ // 归属在移除前取(移除后查不到条目);帧在落状态后发。
1460
+ const sessionId = this.changeSessionId(state, deleted);
1461
+ const removed = new Set(deleted);
1462
+ state.messages = state.messages.filter((message) => !removed.has(message.id));
1463
+ void this.enqueueWrite(state);
1464
+ this.notifyChange(agentId, {
1465
+ reason: 'discarded',
1466
+ messageIds: deleted,
1467
+ ...(sessionId !== undefined ? { sessionId } : {}),
1468
+ });
1469
+ }
1470
+ return { deleted, skipped };
1471
+ }
1472
+
1473
+ async flush(): Promise<void> {
1474
+ await this.writeChain;
1475
+ }
1476
+
1477
+ /**
1478
+ * 变更钩子的唯一调用口:状态已落,观察方抛错只记日志,不打断状态机。
1479
+ * 缺省(无 onChange)零开销。
1480
+ */
1481
+ private notifyChange(agentId: string, change: AgentInboxChange): void {
1482
+ if (this.onChange === undefined) return;
1483
+ try {
1484
+ this.onChange(agentId, change);
1485
+ } catch (error) {
1486
+ this.logger.warn('inbox.onChange.failed', {
1487
+ agent_id: agentId,
1488
+ reason: change.reason,
1489
+ error: error instanceof Error ? error.message : String(error),
1490
+ });
1491
+ }
1492
+ }
1493
+
1494
+ /**
1495
+ * 帧的 `sessionId`:变更条目的**共同已知归属**(§6.2「单条且已知时」的多条推广)。
1496
+ * 任一条目缺归属或归属不一致 ⇒ undefined(wake/quiet / 混合归属不猜)。
1497
+ */
1498
+ private changeSessionId(state: AgentInboxState, ids: readonly string[]): string | undefined {
1499
+ let session: string | undefined;
1500
+ for (const id of ids) {
1501
+ const value = state.messages.find((message) => message.id === id)?.session_id;
1502
+ if (value === undefined) return undefined;
1503
+ if (session === undefined) session = value;
1504
+ else if (session !== value) return undefined;
1505
+ }
1506
+ return session;
1507
+ }
1508
+
1509
+ /**
1510
+ * list / read / notice 共用的唯一计数口径(§0.5.6:`pending` 是派生数字,不是第二套状态)。
1511
+ *
1512
+ * `unread` 只计可读(模型该自己读的),`pending` 只计 `unread ∩ held`(已被某个 body
1513
+ * 接管、会自动作为 run input 到达的)。两者互斥且 `unread + pending = unread 总数`。
1514
+ *
1515
+ * 判据只读 status / async_job / held —— meta 投影与 full 消息共有这些键,故同一判据
1516
+ * 作用于两种视图(q-inbox-metadata-seam:list 走 meta 视图,read 走 full,单源不双份)。
1517
+ */
1518
+ private counts(
1519
+ state: AgentInboxState,
1520
+ messages: ReadonlyArray<{ id: string; status: string; async_job?: InboxAsyncJobMeta }>,
1521
+ ): { unread: number; pending: number } {
1522
+ let unread = 0;
1523
+ let pending = 0;
1524
+ for (const message of messages) {
1525
+ if (message.status !== 'unread') continue;
1526
+ // running 异步作业占位不计 unread(模型还读不到,与 readable 同口径;q-async-bash-viz)。
1527
+ if (isRunningAsyncJob(message)) continue;
1528
+ if (state.held.has(message.id)) pending += 1;
1529
+ else unread += 1;
1530
+ }
1531
+ return { unread, pending };
1532
+ }
1533
+
1534
+ /**
1535
+ * unread 且未被持有,保持插入顺序。
1536
+ *
1537
+ * **running 异步作业占位排除在外**(q-async-bash-viz):它还没结果,不可被 read 消费 /
1538
+ * 弹出,也不当 run input(inputHead 复用本方法)。done/failed 后回到可读队列。
1539
+ */
1540
+ private readable<T extends { id: string; status: string; async_job?: InboxAsyncJobMeta }>(
1541
+ state: AgentInboxState,
1542
+ messages: readonly T[],
1543
+ ): T[] {
1544
+ return messages.filter(
1545
+ (message) =>
1546
+ message.status === 'unread' && !state.held.has(message.id) && !isRunningAsyncJob(message),
1547
+ );
1548
+ }
1549
+
1550
+ /** unread 全集;`includeHeld` 时连 held 一起(read 的 includeHeld 用它)。running 占位仍排除。 */
1551
+ private visible<T extends { id: string; status: string; async_job?: InboxAsyncJobMeta }>(
1552
+ state: AgentInboxState,
1553
+ messages: readonly T[],
1554
+ includeHeld: boolean,
1555
+ ): T[] {
1556
+ if (!includeHeld) return this.readable(state, messages);
1557
+ return messages.filter((message) => message.status === 'unread' && !isRunningAsyncJob(message));
1558
+ }
1559
+
1560
+ private async consume(
1561
+ agentId: string,
1562
+ ids: readonly string[],
1563
+ sessionId?: string,
1564
+ reason: 'consumed' | 'claimed' = 'consumed',
1565
+ ): Promise<void> {
1566
+ const state = this.stateFor(agentId);
1567
+ if (!state.available) return;
1568
+ const wanted = new Set(ids);
1569
+ if (wanted.size === 0) return;
1570
+ const changedIds: string[] = [];
1571
+ for (const message of state.messages) {
1572
+ if (!wanted.has(message.id)) continue;
1573
+ if (message.status !== 'consumed') changedIds.push(message.id);
1574
+ message.status = 'consumed';
1575
+ if (sessionId !== undefined) message.consumed_by_session = sessionId;
1576
+ state.held.delete(message.id);
1577
+ }
1578
+ // startup prompt 不在 inbox 里:未知 id 不触发空写;已 consumed 再消费也不发帧。
1579
+ if (changedIds.length === 0) return;
1580
+ await this.enqueueWrite(state);
1581
+ const attribution = this.changeSessionId(state, changedIds);
1582
+ this.notifyChange(agentId, {
1583
+ reason,
1584
+ messageIds: changedIds,
1585
+ ...(attribution !== undefined ? { sessionId: attribution } : {}),
1586
+ });
1587
+ }
1588
+
1589
+ /** 取 / 建内存条目(**不读盘**):同步懒加载与异步 warm 共用的入口。 */
1590
+ private stateEntry(agentId: string): AgentInboxState {
1591
+ let state = this.agents.get(agentId);
1592
+ if (state === undefined) {
1593
+ state = {
1594
+ path: inboxPath(this.dataDir, this.tenantId, agentId),
1595
+ messages: [],
1596
+ held: new Map(),
1597
+ level: 'none',
1598
+ available: true,
1599
+ };
1600
+ this.agents.set(agentId, state);
1601
+ }
1602
+ return state;
1603
+ }
1604
+
1605
+ private stateFor(agentId: string): AgentInboxState {
1606
+ const state = this.stateEntry(agentId);
1607
+ // mutation / 正文读恒 full:meta 档升级读全文件(held Map 保留,applyRaw 只换 messages)。
1608
+ if (state.level !== 'full') this.loadSync(state);
1609
+ return state;
1610
+ }
1611
+
1612
+ /**
1613
+ * 元数据读路径(q-inbox-metadata-seam,**同步**:`list()` / `historyMeta()` 是同步契约口):
1614
+ * 侧车命中 → meta 档(零整份读);miss / 损坏 / 旧文件无侧车 → 整份 loadSync(fail-safe,
1615
+ * 语义与今天逐字节相同)+ 读侧自愈写侧车(排队收口进 writeChain,flush 覆盖,防「列一次
1616
+ * 就退出」丢写)。held 仅内存 overlay,侧车不承载;事实源 inbox.json 不变。
1617
+ * 异步预热走 `warm()`(await readFile 重叠 IO),两者共用 validate / 水位口径。
1618
+ */
1619
+ private stateForMeta(agentId: string): AgentInboxState {
1620
+ const state = this.stateEntry(agentId);
1621
+ if (state.level !== 'none') return state;
1622
+ let stamp: SidecarStamp | undefined;
1623
+ try {
1624
+ const info = statSync(state.path);
1625
+ stamp = { size: info.size, mtimeMs: info.mtimeMs };
1626
+ } catch {
1627
+ // benign: stat 失败(ENOENT / 不可读)⇒ 无侧车捷径,走整份 loadSync 既有口径。
1628
+ }
1629
+ if (stamp !== undefined) {
1630
+ const meta = readSidecarSync(state.path, stamp, validateInboxMetaSidecar);
1631
+ // inbox validate 永不返回 null(null 是 session 域的「空会话结论」);!= null 同时
1632
+ // 排除 miss(undefined) 与泛型签名里的 null,空数组 [] 是合法命中(零消息)。
1633
+ if (meta != null) {
1634
+ state.meta = meta;
1635
+ state.level = 'meta';
1636
+ return state;
1637
+ }
1638
+ }
1639
+ this.loadSync(state);
1640
+ // 自愈只在主文件可读且戳确认一致时落(读与 stat 之间可能被原子写替换,同 session
1641
+ // infoForPath 的 confirm 口径);写失败静默「下次再算」,绝不影响本次读结果。
1642
+ if (state.available && stamp !== undefined) {
1643
+ try {
1644
+ const confirm = statSync(state.path);
1645
+ if (confirm.size === stamp.size && confirm.mtimeMs === stamp.mtimeMs) {
1646
+ this.queueMetaSidecarWrite(state, stamp);
1647
+ }
1648
+ } catch {
1649
+ // benign: confirm stat 失败 ⇒ 跳过本次自愈(下次再算)。
1650
+ }
1651
+ }
1652
+ return state;
1653
+ }
1654
+
1655
+ /** meta 视图:meta 档用侧车投影数组;full 档从 messages 即时投影(不另存,防双份事实)。 */
1656
+ private metaView(state: AgentInboxState): InboxMessageMeta[] {
1657
+ if (state.level === 'meta' && state.meta !== undefined) return state.meta;
1658
+ return state.messages.map(metaOf);
1659
+ }
1660
+
1661
+ /**
1662
+ * 读侧自愈写排队:payload 在排队时同步派生(与 enqueueWrite 同一快照口径,防半新半旧),
1663
+ * 进 writeChain 串行 —— flush() 收口覆盖,且与主文件写不 interleave。
1664
+ */
1665
+ private queueMetaSidecarWrite(state: AgentInboxState, stamp: SidecarStamp): void {
1666
+ let payload: InboxMetaSidecarFile;
1667
+ try {
1668
+ payload = {
1669
+ v: 1,
1670
+ inbox_size: stamp.size,
1671
+ inbox_mtime_ms: stamp.mtimeMs,
1672
+ messages: state.messages.map(metaOf),
1673
+ };
1674
+ } catch (error) {
1675
+ this.logger.debug('agent.inbox.meta_serialize_failed', {
1676
+ path: state.path,
1677
+ error: errorText(error),
1678
+ });
1679
+ return;
1680
+ }
1681
+ const run = (): Promise<void> => writeSidecar(state.path, payload);
1682
+ this.writeChain = this.writeChain.then(run, run);
1683
+ }
1684
+
1685
+ /** 同步懒加载(整份,full 档);返回 available */
1686
+ private loadSync(state: AgentInboxState): void {
1687
+ state.level = 'full';
1688
+ state.meta = undefined;
1689
+ let raw: string;
1690
+ try {
1691
+ raw = readFileSync(state.path, 'utf8');
1692
+ } catch (error) {
1693
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
1694
+ state.available = false;
1695
+ this.logger.error('agent.inbox.load_failed', {
1696
+ path: state.path,
1697
+ error: errorText(error),
1698
+ });
1699
+ return;
1700
+ }
1701
+ this.applyRaw(state, raw);
1702
+ }
1703
+
1704
+ /**
1705
+ * 异步预热(启动恢复有界并发用,q-inbox-metadata-seam 改 meta 预热):侧车优先
1706
+ * (stat + 小文件读,不碰主文件正文),miss 退回整份 `await readFile`(现行为),
1707
+ * 让多个成员的 inbox 读盘**重叠等待**(q-slow-startup-probe §4/§6.3)。解析 / 校验 /
1708
+ * 裁剪与 `loadSync` 共用 `applyRaw`,语义逐字节相同;预热后 `list()` 命中内存条目,
1709
+ * 不再读盘。**绝不抛**:缺失 / 损坏 / 不可读与 `loadSync` 同口径(ENOENT 当空、其它
1710
+ * 记日志 + available=false),不让启动恢复因单个 inbox 失败。
1711
+ *
1712
+ * 竞态守卫(水位不降级):每个 `await` 之后若别的路径(`stateFor` / 另一次 warm)
1713
+ * 已把水位推到 meta/full,直接返回,不用可能更旧的数据覆盖更新的内存态。
1714
+ */
1715
+ async warm(agentId: string): Promise<void> {
1716
+ const state = this.stateEntry(agentId);
1717
+ if (state.level !== 'none') return;
1718
+ let stamp: SidecarStamp | undefined;
1719
+ try {
1720
+ const info = await stat(state.path);
1721
+ stamp = { size: info.size, mtimeMs: info.mtimeMs };
1722
+ } catch (error) {
1723
+ if (state.level !== 'none') return;
1724
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
1725
+ state.level = 'full';
1726
+ state.meta = undefined;
1727
+ return;
1728
+ }
1729
+ // 其它 stat 错误:不判损坏(与今天 warm 的 readFile 错误口径一致留给整份读判定)。
1730
+ }
1731
+ if (state.level !== 'none') return;
1732
+ if (stamp !== undefined) {
1733
+ const meta = await readSidecar(state.path, stamp, validateInboxMetaSidecar);
1734
+ if (state.level !== 'none') return;
1735
+ // != null 排除 miss(undefined) 与泛型 null(inbox validate 永不返回 null);空数组合法命中。
1736
+ if (meta != null) {
1737
+ state.meta = meta;
1738
+ state.level = 'meta';
1739
+ return;
1740
+ }
1741
+ }
1742
+ let raw: string;
1743
+ try {
1744
+ raw = await readFile(state.path, 'utf8');
1745
+ } catch (error) {
1746
+ if (state.level !== 'none') return;
1747
+ state.level = 'full';
1748
+ state.meta = undefined;
1749
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
1750
+ state.available = false;
1751
+ this.logger.error('agent.inbox.load_failed', {
1752
+ path: state.path,
1753
+ error: errorText(error),
1754
+ });
1755
+ return;
1756
+ }
1757
+ if (state.level !== 'none') return;
1758
+ state.level = 'full';
1759
+ state.meta = undefined;
1760
+ this.applyRaw(state, raw);
1761
+ // 读侧自愈(miss 整份读是白读的,把结论记下):戳确认一致才落,排队进 writeChain。
1762
+ if (state.available && stamp !== undefined) {
1763
+ try {
1764
+ const confirm = await stat(state.path);
1765
+ if (confirm.size === stamp.size && confirm.mtimeMs === stamp.mtimeMs) {
1766
+ this.queueMetaSidecarWrite(state, stamp);
1767
+ }
1768
+ } catch {
1769
+ // benign: confirm stat 失败 ⇒ 跳过本次自愈(下次再算)。
1770
+ }
1771
+ }
1772
+ }
1773
+
1774
+ /** 解析 + 形状校验 + 裁剪(同步 / 异步加载共用,保证两条路口径一致)。 */
1775
+ private applyRaw(state: AgentInboxState, raw: string): void {
1776
+ let parsed: unknown;
1777
+ try {
1778
+ parsed = JSON.parse(raw);
1779
+ } catch (error) {
1780
+ state.available = false;
1781
+ this.logger.error('agent.inbox.corrupt', {
1782
+ path: state.path,
1783
+ error: errorText(error),
1784
+ });
1785
+ return;
1786
+ }
1787
+ if (!isInboxFile(parsed)) {
1788
+ state.available = false;
1789
+ this.logger.error('agent.inbox.corrupt', { path: state.path });
1790
+ return;
1791
+ }
1792
+ state.messages = parsed.messages.map(cloneMessage);
1793
+ this.prune(state);
1794
+ }
1795
+
1796
+ /**
1797
+ * 有界:保留最新 maxMessages 条。
1798
+ *
1799
+ * 顺带清掉被裁消息的 hold —— `held` 现在按 body 释放(不再有 agent 级 `clear()`),
1800
+ * 残留 id 会永久累积并违反 I4(held 必须仍被某条现存消息引用)。
1801
+ */
1802
+ private prune(state: AgentInboxState): void {
1803
+ if (state.messages.length <= this.maxMessages) return;
1804
+ state.messages.splice(0, state.messages.length - this.maxMessages);
1805
+ const alive = new Set(state.messages.map((message) => message.id));
1806
+ for (const id of state.held.keys()) {
1807
+ if (!alive.has(id)) state.held.delete(id);
1808
+ }
1809
+ }
1810
+
1811
+ /** 所有 append 路径的第一步:先裁 consumed(不占 cap,也不保留 hold)。返回是否有变化。 */
1812
+ private pruneConsumed(state: AgentInboxState): boolean {
1813
+ if (!state.messages.some((message) => message.status === 'consumed')) return false;
1814
+ state.messages = state.messages.filter((message) => {
1815
+ if (message.status !== 'consumed') return true;
1816
+ state.held.delete(message.id);
1817
+ return false;
1818
+ });
1819
+ return true;
1820
+ }
1821
+
1822
+ /**
1823
+ * 两级淘汰(0.53):为「再写一条」腾位置时,**先裁非 human 源的最旧条目,再裁 human 源**。
1824
+ *
1825
+ * 理由:一条人写的待处理输入(`input` 投递、带 `session_id`、重启后要被执行)不该被
1826
+ * 成员之间的投递挤掉。被裁掉的 **human 源**条目记 `agent.inbox.evicted`(warn,带
1827
+ * `id` / `session_id` / `ts`)—— 这是用户消息真的丢了,必须能在日志里查到;非 human 源
1828
+ * 属常规轮换,不刷日志。**不发事件**(不为纯诊断新增事件类型)。
1829
+ */
1830
+ private evictForWrite(state: AgentInboxState, count: number): void {
1831
+ for (let removed = 0; removed < count; removed += 1) {
1832
+ if (state.messages.length === 0) return;
1833
+ const victim = state.messages.findIndex((message) => message.source !== HUMAN_PRINCIPAL);
1834
+ const index = victim >= 0 ? victim : 0;
1835
+ const [dropped] = state.messages.splice(index, 1);
1836
+ if (dropped === undefined) return;
1837
+ state.held.delete(dropped.id);
1838
+ if (dropped.source !== HUMAN_PRINCIPAL) continue;
1839
+ this.logger.warn('agent.inbox.evicted', {
1840
+ path: state.path,
1841
+ id: dropped.id,
1842
+ ts: dropped.ts,
1843
+ ...(dropped.session_id !== undefined ? { session_id: dropped.session_id } : {}),
1844
+ });
1845
+ }
1846
+ }
1847
+
1848
+ private enqueueWrite(state: AgentInboxState): Promise<void> {
1849
+ if (!state.available) return Promise.resolve();
1850
+ let data: string;
1851
+ let metaMessages: InboxMessageMeta[];
1852
+ try {
1853
+ // 序列化在入队时同步完成,避免异步窗口里继续改数组导致半新半旧。侧车 payload 与
1854
+ // 主文件 data 从**同一份克隆快照**派生(q-inbox-metadata-seam),保证投影等值(F3)。
1855
+ const cloned = state.messages.map(cloneMessage);
1856
+ const file: InboxFile = {
1857
+ v: AGENT_INBOX_VERSION,
1858
+ messages: cloned,
1859
+ };
1860
+ data = JSON.stringify(file);
1861
+ metaMessages = cloned.map(metaOf);
1862
+ } catch (error) {
1863
+ this.logger.error('agent.inbox.serialize_failed', {
1864
+ path: state.path,
1865
+ error: errorText(error),
1866
+ });
1867
+ return Promise.resolve();
1868
+ }
1869
+ const run = async (): Promise<void> => {
1870
+ try {
1871
+ await atomicWrite(state.path, data, { mode: 0o600, ensureDir: true });
1872
+ } catch (error) {
1873
+ this.logger.error('agent.inbox.write_failed', {
1874
+ path: state.path,
1875
+ error: errorText(error),
1876
+ });
1877
+ // 主文件没写成 ⇒ 不写侧车(派生物不许指向一份没写成的主文件)。
1878
+ return;
1879
+ }
1880
+ // 写侧维护(best-effort,唯一写权威内追加段):主文件写成功后 stat 取**实际**戳
1881
+ // (原子 rename 后 stat 即新戳,与读侧 stat 天然一致)→ 写侧车(durable:false)。
1882
+ // stat / 写失败只记 debug,**绝不影响主文件写入结果**(派生物口径;F1 实测闸)。
1883
+ try {
1884
+ const info = await stat(state.path);
1885
+ const payload: InboxMetaSidecarFile = {
1886
+ v: 1,
1887
+ inbox_size: info.size,
1888
+ inbox_mtime_ms: info.mtimeMs,
1889
+ messages: metaMessages,
1890
+ };
1891
+ await writeSidecar(state.path, payload);
1892
+ } catch (error) {
1893
+ this.logger.debug('agent.inbox.meta_write_failed', {
1894
+ path: state.path,
1895
+ error: errorText(error),
1896
+ });
1897
+ }
1898
+ };
1899
+ const task = this.writeChain.then(run, run);
1900
+ this.writeChain = task;
1901
+ return task;
1902
+ }
1903
+ }
1904
+
1905
+ /**
1906
+ * notice 的模型可见文本:**只有条数,一行,≤ 60 字符**(不含正文)。
1907
+ *
1908
+ * 「`unread` 该自己读、`pending` 会自动作为下一轮输入到达(别重发 / 别重做)、用
1909
+ * `inbox` 工具 list / read 去看」这套用法已经常驻在 `inbox` 工具的 description 里;
1910
+ * 这条尾消息每一轮都在上下文里,只报**计数**,不复述用法(API surface = prompt surface)。
1911
+ *
1912
+ * `pending` 就是「已被某具 body 接管、会自动作为下一轮 run input 到达」的条数,
1913
+ * 与 held 是同一集合(I1–I4:`hold` 只作用于未消费消息),所以不另写 `(N held)`。
1914
+ */
1915
+ /**
1916
+ * inbox 计数行现态格式(q-sub-unify-p2 M4 additive export:inboxSource facade
1917
+ * 纯委托此函数,hook 仍直调——内部机器不改道,线格式逐字保留)。
1918
+ */
1919
+ export function noticeContent(unread: number, pending: number): string {
1920
+ if (pending > 0 && unread > 0) return `[inbox] ${pending} pending · ${unread} unread`;
1921
+ if (pending > 0) return `[inbox] ${pending} pending`;
1922
+ return `[inbox] ${unread} unread`;
1923
+ }
1924
+
1925
+ /**
1926
+ * 成员 BeforeLlm notice hook(0.32 v2;0.51 起按计数去重、无消息不注入)。
1927
+ *
1928
+ * 只发一条 `vessel:notice` 尾消息提示未读条数;**不注入正文、不标 consumed**。
1929
+ * 「要不要提示」只看 `(unread, pending, held)` 三个计数:与上次注入时相同就不再注入
1930
+ * (旧口径把可读消息 id 也编进签名,于是「消费一条 + 进来一条、计数不变」也会多刷一行)。
1931
+ * 三个计数全为 0 时**完全不注入**,不留 `0 unread` 占位。
1932
+ */
1933
+ export function createInboxNoticeHook(options: {
1934
+ inbox: AgentInboxPort;
1935
+ agentId: string;
1936
+ isEnabled?: () => boolean;
1937
+ onNotified?: (data: {
1938
+ runId: string;
1939
+ sessionId?: string;
1940
+ unread: number;
1941
+ pending: number;
1942
+ }) => void;
1943
+ }): Hook {
1944
+ /** 每个 hook(= 每个 body)独立;body 重建时重新开始提示。 */
1945
+ // `undefined` = 这具 body 还没注入过(或计数已归零),下次非零计数必注入。
1946
+ let lastCounts: string | undefined;
1947
+ /**
1948
+ * 最近一次注入的 `(run_id, 正文)`:**同一次 run 内同文只提示一次**。
1949
+ *
1950
+ * 为什么需要:`lastCounts` 判的是三个计数,而「pending 1 → 被取走(0)→ 又来一条(1)」
1951
+ * 会让签名变化、正文却一字不差 —— 模型在同一轮的上下文里已经看着同一行
1952
+ * `[inbox] 1 pending`,再插一条是纯重复。实测 main 会话 09f82ac6:20 条 inbox 卡里
1953
+ * 3 对是同一 run 内的同文重复(run f9d02983 / 5a8fb2e4 / 960a5215)。
1954
+ *
1955
+ * **只按 run 去重**,不做会话级内容去重:换 body(新 run)必须照常收到这条提示,
1956
+ * 否则「新身体不知道自己有未读」,那正是这条提示存在的理由。
1957
+ */
1958
+ let lastInjection: { runId: string; content: string } | undefined;
1959
+ return {
1960
+ name: 'vessel:inbox-notice',
1961
+ type: HookType.BeforeLlm,
1962
+ async run(ctx): Promise<void> {
1963
+ if (options.isEnabled?.() === false) return;
1964
+ const { unread, pending, messages } = options.inbox.list(options.agentId, {
1965
+ includeHeld: true,
1966
+ });
1967
+ // held 与 pending 是同集合:`includeHeld:true` 只返回未消费消息,而 `hold` 也只
1968
+ // 作用于未消费消息 ⇒ 两者恒等。签名仍按三元组写:哪天 `held` 不再等于「会自动送达」
1969
+ // 时不会漏提示,代价只是几个数字的字符串比较。
1970
+ let held = 0;
1971
+ for (const entry of messages) if (entry.held) held += 1;
1972
+ // 一条消息都没有(unread / pending / held 全 0):不注入,也不留 `0 unread` 占位。
1973
+ if (unread === 0 && pending === 0 && held === 0) {
1974
+ lastCounts = undefined;
1975
+ return;
1976
+ }
1977
+ const counts = `${unread}:${pending}:${held}`;
1978
+ if (counts === lastCounts) return;
1979
+ const content = noticeContent(unread, pending);
1980
+ const runId = typeof ctx.run_id === 'string' ? ctx.run_id : '';
1981
+ // 同一次 run 内正文没变 ⇒ 模型已经在上下文里看到过同一行,不再插一条(见 lastInjection)。
1982
+ // 计数签名仍然更新:这样「同一 run 内再来一次同样的计数」不会反复走判定。
1983
+ if (
1984
+ runId !== '' &&
1985
+ lastInjection !== undefined &&
1986
+ lastInjection.runId === runId &&
1987
+ lastInjection.content === content
1988
+ ) {
1989
+ lastCounts = counts;
1990
+ return;
1991
+ }
1992
+ const message: Message = {
1993
+ role: 'user',
1994
+ name: 'vessel:notice',
1995
+ content,
1996
+ timestamp: Date.now(),
1997
+ };
1998
+ ctx.messages = [...(ctx.messages ?? []), message];
1999
+ lastCounts = counts;
2000
+ lastInjection = { runId, content };
2001
+ try {
2002
+ options.onNotified?.({
2003
+ runId: ctx.run_id,
2004
+ ...(ctx.session_id !== undefined ? { sessionId: ctx.session_id } : {}),
2005
+ unread,
2006
+ pending,
2007
+ });
2008
+ } catch {
2009
+ // 观测回调不得影响提示;事件链路的错误由调用方自己负责可见性。
2010
+ }
2011
+ },
2012
+ };
2013
+ }
2014
+
2015
+ /** `inbox` 工具的 description(模型按需读取收件箱)。 */
2016
+ const INBOX_TOOL_DESCRIPTION =
2017
+ 'inspect messages queued while this agent was busy/rotating. ' +
2018
+ 'every reply carries three counts: unread = yours to read now, pending = unread messages ' +
2019
+ 'already held as your next run input(s) (they arrive on their own — do not resend or redo them), ' +
2020
+ 'held = every message currently held (pending is its unread part; today the two numbers are equal). ' +
2021
+ 'list is the ONLY cheap peek: the three counts + per message {id, ts, source, a preview of the first ' +
2022
+ '40 characters, and more_chars = how many characters are NOT shown}. it never returns the body, so it ' +
2023
+ 'never consumes anything — use it to decide what to read. ' +
2024
+ 'read without ids needs no list round: it directly takes the newest messages (default 3, ' +
2025
+ 'returned oldest-first); pass limit for more or ids to pick exactly. ' +
2026
+ 'read TAKES messages: it returns the full text (plus refs = attachment paths when present; view them ' +
2027
+ 'with the media tool) and consumes them, held (pending) ones included — for ' +
2028
+ 'those it also cancels their queued run input, so the same text cannot arrive twice. it is irreversible: ' +
2029
+ 'a message you read is never delivered again and never listed again. there is no peek-then-take: if you ' +
2030
+ 'do not want to handle a message yet, do not read it (list is enough), and never act twice on one ' +
2031
+ 'message. ' +
2032
+ 'delete removes unread, non-held messages by id (held/consumed are skipped): the way to drop a message ' +
2033
+ 'without reading it. insert appends a message to your own inbox; it does not start a run or wake you. ' +
2034
+ "legacy: action:'claim' is accepted as an alias of read (0.51 sessions may still send it).";
2035
+
2036
+ function invalidInput(message: string): string {
2037
+ return JSON.stringify({ error: `invalid_input: ${message}` });
2038
+ }
2039
+
2040
+ /**
2041
+ * `list` 的前缀长度(0.55):只给前 40 个字符 + 「还有 N 字符」。
2042
+ *
2043
+ * 为什么是 40 而不是原来的 160 字 summary:`list` 的定位已经变了 —— 它是**唯一**的廉价
2044
+ * 偷看,模型靠它决定「读哪几条」。160 字足以让模型以为自己已经知道内容、于是不回 `read`
2045
+ * 也不会处理;40 字只够认清「这是谁发的、大概什么事」,正文必须自己拿。
2046
+ */
2047
+ const INBOX_LIST_PREVIEW_CHARS = 40;
2048
+
2049
+ /** `list` 的一行前缀:前 40 字符(截断时补 `…`)+ 还有多少字符没给。 */
2050
+ function listPreview(message: AgentInboxListEntry): { preview: string; more_chars: number } {
2051
+ const preview =
2052
+ message.summary.length > INBOX_LIST_PREVIEW_CHARS
2053
+ ? `${message.summary.slice(0, INBOX_LIST_PREVIEW_CHARS)}…`
2054
+ : message.summary;
2055
+ // 正文长度口径(不是 summary 长度):summary 被裁到 160 字,据此算「还差多少」会撒谎。
2056
+ return { preview, more_chars: Math.max(0, message.chars - INBOX_LIST_PREVIEW_CHARS) };
2057
+ }
2058
+
2059
+ function isRecordValue(value: unknown): value is Record<string, unknown> {
2060
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
2061
+ }
2062
+
2063
+ /**
2064
+ * 成员可见的 `inbox` 工具:`list` 只给 40 字前缀(唯一廉价偷看),`read` 取原文**并拿走**
2065
+ * (unread 与 held 一视同仁,held 的 queued run 一并取消,不可逆),`delete` 删除未持有的
2066
+ * 未读,`insert` 给自己追加一条消息。
2067
+ *
2068
+ * **每个动作都报 `unread` / `pending` / `held` 三个计数**(口径见 `snapshot`):只报一个数字
2069
+ * 会让「3 条在队列里等我」和「read 返回 0 条」看起来互相矛盾 —— 那只是两种口径的差别,
2070
+ * 三个计数只改报告,不改可见范围。
2071
+ *
2072
+ * 只读本地队列,不触达工作区;`checkPermission` 恒 `allow`(deny 模式也注册)。
2073
+ * 返回 JSON 字符串;非法参数返回 `{ error: 'invalid_input: ...' }`,不抛错。
2074
+ */
2075
+ export function createInboxTool(options: {
2076
+ inbox: AgentInboxPort;
2077
+ agentId: string;
2078
+ }): ToolDefinition {
2079
+ /**
2080
+ * 三个计数 + 摘要列表的**唯一读取口**(read / list / insert 共用一份,免得三个动作各报
2081
+ * 一套数)。一次读盘同时给出计数与列表,不想用列表的动作解构掉即可。
2082
+ *
2083
+ * `unread` / `pending` 直接取 `inbox.list` 的 `counts()` 口径(与 notice 那条计数行同源);
2084
+ * `held` 在工具层由同一份 `includeHeld:true` 的列表数出来 —— 它多出来的信息只有一个:
2085
+ * 「held 里有多少条不是 unread」。今天恒等于 `pending`(`hold` 只作用于未消费消息,
2086
+ * 消费即解 hold),但这两个数字在**报告**里分开摆,才会在口径哪天变了时自己露馅,
2087
+ * 而不是让模型以为 `pending` 就是全部 held。
2088
+ */
2089
+ const snapshot = () => {
2090
+ const { unread, pending, messages } = options.inbox.list(options.agentId, {
2091
+ includeHeld: true,
2092
+ });
2093
+ let held = 0;
2094
+ for (const message of messages) if (message.held) held += 1;
2095
+ return { unread, pending, held, messages };
2096
+ };
2097
+
2098
+ return {
2099
+ name: 'inbox',
2100
+ description: INBOX_TOOL_DESCRIPTION,
2101
+ inputSchema: {
2102
+ type: 'object',
2103
+ properties: {
2104
+ // 0.55:`claim` 不在枚举里 —— 它已经并进 `read`。老会话仍发它时按别名执行
2105
+ // (见 handler 的 legacy 分支),但模型看得到的契约只有这四个动作。
2106
+ action: {
2107
+ type: 'string',
2108
+ enum: ['list', 'read', 'delete', 'insert'],
2109
+ description: 'Default list',
2110
+ },
2111
+ ids: {
2112
+ type: 'array',
2113
+ items: { type: 'string' },
2114
+ description: 'read/delete: ids returned by list',
2115
+ },
2116
+ // 只为兼容 0.51 会话保留形状说明;新会话不该用它(read 用 `ids`)。
2117
+ message_ids: {
2118
+ type: 'array',
2119
+ items: { type: 'string' },
2120
+ description: "legacy only: same as `ids` for the old action:'claim' (use read + ids)",
2121
+ },
2122
+ limit: {
2123
+ type: 'integer',
2124
+ minimum: 1,
2125
+ description:
2126
+ 'read: max messages when ids omitted (default 3; takes the newest ones, returned oldest-first)',
2127
+ },
2128
+ content: {
2129
+ type: 'string',
2130
+ description: 'insert: message text (non-empty)',
2131
+ },
2132
+ },
2133
+ },
2134
+ async handler(args, ctx: ToolContext): Promise<string> {
2135
+ const input = isRecordValue(args) ? args : {};
2136
+ // 零参 peek 范式(对齐 skills/recall):缺省 action = list,只读计数不消费。
2137
+ const action = input.action ?? 'list';
2138
+ // 0.55 兼容:`claim` 已并入 `read`。老会话(0.51 的模型契约)还会发它 —— 认作
2139
+ // `read` 的别名执行同一套语义(取正文 + 消费 + 取消 queued run),结果里附一行
2140
+ // `note` 指路。不报错(意图本来就一致),也不静默(模型得知道契约变了)。
2141
+ const legacyClaim = action === 'claim';
2142
+ if (
2143
+ action !== 'list' &&
2144
+ action !== 'read' &&
2145
+ action !== 'delete' &&
2146
+ action !== 'insert' &&
2147
+ !legacyClaim
2148
+ ) {
2149
+ return invalidInput('action must be "list", "read", "delete", or "insert"');
2150
+ }
2151
+ const contentDefined = input.content !== undefined;
2152
+ const idsDefined = input.ids !== undefined;
2153
+ const messageIdsDefined = input.message_ids !== undefined;
2154
+ const limitDefined = input.limit !== undefined;
2155
+ // `includeHeld`(0.55 删除):read 现在天然含 held,这个开关没有第二个语义了。
2156
+ // 老会话带上它时**容忍并忽略**(真按旧语义执行会更糟:把正文吐出来却不拿走);
2157
+ // 不再当非法输入拒绝,也不在结果里复述。
2158
+
2159
+ if (action === 'list') {
2160
+ if (idsDefined || limitDefined || contentDefined) {
2161
+ return invalidInput('list does not accept ids, limit, or content');
2162
+ }
2163
+ if (messageIdsDefined) return invalidInput('list does not accept message_ids');
2164
+ const { unread, pending, held, messages } = snapshot();
2165
+ // 0.55:只给前缀 —— 列表是「决定读哪条」的地方,不是读正文的地方。正文全摊出来
2166
+ // 就等于让模型以为自己读过了,然后既不 read 也不处理。
2167
+ return JSON.stringify({
2168
+ unread,
2169
+ pending,
2170
+ held,
2171
+ messages: messages.map((message) => {
2172
+ const { preview, more_chars } = listPreview(message);
2173
+ return {
2174
+ id: message.id,
2175
+ ts: message.ts,
2176
+ source: message.source,
2177
+ preview,
2178
+ more_chars,
2179
+ held: message.held,
2180
+ // 求救标记(additive):读取前就能认出「这是某 agent 的遇难求救」。
2181
+ ...(message.distress === true ? { distress: true } : {}),
2182
+ };
2183
+ }),
2184
+ });
2185
+ }
2186
+
2187
+ if (action === 'insert') {
2188
+ if (idsDefined) return invalidInput('insert does not accept ids');
2189
+ if (messageIdsDefined) return invalidInput('insert does not accept message_ids');
2190
+ if (limitDefined) return invalidInput('insert does not accept limit');
2191
+ if (input.id !== undefined || input.source !== undefined || input.ts !== undefined) {
2192
+ return invalidInput('insert does not accept id, source, or ts');
2193
+ }
2194
+ if (typeof input.content !== 'string' || input.content === '') {
2195
+ return invalidInput('insert requires non-empty content');
2196
+ }
2197
+ const id = randomUUID();
2198
+ const ts = Date.now();
2199
+ const appended = options.inbox.append(
2200
+ options.agentId,
2201
+ { id, ts, source: options.agentId, text: input.content },
2202
+ // quiet:自述只落自己的 inbox —— 不唤醒、不成为 run input;全满时显式拒绝。
2203
+ // piiScope:自述条目无归属字段,落盘遮蔽用当前会话(读回时同会话句柄可解)。
2204
+ { delivery: 'quiet', rejectWhenFull: true, piiScope: ctx.session_id },
2205
+ );
2206
+ await options.inbox.flush();
2207
+ if (!appended.accepted) {
2208
+ return JSON.stringify({
2209
+ inserted: false,
2210
+ error: appended.reason === 'unavailable' ? 'inbox_unavailable' : 'inbox_full',
2211
+ });
2212
+ }
2213
+ const { unread, pending, held } = snapshot();
2214
+ return JSON.stringify({ inserted: true, id, ts, unread, pending, held });
2215
+ }
2216
+
2217
+ let ids: readonly string[] | undefined;
2218
+ if (idsDefined) {
2219
+ if (
2220
+ !Array.isArray(input.ids) ||
2221
+ !input.ids.every((id): id is string => typeof id === 'string' && id !== '')
2222
+ ) {
2223
+ return invalidInput('ids must be an array of non-empty strings');
2224
+ }
2225
+ ids = input.ids;
2226
+ }
2227
+ let messageIds: readonly string[] | undefined;
2228
+ if (messageIdsDefined) {
2229
+ if (
2230
+ !Array.isArray(input.message_ids) ||
2231
+ !input.message_ids.every((id): id is string => typeof id === 'string' && id !== '')
2232
+ ) {
2233
+ return invalidInput('message_ids must be an array of non-empty strings');
2234
+ }
2235
+ messageIds = input.message_ids;
2236
+ }
2237
+ let limit: number | undefined;
2238
+ if (limitDefined) {
2239
+ if (typeof input.limit !== 'number' || !Number.isInteger(input.limit) || input.limit < 1) {
2240
+ return invalidInput('limit must be a positive integer');
2241
+ }
2242
+ limit = input.limit;
2243
+ }
2244
+
2245
+ if (action === 'delete') {
2246
+ if (limitDefined) return invalidInput('delete does not accept limit');
2247
+ if (contentDefined) return invalidInput('delete does not accept content');
2248
+ if (messageIdsDefined) return invalidInput('delete takes ids, not message_ids');
2249
+ if (ids === undefined || ids.length === 0) {
2250
+ return invalidInput('delete requires a non-empty ids array');
2251
+ }
2252
+ const { deleted, skipped } = options.inbox.discard(options.agentId, ids, {
2253
+ onlyUnheld: true,
2254
+ });
2255
+ return JSON.stringify({ deleted: deleted.length, skipped });
2256
+ }
2257
+
2258
+ // ─── read(0.55:取正文 = 拿走)──────────────────────────────────
2259
+ if (contentDefined) return invalidInput('read does not accept content');
2260
+ let readIds = ids;
2261
+ if (legacyClaim) {
2262
+ // 老会话的 `claim` 用 `message_ids`;两种形状都给时以 message_ids 为准(那才是
2263
+ // 老动作的正式字段),单给 `ids` 也认 —— 兼容优先于挑剔。
2264
+ if (limitDefined) return invalidInput('read does not accept limit with claim');
2265
+ readIds = messageIds ?? ids;
2266
+ if (readIds === undefined || readIds.length === 0) {
2267
+ return invalidInput('read requires a non-empty ids array');
2268
+ }
2269
+ } else if (messageIdsDefined) {
2270
+ return invalidInput('read takes ids, not message_ids');
2271
+ }
2272
+ // `includeHeld: true` 是**恒真**的取值:read 连 held 一起取(这是本动作的定义,
2273
+ // 不是选项)。存储层仍保留该形参(插件端口 `MemberInboxPort.read` 还在用它做
2274
+ // 只读 peek),工具面不再暴露。
2275
+ const read = await options.inbox.read(
2276
+ options.agentId,
2277
+ {
2278
+ ...(readIds !== undefined ? { ids: readIds } : {}),
2279
+ ...(limit !== undefined ? { limit } : {}),
2280
+ includeHeld: true,
2281
+ },
2282
+ ctx.session_id,
2283
+ );
2284
+ // held 的那几条:存储层 read 只吐正文、不消费 held(它拦不住已排程的那次投递)。
2285
+ // 要真的「拿走」,必须走 `AgentService.claim` 的同一条前置收口 —— 本层 `claim`
2286
+ // 构造时注入的 `beforeClaim`(= service 的 `withdrawQueuedRuns`:取消 queued run
2287
+ // + 从 mailbox 出队),再落同一个 `consume`。不许绕开:只标 consumed 的那次 run
2288
+ // 照样会把它当 run input 投一遍,等于「读到了还会再来一次」。
2289
+ const heldIds = read.filter((message) => message.held).map((message) => message.id);
2290
+ let deliveryCancelled = 0;
2291
+ if (heldIds.length > 0) {
2292
+ const claimed = await options.inbox.claim(options.agentId, heldIds, ctx.session_id);
2293
+ deliveryCancelled = claimed.claimed.length;
2294
+ // 不可逆的写:先落盘再回话,否则崩溃/重启后它照样会投递一次。
2295
+ await options.inbox.flush();
2296
+ }
2297
+ // 计数必须在取走**之后**读:先数再拿会把刚读掉的还标在 unread / pending 里。
2298
+ const { unread, pending, held } = snapshot();
2299
+ return JSON.stringify({
2300
+ read: read.length,
2301
+ // 这次顺手取消了几个「已排程的下一轮输入」—— 模型该知道这几条不会自己再来了。
2302
+ ...(deliveryCancelled > 0 ? { delivery_cancelled: deliveryCancelled } : {}),
2303
+ unread,
2304
+ pending,
2305
+ held,
2306
+ messages: read.map((message) => ({
2307
+ id: message.id,
2308
+ ts: message.ts,
2309
+ source: message.source,
2310
+ // q-pii-redaction-unify:磁盘句柄属于存储作用域;消费会话不同(rotate
2311
+ // 后新 body read)时先翻译回真值,工具结果过 append 闸重新句柄化。
2312
+ // 同会话 ⇒ 原样(句柄已知,闸幂等)。死句柄原样保留(下游报 expired)。
2313
+ text: rescopeInboxText(message.text, inboxStorageScopeOf(message), ctx.session_id),
2314
+ // 求救标记(additive):与正文一并交出,模型据此知道这是遇难求救。
2315
+ ...(message.distress === true ? { distress: true } : {}),
2316
+ // 附件引用随正文一并交出(与直接投递同口径):丢了它,带图消息经 inbox
2317
+ // 取走后模型就不知道有附件 —— 存储里有 refs 也等于没有。无附件时字段不出现,
2318
+ // 旧结果形状逐字节不变(Web inbox-read 投影只认 id/text/source,additive 安全)。
2319
+ ...(message.refs !== undefined && message.refs.length > 0 ? { refs: message.refs } : {}),
2320
+ })),
2321
+ ...(legacyClaim
2322
+ ? {
2323
+ note:
2324
+ "action:'claim' has been merged into 'read' (0.55): read now returns the full text and " +
2325
+ 'takes the message — held/pending ones included, their queued run cancelled. use ' +
2326
+ "action:'read' with ids next time.",
2327
+ }
2328
+ : {}),
2329
+ });
2330
+ },
2331
+ async checkPermission(): Promise<'allow'> {
2332
+ return 'allow';
2333
+ },
2334
+ };
2335
+ }