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

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/runtime.ts ADDED
@@ -0,0 +1,2501 @@
1
+ /**
2
+ * 进程内成员执行内核适配(MemberExecutionPort)。
3
+ *
4
+ * 每个成员独占一个 ExecutionUnit / Context / EventStream;工具从父 PluginHost
5
+ * **全量复制**(0.51:节点有什么就给什么,只减 deny 档的只读集合与「需要人类应答但没有
6
+ * bridge」这一条,见 `toolBlocked`),hooks / guardrails 一并继承。
7
+ * `permissionMode: 'bridge'` 时
8
+ * 成员的权限/提问请求转发到 `parentEvents`,父级应答原样回灌成员事件流;
9
+ * 没有 `parentEvents` 时退化为 ask → deny(A3a 行为),避免 run 永久等待。
10
+ *
11
+ * @module @vessel-agent/agent
12
+ */
13
+
14
+ import { randomUUID } from 'node:crypto';
15
+ import {
16
+ type EnvInjectionConfig,
17
+ finestCadence,
18
+ resolveEnvCadence,
19
+ resolveEnvChannel,
20
+ type TeamPermissionPolicy,
21
+ } from '@vessel-agent/config';
22
+ import {
23
+ CORE_NOTICE_PRODUCER,
24
+ type CompactionReport,
25
+ type ContextAnchor,
26
+ type ContextSummarizer,
27
+ DEFAULT_COMPACT_THRESHOLD,
28
+ type EventStream,
29
+ type ExecutionUnitOptions,
30
+ type LeaseGrant,
31
+ type Logger,
32
+ type MemberBodyContribution,
33
+ type MemberBodyNoticeEvent,
34
+ type MemberBodyPort,
35
+ MemoryEventStream,
36
+ MemoryPluginHost,
37
+ MemoryWorkingContext,
38
+ type Message,
39
+ noopLogger,
40
+ type PluginHost,
41
+ type RunEvent,
42
+ type RunInterruptReason,
43
+ type RunnableAgent,
44
+ type RunOptions,
45
+ type RunRecord,
46
+ type Runtime,
47
+ type RuntimePermissionConfig,
48
+ type SelfCardOptions,
49
+ type SessionState,
50
+ type SessionTitleSource,
51
+ type TerminationPolicy,
52
+ type ToolDefinition,
53
+ type ToolResultWhitelistRule,
54
+ type Usage,
55
+ type UsageLimits,
56
+ type WorkingContext,
57
+ } from '@vessel-agent/core';
58
+ import { type AddressStyle, DEFAULT_ADDRESS_STYLE, formatAddress } from './address-display.js';
59
+ import { type AgentInboxPort, createInboxNoticeHook, createInboxTool } from './inbox.js';
60
+ import { resolveMemberCwd } from './member-cwd.js';
61
+ import { buildMemberBodyPorts } from './member-ports.js';
62
+ import {
63
+ createSelfCardDeltaHook,
64
+ SELF_CARD_SCOPES,
65
+ selfCardIdentityOf,
66
+ } from './self-card-delta.js';
67
+ import { HUMAN_PRINCIPAL, SYSTEM_PRINCIPAL } from './team-address.js';
68
+ import type {
69
+ AgentMessage,
70
+ AgentRole,
71
+ MemberExecutionMember,
72
+ MemberExecutionPort,
73
+ MemberPermissionState,
74
+ MemberToolEntry,
75
+ MemberTurnResult,
76
+ } from './types.js';
77
+
78
+ /*
79
+ * 成员工具面 = **节点全量**(0.51 权限模型变更,用户裁定)。
80
+ *
81
+ * 工具面共有 **4 层闸门**,这里只是「成员选择」这一层。改工具面前先看清改的是哪层:
82
+ * 1. 本文件 —— 成员能从父宿主挑哪些(**父宿主注册了什么就给什么**;只剩两条真实闸:
83
+ * deny 档收成只读集合、`ask` 这类需要父级应答的工具要求 bridge)
84
+ * 2. `packages/config/src/tenant-tools.ts` —— tenant 级 allow/deny(**注册侧**)
85
+ * 3. `packages/core/src/runtime/permission-policy.ts` —— 单次调用放行(allow/ask/deny)
86
+ * 4. `src/permission-store.ts` —— `autoApprove` / `neverAutoApprove`(是否跳过审批)
87
+ *
88
+ * 为什么不再有白名单(0.51 之前是 `bash`/`read`/`edit`/`agent` 四件套):白名单要求
89
+ * 「节点上每加一个工具就要记得在这里加一条」,漏加是**静默**的能力缺失(`ask` 就这样
90
+ * 丢过一次 —— 注册侧加了、选择侧不认、且不报错,见 `docs/lessons/L-011`)。用户裁定
91
+ * 「节点有的 agent 都可以用,现在不做 agent 细分,所以也不需要白名单」,判据因此变成
92
+ * 「父宿主有什么就给什么」:注册侧是唯一的能力声明,本层没有任何按工具名的清单,
93
+ * 只留两条例外规则(deny 只读档、`ask` 缺 bridge)。
94
+ *
95
+ * **安全影响是明知故犯,不是隐式默认**:成员现在能拿到节点插件面里的一切 —— 含插件
96
+ * 工具与 MCP 动态注册的外部工具 —— 并且装配侧的 `withMemberAutoApprove` 会给成员免确认
97
+ * `agent`(bridge 档的其余工具仍按 `permission` 逐次确认)。这由用户在 0.51 明确接受
98
+ * (「全部放开(含 MCP 动态工具),接受成员自动放行」)。要收紧就收紧**注册侧**
99
+ * (#2 tenant allow/deny)或权限策略(#3/#4),不要在下面重新长出一份白名单。
100
+ */
101
+
102
+ /**
103
+ * deny(只读)档保留的工具:用户点名的这三件(`read` + `media` + `subscribe`)。
104
+ *
105
+ * 注意 `subscribe` 是按**工具**粒度给的:它的 `add` / `remove` 会改会话订阅状态,这里
106
+ * 给的就是整个工具。用户知情的取舍 —— 只读档要能把「订阅了什么」读出来、能订阅后再读,
107
+ * 代价是 deny 档下仍可增删订阅(不改工作区文件,只改本会话的订阅表)。
108
+ */
109
+ const DEFAULT_READ_ONLY_TOOLS = ['read', 'media', 'subscribe'] as const;
110
+
111
+ /**
112
+ * 需要父级(有人类应答者)转发才能收口的工具。
113
+ *
114
+ * 这些工具通过事件流发布请求并等待应答;成员 ExecutionUnit 只有 bridge 才能把请求送到
115
+ * 父事件流。没有 bridge / 父流时注册进来只会让 run 永久等待,因此不放行。
116
+ *
117
+ * `ask` 是现行工具名;`ask_user` 是它的历史名(0.52 前)—— 双认,免得旧装配 / 旧插件
118
+ * 注册的旧名工具绕过闸门、让成员 run 永久等待。
119
+ */
120
+ const PARENT_ANSWERED_TOOL_NAMES: ReadonlySet<string> = new Set(['ask', 'ask_user']);
121
+
122
+ /** 缺省终止策略:不设累计上限(交互 run 靠自动压缩、模型自然停止与用户中断收口) */
123
+ const DEFAULT_TERMINATION: TerminationPolicy = {};
124
+
125
+ /** 缺省上下文预算 */
126
+ const DEFAULT_CONTEXT_MAX_TOKENS = 1_000_000;
127
+
128
+ /**
129
+ * 成员 ExecutionUnit 恒定免确认的工具:`agent` 工具只允许成员操作自己(rotate)/ 可见 roster
130
+ * / 自有 contractor,close 的审批由工具 `checkPermission` 与 `neverAutoApprove`
131
+ * (`agent.close`)决定。owner 同源规则在热应用时会整体替换,这里每次应用前补回。
132
+ */
133
+ function withMemberAutoApprove(rules: RuntimePermissionConfig): RuntimePermissionConfig {
134
+ return {
135
+ ...rules,
136
+ autoApprove: [...new Set([...(rules.autoApprove ?? []), 'agent'])],
137
+ };
138
+ }
139
+
140
+ /** 未 spawn 成员的待注入 notice 上限(按成员条数 / 成员数双边界) */
141
+ const MAX_PENDING_NOTICES = 20;
142
+ const MAX_PENDING_NOTICE_MEMBERS = 100;
143
+
144
+ /**
145
+ * 按角色包装 per-body `WorkingContext`:**自动压缩开关可在活体上热切换**。
146
+ *
147
+ * 为什么不是 spawn 时直接把 `autoCompact` 交给 core(0.28 之前的做法):那是构造期
148
+ * 配置,没有 setter。转正(`temporary → member`)要求「同一具 live body 不重建,
149
+ * 但下一次 run 按新身份生效」,于是开关必须能在活体上翻转(契约 §5 / D6)。
150
+ *
151
+ * 分层不变:本类只接收**裸参数**(一个布尔),不认 `role`;角色语义仍留在本文件的
152
+ * spawn(`role === 'temporary'`)与 `applyContextPolicy`。本类只使用 `WorkingContext`
153
+ * 接口上已有的方法,core 不知道这里存在。
154
+ *
155
+ * 内层 `MemoryWorkingContext` 恒以 `autoCompact: false` 构造,原因有两条:
156
+ * - 真要把开关交给本类,内层就不能自己按阈值压缩(否则 `add()` 会绕过本类的开关,
157
+ * 也就是 temporary 会在 `add()` 里被压缩 —— 正是契约禁止的);
158
+ * - 内层仍负责**硬兜底**:消息条数上限的摘要与移除在 `add()` 里独立于 `autoCompact`。
159
+ *
160
+ * 因此压缩时机从「`add()` 时」挪到「请求组装前」,这是本包装唯一的可观测差异:
161
+ * 同一轮内水位到阈值时,压缩发生在下一次请求之前而不是写入那一刻。结果一致,
162
+ * 且这正是 core 在有 summarizer 时走的既有路径。
163
+ */
164
+ class RoleAwareContext implements WorkingContext {
165
+ /** 自动压缩是否开启;`setAutoCompact` 是唯一的写入口。 */
166
+ private compacting: boolean;
167
+
168
+ constructor(
169
+ private readonly inner: MemoryWorkingContext,
170
+ autoCompact: boolean,
171
+ ) {
172
+ this.compacting = autoCompact;
173
+ }
174
+
175
+ /** 热切换自动压缩;返回是否真的变了(调用方据此决定要不要提示)。 */
176
+ setAutoCompact(next: boolean): boolean {
177
+ if (this.compacting === next) return false;
178
+ this.compacting = next;
179
+ return true;
180
+ }
181
+
182
+ /** 当前开关(供装配层 / 探针直接读)。 */
183
+ get enabled(): boolean {
184
+ return this.compacting;
185
+ }
186
+
187
+ add(msg: Message): void {
188
+ this.inner.add(msg);
189
+ }
190
+
191
+ get messages(): Message[] {
192
+ return this.inner.messages;
193
+ }
194
+
195
+ compact(): number {
196
+ return this.inner.compact();
197
+ }
198
+
199
+ /**
200
+ * 手动 / overflow 压缩入口,**原样透传**(`compactAsync()` 的 `force` 缺省为 true,
201
+ * 与 core 一致):调用方是 `compactContext` / `forceCompact`,包装不得改写强制语义。
202
+ */
203
+ compactAsync(): Promise<number> {
204
+ return this.inner.compactAsync();
205
+ }
206
+
207
+ /**
208
+ * 主动压缩。关闭时返回 0 —— **硬兜底不经过这里**:消息条数上限由内层 `add()`
209
+ * 处理,provider overflow 由 runtime 的 `forceCompact`(`compactAsync`)处理。
210
+ * 「不主动压缩」≠「绝不压缩」(契约 §5)。
211
+ *
212
+ * 开启时自己判阈值:内层的 `autoCompact` 恒为 false,所以不能委派
213
+ * `inner.autoCompactAsync()`(那会恒返回 0)。判完再走 `inner.compactAsync(false)`,
214
+ * 摘要器 / 并发去重 / 应用逻辑仍然只有 core 一份。
215
+ *
216
+ * **`false` 不是笔误**:core 的 `autoCompactAsync` 也是 `compactAsync(false)`
217
+ * (`context-manager.ts:205`)—— 非强制模式按 token 预算保留最近的尾部消息;
218
+ * 传 `true` 会「至少摘要到只剩 2 条」,比设计意图激进得多。
219
+ */
220
+ async autoCompactAsync(): Promise<number> {
221
+ if (!this.compacting) return 0;
222
+ const max = this.inner.maxTokens;
223
+ if (max !== undefined && max > 0) {
224
+ // 唯一真相源:内层 `WorkingContext.compactThreshold`(应用层由 config 注入,
225
+ // core 未配置时兜底 0.85 —— 与 CONTRACT-0.34-context C5 一致)。
226
+ const threshold = this.inner.compactThreshold ?? DEFAULT_COMPACT_THRESHOLD;
227
+ if (this.inner.tokenCount <= max * threshold) return 0;
228
+ }
229
+ return this.inner.compactAsync(false);
230
+ }
231
+
232
+ /**
233
+ * q-arch-p0-fixes ctx-F1:**转发最近一次压缩报告**。
234
+ *
235
+ * `WorkingContext.lastCompaction` 在接口里是可选的 —— 少实现它不报错,只会让
236
+ * runtime 侧(`execution-unit.ts` 的 `publishCompacted` / `buildCompactionEntry` /
237
+ * `publishUntrackedCompaction`)拿到 `undefined`:成员会话的压缩索引
238
+ * `removed_indices` 恒空 ⇒ `removed_ranges` 恒空、全部记 `unmapped_messages`,
239
+ * recall 按 seq 读回原文的承诺静默落空(owner 直连 `MemoryWorkingContext` 不受影响)。
240
+ * 与 `setContextAnchor` 同一类坑:可选成员被包装层吃掉,新增转发时一并检查。
241
+ */
242
+ get lastCompaction(): CompactionReport | undefined {
243
+ return this.inner.lastCompaction;
244
+ }
245
+
246
+ /**
247
+ * 0.56:**转发锚点注入**。
248
+ *
249
+ * 缺这一行时,内层窗口永远拿不到按会话落盘的锚点,于是 `estimatedUpperTokens` 恒按
250
+ * `NO_ANCHOR_SAFETY_MARGIN`(×1.15)高报 —— 结果是「判据说超预算、账本说没超」,
251
+ * 重启后(锚点一度丢失)就会触发一次**不该发生的 compaction**,766 条消息被摘要替换、
252
+ * 模型再也看不到(ctx-drop 单的真实事故:−41% 请求体积)。
253
+ *
254
+ * `WorkingContext.setContextAnchor` 在接口里是**可选**的,所以少实现它不会报错,
255
+ * 只会安静地丢掉这个校正 —— 这类「可选成员被包装层吃掉」的坑,新增包装层时要一并检查。
256
+ */
257
+ setContextAnchor(anchor: ContextAnchor | undefined, model?: string): void {
258
+ this.inner.setContextAnchor?.(anchor, model);
259
+ }
260
+
261
+ get contextAnchor(): ContextAnchor | undefined {
262
+ return this.inner.contextAnchor;
263
+ }
264
+
265
+ clear(): void {
266
+ this.inner.clear();
267
+ }
268
+
269
+ get tokenCount(): number {
270
+ return this.inner.tokenCount;
271
+ }
272
+
273
+ get maxTokens(): number | undefined {
274
+ return this.inner.maxTokens;
275
+ }
276
+
277
+ /**
278
+ * 必须返回**当前**开关:runtime 用它决定压力提示的上界(`agent-runtime.ts:1673`)。
279
+ * 返回固定的 false 会让转正后 0.9 以上的提示继续发;返回固定的 true 会让
280
+ * temporary 的提示在 0.9 以上静默 —— 两边都是契约 §5 明禁的静默。
281
+ */
282
+ get autoCompact(): boolean {
283
+ return this.compacting;
284
+ }
285
+
286
+ setSessionId(sessionId: string): void {
287
+ this.inner.setSessionId(sessionId);
288
+ }
289
+
290
+ getSessionId(): string {
291
+ return this.inner.getSessionId();
292
+ }
293
+
294
+ updateRealTokens(total: number): void {
295
+ this.inner.updateRealTokens(total);
296
+ }
297
+ }
298
+
299
+ /** temporary 的压力提示(与 0.28 前的文案逐字一致)。 */
300
+ const TEMPORARY_PRESSURE_HINT =
301
+ 'Report what is done and what remains, then ask the user to start a new ' +
302
+ 'session or compact the context; this member does not compact automatically.';
303
+
304
+ /**
305
+ * 角色 → 上下文策略(**唯一**映射点)。
306
+ *
307
+ * 只这里是 `role` 的消费者:core 不认 role(契约 §5),spawn 与热切换都从这里取
308
+ * 同一份策略,所以「转正后下一次 run 用的策略」与「转正那天新建 body 会用的策略」
309
+ * 结构上不可能漂移。
310
+ */
311
+ interface ContextPolicy {
312
+ /** 是否主动按阈值压缩 */
313
+ autoCompact: boolean;
314
+ /** 压力提示尾句;缺省 = core 的 `agent(rotate)` 原文案 */
315
+ pressureHint?: string;
316
+ }
317
+
318
+ function contextPolicyFor(role: AgentRole): ContextPolicy {
319
+ if (role === 'temporary') {
320
+ // rotate 对 temporary 不禁用(D6):换 body 仍是合法出路。文案只换成
321
+ // 「上报状态 / 请用户手动切上下文」,因为临时会话的收尾由用户决定。
322
+ return { autoCompact: false, pressureHint: TEMPORARY_PRESSURE_HINT };
323
+ }
324
+ return { autoCompact: true };
325
+ }
326
+
327
+ /** 身份变更 notice 的上下文消息形状(与 core appendNotice 一致) */
328
+ function noticeMessage(text: string, timestamp?: number): Message {
329
+ return {
330
+ role: 'user',
331
+ name: 'vessel:notice',
332
+ // 装配层自产纯状态卡(身份变更 / 启动恢复提示):与 core appendNotice 同一
333
+ // 生产者白名单,append 侧豁免脱敏(q-pii-redaction-unify)。
334
+ notice_producer: CORE_NOTICE_PRODUCER,
335
+ content: text,
336
+ timestamp: timestamp ?? Date.now(),
337
+ };
338
+ }
339
+
340
+ /**
341
+ * 待注入 notice。
342
+ *
343
+ * `timestamp` 是这段环境信息的**产生时刻**(0.52 S1c:启动恢复卡在启动时就产生,
344
+ * 要早于它之后被放行的那条输入所在的 run);缺省就用注入时刻,与既有行为一致。
345
+ */
346
+ interface PendingNotice {
347
+ text: string;
348
+ timestamp?: number;
349
+ }
350
+
351
+ /** 成员权限模式;bridge 把交互请求转到父事件流,缺省 allow */
352
+ export type MemberExecutionPermissionMode = 'allow' | 'deny' | 'bridge';
353
+
354
+ /** 需要父级应答的交互请求事件 */
355
+ const PERMISSION_REQUEST_EVENTS: ReadonlySet<string> = new Set([
356
+ 'tool.permission.request',
357
+ 'ask.user.requested',
358
+ ]);
359
+
360
+ /** 父级发回的交互应答事件 */
361
+ const PERMISSION_RESPONSE_EVENTS: ReadonlySet<string> = new Set([
362
+ 'tool.permission.response',
363
+ 'ask.user.answered',
364
+ ]);
365
+
366
+ /** run 终态事件:并入父流时补成员归属(TeamService / TUI 都读 data.agent_id) */
367
+ const RUN_TERMINAL_EVENTS: ReadonlySet<string> = new Set([
368
+ 'run.completed',
369
+ 'run.failed',
370
+ 'run.cancelled',
371
+ ]);
372
+
373
+ /** bridge 内待答请求;deny-after 只挂在有 parentEvents 的桥上 */
374
+ interface PendingBridgeRequest {
375
+ kind: 'permission' | 'ask';
376
+ timer?: ReturnType<typeof setTimeout>;
377
+ }
378
+
379
+ /**
380
+ * 成员 runtime 额外需要的中断能力(ExecutionUnit 已实现)。
381
+ *
382
+ * `resumeRun` 用 `RunRecord` 而非公开门面的 `runId`(Stage 4):调用方
383
+ * (AgentService)先经 RunRecordStore 加载记录,再委托到这里。因此这里用
384
+ * `Omit` 摘掉 `RunnableAgent` 的 runId 签名,避免两条恢复语义并存。
385
+ */
386
+ export interface MemberRunnableAgent extends Omit<RunnableAgent, 'resumeRun'> {
387
+ /** Stage 4:用已加载的 RunRecord 恢复同一 run(ExecutionUnit 已实现)。 */
388
+ resumeRun?(record: RunRecord, opts?: RunOptions): Promise<string>;
389
+ /** Stage 4:上一 Run 结束时的上下文水位;无 active Run 时供 host 读取。 */
390
+ lastContextRatio?: number;
391
+ interrupt?(reason?: RunInterruptReason): void;
392
+ /** Stage 3:当前 session 有效 SessionLease 的 fencingToken(ExecutionUnit 已实现)。 */
393
+ sessionLeaseToken?(sessionId: string): number | undefined;
394
+ /** Stage 3:seeded create / restart 预取新 primary 的 SessionLease(ExecutionUnit 已实现)。 */
395
+ ensureSessionLease?(sessionId: string, minFence?: number): Promise<LeaseGrant | undefined>;
396
+ /** 只追加上下文,不启动 turn(ExecutionUnit 已实现) */
397
+ appendNotice?(text: string): void;
398
+ /**
399
+ * 0.28(additive):热应用上下文策略,下一轮请求生效(`ExecutionUnit` 已实现)。
400
+ * 只用于压力提示尾句;自动压缩开关由 `RoleAwareContext` 承担。
401
+ */
402
+ applyContextPolicy?(policy: { contextPressureHint?: string }): void;
403
+ }
404
+
405
+ /** 进程内成员执行宿主选项 */
406
+ export interface MemberExecutionHostOptions {
407
+ /**
408
+ * Stage 4:per-node Runtime(必填)。成员的 ExecutionUnit 一律经
409
+ * `getOrCreateExecutionUnit` 取得,不再在 host 内直接构造。
410
+ */
411
+ runtime: Runtime;
412
+ /**
413
+ * 成员未指定 model 时的宿主缺省 **ref**(第 6 修:条目键 / legacy 透传 ref,
414
+ * 不是 wire 名);spawn 继承经 resolveModelRef 解析。两者都缺省时 spawn 失败。
415
+ */
416
+ model?: string;
417
+ /**
418
+ * 宿主缺省的展示 wire 名(selfCard / delta 真值盒用;与缺省 ref 分离)。
419
+ * 缺省回落 model 原值(mock / 未注入装配层与旧行为字节等价)。
420
+ */
421
+ modelWire?: string;
422
+ /** 工具 / hooks / guardrails 的来源(父宿主);缺省时成员没有工具 */
423
+ pluginHost?: PluginHost;
424
+ /**
425
+ * deny(只读)档保留的工具名;缺省 `read` / `media` / `subscribe`。
426
+ *
427
+ * 给了就**整体替换**缺省集合(不是追加):这是「只读档到底给什么」的唯一开关。
428
+ */
429
+ readOnlyTools?: readonly string[];
430
+ /** 缺省 allow;deny 只保留只读工具;bridge 需配合 parentEvents */
431
+ permissionMode?: MemberExecutionPermissionMode;
432
+ /**
433
+ * 有 team_id 的成员强制 bridge(忽略全局 `allow`);缺省开启。
434
+ * 无 parentEvents 时仍走 fail-closed 的 ask → deny。
435
+ */
436
+ forceBridgeForTeams?: boolean;
437
+ /** 按成员所属 team 解析无人值守策略;只影响 bridge 内的 deny-after 定时器 */
438
+ permissionPolicy?: (teamId: string | undefined) => TeamPermissionPolicy | undefined;
439
+ /** allow / bridge 模式的权限配置(autoApprove / default / timeoutMs) */
440
+ permission?: RuntimePermissionConfig;
441
+ /**
442
+ * 父级事件流(owner)。bridge 模式下把成员的
443
+ * `tool.permission.request` / `ask.user.requested` 转发到这里,并订阅
444
+ * `tool.permission.response` / `ask.user.answered` 回灌成员事件流。
445
+ */
446
+ parentEvents?: EventStream;
447
+ /** bridge 模式下成员进入/离开权限等待时回调(入口层接 AgentService 状态) */
448
+ onPermissionState?: (memberId: string, sessionId: string, state: MemberPermissionState) => void;
449
+ /** 成员引擎事件回流(当前只转发 agent.limit.warning) */
450
+ onMemberEvent?: (memberId: string, sessionId: string, event: RunEvent) => void;
451
+ limits?: UsageLimits;
452
+ termination?: TerminationPolicy;
453
+ /** 上下文预算;同时写入 Self Card 的 context.max */
454
+ contextMaxTokens?: number;
455
+ /**
456
+ * 成员上下文的压缩阈值(0.34 S2 / C5)。装配层传入 `config.context.compactThreshold`;
457
+ * 缺省时内层 `MemoryWorkingContext` 用 core 兜底值。
458
+ */
459
+ contextCompactThreshold?: number;
460
+ /**
461
+ * 工具结果压缩白名单(q-tool-result-whitelist)。装配层传
462
+ * `config.context.toolResultWhitelist`;缺省不传 ⇒ 内层窗口走 core 内置默认
463
+ * (inbox read + agent read)。显式 [] ⇒ 关闭。构造期注入,重启生效。
464
+ */
465
+ contextToolResultWhitelist?: readonly ToolResultWhitelistRule[];
466
+ /**
467
+ * 环境信息注入节奏配置(YAML `env_injection`)。装配层传入 `config.envInjection`;
468
+ * self-card-delta hook 的 cadence 取 SELF_CARD_SCOPES(identity/model/context/tools,
469
+ * 派生 FIELD_SCOPE 值域)的最细值。
470
+ * 缺省 ⇒ 内置默认表(全 request)= 今天行为,零回归。
471
+ */
472
+ envInjection?: EnvInjectionConfig;
473
+ /**
474
+ * 活配置 env_injection getter(P2 热加载):self-card-delta hook 的 cadence / channel /
475
+ * scopeOff resolver 每请求求值 ⇒ 热改 env_injection 下一请求生效(live body 无需重 spawn)。
476
+ * 缺省 ⇒ 读 envInjection 快照(旧 caller 零回归)。
477
+ */
478
+ getEnvInjection?: () => EnvInjectionConfig | undefined;
479
+ /**
480
+ * 订阅静音查询(q-sub-unify-p2 M3a,设计 §4.3,additive):装配层注入静音镜像桥
481
+ * (session 键;source/target 拼注册表条目键)。inbox 计数 hook 的 isEnabled 组合
482
+ * `!isSourceMuted(bodySession,'inbox','*')`——静音不注入计数行,消息层投递不动。
483
+ * 缺省 ⇒ 恒不静音(旧 caller 零回归)。
484
+ */
485
+ isSourceMuted?: (sessionId: string, source: string, target: string) => boolean;
486
+ /** 成员上下文的真实摘要器;缺省时压缩退回占位摘要。 */
487
+ summarizer?: ContextSummarizer;
488
+ /**
489
+ * 0.34 S4 / R7:按 session 取带熔断的摘要器(与 owner 共享计数)。
490
+ * 缺省时回落到 `summarizer`。
491
+ */
492
+ summarizerForSession?: (sessionId: string) => ContextSummarizer;
493
+ /**
494
+ * 0.51:按成员解析 Team 基础路径(运行期兜底,`MemberRecord.cwd` 缺失时才用)。
495
+ *
496
+ * 为什么还要这一条:记录里的 cwd 是 create 那一刻的快照,老快照 / 手工写的记录没有它;
497
+ * 而 `team_id` 是持久化的,装配层拿 `teamStore.get(teamId)?.workspace` 就能重算。
498
+ * 实现方**必须自己排除锚点 Team**(装配层传 `anchorWorkspaces` 给 AgentService 的那份)。
499
+ */
500
+ cwdFor?: (member: MemberExecutionMember) => string | undefined;
501
+ /**
502
+ * 成员深度(Self Card **兜底**):`depthFor` 解析不出真值时才用(缺省 1)。
503
+ * depth-color D1 起 per-member 真值由 `depthFor` 提供(host 标量不再是唯一来源)。
504
+ */
505
+ depth?: number;
506
+ /**
507
+ * 按成员解析树深度(depth-color D1):装配层注入 `AgentService.memberDepth`
508
+ * (parent 链单一事实源,与卡片颜色同口径)。缺省 / 返回 undefined ⇒ 回落
509
+ * host `depth` 兜底(纯内存构造 / 老装配零回归)。与 `cwdFor` 同款运行期解析钩子。
510
+ */
511
+ depthFor?: (member: MemberExecutionMember) => number | undefined;
512
+ logger?: Logger;
513
+ tenantId?: string;
514
+ /**
515
+ * 本机 node id,只用于来源行(`<principal>@<node>:<team>`)。
516
+ *
517
+ * 必由装配层从 bootstrap 的 `resolveNodeIdentity()` 传入:那里是 nodeId 的唯一来源。
518
+ * 执行内核不调 `os.hostname()`、不读 config / node.json —— 逐条消息重算会与
519
+ * federation 端口用的 nodeId 漂移,而它本身是进程级常量。
520
+ *
521
+ * 缺省(纯内存构造 / 测试)时来源行退回两段 `principal@<team>`,不报错。
522
+ */
523
+ nodeId?: string;
524
+ /**
525
+ * 本机展示名(q-addr-display):来源行 node 段 name 档的渲染来源。
526
+ * 与 nodeId 同源(bootstrap `resolveNodeIdentity()`),装配期传一次。
527
+ * 缺省 / 字符集不安全时 node 段兜底短 id(`formatAddress` 兜底链)。
528
+ */
529
+ nodeName?: string;
530
+ /**
531
+ * 地址显示风格(q-addr-display;`ui.addressStyle`,装配层读 config 传入)。
532
+ * 缺省 name 优先。只影响来源行显示,路由地址(`to`)不受影响。
533
+ */
534
+ addressStyle?: AddressStyle;
535
+ includeReasoning?: boolean;
536
+ /** tenant SessionStore;同 session_id 可跨进程续接历史 */
537
+ session?: ExecutionUnitOptions['session'];
538
+ /** tenant 会话事件日志(唯一真相源;存在时成员事件同样落盘) */
539
+ eventLog?: ExecutionUnitOptions['eventLog'];
540
+ /**
541
+ * Stage 3:per-tenant 租约服务,透传给每个成员 ExecutionUnit(SessionLease)。
542
+ * 缺省时 EU 侧租约为 no-op。
543
+ */
544
+ leaseService?: ExecutionUnitOptions['leaseService'];
545
+ /**
546
+ * tools-engine P2 批次 3:inbox 逐 body 创建后的转发接线端口(装配层注入
547
+ * engine-client wireTool;成员身份在 handler 闭包,callback 经 pending 关联执行)。
548
+ * spawn 与工具热刷新都经 inboxTool() 触发;缺省 = 不接线(in-process 直执行)。
549
+ */
550
+ wireInboxTool?: (tool: ToolDefinition, memberId: string) => void;
551
+ }
552
+
553
+ interface MemberExecutionEntry {
554
+ runtime: MemberRunnableAgent;
555
+ /** 成员 id(entries 按 ExecutionUnit session 建键,notice 按成员 id 寻址) */
556
+ memberId: string;
557
+ /**
558
+ * 这具 body 的会话 id(= entries 的键)。
559
+ * 0.51:成员面端口要它 —— 端口是「一具 body 的端口」,`MemberBodyPort.sessionId` 与
560
+ * `read` 的消费归属(`consumed_by_session`)都得说清是哪一具,不能靠调用方另传。
561
+ */
562
+ sessionId: string;
563
+ /**
564
+ * per-body 上下文策略(可变):每次 Run 新建 `RoleAwareContext` 时读取;
565
+ * `applyContextPolicy` 只改这里,下一次 Run 自然生效(Stage 4 per-Run context)。
566
+ */
567
+ contextPolicy: { autoCompact: boolean };
568
+ /**
569
+ * body 独占工具宿主(spawn 时快照)。`refreshTools` 原地替换其中的定义,
570
+ * 不动 runtime / session / context / provider,下一轮请求即读到新工具面。
571
+ */
572
+ pluginHost: MemoryPluginHost;
573
+ /** spawn 时选定的权限模式;refreshTools 用它重新筛工具 */
574
+ mode: MemberExecutionPermissionMode;
575
+ /** 是否有在跑轮:工具热刷新只在轮边界应用(单 run + prompt prefix 冻结) */
576
+ running: boolean;
577
+ /** 在跑轮期间收到过 refreshTools:轮结束再应用 */
578
+ toolsRefreshPending: boolean;
579
+ /** pending 的工具来源(调用方显式传入的快照;缺省时轮结束再读父宿主) */
580
+ pendingTools?: readonly ToolDefinition[];
581
+ /** 是否已执行过 runTurn;未执行过的空上下文不能直接 appendNotice,否则会跳过历史恢复 */
582
+ started: boolean;
583
+ /** 成员独占事件流;bridge 请求/应答都经过它 */
584
+ events: MemoryEventStream;
585
+ /** bridge 订阅取消函数(dispose 时回收) */
586
+ unsubscribers: Array<() => void>;
587
+ /** 已转发给父级、尚未应答的 requestId;deny-after 的 deadline 随条目清理 */
588
+ pendingPermissions: Map<string, PendingBridgeRequest>;
589
+ /** 是否已通过 onPermissionState 报过 waiting(避免重复回调) */
590
+ waiting: boolean;
591
+ /**
592
+ * 0.32:该 ExecutionUnit 的 inbox hook 开关(spawn 时 attach 了收件箱才有)。
593
+ * hook 在 spawn 时注册、之后才建 entry,故开关由这个可变对象承载。
594
+ */
595
+ inboxState?: { enabled: boolean };
596
+ /**
597
+ * 0.52:这具 body 的「基础信息真值」(spawn 快照起步,之后由 `noteSelfCardIdentity`
598
+ * 推进)。Self Card 本身仍是构造期只读快照;变化经这个盒子在下一轮 BeforeLlm 变成一条
599
+ * 环境信息(`self-card-delta` hook),不重建 body、不改 system 前缀。
600
+ */
601
+ selfCardIdentity: { member: MemberExecutionMember };
602
+ }
603
+
604
+ /** `buildSurface` 的结果:成员应有的工具(spawn / 热刷新 / 推导共用这一份规格)。 */
605
+ interface MemberSurfaceBuild {
606
+ mode: MemberExecutionPermissionMode;
607
+ /** 已按 mode / bridge 收窄,按注册顺序排列(父宿主工具 → 注入工具) */
608
+ tools: ToolDefinition[];
609
+ }
610
+
611
+ function isRecord(value: unknown): value is Record<string, unknown> {
612
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
613
+ }
614
+
615
+ /** core 的交互事件用 camelCase requestId;应答按它匹配 */
616
+ function readRequestId(data: unknown): string | undefined {
617
+ return isRecord(data) && typeof data.requestId === 'string' ? data.requestId : undefined;
618
+ }
619
+
620
+ /**
621
+ * 转发到父流前补齐成员归属字段;已有字段不覆盖。
622
+ *
623
+ * 归属**只写 agent 维度**(`parent_agent_id`)是 0.51 的核心不变量:父会话 id 是
624
+ * 从父 agent 上溯出来的展示信息,不是这条请求的事实,多写一个键就多一处会漂移的
625
+ * 来源(0.19 的混用正是这么来的)。这个形状由 `scripts/check-ask-attribution.ts`
626
+ * 按源码对拍(`src/ask-attribution.test.ts` 覆盖读侧 —— 本模块 import 了
627
+ * `@vessel-agent/core`,测试进程里不好单独拉起)。
628
+ */
629
+ function bridgeRequestData(
630
+ event: RunEvent,
631
+ member: MemberExecutionMember,
632
+ ): Record<string, unknown> {
633
+ const data = isRecord(event.data) ? { ...event.data } : {};
634
+ // core 契约用 camelCase requestId;UI / 0.16 形状用 snake_case,别名 additive。
635
+ const requestId = readRequestId(data);
636
+ if (requestId !== undefined && typeof data.request_id !== 'string') {
637
+ data.request_id = requestId;
638
+ }
639
+ data.agent_id = member.id;
640
+ if (typeof data.team_id !== 'string' && typeof member.team_id === 'string' && member.team_id) {
641
+ data.team_id = member.team_id;
642
+ }
643
+ if (typeof data.session_id !== 'string') data.session_id = member.session_id;
644
+ // 父**agent** 归属单独一个键(additive):父子链的 agent 身份。
645
+ //
646
+ // 归属只需要 agent 这一个维度:会话维度已经由成员自己的 `session_id` 表达了,
647
+ // 而「父会话是谁」是读侧从 `parent_agent_id` + roster 上溯出来的**展示**信息
648
+ // (agent id 与会话 id 只在某具 body 上偶然相等,一旦写进事件就是第二个会漂移的
649
+ // 事实源)。所以这里**刻意不写父会话 id**,也不加回来(`scripts/check-ask-attribution.ts`
650
+ // 的 C1 反向检查盯着这一条)。
651
+ if (typeof data.parent_agent_id !== 'string' && member.parent_id !== undefined) {
652
+ data.parent_agent_id = member.parent_id;
653
+ }
654
+ if (data.delegate_path === undefined) {
655
+ data.delegate_path =
656
+ member.parent_id !== undefined ? [member.parent_id, member.id] : [member.id];
657
+ }
658
+ if (typeof data.tool !== 'string' && event.type === 'ask.user.requested') {
659
+ // 工具名兜底(生产侧):新名是 `ask`;历史事件里这个字段仍是 `ask_user`。
660
+ data.tool = 'ask';
661
+ }
662
+ if (data.input === undefined && event.type === 'ask.user.requested') {
663
+ data.input = data.questions;
664
+ }
665
+ if (typeof data.source !== 'string') data.source = 'runtime';
666
+ return data;
667
+ }
668
+
669
+ /**
670
+ * run 终态并入父流前补齐成员归属(0.27):写在 `data` 内而非事件顶层,
671
+ * TeamService 与 TUI 都读 `data.agent_id`。已存在的值不覆盖;`data` 不是
672
+ * 对象时原样返回(不抛错)。
673
+ */
674
+ function withMemberIdentity(event: RunEvent, member: MemberExecutionMember): RunEvent {
675
+ if (!isRecord(event.data)) return event;
676
+ const data: Record<string, unknown> = { ...event.data };
677
+ if (data.agent_id === undefined) data.agent_id = member.id;
678
+ if (data.team_id === undefined && member.team_id !== undefined) {
679
+ data.team_id = member.team_id;
680
+ }
681
+ if (data.visibility === undefined) data.visibility = member.visibility;
682
+ return { ...event, data };
683
+ }
684
+
685
+ /** 读 run.completed 事件里的 usage */
686
+ function readUsage(data: unknown): Usage | undefined {
687
+ if (typeof data !== 'object' || data === null) return undefined;
688
+ const value = (data as Record<string, unknown>).usage;
689
+ return typeof value === 'object' && value !== null ? (value as Usage) : undefined;
690
+ }
691
+
692
+ /** 来源元数据不可信:压成单行并限长,避免伪造出额外的提示行 */
693
+ function sanitizeSource(value: string): string {
694
+ const cleaned = value.replace(/\s+/g, ' ').trim();
695
+ return cleaned.length > 120 ? `${cleaned.slice(0, 117)}...` : cleaned;
696
+ }
697
+
698
+ /**
699
+ * XML 属性值转义。名字是模型可控的字符串,`"` 不转义就能闭合属性再伪造一个
700
+ * `id="..."`——和块注释结束标记同一类问题:不报错,只会静默错乱。
701
+ * 顺序要紧:`&` 必须先换,否则会把后面换出来的实体再转一遍。
702
+ */
703
+ function escapeAttr(value: string): string {
704
+ return value
705
+ .replace(/&/g, '&amp;')
706
+ .replace(/</g, '&lt;')
707
+ .replace(/>/g, '&gt;')
708
+ .replace(/"/g, '&quot;');
709
+ }
710
+
711
+ /**
712
+ * principal 段是否合法到能被 `resolveAddress` 接受。
713
+ *
714
+ * 与 `src/federation-address.ts:23` 的 `FEDERATION_PRINCIPAL_RE` 同源同形状
715
+ * (`[A-Za-z0-9_-]{1,64}`)。不 import 它:`packages/agent` 不依赖应用层 `src/`,
716
+ * 方向是 `core ← packages ← src`。改这一处要同步改那边,反之亦然。
717
+ *
718
+ * 需要这个判定是因为成员名只校验非空(`AgentService.create` 的 `optionalString`),
719
+ * 没有任何字符集约束:`my.agent`(含点)、`docs core`(含空格)、中文名、超 64 字符
720
+ * 全都能存进 registry。这类名字直接拼进地址会让 `parseFederationAddress` 在
721
+ * **形状校验**就失败(不是 `unknown_member`,是整个地址非法),模型抄回去必然发不出去。
722
+ */
723
+ function isAddressSafePrincipal(name: string): boolean {
724
+ return /^[A-Za-z0-9_-]{1,64}$/.test(name);
725
+ }
726
+
727
+ /**
728
+ * 缺 source 时按 from 退化推断;生产路径由 AgentService 入队时标注。
729
+ *
730
+ * `main` 不在此列:它是 agent(role single),不是人类。曾经把 `main` 当 human
731
+ * 是因为人类消息的 `from` 就是 `main`(成员归属的缺省值被误用成消息发送者);
732
+ * 缺省发送者改成 `human` 之后这个特例不再成立。
733
+ */
734
+ function inferMessageSource(from: string): NonNullable<AgentMessage['source']> {
735
+ if (from === SYSTEM_PRINCIPAL) return 'system';
736
+ if (from === HUMAN_PRINCIPAL) return 'human';
737
+ return 'agent';
738
+ }
739
+
740
+ /**
741
+ * 渲染本轮消息来源。由 `runTurn` 作为 `RunOptions.messages` 注入为持久化的
742
+ * `vessel:source` 消息,不改写 system。
743
+ *
744
+ * **渲染成可回信的地址,不渲染成描述**:`<from location="docs-core@a1b2c3d4:vessel-core" />`。
745
+ * 地址就是 `resolveAddress` / `agent send` 吃的同一形态,模型不需要第二套语法:
746
+ * 回信时把 `location` 的值原样填进 `to` 即可。
747
+ *
748
+ * **本机来源也写满三段**,node 段来自装配层传入的 `nodeId`(见
749
+ * `MemberExecutionHostOptions.nodeId`),不在这里解析。让模型只学一种地址形态,
750
+ * 比「本机两段、跨机三段」少一条分支:早先本机来源省掉 node 段,模型抄回去的
751
+ * 两段地址是否算本机取决于当时有没有 federation 开着,行为不一致。
752
+ *
753
+ * **principal 段必须是能解析到的值**,一条规则两种情况:
754
+ * - 名字合法(见 `isAddressSafePrincipal`)就写名字:`docs-core@<node>:<team>`;
755
+ * - 名字不可用、或成员无名,一律写**完整 uuid**。
756
+ *
757
+ * **principal 不缩成短 id**:`registry.resolve("3ae686c0")` 只做 id / session / body
758
+ * 的精确匹配、没有前缀匹配,短 principal 必然是 `unknown_member` —— 消息发不出去。
759
+ * 来源行还会持久化进历史,模型下一轮照样抄。名字不可用时不做截断降级,
760
+ * uuid 是唯一保证合法的 principal(`formatAddress` 的 replyable 兜底同此裁定)。
761
+ *
762
+ * **node 段按 `addressStyle` 渲染**(q-addr-display):name 档用本机展示名
763
+ * (`isLocalNodeSegment` 认本机名,大小写不敏感),compact 档用短 id ——
764
+ * `isLocalNodeSegment` 已支持本机 nodeId 的 ≥8 位前缀匹配(只对本机一个 id,
765
+ * 无前缀歧义),两种写法回信都可解析。名字字符集不安全(含点 / 空格等)时
766
+ * 不进地址,走短 id 兜底。federation 入站不走此路(远端 node 无名可查、
767
+ * 短 id 不可路由),保持 canonical。
768
+ *
769
+ * **缺 `nodeId` 时退回两段** `principal@<team>`(纯内存构造 / 测试路径):不伪造 node 段,
770
+ * 也不去猜一个主机名。
771
+ *
772
+ * `channel` 是消息的元属性,只进 trace / 日志,不渲染进提示词。
773
+ *
774
+ * 联邦入站的 `from` 已自带 `<principal>@<node>:<team>`:整体作为 location 原样渲染,
775
+ * 不再拼本机 node/team(否则会把它伪装成本机成员)。
776
+ */
777
+ function formatMessageSource(
778
+ message: AgentMessage,
779
+ teamId: string | undefined,
780
+ nodeId: string | undefined,
781
+ nodeName: string | undefined,
782
+ style: AddressStyle,
783
+ ): string {
784
+ if (message.from.startsWith('federation:')) {
785
+ const address = sanitizeSource(message.from.slice('federation:'.length));
786
+ return `<from location="${escapeAttr(address)}" />`;
787
+ }
788
+ const source = message.source ?? inferMessageSource(message.from);
789
+ // 一条规则覆盖两种情况:principal 段必须是 resolveAddress 收得下的形状,
790
+ // 收不下就用完整 uuid(uuid 一定合法)。名字不可用时不做「换个短一点的写法」
791
+ // 之类的降级 —— 解析侧只做精确匹配,任何截断都是另一种死地址。
792
+ const named = message.from_name === undefined ? undefined : sanitizeSource(message.from_name);
793
+ const principal =
794
+ source === 'agent'
795
+ ? named !== undefined && isAddressSafePrincipal(named)
796
+ ? named
797
+ : sanitizeSource(message.from)
798
+ : source;
799
+ const scope = teamId === undefined ? undefined : sanitizeSource(teamId);
800
+ // node 名只有字符集安全(与 FEDERATION_NODE_ID_RE 同形状)才进地址:
801
+ // hostname 派生名可能含点 / 空格,直接拼会让 parseFederationAddress 形状校验失败。
802
+ const safeNodeName =
803
+ nodeName !== undefined && nodeName !== '' && isAddressSafePrincipal(nodeName)
804
+ ? nodeName
805
+ : undefined;
806
+ const nodeNames =
807
+ nodeId !== undefined && safeNodeName !== undefined
808
+ ? { node: new Map([[nodeId, safeNodeName]]) }
809
+ : undefined;
810
+ // 段数决定语义:有 node 才写三段,有 team 才写 `@team`。缺的段不补占位符
811
+ // (formatAddress 同口径)。replyable:principal 兜底跳过短 id 直达 full uuid。
812
+ const address = formatAddress({ principal, node: nodeId, team: scope }, style, nodeNames, {
813
+ replyable: true,
814
+ });
815
+ return `<from location="${escapeAttr(address)}" />`;
816
+ }
817
+
818
+ /**
819
+ * async `ask` 答案投递的消息名(`Message.name`,随 `user.message` 持久化)。
820
+ *
821
+ * 它不是 `vessel:*`(那是**模型侧上下文**、不算 turn 锚点):这条消息就是该轮真实的
822
+ * 用户输入,只是人来路不同 —— Web 据此渲染「待批答复」卡而不是用户气泡。
823
+ * 字面量与 `apps/web/src/domains/chat/ask-answer.ts` 必须一致(`check-transcript-items` 守)。
824
+ */
825
+ export const ASK_ANSWER_INPUT_NAME = 'ask:answer';
826
+
827
+ /**
828
+ * 异步 bash 作业完成投递的消息名(`Message.name`,随 `user.message` 持久化)。
829
+ *
830
+ * 它不是「谁说的话」:作业是该成员自己起的后台 bash,结果投回自己。过去不写 name,
831
+ * 落进 `agentInputName` 的 A2A 推导 ⇒ Web 渲成「来自 agent <成员自己>」(用户反馈的
832
+ * 正是这条:看起来像成员给自己发了条消息)。现在显式声明工具来源 `tool:bash`,
833
+ * Web 渲成「来自 bash」卡(身份判定在 `apps/web/src/domains/chat/agent-sender.ts`)。
834
+ * 与 `ask:answer` 同理:它是该轮真实的输入锚点,不是 `vessel:*` 上下文。
835
+ */
836
+ export const BASH_JOB_INPUT_NAME = 'tool:bash';
837
+
838
+ /** `name` 只允许简单标签:Provider 侧把 `name` 当标识符,空格 / 符号 / 中文都不进。 */
839
+ function sanitizeAlias(value: string): string {
840
+ return value.replace(/[^A-Za-z0-9_-]/g, '');
841
+ }
842
+
843
+ /** `node:agent` / `federation:principal@node:team` → agent / principal 段(取 id 用)。 */
844
+ function agentIdOf(from: string): string {
845
+ const stripped = from.startsWith('federation:') ? from.slice('federation:'.length) : from;
846
+ const principal = stripped.split('@')[0] ?? stripped;
847
+ return principal.slice(principal.lastIndexOf(':') + 1);
848
+ }
849
+
850
+ /**
851
+ * 本轮输入那条 user 消息的 `name`:声明的身份优先,否则按 A2A 来源推导。
852
+ *
853
+ * - `message.input_name`:投递方**显式声明**的身份,只用于运行时合成输入与交接嘱托
854
+ * (rotate 交接 = `rotate:handoff:<epoch>`,见 `AgentService.ROTATE_HANDOFF_INPUT_NAME`;
855
+ * bash 作业结果 = `tool:bash`,见 `BASH_JOB_INPUT_NAME`)。上下文
856
+ * 身份不只能从 `source` 推理出来:`startup_prompt` 与唤醒曾同为 system principal
857
+ * 投递 —— rotate 路径是 agent 写的交接书、restart / activate 是人的开场白,只能由
858
+ * 生产者说清楚;agent 经内置工具 create / hire 的 startup_prompt 归属创建者
859
+ * (from=创建者 ⇒ source='agent',走下面的 `agent:<alias>` 推导,见 service.ts
860
+ * `deliverStartupPrompt`)。
861
+ * - `agent:<alias>`:A2A 投递(`agentInputName`)。
862
+ * - 人类 / 系统 / 联邦来源返回 undefined,消息不带 `name`(保持 nil)。
863
+ *
864
+ * 改动只落在既有的 `Message.name`(已随 `user.message` 持久化)上——不新增字段,
865
+ * 也不把 `vessel:source` 重新放回可见;Web / TUI 侧据此决定这条输入是「谁说的话」。
866
+ */
867
+ function inputNameOf(message: AgentMessage): string | undefined {
868
+ const declared = message.input_name;
869
+ if (typeof declared === 'string' && declared.length > 0) return declared;
870
+ return agentInputName(message);
871
+ }
872
+
873
+ /**
874
+ * A2A 输入那条 user 消息的 `name`:`agent:<alias>`。
875
+ *
876
+ * 只标「agent 发来的」:人类 / 系统来源返回 undefined,消息不带 `name`(保持 nil)。
877
+ * alias 用发送者显示名清洗成 `[A-Za-z0-9_-]`;没有显示名(远端 / 联邦 / 未注册)
878
+ * 时退回 agent 地址里的 id 前 8 位。
879
+ */
880
+ function agentInputName(message: AgentMessage): string | undefined {
881
+ const source = message.source ?? inferMessageSource(message.from);
882
+ if (source !== 'agent') return undefined;
883
+ const named = sanitizeAlias(message.from_name ?? '');
884
+ const alias = named.length > 0 ? named : sanitizeAlias(agentIdOf(message.from)).slice(0, 8);
885
+ return alias.length > 0 ? `agent:${alias}` : undefined;
886
+ }
887
+
888
+ /** 成员侧 agent 工具可用的动作(close 的审批在 checkPermission;create 需要成员自己所属 Team) */
889
+ const MEMBER_AGENT_ACTIONS: readonly string[] = [
890
+ 'create',
891
+ 'hire',
892
+ 'close',
893
+ 'rotate',
894
+ 'post',
895
+ 'send',
896
+ 'list',
897
+ 'read',
898
+ ];
899
+
900
+ /** 成员侧 agent 工具的可见参数;父级 schema 有同名字段时沿用父级定义 */
901
+ const MEMBER_AGENT_PROPERTIES: Readonly<Record<string, Record<string, unknown>>> = {
902
+ action: {
903
+ type: 'string',
904
+ enum: [...MEMBER_AGENT_ACTIONS],
905
+ description: 'create | hire | close | rotate | post | send | list | read',
906
+ },
907
+ name: { type: 'string', description: 'create/hire: display name' },
908
+ model: { type: 'string', description: 'create/hire: model override' },
909
+ system_prompt: { type: 'string', description: 'create/hire: optional system prompt' },
910
+ // q-session-naming:成员侧也要能命名会话(正常路径沿用父级 tool.ts 的同名定义)。
911
+ title: {
912
+ type: 'string',
913
+ description:
914
+ 'create/hire/rotate: optional session title; omitted = the member name; ' +
915
+ 'AI titling never renames a named session',
916
+ },
917
+ to: {
918
+ type: 'string',
919
+ description:
920
+ 'send: target agent; use the location value from the source line as-is, or a member id; ' +
921
+ 'read: member id, session id or name',
922
+ },
923
+ content: { type: 'string', description: 'send/post: message text' },
924
+ interrupt: {
925
+ type: 'boolean',
926
+ description:
927
+ 'send: urgent — cancel the target body active run and put this message first ' +
928
+ '(work/queued messages are preserved; cannot combine with notify)',
929
+ },
930
+ notify: {
931
+ type: 'boolean',
932
+ description:
933
+ 'send: append to the target inbox as unread and wake it with a summary notice; ' +
934
+ 'does not run, queue, or cancel anything (cannot combine with interrupt)',
935
+ },
936
+ message_id: {
937
+ type: 'string',
938
+ description:
939
+ 'send: with interrupt, deliver an existing inbox message id instead of new content',
940
+ },
941
+ messages: {
942
+ type: 'array',
943
+ // items 显式声明(q-agent-close-tool-bug):无 items 数组在 dashscope/qwen
944
+ // 约束生成下元素被抑制恒空;与父级 tool.ts 同口径(正常路径沿用父级定义)。
945
+ items: {
946
+ type: 'object',
947
+ properties: {
948
+ to: { type: 'string' },
949
+ content: { type: 'string' },
950
+ interrupt: { type: 'boolean' },
951
+ notify: { type: 'boolean' },
952
+ message_id: { type: 'string' },
953
+ },
954
+ },
955
+ description: 'send: [{to, content, interrupt?, notify?, message_id?}]',
956
+ },
957
+ limit: {
958
+ type: 'integer',
959
+ minimum: 1,
960
+ maximum: 50,
961
+ description: 'read: how many trailing messages to return (default 20, max 50)',
962
+ },
963
+ members: {
964
+ type: 'array',
965
+ // items 显式声明(q-agent-close-tool-bug):无 items 数组在 dashscope/qwen
966
+ // 约束生成下元素被抑制恒空;与父级 tool.ts 同口径(正常路径沿用父级定义)。
967
+ items: {
968
+ type: ['string', 'object'],
969
+ description:
970
+ 'close: a member id or session id string; ' +
971
+ 'create/hire: an object {name?, model?, system_prompt?, visibility?, title?, startup_prompt?}',
972
+ },
973
+ description:
974
+ 'create/hire: [{name?, model?, system_prompt?, visibility?, title?, startup_prompt?}]; ' +
975
+ 'close: [member id or session id]. ' +
976
+ 'Always emit the explicit entries; never an empty array',
977
+ },
978
+ startup_prompt: {
979
+ type: 'string',
980
+ // 正常路径沿用父级(tool.ts)那份描述,这里只是父级 schema 缺失时的兜底;
981
+ // 两份措辞保持一致,避免成员侧又说回「必填即可」。
982
+ description:
983
+ 'create/hire: optional first user message (the task), delivered at creation — ' +
984
+ 'the new member starts its first run at once, no follow-up send needed; ' +
985
+ 'omit = created idle. ' +
986
+ 'rotate: required; the new body first message and the only handoff channel — ' +
987
+ 'it does not inherit this conversation, so write everything the next body needs',
988
+ },
989
+ state: { type: 'string', description: 'list: filter by member state' },
990
+ visibility: {
991
+ type: 'string',
992
+ enum: ['private', 'team', 'tenant'],
993
+ description:
994
+ 'create: team only; hire: visibility (default private for unbound, team with a team); ' +
995
+ 'list: filter by visibility',
996
+ },
997
+ };
998
+
999
+ /** 同一个 agent 工具,按成员能力收窄 schema(handler / checkPermission 原样保留) */
1000
+ function restrictAgentTool(tool: ToolDefinition): ToolDefinition {
1001
+ const schema = isRecord(tool.inputSchema) ? tool.inputSchema : {};
1002
+ const source = isRecord(schema.properties) ? schema.properties : {};
1003
+ // 无论父级 schema 有几种 action,成员侧只暴露 create/hire/rotate/post/send/list
1004
+ const properties: Record<string, unknown> = {
1005
+ action: isRecord(source.action)
1006
+ ? { ...source.action, enum: [...MEMBER_AGENT_ACTIONS] }
1007
+ : MEMBER_AGENT_PROPERTIES.action,
1008
+ };
1009
+ for (const [key, fallback] of Object.entries(MEMBER_AGENT_PROPERTIES)) {
1010
+ if (key !== 'action') properties[key] = source[key] ?? fallback;
1011
+ }
1012
+ return {
1013
+ ...tool,
1014
+ // 与 owner 侧同一句不变量:交接只有 startup_prompt 一条通道(成员没有别的
1015
+ // 手段把信息带给下一个身体);「必填」不足以表达这一点。
1016
+ description:
1017
+ 'Member actions: create (create peer member(s) in your team), ' +
1018
+ 'hire (create contractor member(s) owned by you), ' +
1019
+ 'close (release member(s); closing a peer requires human approval, while closing ' +
1020
+ 'your own contractor or yourself needs no approval), ' +
1021
+ 'rotate (rotate your own body; startup_prompt is the only handoff — the new body ' +
1022
+ 'starts at once and does not inherit this conversation, so it must carry everything ' +
1023
+ 'the next body needs to know), ' +
1024
+ 'post (append to your team log only; nobody is notified), ' +
1025
+ 'send (dispatch a message to a member; this is the default channel for reporting to ' +
1026
+ 'your parent — progress, blockers, a decision you made, a question you cannot settle ' +
1027
+ 'alone; interrupt:true for urgent, notify:true to append to the target inbox plus a ' +
1028
+ 'summary wake), ' +
1029
+ 'list (list the caller-visible roster), ' +
1030
+ 'read (read the last messages of a member session; read-only, role + truncated text).',
1031
+ inputSchema: {
1032
+ ...schema,
1033
+ properties,
1034
+ required: ['action'],
1035
+ },
1036
+ };
1037
+ }
1038
+
1039
+ /**
1040
+ * 0.51:`ToolDefinition` → `tools.list` 的条目。
1041
+ *
1042
+ * 没有来源维度:运行期注入的 `inbox` 与父宿主工具在这里是同一种条目。要恢复「哪些是
1043
+ * 注入的」这种信息,只能走「inbox 自己也变成插件」这条路(把注入点搬到节点插件面),
1044
+ * 不要在这里重新长出 `source` 标记 —— 那是被用户明确删掉的一层区分。
1045
+ */
1046
+ function describeTools(tools: readonly ToolDefinition[]): MemberToolEntry[] {
1047
+ return tools.map((tool) => ({
1048
+ name: tool.name,
1049
+ description: tool.description,
1050
+ input_schema: tool.inputSchema,
1051
+ has_permission_check: typeof tool.checkPermission === 'function',
1052
+ }));
1053
+ }
1054
+
1055
+ /**
1056
+ * 推导路径(没有活身体,或只是问「新身体会拿到什么」)用的端口载体:`isActive` 恒 true、
1057
+ * `publish` 是 noop —— 那是 `tools()` 的纯度要求,不是「假装活着」。真 body 的实例在 spawn 里建。
1058
+ */
1059
+ const DERIVED_BODY: {
1060
+ isActive: () => boolean;
1061
+ publish: (event: MemberBodyNoticeEvent) => void;
1062
+ } = {
1063
+ isActive: () => true,
1064
+ publish: () => {},
1065
+ };
1066
+
1067
+ /** 进程内成员执行内核 */
1068
+ export class MemberExecutionHost implements MemberExecutionPort {
1069
+ /**
1070
+ * 宿主缺省 model **ref**(条目键 / legacy 透传 ref);`provider.model` 热应用会经
1071
+ * `updateDefaultModel` 整体替换(非 readonly)。spawn 继承用它走 resolveModelRef。
1072
+ */
1073
+ private model?: string;
1074
+ /** 宿主缺省的展示 wire 快照(selfCard / delta 真值盒);与 ref 同步热应用替换。 */
1075
+ private modelWire?: string;
1076
+ private readonly pluginHost?: PluginHost;
1077
+ private readonly readOnlyTools: ReadonlySet<string>;
1078
+ private readonly permissionMode: MemberExecutionPermissionMode;
1079
+ private readonly forceBridgeForTeams: boolean;
1080
+ private readonly permissionPolicy?: (
1081
+ teamId: string | undefined,
1082
+ ) => TeamPermissionPolicy | undefined;
1083
+ /** 成员兜底权限(热应用会整体替换,故非 readonly) */
1084
+ private permission?: RuntimePermissionConfig;
1085
+ private readonly parentEvents?: EventStream;
1086
+ private readonly onPermissionState?: (
1087
+ memberId: string,
1088
+ sessionId: string,
1089
+ state: MemberPermissionState,
1090
+ ) => void;
1091
+ private readonly onMemberEvent?: (memberId: string, sessionId: string, event: RunEvent) => void;
1092
+ private readonly limits: UsageLimits;
1093
+ private readonly termination: TerminationPolicy;
1094
+ private readonly contextMaxTokens: number;
1095
+ private readonly contextCompactThreshold: number | undefined;
1096
+ /** q-tool-result-whitelist:原样存注入值(undefined ⇒ 内层窗口走 core 内置默认)。 */
1097
+ private readonly contextToolResultWhitelist: readonly ToolResultWhitelistRule[] | undefined;
1098
+ private readonly envInjection: EnvInjectionConfig | undefined;
1099
+ private readonly getEnvInjection: (() => EnvInjectionConfig | undefined) | undefined;
1100
+ /** q-sub-unify-p2 M3a:订阅静音查询(装配注入;缺省恒不静音) */
1101
+ private readonly isSourceMuted:
1102
+ | ((sessionId: string, source: string, target: string) => boolean)
1103
+ | undefined;
1104
+ private readonly summarizer: ContextSummarizer | undefined;
1105
+ private readonly summarizerForSession: ((sessionId: string) => ContextSummarizer) | undefined;
1106
+ private readonly depth: number;
1107
+ /** depth-color D1:per-member 树深度解析(装配层注入;缺省回落 host depth 兜底) */
1108
+ private readonly depthFor: ((member: MemberExecutionMember) => number | undefined) | undefined;
1109
+ /** 0.51:记录里没有 cwd 时的运行期兜底(装配层按 team_id 查 Team 基础路径) */
1110
+ private readonly cwdFor: ((member: MemberExecutionMember) => string | undefined) | undefined;
1111
+ private readonly logger: Logger;
1112
+ private readonly tenantId?: string;
1113
+ private readonly nodeId?: string;
1114
+ private readonly nodeName?: string;
1115
+ private readonly addressStyle: AddressStyle;
1116
+ private readonly includeReasoning?: boolean;
1117
+ private readonly session?: ExecutionUnitOptions['session'];
1118
+ private readonly eventLog?: ExecutionUnitOptions['eventLog'];
1119
+ private readonly leaseService?: ExecutionUnitOptions['leaseService'];
1120
+ private readonly wireInboxTool?: (tool: ToolDefinition, memberId: string) => void;
1121
+ private readonly runtime: Runtime;
1122
+ private readonly entries = new Map<string, MemberExecutionEntry>();
1123
+ /** 未 spawn / 未开跑成员的待注入 notice(member id → 有界队列) */
1124
+ private readonly pendingNotices = new Map<string, PendingNotice[]>();
1125
+ /** 0.32:由装配层挂上的收件箱;spawn 时据此注册 notice hook 与 `inbox` 工具 */
1126
+ private inbox?: AgentInboxPort;
1127
+ /** issue-0:轮边界应用 pending 工具刷新后的回调(装配层冲刷引擎 retain);可变,晚绑定 */
1128
+ private toolsRefreshListener?: () => void;
1129
+
1130
+ constructor(options: MemberExecutionHostOptions) {
1131
+ this.model = options.model;
1132
+ this.modelWire = options.modelWire ?? options.model;
1133
+ this.pluginHost = options.pluginHost;
1134
+ this.readOnlyTools = new Set(options.readOnlyTools ?? DEFAULT_READ_ONLY_TOOLS);
1135
+ this.permissionMode = options.permissionMode ?? 'allow';
1136
+ this.forceBridgeForTeams = options.forceBridgeForTeams !== false;
1137
+ this.permissionPolicy = options.permissionPolicy;
1138
+ this.permission =
1139
+ options.permission !== undefined ? withMemberAutoApprove(options.permission) : undefined;
1140
+ this.parentEvents = options.parentEvents;
1141
+ this.onPermissionState = options.onPermissionState;
1142
+ this.onMemberEvent = options.onMemberEvent;
1143
+ this.limits = options.limits ?? {};
1144
+ this.termination = options.termination ?? DEFAULT_TERMINATION;
1145
+ this.contextMaxTokens = options.contextMaxTokens ?? DEFAULT_CONTEXT_MAX_TOKENS;
1146
+ this.contextCompactThreshold = options.contextCompactThreshold;
1147
+ this.contextToolResultWhitelist = options.contextToolResultWhitelist;
1148
+ this.envInjection = options.envInjection;
1149
+ this.getEnvInjection = options.getEnvInjection;
1150
+ this.isSourceMuted = options.isSourceMuted;
1151
+ this.summarizer = options.summarizer;
1152
+ this.summarizerForSession = options.summarizerForSession;
1153
+ this.depth = options.depth ?? 1;
1154
+ this.depthFor = options.depthFor;
1155
+ this.cwdFor = options.cwdFor;
1156
+ this.logger = options.logger ?? noopLogger;
1157
+ this.tenantId = options.tenantId;
1158
+ this.nodeId = options.nodeId;
1159
+ this.nodeName = options.nodeName;
1160
+ this.addressStyle = options.addressStyle ?? DEFAULT_ADDRESS_STYLE;
1161
+ this.includeReasoning = options.includeReasoning;
1162
+ this.session = options.session;
1163
+ this.eventLog = options.eventLog;
1164
+ this.leaseService = options.leaseService;
1165
+ this.wireInboxTool = options.wireInboxTool;
1166
+ this.runtime = options.runtime;
1167
+ if (this.permissionMode === 'bridge' && this.parentEvents === undefined) {
1168
+ this.logger.warn('agent.member.permission_bridge_unavailable', {
1169
+ fallback: 'ask_denied',
1170
+ });
1171
+ }
1172
+ }
1173
+
1174
+ /**
1175
+ * 替换宿主缺省 model(`provider.model` 热应用的写入口,P0-1 D4 批准)。
1176
+ *
1177
+ * 只影响**此后 spawn** 的成员 body(`member.model ?? this.model` 的回落端);
1178
+ * live body 的 model 是构造期只读快照(system 前缀不变量),本具仍旧值、
1179
+ * 下一具才用新值。不触碰任何 live ExecutionUnit,也不改显式 pin(record.model)。
1180
+ *
1181
+ * 第 6 修:`model` 是可重解析的缺省 **ref**(条目键 / legacy 透传 ref),
1182
+ * `wireModel` 是配套展示 wire(selfCard / delta 真值盒);缺省 wire 回落 ref 原值。
1183
+ */
1184
+ updateDefaultModel(model: string, wireModel?: string): void {
1185
+ this.model = model;
1186
+ this.modelWire = wireModel ?? model;
1187
+ }
1188
+
1189
+ /**
1190
+ * q-error-e2(§3.6,裁定 B):宿主缺省 ref 只读面(MemberExecutionPort additive)。
1191
+ * spawn_failed 证据契约 default 档 resolution.ref 用;与 spawn 回落端同源。
1192
+ */
1193
+ defaultModelRef(): string | undefined {
1194
+ return this.model;
1195
+ }
1196
+
1197
+ async spawn(member: MemberExecutionMember): Promise<void> {
1198
+ if (this.entries.has(member.session_id)) {
1199
+ throw new Error(`member runtime already spawned: ${member.session_id}`);
1200
+ }
1201
+ // 第 6 修(SPAWN-02):继承值是缺省 **ref**(条目键 / legacy 透传 ref),经
1202
+ // EU 的 resolveModel 解析成 wire;裸 wire 名在 legacyPresent=false 时无命中会
1203
+ // ModelRefError,故宿主缺省不再存 wire。展示面(selfCard / delta)仍用 wire。
1204
+ const model = member.model ?? this.model;
1205
+ if (!model) {
1206
+ throw new Error(`member runtime model is required: ${member.id}`);
1207
+ }
1208
+ // 显式 pin 展示原值(与旧行为字节等价);缺省继承展示宿主 wire 快照。
1209
+ const displayModel = member.model ?? this.modelWire ?? model;
1210
+
1211
+ const surface = this.buildSurface(member);
1212
+ const mode = surface.mode;
1213
+ // 0.32:只有 spawn 时已 attach 收件箱的 ExecutionUnit 才注册 notice hook 与 inbox 工具;
1214
+ // 开关放在可变对象里,`disableInbox` 之后(rotate / retire 的旧 ExecutionUnit)hook 直接返回。
1215
+ const inbox = this.inbox;
1216
+ const inboxState = inbox !== undefined ? { enabled: true } : undefined;
1217
+ const pluginHost = new MemoryPluginHost();
1218
+ for (const hook of this.pluginHost?.getHooks() ?? []) pluginHost.registerHook(hook);
1219
+ for (const guardrail of this.pluginHost?.getGuardrails() ?? []) {
1220
+ pluginHost.registerGuardrail(guardrail);
1221
+ }
1222
+ for (const tool of surface.tools) pluginHost.registerTool(tool);
1223
+
1224
+ const selfCard = this.buildSelfCard(member, displayModel, surface.tools);
1225
+ // 0.52:Self Card 是构造期只读快照 —— 基础信息改了不能热替换它(那是 system 前缀,
1226
+ // 变一次就让整段历史缓存失效)。改成「增量告知」:这具 body 自带一个真值盒(此刻 =
1227
+ // 这张卡),`AgentService.update` 时推进;hook 每轮 diff「模型相信的值」与它,变了就
1228
+ // 注入一条环境信息。每个 hook 实例 = 一具 body,rotate 换身体时状态自然重置。
1229
+ const selfCardIdentity = { member };
1230
+ pluginHost.registerHook(
1231
+ createSelfCardDeltaHook({
1232
+ // 基线 / 真值都用**有效展示 model**(显式 pin ?? 宿主缺省 wire),与 Self Card
1233
+ // 同口径:记录缺省跟随 config 后 record.model 多为 undefined,若按记录值做基线,
1234
+ // 卡显示 X 而相信值是 (none),之后设 pin 会误报「(none) → X」。
1235
+ baseline: selfCardIdentityOf({ ...member, model: displayModel }, mode),
1236
+ // 权限档每轮现算:Team 成员在 `forceBridgeForTeams` 下会被强制 bridge,是「进队 /
1237
+ // 转正」直接改出来的身份变化,不能只报 team 那一行。
1238
+ current: () =>
1239
+ selfCardIdentityOf(
1240
+ {
1241
+ ...selfCardIdentity.member,
1242
+ model: selfCardIdentity.member.model ?? this.modelWire ?? this.model,
1243
+ },
1244
+ this.effectivePermissionMode(selfCardIdentity.member),
1245
+ ),
1246
+ // 整 hook 取最细(不做 per-kind 分裂,见 SelfCardDeltaHookOptions.cadence):
1247
+ // 四个活 scope(SELF_CARD_SCOPES 派生 FIELD_SCOPE 值域)任一 request ⇒ request;
1248
+ // 缺省配置全 request = 今天行为。
1249
+ // P2:live resolver 每请求求值(热改即时生效);finestCadence 忽略 off 组(全 off ⇒ off)。
1250
+ cadence: () =>
1251
+ finestCadence(SELF_CARD_SCOPES, this.getEnvInjection?.() ?? this.envInjection),
1252
+ // P2 轴 C / per-scope off:同源 live 配置。
1253
+ channel: (scope) => resolveEnvChannel(scope, this.getEnvInjection?.() ?? this.envInjection),
1254
+ scopeOff: (scope) =>
1255
+ resolveEnvCadence(scope, this.getEnvInjection?.() ?? this.envInjection) === 'off',
1256
+ }),
1257
+ );
1258
+ // tools-body-snapshot:工具面变更卡改由 core EU 生产(ExecutionUnit.appendToolSurfaceNotice,
1259
+ // 对会话 tools[] 快照 diff live 宿主)—— 旧 createToolSurfaceDeltaHook 在此撤注册防双卡。
1260
+ const events = new MemoryEventStream();
1261
+ if (inbox !== undefined && inboxState !== undefined) {
1262
+ pluginHost.registerHook(
1263
+ createInboxNoticeHook({
1264
+ inbox,
1265
+ agentId: member.id,
1266
+ // q-sub-unify-p2 M3a(§4.3):组合订阅静音闸——inbox:* muted ⇒ 不注入计数行
1267
+ // (消息层 input/wake/quiet 投递不动;onNotified 事实通道在 run 内,闸同位生效)。
1268
+ isEnabled: () =>
1269
+ inboxState.enabled && !(this.isSourceMuted?.(member.session_id, 'inbox', '*') ?? false),
1270
+ onNotified: ({ runId, unread, pending }) => {
1271
+ // 人类可见的提示:模型侧另有一条 `vessel:notice` 尾消息(不含正文)。
1272
+ // 事实通道为主(q-card-robust P-A 同构):经 EU.emitFact → publishEvent →
1273
+ // journal.appendFact → 时间线双写,WebUI 时间线订阅 live 可见+刷新可回放重建。
1274
+ // 此前直发成员本地裸流(events.publish)只经 appendObserved(runtime.notice 不在
1275
+ // 观察落盘白名单)⇒不进时间线、Web 收不到卡(根因见
1276
+ // docs/dev/plans/envcard-run-visibility-research.md Part II)。publishEvent 内部
1277
+ // publishRaw 仍发裸流⇒父流并入 / bridge 旧订阅兼容保留。runtime 在下方装配创建,
1278
+ // 本回调运行期(EU run 中)才触发,届时已初始化。
1279
+ runtime.emitFact({
1280
+ type: 'runtime.notice',
1281
+ run_id: runId,
1282
+ data: {
1283
+ scope: 'inbox',
1284
+ summary:
1285
+ `[inbox] ${unread} unread message(s), ${pending} pending; ` +
1286
+ 'use the inbox tool (action="list") to view them.',
1287
+ ok: true,
1288
+ },
1289
+ ts: Date.now(),
1290
+ });
1291
+ },
1292
+ }),
1293
+ );
1294
+ }
1295
+ // 0.51:成员面贡献的 hook —— 一具 body 只在这里建一次(`hooks()` 的契约);工具不在这里,
1296
+ // 它们在 `buildSurface` 里按同一份贡献产出,好让「推导值 = 新身体会拿到的」继续成立。
1297
+ this.registerContributionHooks(pluginHost, member, inboxState, events);
1298
+ // 0.28 D6/D7:temporary 不主动压缩(一具 body 的生命周期由调用方的会话决定,
1299
+ // 压缩会把调用方还在看的历史摘要掉);到线只提示。core 只收到裸参数,不认 role。
1300
+ // 两道硬兜底仍然生效:消息条数上限(`RoleAwareContext` 内层,与开关无关)
1301
+ // 与 provider overflow 的 forceCompact(runtime 内的 overflow 重试)。
1302
+ //
1303
+ // 开关放在 `RoleAwareContext` 而不是 core 的构造配置:转正后同一具 live body
1304
+ // 必须能翻转策略(契约 §5 / D6)。内层恒 `autoCompact: false`,由包装决定要不要
1305
+ // 主动压缩 —— 否则 `add()` 会绕过包装、在 temporary 上按阈值压缩。
1306
+ const policy = contextPolicyFor(member.role);
1307
+ // per-body 可变策略:每次 Run 的 `contextFactory` 读取同一对象,
1308
+ // `applyContextPolicy` 只改这里,下一次 Run 自然生效。
1309
+ const contextPolicy = { autoCompact: policy.autoCompact };
1310
+ // 0.51 Bug 1:成员 cwd 在 spawn 时定一次(与 selfCard / systemPrompt 同一档快照语义)。
1311
+ // 拿不到有效目录就**降级**:warn 一次,然后不注入 —— 工具会退回 agent.cwd / process.cwd()。
1312
+ // 绝不让「Team 目录不在」把 bash / read / edit 变成硬错(`main` 的工具面同理)。
1313
+ const memberCwd = this.memberCwdFor(member);
1314
+ const runtime = await this.runtime.getOrCreateExecutionUnit({
1315
+ tenantId: this.tenantId ?? 'default',
1316
+ sessionId: member.session_id,
1317
+ agentId: member.id,
1318
+ // 成员自有事件流;所有 body 事件仍由下方订阅并入父流。
1319
+ events,
1320
+ ...(this.session !== undefined ? { session: this.session } : {}),
1321
+ ...(this.eventLog !== undefined ? { eventLog: this.eventLog } : {}),
1322
+ ...(this.leaseService !== undefined ? { leaseService: this.leaseService } : {}),
1323
+ // Stage 3:ControlPlane 获取的 BindingLease 凭据随 spawn 透传给 EU(EU 只续租/释放)。
1324
+ ...(member.binding_lease !== undefined ? { bindingLease: member.binding_lease } : {}),
1325
+ // 0.51 Bug 1:成员 cwd 的唯一注入点 —— EU 每次工具调用把它放进 `ToolContext.cwd`。
1326
+ ...(memberCwd !== undefined ? { cwd: memberCwd } : {}),
1327
+ pluginHost,
1328
+ // 成员宿主已自带工具面;不让 tenant profile 的插件再次安装进来。
1329
+ plugins: [],
1330
+ limits: this.limits,
1331
+ termination: this.termination,
1332
+ ...(this.includeReasoning !== undefined ? { includeReasoning: this.includeReasoning } : {}),
1333
+ logger: this.logger,
1334
+ // Stage 4:WorkingContext 是 per-Run 实例;这里只给工厂,EU 每次 Run 调用它。
1335
+ contextFactory: () => {
1336
+ // R7:成员与 owner 按同一 session_id 取熔断器;未接线时回落裸 summarizer。
1337
+ const summarizer = this.summarizerForSession?.(member.session_id) ?? this.summarizer;
1338
+ return new RoleAwareContext(
1339
+ new MemoryWorkingContext({
1340
+ maxTokens: this.contextMaxTokens,
1341
+ autoCompact: false,
1342
+ compactThreshold: this.contextCompactThreshold,
1343
+ // q-tool-result-whitelist:与 owner 同一口径(缺省 ⇒ core 内置默认)。
1344
+ ...(this.contextToolResultWhitelist !== undefined
1345
+ ? { toolResultWhitelist: [...this.contextToolResultWhitelist] }
1346
+ : {}),
1347
+ ...(summarizer !== undefined ? { summarizer } : {}),
1348
+ }),
1349
+ contextPolicy.autoCompact,
1350
+ );
1351
+ },
1352
+ overrides: {
1353
+ model,
1354
+ // 与 owner 同源的权限规则:工具 checkPermission 返回 ask 时,core 仍按
1355
+ // autoApprove / neverAutoApprove 判定,否则 auto_approve 的 bash/edit 会在
1356
+ // 成员 ExecutionUnit 上重新弹卡片(热应用后新建的 ExecutionUnit 同样走这里)。
1357
+ permission: this.permission ?? { default: 'allow' },
1358
+ selfCard,
1359
+ ...(policy.pressureHint !== undefined ? { contextPressureHint: policy.pressureHint } : {}),
1360
+ ...(member.system_prompt !== undefined ? { systemPrompt: member.system_prompt } : {}),
1361
+ },
1362
+ });
1363
+ const entry: MemberExecutionEntry = {
1364
+ runtime,
1365
+ memberId: member.id,
1366
+ sessionId: member.session_id,
1367
+ started: false,
1368
+ events,
1369
+ unsubscribers: [],
1370
+ pendingPermissions: new Map(),
1371
+ waiting: false,
1372
+ contextPolicy,
1373
+ pluginHost,
1374
+ mode,
1375
+ running: false,
1376
+ toolsRefreshPending: false,
1377
+ // 与注册给 hook 的是**同一个对象**:`noteSelfCardIdentity` 写这里,hook 下一轮就读到。
1378
+ selfCardIdentity,
1379
+ ...(inboxState !== undefined ? { inboxState } : {}),
1380
+ };
1381
+ this.entries.set(member.session_id, entry);
1382
+ if (this.onMemberEvent !== undefined) {
1383
+ const onMemberEvent = this.onMemberEvent;
1384
+ entry.unsubscribers.push(
1385
+ entry.events.subscribe((event: RunEvent) => {
1386
+ if (event.type !== 'agent.limit.warning') return;
1387
+ try {
1388
+ onMemberEvent(member.id, member.session_id, event);
1389
+ } catch (error) {
1390
+ this.logger.warn('agent.member.event_callback_failed', {
1391
+ member_id: member.id,
1392
+ session_id: member.session_id,
1393
+ error: error instanceof Error ? error.message : String(error),
1394
+ });
1395
+ }
1396
+ }),
1397
+ );
1398
+ }
1399
+ if (mode === 'bridge' && this.parentEvents !== undefined) {
1400
+ this.attachBridge(member, entry);
1401
+ }
1402
+ // 0.27:所有 body 事件无条件并入父事件流;权限/ask 请求与应答仍由 bridge 独占。
1403
+ if (this.parentEvents !== undefined) {
1404
+ const parentEvents = this.parentEvents;
1405
+ entry.unsubscribers.push(
1406
+ entry.events.subscribe((event: RunEvent) => {
1407
+ // 权限/提问请求与应答由 bridge 独占转发;这里再发一次会重复卡片并形成回环。
1408
+ if (
1409
+ PERMISSION_REQUEST_EVENTS.has(event.type) ||
1410
+ PERMISSION_RESPONSE_EVENTS.has(event.type)
1411
+ ) {
1412
+ return;
1413
+ }
1414
+ if (this.entries.get(member.session_id) !== entry) return;
1415
+ // 成员 run 与 owner run 一样并入 tenant 事件流:Web 会话窗口 / trace /
1416
+ // 观测都靠这条流看到 llm、tool 与 run 生命周期事件(session_id 已在 payload 内)。
1417
+ // 终态事件额外补成员归属,Team 侧才能把 reply / 失败写进团队日志。
1418
+ // q-human-notify P1:成员 notify 请求并入父流时补成员归属(agent_id/team_id/
1419
+ // parent_agent_id),注册表据此建 kind:'notify' 记录。notify 无需答,不进 bridge
1420
+ // 的 pending/waiting/deny-after 机器(fire-and-forget),只走这条通用并入路径。
1421
+ const forwarded: RunEvent = RUN_TERMINAL_EVENTS.has(event.type)
1422
+ ? withMemberIdentity(event, member)
1423
+ : event.type === 'notify.user.requested'
1424
+ ? { ...event, data: bridgeRequestData(event, member) }
1425
+ : event;
1426
+ parentEvents.publish(forwarded);
1427
+ }),
1428
+ );
1429
+ }
1430
+ }
1431
+
1432
+ async runTurn(
1433
+ member: MemberExecutionMember,
1434
+ message: AgentMessage,
1435
+ scheduledRunId?: string,
1436
+ ): Promise<MemberTurnResult> {
1437
+ return this.executeTurn(member, message, scheduledRunId, false);
1438
+ }
1439
+
1440
+ /**
1441
+ * Q5:按 session 历史启动一次新 run(`-r/--resume` 与 AgentService 的
1442
+ * resume 准入路径显式走这里)。与 `runTurn` 共用调度、事件、终态逻辑;
1443
+ * 唯一区别是 core 侧调用 `resumeSession(sessionId, input)` 而不是 `run`。
1444
+ */
1445
+ async resumeTurn(
1446
+ member: MemberExecutionMember,
1447
+ message: AgentMessage,
1448
+ scheduledRunId?: string,
1449
+ ): Promise<MemberTurnResult> {
1450
+ return this.executeTurn(member, message, scheduledRunId, true);
1451
+ }
1452
+
1453
+ private async executeTurn(
1454
+ member: MemberExecutionMember,
1455
+ message: AgentMessage,
1456
+ scheduledRunId: string | undefined,
1457
+ resume: boolean,
1458
+ ): Promise<MemberTurnResult> {
1459
+ const entry = this.requireEntry(member);
1460
+ entry.started = true;
1461
+ entry.running = true;
1462
+ // 未 spawn / 未开跑期间暂存的 notice 在历史恢复之后、用户输入之前注入。
1463
+ const pendingNotices = this.takePendingNotices(member.id);
1464
+ const runId = scheduledRunId ?? randomUUID();
1465
+ let terminal: 'completed' | 'failed' | 'cancelled' | 'paused' | undefined;
1466
+ let usage: Usage | undefined;
1467
+ const unsubscribe = entry.runtime.events.subscribe((event: RunEvent) => {
1468
+ if (event.run_id !== runId) return;
1469
+ if (event.type === 'run.completed') {
1470
+ terminal = 'completed';
1471
+ usage = readUsage(event.data);
1472
+ } else if (event.type === 'run.cancelled') {
1473
+ terminal = 'cancelled';
1474
+ } else if (event.type === 'run.failed') {
1475
+ terminal = 'failed';
1476
+ } else if (event.type === 'run.paused') {
1477
+ // q-restart-p2a:安全点暂停(interrupted + run.paused)——不是失败,
1478
+ // 重启后 auto-resume 续同一 run;收口按 interrupted 记账。
1479
+ terminal = 'paused';
1480
+ }
1481
+ });
1482
+
1483
+ // 来源标注作为用户输入之前的持久化消息注入;不改 system,也不改写用户文本。
1484
+ const sourceMessage: Message = {
1485
+ role: 'user',
1486
+ name: 'vessel:source',
1487
+ content: formatMessageSource(
1488
+ message,
1489
+ member.team_id,
1490
+ this.nodeId,
1491
+ this.nodeName,
1492
+ this.addressStyle,
1493
+ ),
1494
+ timestamp: Date.now(),
1495
+ };
1496
+ // 输入本身可能带结构化身份:A2A 是 agent:<alias>(Web 渲染成 agent 消息卡),
1497
+ // 运行时合成输入(idle 唤醒)是 vessel:notice(环境信息卡),async ask 的答案
1498
+ // (human 来源)是 ask:answer(待批答复卡),异步 bash 作业完成是 tool:bash
1499
+ // (「来自 bash」卡),rotate 交接嘱托是 rotate:handoff:<epoch>(交接卡),
1500
+ // restart --self 跨进程续作嘱托是 tool:system(「来自 system」卡)。
1501
+ // 人类 / 系统正文来源保持 nil。
1502
+ const inputName =
1503
+ message.origin === 'ask_answer'
1504
+ ? ASK_ANSWER_INPUT_NAME
1505
+ : message.origin === 'bash_job'
1506
+ ? BASH_JOB_INPUT_NAME
1507
+ : inputNameOf(message);
1508
+ // 附件引用(0.52):只有路径与种类,随 user 消息落进 `user.message` 事件与
1509
+ // SessionState。refs 不进 `RunOptions.messages`,正文也永不在这里被读出来。
1510
+ const refs = message.refs !== undefined && message.refs.length > 0 ? message.refs : undefined;
1511
+ const userInput: string | Message =
1512
+ inputName === undefined && refs === undefined
1513
+ ? message.content
1514
+ : {
1515
+ role: 'user',
1516
+ content: message.content,
1517
+ ...(inputName !== undefined ? { name: inputName } : {}),
1518
+ ...(refs !== undefined ? { refs } : {}),
1519
+ };
1520
+ try {
1521
+ const turnOptions = {
1522
+ runId,
1523
+ messages: [
1524
+ ...pendingNotices.map((notice) => noticeMessage(notice.text, notice.timestamp)),
1525
+ sourceMessage,
1526
+ ],
1527
+ // E2 §3.7:RPC correlation 显式透传(裁定④);内部触发缺省不写。
1528
+ ...(message.triggered_by !== undefined ? { triggered_by: message.triggered_by } : {}),
1529
+ };
1530
+ const content =
1531
+ resume && entry.runtime.resumeSession !== undefined
1532
+ ? await entry.runtime.resumeSession(member.session_id, userInput, turnOptions)
1533
+ : await entry.runtime.run(userInput, member.session_id, turnOptions);
1534
+ return {
1535
+ content,
1536
+ outcome: 'completed',
1537
+ ...(usage !== undefined ? { usage } : {}),
1538
+ };
1539
+ } catch (error) {
1540
+ // 取消不是失败:interrupt('user') 让 core 发 run.cancelled 并 reject。
1541
+ if (terminal === 'cancelled') return { outcome: 'cancelled' };
1542
+ // q-restart-p2a:安全点暂停不是失败(SafePointPauseError reject)——
1543
+ // 按 interrupted 收口,不触发硬错误闸 / distress;重启后 auto-resume 续段。
1544
+ if (terminal === 'paused') return { outcome: 'interrupted' };
1545
+ throw error;
1546
+ } finally {
1547
+ unsubscribe();
1548
+ // 取消 / 失败时可能仍停在等待:清掉挂起请求与 deadline,把状态还回 running,
1549
+ // 让 AgentService 能正常进入终态(应答随后到达时已无人等待)。
1550
+ this.clearPending(entry);
1551
+ if (entry.waiting) {
1552
+ entry.waiting = false;
1553
+ this.notifyPermissionState(member.id, member.session_id, 'running');
1554
+ }
1555
+ this.finishRun(member, entry);
1556
+ }
1557
+ }
1558
+
1559
+ cancel(member: MemberExecutionMember, reason: RunInterruptReason = 'user'): void {
1560
+ this.entries.get(member.session_id)?.runtime.interrupt?.(reason);
1561
+ }
1562
+
1563
+ /**
1564
+ * 身份变更 notice:live 且已开跑 → 立即追加到上下文(本轮后续请求可见);
1565
+ * 未 spawn / 未开跑 → 暂存,下一次 runTurn 注入。不启动 turn、不入队。
1566
+ */
1567
+ notice(memberId: string, text: string, options?: { timestamp?: number }): void {
1568
+ if (text.length === 0) return;
1569
+ let delivered = false;
1570
+ for (const entry of this.entries.values()) {
1571
+ if (entry.memberId !== memberId) continue;
1572
+ if (entry.started && entry.runtime.appendNotice !== undefined) {
1573
+ entry.runtime.appendNotice(text);
1574
+ delivered = true;
1575
+ }
1576
+ }
1577
+ if (!delivered) {
1578
+ this.queuePendingNotice(
1579
+ memberId,
1580
+ options?.timestamp === undefined ? { text } : { text, timestamp: options.timestamp },
1581
+ );
1582
+ }
1583
+ }
1584
+
1585
+ /**
1586
+ * 0.31:body 上下文水位。Stage 4 起读上一 Run 结束时 EU 记录的标量,
1587
+ * 不重建窗口、不推断;没有活体或无 token 预算时返回 undefined。
1588
+ */
1589
+ contextRatio(sessionId: string): number | undefined {
1590
+ return this.entries.get(sessionId)?.runtime.lastContextRatio;
1591
+ }
1592
+
1593
+ /**
1594
+ * 0.31:该 body 的交互请求能否到达人类。只认「bridge 已挂上」:
1595
+ * permissionMode=allow 的无 team body 不发请求,避免请求发进无人订阅的
1596
+ * 成员事件流后永久等待。有父流但没 bridge 同样不算。
1597
+ */
1598
+ canConfirm(sessionId: string): boolean {
1599
+ const entry = this.entries.get(sessionId);
1600
+ return entry !== undefined && entry.mode === 'bridge' && this.parentEvents !== undefined;
1601
+ }
1602
+
1603
+ /**
1604
+ * 0.32:挂上 / 摘掉收件箱。只影响之后 spawn 的 ExecutionUnit;已存在的 ExecutionUnit 按 CONTRACT
1605
+ * 保留 spawn 时的决定(`disableInbox` 负责逐 ExecutionUnit 关闭)。
1606
+ */
1607
+ attachInbox(inbox: AgentInboxPort | undefined): void {
1608
+ this.inbox = inbox;
1609
+ }
1610
+
1611
+ /** 0.32:旧 ExecutionUnit 的 inbox hook 不再取消息(rotate / retire)。 */
1612
+ disableInbox(sessionId: string): void {
1613
+ const entry = this.entries.get(sessionId);
1614
+ if (entry?.inboxState !== undefined) entry.inboxState.enabled = false;
1615
+ }
1616
+
1617
+ /** 0.32:rotate 回滚时恢复旧 ExecutionUnit 的 inbox hook。 */
1618
+ enableInbox(sessionId: string): void {
1619
+ const entry = this.entries.get(sessionId);
1620
+ if (entry?.inboxState !== undefined) entry.inboxState.enabled = true;
1621
+ }
1622
+
1623
+ /** 0.32:清掉该成员尚未注入的 notice(retire 时避免串到新 ExecutionUnit)。 */
1624
+ clearPendingNotices(memberId: string): void {
1625
+ this.pendingNotices.delete(memberId);
1626
+ }
1627
+
1628
+ private queuePendingNotice(memberId: string, notice: PendingNotice): void {
1629
+ const existing = this.pendingNotices.get(memberId);
1630
+ if (existing !== undefined) {
1631
+ existing.push(notice);
1632
+ if (existing.length > MAX_PENDING_NOTICES) {
1633
+ existing.splice(0, existing.length - MAX_PENDING_NOTICES);
1634
+ }
1635
+ return;
1636
+ }
1637
+ if (this.pendingNotices.size >= MAX_PENDING_NOTICE_MEMBERS) {
1638
+ const oldest = this.pendingNotices.keys().next().value;
1639
+ if (oldest !== undefined) this.pendingNotices.delete(oldest);
1640
+ }
1641
+ this.pendingNotices.set(memberId, [notice]);
1642
+ }
1643
+
1644
+ private takePendingNotices(memberId: string): PendingNotice[] {
1645
+ const notices = this.pendingNotices.get(memberId);
1646
+ if (notices === undefined) return [];
1647
+ this.pendingNotices.delete(memberId);
1648
+ return notices;
1649
+ }
1650
+
1651
+ async dispose(member: MemberExecutionMember): Promise<void> {
1652
+ const entry = this.entries.get(member.session_id);
1653
+ if (!entry) return;
1654
+ // 先移除,避免 dispose 期间 / 之后又有 runTurn 走进已释放的 runtime
1655
+ this.entries.delete(member.session_id);
1656
+ for (const unsubscribe of entry.unsubscribers) unsubscribe();
1657
+ entry.unsubscribers.length = 0;
1658
+ this.clearPending(entry);
1659
+ // Stage 4:EU 生命周期归 Runtime 目录;直接 dispose 会留下 stale cache,
1660
+ // 同 (tenant, session) 再 spawn 时拿回已释放的实例。
1661
+ await this.runtime.retireExecutionUnit({
1662
+ tenantId: this.tenantId ?? 'default',
1663
+ sessionId: member.session_id,
1664
+ });
1665
+ }
1666
+
1667
+ /**
1668
+ * Stage 4:用已加载的 RunRecord 恢复成员的一轮 run。
1669
+ *
1670
+ * 调用方(AgentService)负责 RunRecord 加载与 scheduler 串行;这里只按
1671
+ * `record.session_id` 找活的 ExecutionUnit。未 spawn 时抛稳定错误码,
1672
+ * 由装配层映射到 RPC,不做隐式 spawn(语义由 AgentService 决定)。
1673
+ */
1674
+ async resumeRun(record: RunRecord, opts?: RunOptions): Promise<string> {
1675
+ const entry = this.entries.get(record.session_id);
1676
+ if (entry === undefined || entry.runtime.resumeRun === undefined) {
1677
+ throw new Error(`member_execution_not_found: ${record.session_id}`);
1678
+ }
1679
+ return entry.runtime.resumeRun(record, opts);
1680
+ }
1681
+
1682
+ sessionLeaseToken(sessionId: string): number | undefined {
1683
+ return this.entries.get(sessionId)?.runtime.sessionLeaseToken?.(sessionId);
1684
+ }
1685
+
1686
+ /**
1687
+ * Additive (title_source): name a session shell explicitly.
1688
+ *
1689
+ * Only touches the shell (title / title_source / updated_at); messages and run
1690
+ * state stay with the Run projection. A shell already marked 'manual' is never
1691
+ * downgraded by a 'generated' write, so a late AI pass cannot clobber a rename.
1692
+ * Returns false when this host has no SessionStore (headless / pure memory).
1693
+ */
1694
+ async setSessionTitle(
1695
+ sessionId: string,
1696
+ title: string,
1697
+ source: SessionTitleSource,
1698
+ ): Promise<boolean> {
1699
+ const store = this.session;
1700
+ if (store === undefined) return false;
1701
+ // 空 / 非字符串标题绝不落壳:占位值会遮住有意义的命名(undefined 不该出现)。
1702
+ // 调用方(nameNewSession / sessions.rename)应给出真实名字;这里兜底拒写。
1703
+ if (typeof title !== 'string' || title.trim() === '') return false;
1704
+ const stored = await store.load(sessionId);
1705
+ if (stored?.title_source === 'manual' && source !== 'manual') return false;
1706
+ const now = Date.now();
1707
+ // A brand-new body has no shell yet: synthesise a name-only one. status must
1708
+ // not be left to the backend default (SQLite stores 'running'), otherwise the
1709
+ // liveness sweep would treat a session that never ran as a crashed run.
1710
+ const base: SessionState = stored ?? {
1711
+ session_id: sessionId,
1712
+ created_at: now,
1713
+ updated_at: now,
1714
+ status: 'completed',
1715
+ };
1716
+ await store.save({ ...base, title, title_source: source, updated_at: now });
1717
+ return true;
1718
+ }
1719
+
1720
+ /**
1721
+ * Additive(q-session-fix):壳缺失时合成一份最小壳;已存在则零写入。
1722
+ *
1723
+ * 与 `setSessionTitle` 的「新 body 无壳」分支同一口径:`status: 'completed'`,
1724
+ * 不留给后端默认(SQLite 默认 'running' 会让 liveness sweep 误判崩溃 run)。
1725
+ * 不写 title / messages —— 标题仍走既有命名链路,正文由首轮 run 落盘。
1726
+ */
1727
+ async ensureSessionShell(sessionId: string): Promise<boolean> {
1728
+ const store = this.session;
1729
+ if (store === undefined) return false;
1730
+ const stored = await store.load(sessionId);
1731
+ if (stored !== null) return false;
1732
+ const now = Date.now();
1733
+ await store.save({
1734
+ session_id: sessionId,
1735
+ created_at: now,
1736
+ updated_at: now,
1737
+ status: 'completed',
1738
+ });
1739
+ return true;
1740
+ }
1741
+
1742
+ async ensureSessionLease(sessionId: string, minFence?: number): Promise<LeaseGrant | undefined> {
1743
+ const entry = this.entries.get(sessionId);
1744
+ if (entry === undefined) return undefined;
1745
+ return entry.runtime.ensureSessionLease?.(sessionId, minFence);
1746
+ }
1747
+
1748
+ /**
1749
+ * CONTRACT-hot-apply §4:把权限规则热应用到所有存活成员 ExecutionUnit。
1750
+ *
1751
+ * 规则整体替换(与 owner 侧同一语义)。这里只覆盖 core `PermissionPolicy` 的
1752
+ * 判定面;成员工具的 checkPermission 包装(`restrictPermissions`)把 ask 折回
1753
+ * bridge / deny,属于装配期决定,热应用不改它。
1754
+ * `members` 有记录但尚未 spawn 出 ExecutionUnit 时没有可应用的 runtime,跳过并计入未应用。
1755
+ */
1756
+ applyPermissionRules(rules: RuntimePermissionConfig): number {
1757
+ // 热应用来自 owner 同源配置;补回成员自有的 `agent` 免确认后同时供存活的
1758
+ // ExecutionUnit 与之后新建的 ExecutionUnit(spawn)使用。
1759
+ const memberRules = withMemberAutoApprove(rules);
1760
+ this.permission = memberRules;
1761
+ let applied = 0;
1762
+ for (const [sessionId, entry] of this.entries) {
1763
+ const runtime = entry.runtime as MemberRunnableAgent & {
1764
+ applyPermissionRules?: (next: RuntimePermissionConfig) => void;
1765
+ };
1766
+ if (typeof runtime.applyPermissionRules !== 'function') continue;
1767
+ try {
1768
+ runtime.applyPermissionRules(memberRules);
1769
+ applied += 1;
1770
+ } catch (error) {
1771
+ // 单个 ExecutionUnit 失败不影响其它 ExecutionUnit;装配层按数量判定是否全部生效。
1772
+ this.logger.warn('agent.member.permission_apply_failed', {
1773
+ session_id: sessionId,
1774
+ error: error instanceof Error ? error.message : String(error),
1775
+ });
1776
+ }
1777
+ }
1778
+ return applied;
1779
+ }
1780
+
1781
+ /**
1782
+ * 工具热重载(CONTRACT-hot-apply §4,additive):在**同一具 body** 上重跑工具筛选,
1783
+ * 原地替换 body 自己的工具宿主,不重建 body、不动 session / context / provider。
1784
+ *
1785
+ * - 没有在跑轮 → 立即应用;
1786
+ * - 有在跑轮 → 置 pending,run 结束再应用(ADR-054 单 run;run 中途换工具面会打乱
1787
+ * 已在途的工具调用与 prompt prefix)。
1788
+ *
1789
+ * `tools` 缺省取父宿主当前工具面;传入时以传入集合为来源(调用方刚应用过的快照)。
1790
+ * 返回实际刷新的 body 数。
1791
+ */
1792
+ refreshTools(tools?: readonly ToolDefinition[]): number {
1793
+ const source = tools ?? this.pluginHost?.listTools() ?? [];
1794
+ let applied = 0;
1795
+ for (const entry of this.entries.values()) {
1796
+ if (entry.running) {
1797
+ entry.toolsRefreshPending = true;
1798
+ entry.pendingTools = source;
1799
+ continue;
1800
+ }
1801
+ if (this.applyToolsToEntry(entry, source)) applied += 1;
1802
+ }
1803
+ return applied;
1804
+ }
1805
+
1806
+ /**
1807
+ * issue-0:running body 当前广告的工具名并集(实读各 body 自己的工具宿主)。
1808
+ *
1809
+ * 工具热应用把引擎注册表立即推到新集,而 running 成员的工具面延迟到轮边界才刷新。
1810
+ * 装配层用这份并集设引擎 retain,使窗口期内引擎仍能执行活体成员面仍广告的工具。
1811
+ * idle body 的面已被 refreshTools 即时刷新到宿主新集,无需 retain,故只收 running。
1812
+ */
1813
+ runningToolNames(): Set<string> {
1814
+ const names = new Set<string>();
1815
+ for (const entry of this.entries.values()) {
1816
+ if (!entry.running) continue;
1817
+ for (const tool of entry.pluginHost.listTools()) names.add(tool.name);
1818
+ }
1819
+ return names;
1820
+ }
1821
+
1822
+ /** issue-0:挂上轮边界工具刷新回调(传 undefined 关闭);finishRun 应用 pending 刷新后触发。 */
1823
+ setToolsRefreshListener(listener: (() => void) | undefined): void {
1824
+ this.toolsRefreshListener = listener;
1825
+ }
1826
+
1827
+ /**
1828
+ * 0.51:该成员这一份工具清单(canonical `tools.list{agent_id}` 的唯一数据源)。
1829
+ *
1830
+ * 两条路径,都是真实注册路径的结果:
1831
+ * - **有活身体**:直接读那具 body 自己的 `MemoryPluginHost`。工具热刷新、`disableInbox`、
1832
+ * `inboxState` 之类只在运行期发生的事都会被如实反映 —— 这是实读,不是按配置重算。
1833
+ * - **当前没有活身体**:调用 `buildSurface`,也就是 `spawn` 注册进新宿主用的**同一个
1834
+ * 函数**(同一个 `effectivePermissionMode` 判定、同一份 `selectTools(mode)` +
1835
+ * `restrictPermissions`、同一个 inbox 工具判定)。所以它答出的就是「一具新身体此刻
1836
+ * 会拿到什么」;唯一差别是这里不建 body —— 不 spawn、不占 `maxLiveBodies` 名额、
1837
+ * 不留任何副作用。想让两条路径保持一致,唯一的办法就是共用 `buildSurface`。
1838
+ *
1839
+ * 为什么不再报 `surface: 'live' | 'derived'`:那是「两个工具面」的残留口径。成员用的
1840
+ * 就是节点那一份清单,实读与推导只是取数路径的差别,调用方不需要知道。
1841
+ */
1842
+ toolSurface(member: MemberExecutionMember): MemberToolEntry[] {
1843
+ const entry = this.entries.get(member.session_id);
1844
+ if (entry !== undefined && entry.memberId === member.id) {
1845
+ return describeTools(entry.pluginHost.listTools());
1846
+ }
1847
+ return describeTools(this.buildSurface(member).tools);
1848
+ }
1849
+
1850
+ /**
1851
+ * 通用成员级工具(当前只有 `inbox`):每具 body 都会拿到、与具体成员无关的工具。
1852
+ *
1853
+ * 工具权限统一规范:节点口径的工具清单(`tools.list` / `capabilities.list`)与
1854
+ * `permissions.setToolPolicy` 的存在性校验经此把通用成员工具纳入同一份权限面 ——
1855
+ * 不再按注册作用域分裂成「全局工具可查可设、成员工具不可见」。
1856
+ *
1857
+ * 判据仍只在真实注册路径一处:定义用 spawn 同源的 `createInboxTool` 构造,只读
1858
+ * 描述符(name / description / schema / checkPermission 都与 agentId 无关,只有
1859
+ * handler 闭包绑具体 body)——这里的产物**只作描述,绝不注册或执行**,agentId
1860
+ * 占位空串即可。内核没 attach 收件箱时没有这个工具,返回空数组。
1861
+ *
1862
+ * 未来新增「所有 agent 都有」的成员级工具时,只在这里追加,不在 serve 另拼清单。
1863
+ */
1864
+ commonMemberTools(): MemberToolEntry[] {
1865
+ if (this.inbox === undefined) return [];
1866
+ return describeTools([createInboxTool({ inbox: this.inbox, agentId: '' })]);
1867
+ }
1868
+
1869
+ /** 轮结束:清 running;若期间收到过工具刷新,在轮边界应用。 */
1870
+ private finishRun(member: MemberExecutionMember, entry: MemberExecutionEntry): void {
1871
+ entry.running = false;
1872
+ if (!entry.toolsRefreshPending) return;
1873
+ entry.toolsRefreshPending = false;
1874
+ const source = entry.pendingTools ?? this.pluginHost?.listTools() ?? [];
1875
+ entry.pendingTools = undefined;
1876
+ // body 已被 dispose(entries 里已无此条目)时不再触碰其宿主。
1877
+ if (this.entries.get(member.session_id) !== entry) return;
1878
+ this.applyToolsToEntry(entry, source);
1879
+ // issue-0:成员面已在轮边界刷新 → 通知装配层重算引擎 retain、冲刷已释放工具的移除,
1880
+ // 使引擎注册表与成员工具面在同一轮边界收敛(消除热应用不同步窗口)。
1881
+ this.toolsRefreshListener?.();
1882
+ }
1883
+
1884
+ /**
1885
+ * 成员应有的工具面(**唯一一份规格**)。
1886
+ *
1887
+ * spawn、工具热刷新、`tools.list{agent_id}` 的推导路径都调这里:谁都不许再写一份
1888
+ * 「成员有哪些工具」——无身体时答出的「新身体会拿到的」,靠的就是这里与 spawn 是
1889
+ * 同一个函数,不是两段长得像的代码。
1890
+ *
1891
+ * 内容 = `effectivePermissionMode`(或调用方钉死的 mode)+ `selectTools(mode)` +
1892
+ * `restrictPermissions` + inbox 工具判定 + 成员面贡献的工具。
1893
+ *
1894
+ * `injectInbox` 缺省按「这台内核此刻是否 attach 了收件箱」;工具热刷新要沿用**该 body
1895
+ * 建成时**的判定(`entry.inboxState`),所以可以显式覆盖。
1896
+ */
1897
+ private buildSurface(
1898
+ member: Pick<MemberExecutionMember, 'id' | 'session_id'> & { team_id?: string },
1899
+ options: {
1900
+ mode?: MemberExecutionPermissionMode;
1901
+ /** 显式工具来源快照;缺省读父宿主当前工具面 */
1902
+ source?: readonly ToolDefinition[];
1903
+ injectInbox?: boolean;
1904
+ } = {},
1905
+ ): MemberSurfaceBuild {
1906
+ const mode = options.mode ?? this.effectivePermissionMode(member);
1907
+ const tools = this.selectTools(mode, options.source).map((tool) =>
1908
+ this.restrictPermissions(tool, member.id, mode),
1909
+ );
1910
+ const inboxTool =
1911
+ (options.injectInbox ?? this.inbox !== undefined)
1912
+ ? this.inboxTool(member.id, mode)
1913
+ : undefined;
1914
+ // 0.51:成员面贡献(插件申请端口后给这具 body 的工具)。与 inbox 工具同在
1915
+ // `selectTools` 交集之后追加 —— 只注册在成员身体、不是工作区能力,deny 模式也给。
1916
+ const contributed = this.contributionTools(
1917
+ member,
1918
+ new Set([
1919
+ ...tools.map((tool) => tool.name),
1920
+ ...(inboxTool === undefined ? [] : [inboxTool.name]),
1921
+ ]),
1922
+ );
1923
+ // inbox 工具只读本地队列,不是工作区能力:deny 模式也注册;顺序恒定在父宿主工具之后,
1924
+ // 与 spawn 注册进宿主、`--tools` / 卡片展示的顺序一致。贡献工具排在它后面(0.51 期 0
1925
+ // 的空壳贡献不产出工具,输出因此与 0.50 逐字相同)。
1926
+ return {
1927
+ mode,
1928
+ tools: [...tools, ...(inboxTool === undefined ? [] : [inboxTool]), ...contributed],
1929
+ };
1930
+ }
1931
+
1932
+ /** 运行期注入的收件箱工具;内核没 attach 收件箱时没有这个工具。 */
1933
+ private inboxTool(
1934
+ memberId: string,
1935
+ mode: MemberExecutionPermissionMode,
1936
+ ): ToolDefinition | undefined {
1937
+ const inbox = this.inbox;
1938
+ if (inbox === undefined) return undefined;
1939
+ const tool = this.restrictPermissions(
1940
+ createInboxTool({ inbox, agentId: memberId }),
1941
+ memberId,
1942
+ mode,
1943
+ );
1944
+ // tools-engine P2:接线端口(缺省 no-op)。就地换 handler,def 身份不变 ⇒
1945
+ // spawn 注册 / 快照不受影响;callback 执行的是本 body 的原闭包(agentId 在内)。
1946
+ this.wireInboxTool?.(tool, memberId);
1947
+ return tool;
1948
+ }
1949
+
1950
+ /** 本内核能拿到的成员面贡献。老宿主 / 纯内存构造没实现这两个可选方法 ⇒ 空数组。 */
1951
+ private memberBodyContributions(): readonly MemberBodyContribution[] {
1952
+ return this.pluginHost?.getMemberBodyContributions?.() ?? [];
1953
+ }
1954
+
1955
+ /**
1956
+ * 一具 body 由成员面贡献产出的工具(纯函数,可重复调用)。
1957
+ *
1958
+ * 这里给的端口是**推导值**:`isActive()` 恒 true、`publish` 是 noop。理由:`tools()` 的
1959
+ * 契约是纯函数,不该看 rotate 开关、也不该发事件;推导路径(`tools.list{agent_id}` 没有
1960
+ * 活身体时、工具热刷新)就在这类调用里。真 body 的端口在 spawn 里另建一次(只有 hooks 用它)。
1961
+ *
1962
+ * @param taken 已经占用的工具名(父宿主 + inbox 注入的):同名冲突以既有定义为谁,
1963
+ * 贡献顶不掉宿主工具,也不能让 `registerTool` 在 spawn 时抛错把整具 body 建失败
1964
+ */
1965
+ private contributionTools(
1966
+ member: { id: string; session_id: string },
1967
+ taken: ReadonlySet<string>,
1968
+ ): ToolDefinition[] {
1969
+ const contributed: ToolDefinition[] = [];
1970
+ const used = new Set(taken);
1971
+ for (const contribution of this.memberBodyContributions()) {
1972
+ const port = this.memberBodyPort(contribution, member, DERIVED_BODY);
1973
+ if (port === undefined) continue;
1974
+ for (const tool of contribution.tools(port)) {
1975
+ if (used.has(tool.name)) continue;
1976
+ used.add(tool.name);
1977
+ contributed.push(tool);
1978
+ }
1979
+ }
1980
+ return contributed;
1981
+ }
1982
+
1983
+ /**
1984
+ * 一具 body 的端口载体(含端口表)。
1985
+ *
1986
+ * 端口表缺任何一项 ⇒ 返回 undefined,这条贡献在这具 body 上**整条不生效**(fail-closed)。
1987
+ * 典型来源:内核没 attach 收件箱(未配置 dataDir),端口无从谈起 —— 给它一个方法全抛错的
1988
+ * 壳只会把「没有这个能力」变成更晚、更难查的运行期惊喜。
1989
+ */
1990
+ private memberBodyPort(
1991
+ contribution: MemberBodyContribution,
1992
+ member: { id: string; session_id: string },
1993
+ body: { isActive: () => boolean; publish: (event: MemberBodyNoticeEvent) => void },
1994
+ ): MemberBodyPort | undefined {
1995
+ const ports = buildMemberBodyPorts({
1996
+ requested: contribution.ports,
1997
+ inbox: this.inbox,
1998
+ agentId: member.id,
1999
+ sessionId: member.session_id,
2000
+ });
2001
+ if (ports === undefined) return undefined;
2002
+ return {
2003
+ pluginId: contribution.name,
2004
+ agentId: member.id,
2005
+ sessionId: member.session_id,
2006
+ ports,
2007
+ isActive: body.isActive,
2008
+ publish: body.publish,
2009
+ };
2010
+ }
2011
+
2012
+ /**
2013
+ * spawn 里一次性登记成员面贡献的 hook。
2014
+ *
2015
+ * 与 `contributionTools` 分开的**唯一**原因:`hooks()` 一具 body 只许调一次(它内部持有
2016
+ * per-body 状态)。若让它也在推导路径跑,rotate 期间就会多出一批不该存在的 hook。
2017
+ */
2018
+ private registerContributionHooks(
2019
+ bodyHost: MemoryPluginHost,
2020
+ member: MemberExecutionMember,
2021
+ inboxState: { enabled: boolean } | undefined,
2022
+ events: MemoryEventStream,
2023
+ ): void {
2024
+ for (const contribution of this.memberBodyContributions()) {
2025
+ const port = this.memberBodyPort(contribution, member, {
2026
+ // 与 0.32 的 `disableInbox` 一一对应:rotate / retire 后旧 body 的 `enabled` 翻 false。
2027
+ // 没 attach 收件箱时没有这层开关,恒 true(这具 body 就是它身份的唯一持有者)。
2028
+ isActive: () => inboxState?.enabled ?? true,
2029
+ // notice 必须写进**这具 body** 的事件流:写父流会让 rotate 期间新旧 body 的提示串台。
2030
+ publish: (event) => events.publish(event),
2031
+ });
2032
+ if (port === undefined) continue;
2033
+ for (const hook of contribution.hooks?.(port) ?? []) bodyHost.registerHook(hook);
2034
+ }
2035
+ }
2036
+
2037
+ /**
2038
+ * 把目标工具面替换进 body 自己的宿主。
2039
+ *
2040
+ * `MemoryPluginHost.registerTool` 对同名重复注册抛错,因此先清空旧工具再注册新集合;
2041
+ * 失败时尽量恢复旧定义(best-effort),不让 body 停在半空状态。返回是否成功。
2042
+ */
2043
+ private applyToolsToEntry(
2044
+ entry: MemberExecutionEntry,
2045
+ source: readonly ToolDefinition[],
2046
+ ): boolean {
2047
+ const previous = entry.pluginHost.listTools();
2048
+ // 与 spawn 同一套判定(`buildSurface`);只有「来源快照 / 该 body 的 mode /
2049
+ // 它建成时是否已 attach 收件箱」这三项按 entry 走。
2050
+ const surface = this.buildSurface(
2051
+ { id: entry.memberId, session_id: entry.sessionId },
2052
+ {
2053
+ mode: entry.mode,
2054
+ source,
2055
+ injectInbox: this.inbox !== undefined && entry.inboxState !== undefined,
2056
+ },
2057
+ );
2058
+ const tools = surface.tools;
2059
+ try {
2060
+ for (const existing of previous) entry.pluginHost.unregisterTool(existing.name);
2061
+ for (const tool of tools) entry.pluginHost.registerTool(tool);
2062
+ return true;
2063
+ } catch (error) {
2064
+ try {
2065
+ for (const tool of entry.pluginHost.listTools()) {
2066
+ entry.pluginHost.unregisterTool(tool.name);
2067
+ }
2068
+ for (const tool of previous) entry.pluginHost.registerTool(tool);
2069
+ } catch {
2070
+ // 回滚是 best-effort:不掩盖原始错误
2071
+ }
2072
+ this.logger.warn('agent.member.tools_refresh_failed', {
2073
+ member_id: entry.memberId,
2074
+ error: error instanceof Error ? error.message : String(error),
2075
+ });
2076
+ return false;
2077
+ }
2078
+ }
2079
+
2080
+ /**
2081
+ * 0.28 D6:角色转换后把上下文策略热应用到该成员的**活体**(契约 §5 / R4)。
2082
+ *
2083
+ * 两件事一起换,body 不重建、历史不动 —— 「转正那天同一具活着的 body
2084
+ * 不必重建,但下一次 run 的上下文策略按新身份生效」:
2085
+ * - 自动压缩开关(entry 上的可变 `contextPolicy`,per-Run 工厂读取);
2086
+ * - 50%–85% 压力提示的尾句文案(core `ExecutionUnit.applyContextPolicy`)。
2087
+ *
2088
+ * 返回实际应用的 body 数。未 spawn(没有活体)时返回 0:那种情况下策略由
2089
+ * 下一次 `spawn` 的 `contextPolicyFor(role)` 生效,两条路径共用同一份映射。
2090
+ */
2091
+ applyContextPolicy(member: MemberExecutionMember): number {
2092
+ const policy = contextPolicyFor(member.role);
2093
+ let applied = 0;
2094
+ for (const [sessionId, entry] of this.entries) {
2095
+ if (entry.memberId !== member.id) continue;
2096
+ try {
2097
+ let touched = entry.contextPolicy.autoCompact !== policy.autoCompact;
2098
+ entry.contextPolicy.autoCompact = policy.autoCompact;
2099
+ if (typeof entry.runtime.applyContextPolicy === 'function') {
2100
+ entry.runtime.applyContextPolicy({ contextPressureHint: policy.pressureHint });
2101
+ touched = true;
2102
+ }
2103
+ if (touched) applied += 1;
2104
+ } catch (error) {
2105
+ // 单个 ExecutionUnit 失败不影响其它 ExecutionUnit;装配层按数量判定。
2106
+ this.logger.warn('agent.member.context_policy_apply_failed', {
2107
+ session_id: sessionId,
2108
+ error: error instanceof Error ? error.message : String(error),
2109
+ });
2110
+ }
2111
+ }
2112
+ return applied;
2113
+ }
2114
+
2115
+ /**
2116
+ * 0.52:基础信息变更的真值同步(**不**重建 body、**不**碰 Self Card)。
2117
+ *
2118
+ * `member` 是变更后的完整身份(`AgentService` 从 registry 记录现算)。这里只把它写进该
2119
+ * body 的真值盒:下一轮 BeforeLlm 由 `self-card-delta` hook 与「模型相信的值」diff,变了
2120
+ * 就注入一条环境信息,没变就什么都不发(同一变更因此只报一次)。
2121
+ *
2122
+ * 返回命中的 body 数(与 `applyContextPolicy` 同口径)。0 = 没有活体:此时下一次 spawn
2123
+ * 直接用新记录建卡,本来就不需要告知。
2124
+ */
2125
+ noteSelfCardIdentity(member: MemberExecutionMember): number {
2126
+ const entry = this.entries.get(member.session_id);
2127
+ if (entry === undefined || entry.memberId !== member.id) return 0;
2128
+ // 真值盒存入有效展示 model(显式 pin ?? 宿主缺省 wire),与 delta 基线 / Self Card 同口径。
2129
+ entry.selfCardIdentity.member = {
2130
+ ...member,
2131
+ model: member.model ?? this.modelWire ?? this.model,
2132
+ };
2133
+ return 1;
2134
+ }
2135
+
2136
+ /**
2137
+ * 权限 bridge:成员请求 → 父流(补成员归属字段);父级应答 → 成员流。
2138
+ * 只回灌本成员挂起过的 requestId,父流上的其它应答不会串台。
2139
+ */
2140
+ private attachBridge(member: MemberExecutionMember, entry: MemberExecutionEntry): void {
2141
+ const parentEvents = this.parentEvents;
2142
+ if (!parentEvents) return;
2143
+
2144
+ entry.unsubscribers.push(
2145
+ entry.events.subscribe((event: RunEvent) => {
2146
+ if (!PERMISSION_REQUEST_EVENTS.has(event.type)) return;
2147
+ if (this.entries.get(member.session_id) !== entry) return;
2148
+
2149
+ const kind = event.type === 'ask.user.requested' ? 'ask' : 'permission';
2150
+ const requestId = readRequestId(event.data);
2151
+ if (requestId !== undefined) entry.pendingPermissions.set(requestId, { kind });
2152
+ if (!entry.waiting) {
2153
+ entry.waiting = true;
2154
+ this.notifyPermissionState(member.id, member.session_id, 'waiting');
2155
+ }
2156
+ const data = bridgeRequestData(event, member);
2157
+ const forwarded: RunEvent = { ...event, data };
2158
+ parentEvents.publish(forwarded);
2159
+ if (requestId !== undefined) {
2160
+ this.scheduleDenyAfter(member, entry, requestId, kind, forwarded);
2161
+ }
2162
+ }),
2163
+ );
2164
+
2165
+ entry.unsubscribers.push(
2166
+ parentEvents.subscribe((event: RunEvent) => {
2167
+ if (!PERMISSION_RESPONSE_EVENTS.has(event.type)) return;
2168
+ if (this.entries.get(member.session_id) !== entry) return;
2169
+
2170
+ const requestId = readRequestId(event.data);
2171
+ if (requestId === undefined) return;
2172
+ const pending = entry.pendingPermissions.get(requestId);
2173
+ if (pending === undefined) return;
2174
+
2175
+ // only-human:缺 answered_by 视为 legacy human;policy 只接受 deny_after。
2176
+ const data = isRecord(event.data) ? event.data : {};
2177
+ const answeredBy = data.answered_by;
2178
+ if (
2179
+ answeredBy !== undefined &&
2180
+ answeredBy !== 'human' &&
2181
+ !(answeredBy === 'policy' && data.policy === 'deny_after')
2182
+ ) {
2183
+ this.logger.warn('agent.member.permission_response_dropped', {
2184
+ member_id: member.id,
2185
+ session_id: member.session_id,
2186
+ request_id: requestId,
2187
+ answered_by: answeredBy,
2188
+ policy: data.policy,
2189
+ });
2190
+ return;
2191
+ }
2192
+
2193
+ entry.pendingPermissions.delete(requestId);
2194
+ if (pending.timer !== undefined) clearTimeout(pending.timer);
2195
+ // 原样交给成员事件流,由 core 按 requestId 路由回发起请求的 waitFor。
2196
+ entry.events.publish(event);
2197
+ this.noteBridgeSettled(member, entry);
2198
+ }),
2199
+ );
2200
+ }
2201
+
2202
+ /**
2203
+ * 非空 team_id 的成员把全局 allow 提升为 bridge;显式 deny 保持只读工具,
2204
+ * 不因 Team 绑定放宽。缺 parentEvents 时仍由 ask → deny 收口。
2205
+ *
2206
+ * 只读 `team_id`:`tools.list{agent_id}` 的推导路径只有一份成员视图,不必拼整条
2207
+ * `MemberExecutionMember`(推导不 spawn,用不到 session / binding)。
2208
+ */
2209
+ private effectivePermissionMode(member: { team_id?: string }): MemberExecutionPermissionMode {
2210
+ if (
2211
+ this.forceBridgeForTeams &&
2212
+ this.permissionMode === 'allow' &&
2213
+ typeof member.team_id === 'string' &&
2214
+ member.team_id.length > 0
2215
+ ) {
2216
+ return 'bridge';
2217
+ }
2218
+ return this.permissionMode;
2219
+ }
2220
+
2221
+ private clearPending(entry: MemberExecutionEntry): void {
2222
+ for (const pending of entry.pendingPermissions.values()) {
2223
+ if (pending.timer !== undefined) clearTimeout(pending.timer);
2224
+ }
2225
+ entry.pendingPermissions.clear();
2226
+ }
2227
+
2228
+ private noteBridgeSettled(member: MemberExecutionMember, entry: MemberExecutionEntry): void {
2229
+ if (entry.pendingPermissions.size === 0 && entry.waiting) {
2230
+ entry.waiting = false;
2231
+ this.notifyPermissionState(member.id, member.session_id, 'running');
2232
+ }
2233
+ }
2234
+
2235
+ /**
2236
+ * team 显式 deny-after 的单次 deadline;hold / 缺失 / 非法秒数都不建定时器。
2237
+ * 到期后把 normal response 同时交给成员流(解除等待)与父流(供父入口观测)。
2238
+ */
2239
+ private scheduleDenyAfter(
2240
+ member: MemberExecutionMember,
2241
+ entry: MemberExecutionEntry,
2242
+ requestId: string,
2243
+ kind: 'permission' | 'ask',
2244
+ forwarded: RunEvent,
2245
+ ): void {
2246
+ // 定时器只能由 bridge 创建;没有父流就没有人端,走既有的 ask → deny。
2247
+ if (this.parentEvents === undefined) return;
2248
+ const policy = this.permissionPolicy?.(member.team_id);
2249
+ if (policy?.unattended !== 'deny-after') return;
2250
+ const seconds = policy.denyAfterSeconds;
2251
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0) return;
2252
+
2253
+ const timer = setTimeout(
2254
+ () => {
2255
+ if (this.entries.get(member.session_id) !== entry) return;
2256
+ const pending = entry.pendingPermissions.get(requestId);
2257
+ if (pending === undefined || pending.kind !== kind) return;
2258
+ entry.pendingPermissions.delete(requestId);
2259
+ const data = isRecord(forwarded.data) ? forwarded.data : {};
2260
+ const sessionId =
2261
+ typeof data.session_id === 'string' && data.session_id.length > 0
2262
+ ? data.session_id
2263
+ : undefined;
2264
+ const responseData =
2265
+ kind === 'ask'
2266
+ ? {
2267
+ requestId,
2268
+ answers: [],
2269
+ ...(sessionId !== undefined ? { session_id: sessionId } : {}),
2270
+ answered_by: 'policy',
2271
+ answered_via: 'policy',
2272
+ policy: 'deny_after',
2273
+ }
2274
+ : {
2275
+ requestId,
2276
+ decision: 'deny',
2277
+ scope: 'once',
2278
+ ...(sessionId !== undefined ? { session_id: sessionId } : {}),
2279
+ answered_by: 'policy',
2280
+ answered_via: 'policy',
2281
+ policy: 'deny_after',
2282
+ reason: 'deny_after',
2283
+ };
2284
+ const response: RunEvent = {
2285
+ type: kind === 'ask' ? 'ask.user.answered' : 'tool.permission.response',
2286
+ run_id: forwarded.run_id,
2287
+ data: responseData,
2288
+ ts: Date.now(),
2289
+ };
2290
+ entry.events.publish(response);
2291
+ this.parentEvents?.publish(response);
2292
+ this.noteBridgeSettled(member, entry);
2293
+ },
2294
+ Math.round(seconds * 1000),
2295
+ );
2296
+ // 不能 unref:Bun 在只剩 unref 定时器的 await 上会直接退出/不触发 deadline。
2297
+ entry.pendingPermissions.set(requestId, { kind, timer });
2298
+ }
2299
+
2300
+ private notifyPermissionState(
2301
+ memberId: string,
2302
+ sessionId: string,
2303
+ state: MemberPermissionState,
2304
+ ): void {
2305
+ try {
2306
+ this.onPermissionState?.(memberId, sessionId, state);
2307
+ } catch (error) {
2308
+ this.logger.warn('agent.member.permission_state_callback_failed', {
2309
+ member_id: memberId,
2310
+ session_id: sessionId,
2311
+ error: error instanceof Error ? error.message : String(error),
2312
+ });
2313
+ }
2314
+ }
2315
+
2316
+ /** 该身体能否把「等人类应答」的请求送到父事件流(只有 bridge 有这个订阅)。 */
2317
+ private bridgeAvailable(mode: MemberExecutionPermissionMode): boolean {
2318
+ return mode === 'bridge' && this.parentEvents !== undefined;
2319
+ }
2320
+
2321
+ /**
2322
+ * 该工具在这具成员身体上是否被规则挡住(0.51 只剩两条真实闸)。
2323
+ *
2324
+ * 这是成员侧筛选规则的**唯一**实现:`selectTools` 只问它一个问题。判据顺序有语义 —
2325
+ * - `read`/`media`/`subscribe` 之外的 deny(只读)档:先判,所以 `ask` 在这一档的
2326
+ * 原因是「档位不给」(就算有 bridge,deny 也不会放它);
2327
+ * - 需要父级转发人类应答的 `ask` / `ask_user`:只在真能 bridge 时才进面 —— 成员只会把
2328
+ * 请求发到自己的事件流,没人转发就没人应答,注册进来只会让 run 永久等待。
2329
+ */
2330
+ private toolBlocked(name: string, mode: MemberExecutionPermissionMode): boolean {
2331
+ if (mode === 'deny' && !this.readOnlyTools.has(name)) return true;
2332
+ return PARENT_ANSWERED_TOOL_NAMES.has(name) && !this.bridgeAvailable(mode);
2333
+ }
2334
+
2335
+ /**
2336
+ * 从父宿主挑工具:**父宿主有什么就给什么**,只减上面那两条闸(0.51)。
2337
+ *
2338
+ * 0.51 起不再产出「谁被挡 / 为什么被挡」:那层解释只服务于「两个工具面」的展示,
2339
+ * 用户已裁定删掉。判据没有删 —— 它仍然决定这具身体能调什么。
2340
+ */
2341
+ private selectTools(
2342
+ mode: MemberExecutionPermissionMode,
2343
+ source: readonly ToolDefinition[] = this.pluginHost?.listTools() ?? [],
2344
+ ): ToolDefinition[] {
2345
+ const tools: ToolDefinition[] = [];
2346
+ for (const tool of source) {
2347
+ if (this.toolBlocked(tool.name, mode)) continue;
2348
+ tools.push(tool.name === 'agent' ? restrictAgentTool(tool) : tool);
2349
+ }
2350
+ return tools;
2351
+ }
2352
+
2353
+ /**
2354
+ * ask 的收口顺序(0.54 Bug:用户配了 `auto_approve: [bash]` 仍被拒):
2355
+ *
2356
+ * 1. `autoApprove` 命中(且不在 `neverAutoApprove` 里)⇒ **allow**。这是用户的显式授权
2357
+ * (REPL 的 "always" 也写回这里),无论如何都不该再问一次、更不该折成 deny;
2358
+ * 2. bridge 可用 ⇒ 放行给 core(发请求事件 → 父级应答);
2359
+ * 3. 其余按 deny 收口并记日志,避免 run 永久等待应答。
2360
+ *
2361
+ * 为什么 1 必须在 2 之前:2 的前提是「有人能应答」,而 autoApprove 已经是事前的答案。
2362
+ * 为什么这条以前漏了:`autoApprove` 只在 `fallbackDecision`(**没有** checkPermission 的
2363
+ * 工具)里查过;bash / read / edit 自带 checkPermission 并统一返回 `ask`(想让 core 的
2364
+ * PermissionPolicy 去查表白名单),而本方法在非 bridge 档把 ask 直接折成 deny ——
2365
+ * 于是「越需要免确认的重工具越拿不到 autoApprove」,正好反了。
2366
+ */
2367
+ private restrictPermissions(
2368
+ tool: ToolDefinition,
2369
+ memberId: string,
2370
+ mode: MemberExecutionPermissionMode,
2371
+ ): ToolDefinition {
2372
+ const check = tool.checkPermission;
2373
+ return {
2374
+ ...tool,
2375
+ checkPermission: async (input, ctx) => {
2376
+ const decision = check ? await check(input, ctx) : this.fallbackDecision(tool.name);
2377
+ if (decision !== 'ask') return decision;
2378
+ if (this.autoApproved(tool.name)) return 'allow';
2379
+ if (mode === 'bridge' && this.parentEvents !== undefined) return 'ask';
2380
+ this.logger.warn('agent.member.permission_ask_denied', {
2381
+ member_id: memberId,
2382
+ tool: tool.name,
2383
+ });
2384
+ return 'deny';
2385
+ },
2386
+ };
2387
+ }
2388
+
2389
+ /** 用户显式免确认(`neverAutoApprove` 的精确工具名命中优先,永远否决)。 */
2390
+ private autoApproved(toolName: string): boolean {
2391
+ if (this.permission?.neverAutoApprove?.includes(toolName) === true) return false;
2392
+ return this.permission?.autoApprove?.includes(toolName) === true;
2393
+ }
2394
+
2395
+ /** 无 checkPermission 的工具:autoApprove 放行,default=ask 因无 bridge 转为 deny */
2396
+ private fallbackDecision(toolName: string): 'allow' | 'deny' {
2397
+ if (this.autoApproved(toolName)) return 'allow';
2398
+ return this.permission?.default === 'ask' ? 'deny' : 'allow';
2399
+ }
2400
+
2401
+ /**
2402
+ * `how to ask for help` 文案。
2403
+ *
2404
+ * 判据只有一个:`ask` 是否真的在成员工具面里(即父宿主注册了 + bridge 可用)。
2405
+ * 没有它时给异步路径:`agent` 工具的 `action=send` 发到本机人类。
2406
+ * 异步路径要同时成立才写:成员能调 `agent`(deny 档只留只读工具,没有 `agent`);成员有
2407
+ * Team(地址路要求 caller.team_id 来补 team 段)。否则只是把阻塞写进最终文本。
2408
+ */
2409
+ private askHelpText(toolNames: readonly string[], teamId: string | undefined): string {
2410
+ // 双认工具名:新名 `ask`,旧名 `ask_user`(0.52 前注册的成员工具面仍可能带旧名)。
2411
+ if (toolNames.includes('ask') || toolNames.includes('ask_user')) {
2412
+ return 'Use the ask tool to request human input.';
2413
+ }
2414
+ if (toolNames.includes('agent') && typeof teamId === 'string' && teamId.length > 0) {
2415
+ return (
2416
+ 'No human is watching this run, so ask is unavailable. To reach a human, ' +
2417
+ 'call the agent tool with action=send and to="human", then end your turn ' +
2418
+ 'with the blocker in your final text.'
2419
+ );
2420
+ }
2421
+ return 'This is a non-interactive run; state blockers in your final text.';
2422
+ }
2423
+
2424
+ /**
2425
+ * 解析本具 body 的 cwd(0.51 Bug 1)。
2426
+ *
2427
+ * 顺序:记录快照(`member.cwd`,create 时烧进去的显式 Team 基础路径)> 装配层的
2428
+ * `cwdFor`(按 `team_id` 重查 Team)。两级都不可用 → 返回 `undefined`,工具退回
2429
+ * `agent.cwd` / `process.cwd()`。
2430
+ *
2431
+ * 为什么在这里做 fs 校验并 warn:这是**唯一**知道「这个值是从哪一级来的」的地方,
2432
+ * 也是第一个有 logger 的地方。工具侧还会再判一次(目录可能在 body 活着的过程中消失),
2433
+ * 那次只能静默降级 —— 所以「降级发生过」这件事只能在这里说清楚。
2434
+ */
2435
+ private memberCwdFor(member: MemberExecutionMember): string | undefined {
2436
+ const teamCwd = member.cwd === undefined ? this.cwdFor?.(member) : undefined;
2437
+ const picked = resolveMemberCwd({
2438
+ ...(member.cwd !== undefined ? { recordCwd: member.cwd } : {}),
2439
+ ...(teamCwd !== undefined ? { teamCwd } : {}),
2440
+ });
2441
+ if (picked.cwd !== undefined) return picked.cwd;
2442
+ if (picked.degraded === 'not_a_directory') {
2443
+ this.logger.warn('agent.member.cwd_degraded', {
2444
+ member_id: member.id,
2445
+ session_id: member.session_id,
2446
+ ...(member.team_id !== undefined ? { team_id: member.team_id } : {}),
2447
+ rejected: picked.rejected,
2448
+ fallback: 'agent.cwd / process.cwd()',
2449
+ });
2450
+ }
2451
+ return undefined;
2452
+ }
2453
+
2454
+ private buildSelfCard(
2455
+ member: MemberExecutionMember,
2456
+ model: string,
2457
+ tools: readonly ToolDefinition[],
2458
+ ): SelfCardOptions {
2459
+ const toolNames = tools.map((tool) => tool.name);
2460
+ const teamId =
2461
+ typeof member.team_id === 'string' && member.team_id.length > 0 ? member.team_id : undefined;
2462
+ return {
2463
+ role: member.name ?? 'member',
2464
+ ...(member.parent_id !== undefined ? { parent_id: member.parent_id } : {}),
2465
+ // 只有绑定 Team 的成员才带该字段;unbound 不伪造。
2466
+ ...(teamId !== undefined ? { team_id: teamId } : {}),
2467
+ // depth-color D1:per-member parent 链真值(与卡片颜色同口径);
2468
+ // 解析不出(老装配 / 未知成员)才回落 host 标量兜底。
2469
+ depth: this.depthFor?.(member) ?? this.depth,
2470
+ model,
2471
+ tools: toolNames,
2472
+ limits: {
2473
+ ...this.limits,
2474
+ ...(this.termination.maxIterations !== undefined
2475
+ ? { maxIterations: this.termination.maxIterations }
2476
+ : {}),
2477
+ ...(this.termination.maxRuntimeSeconds !== undefined
2478
+ ? { maxRuntimeSeconds: this.termination.maxRuntimeSeconds }
2479
+ : {}),
2480
+ },
2481
+ context: { max: this.contextMaxTokens },
2482
+ how_to_ask: this.askHelpText(toolNames, teamId),
2483
+ };
2484
+ }
2485
+
2486
+ private requireEntry(member: MemberExecutionMember): MemberExecutionEntry {
2487
+ const entry = this.entries.get(member.session_id);
2488
+ if (!entry) throw new Error(`member runtime not spawned: ${member.session_id}`);
2489
+ return entry;
2490
+ }
2491
+ }
2492
+
2493
+ /**
2494
+ * 工厂:执行消费面仍只依赖 MemberExecutionPort(createAgentService 的 runtime 选项);
2495
+ * 返回具体宿主类型,装配层据此可达 `updateDefaultModel`(provider.model 热应用写入口)。
2496
+ */
2497
+ export function createMemberExecutionHost(
2498
+ options: MemberExecutionHostOptions,
2499
+ ): MemberExecutionHost {
2500
+ return new MemberExecutionHost(options);
2501
+ }