@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/tool.ts ADDED
@@ -0,0 +1,1306 @@
1
+ /**
2
+ * 内置 `agent` 工具:模型侧唯一的成员生命周期入口。
3
+ *
4
+ * 只做参数映射与错误码格式化;registry、生命周期、批次并行都在 AgentService。
5
+ * 不提供 wait / inbox / status / cancel——等待语义是结束这一轮、回复作为新 turn 到达。
6
+ *
7
+ * @module @vessel-agent/agent
8
+ */
9
+
10
+ import { randomUUID } from 'node:crypto';
11
+ import {
12
+ CONTEXT_PRESSURE_WARN_RATIO,
13
+ type MessageRef,
14
+ type RunEvent,
15
+ type ToolContext,
16
+ type ToolDefinition,
17
+ } from '@vessel-agent/core';
18
+ import { errorText } from './error-text.js';
19
+ import { deliveryFromNotify } from './inbox.js';
20
+ import { HUMAN_PRINCIPAL } from './team-address.js';
21
+ import { TeamMetadataCorruptError } from './team-store.js';
22
+ import {
23
+ AgentError,
24
+ type AgentService,
25
+ type AgentTeamService,
26
+ type BatchItemResult,
27
+ type CloseInput,
28
+ type CreateMemberInput,
29
+ DEFAULT_OWNER,
30
+ type DispatchResult,
31
+ type ListFilter,
32
+ MAX_SESSION_TITLE_LENGTH,
33
+ type MemberState,
34
+ type MemberStatus,
35
+ type MemberVisibility,
36
+ RELEASED_MEMBER_DEFAULT_FIELDS,
37
+ RELEASED_MEMBER_FIELDS,
38
+ RELEASED_MEMBER_LIMIT_DEFAULT,
39
+ RELEASED_MEMBER_LIMIT_MAX,
40
+ type ReleasedMemberField,
41
+ type ReleasedMembersQuery,
42
+ type SendResult,
43
+ type TeamAgentSendResult,
44
+ TeamError,
45
+ } from './types.js';
46
+
47
+ const ACTIONS = ['create', 'hire', 'send', 'close', 'list', 'rotate', 'read'] as const;
48
+
49
+ /** root owner 可见的动作:root 没有 Team,不暴露 create(派 peer 需要 Team) */
50
+ const OWNER_ACTIONS = ['hire', 'send', 'close', 'list', 'rotate', 'read'] as const;
51
+
52
+ /** 成员 ExecutionUnit 可用的动作;rotate 在动作闸门之前单独处理 */
53
+ const BODY_ACTIONS: readonly string[] = [
54
+ 'create',
55
+ 'hire',
56
+ 'close',
57
+ 'rotate',
58
+ 'send',
59
+ 'list',
60
+ 'read',
61
+ ];
62
+
63
+ const VISIBILITIES: readonly MemberVisibility[] = ['private', 'team', 'tenant'];
64
+
65
+ /** `read` 返回的成员会话消息条数:缺省 20,封顶 50(与 sessions.get 的分页上限同量级)。 */
66
+ const READ_MESSAGE_LIMIT_DEFAULT = 20;
67
+ const READ_MESSAGE_LIMIT_MAX = 50;
68
+ /** `read` 单条正文的截断长度(字符):只够看清结论 / 摘要,不搬整段工具输出。 */
69
+ const READ_MESSAGE_MAX_CHARS = 1000;
70
+
71
+ /**
72
+ * rotate 人工批准等待的**上限**(毫秒)。
73
+ *
74
+ * 为什么必须有:这条等待原本没有时限。权限卡要是根本到不了人(浏览器 `POST /v1/rpc`
75
+ * 401、待批页拉不到 pending、TUI 没接 bridge),`waitFor` 就永远不返回 —— 模型这一轮
76
+ * 挂死,人类只看到「卡住」然后按停止。到点按「批准不可用 / 超时」收口,模型拿到明确的
77
+ * `rotate_not_needed` + reason 就能按原计划继续,而不是等一个不会来的应答。
78
+ *
79
+ * 2 分钟的量级:够人看清一张卡再点(页面要重连、还要读上下文);比这更久说明通道
80
+ * 有问题,继续等没有价值(人类随时可以再让模型 rotate 一次)。
81
+ */
82
+ const ROTATE_APPROVAL_TIMEOUT_MS = 120_000;
83
+
84
+ /**
85
+ * 超时档的 reason:与 `approval_unavailable`(等待被别的错误打断)分开。
86
+ *
87
+ * 两者要做的事不同:`approval_timeout` = 人在时限内没答(卡可能没送到);
88
+ * `approval_unavailable` = 这次等待本身出了别的问题。
89
+ */
90
+ const ROTATE_APPROVAL_TIMEOUT_REASON = 'approval_timeout';
91
+
92
+ const MEMBER_STATES: readonly MemberState[] = [
93
+ 'created',
94
+ 'idle',
95
+ 'running',
96
+ 'waiting_permission',
97
+ 'completed',
98
+ 'failed',
99
+ 'cancelled',
100
+ 'closed',
101
+ 'stale',
102
+ ];
103
+
104
+ /** 与 AgentService 一致:对象且不是数组 */
105
+ function isRecord(value: unknown): value is Record<string, unknown> {
106
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
107
+ }
108
+
109
+ function invalid(message: string): AgentError {
110
+ return new AgentError('invalid_input', message);
111
+ }
112
+
113
+ /** 带稳定 code 的错误:AgentError / TeamError / Team 元数据损坏 */
114
+ function isCodedError(error: unknown): error is Error & { code: string } {
115
+ return (
116
+ error instanceof AgentError ||
117
+ error instanceof TeamError ||
118
+ error instanceof TeamMetadataCorruptError
119
+ );
120
+ }
121
+
122
+ /**
123
+ * 取消(run 被中止)判定。
124
+ *
125
+ * 三条来源,缺一条都会把「用户按了停止」说成别的事:
126
+ * - `signal.aborted`:最权威 —— 工具等待时 run 已经中止;
127
+ * - `name === 'AbortError'`:core 的 `EventStream#waitFor` 在 `signal.reason` 是字符串时
128
+ * 把它包成 `Error(reason)` 并置这个 name(`reason === 'user'` 就走这条路);
129
+ * - `code`:`PermissionAbortedError`(`permission_cancelled`)等自带稳定码的取消错误。
130
+ */
131
+ function isCancellation(error: unknown, signal?: AbortSignal): boolean {
132
+ if (signal?.aborted === true) return true;
133
+ if (typeof error !== 'object' || error === null) return false;
134
+ const { name, code } = error as { name?: unknown; code?: unknown };
135
+ return name === 'AbortError' || code === 'cancelled' || code === 'permission_cancelled';
136
+ }
137
+
138
+ /**
139
+ * 取消原因的**可读文本**。
140
+ *
141
+ * 取 `signal.reason` 优先:`waitFor` 把字符串 reason 包成 `Error(reason)`、Error reason
142
+ * 则原样抛,只有 signal 两种都拿得到(真机上中断原因是字符串 `'user'`)。
143
+ */
144
+ function cancellationReason(error: unknown, signal?: AbortSignal): string {
145
+ const reason: unknown = signal?.aborted === true ? signal.reason : undefined;
146
+ const text =
147
+ typeof reason === 'string' && reason.length > 0
148
+ ? reason
149
+ : reason instanceof Error && reason.message.length > 0
150
+ ? reason.message
151
+ : errorText(error);
152
+ return text.trim() === '' ? 'cancelled' : text.trim();
153
+ }
154
+
155
+ /**
156
+ * 批准等待**超时**判定。
157
+ *
158
+ * core 的 `EventStream#waitFor` 超时只抛一种错误:`Timed out after <ms>ms waiting for
159
+ * event "<name>"`(且 `name !== 'AbortError'`)。取消走的是另一条路(AbortError / 取消码),
160
+ * 所以这里只认这条前缀;别的错误仍归 `approval_unavailable`。
161
+ */
162
+ function isApprovalTimeout(error: unknown): boolean {
163
+ return (
164
+ error instanceof Error &&
165
+ error.name !== 'AbortError' &&
166
+ error.message.startsWith('Timed out after ')
167
+ );
168
+ }
169
+
170
+ /**
171
+ * 错误串形状固定;message 已带 code 前缀时去重。
172
+ *
173
+ * 取消必须走 `cancelled` 码,不能落到下面的 `invalid_input` 兜底:兜底会把中断原因
174
+ * (`user`)当成参数错误报给模型,模型据此以为「我的输入有问题」而重试 ——
175
+ * 正确结论是「这一轮被取消了,不要再重试同一件事」。
176
+ */
177
+ function errorResult(error: unknown, signal?: AbortSignal): string {
178
+ if (isCancellation(error, signal)) {
179
+ return `Error: cancelled: ${cancellationReason(error, signal)}`;
180
+ }
181
+ if (!isCodedError(error)) {
182
+ return `Error: invalid_input: ${errorText(error)}`;
183
+ }
184
+ const prefix = `${error.code}: `;
185
+ const message = error.message.startsWith(prefix)
186
+ ? error.message.slice(prefix.length)
187
+ : error.message;
188
+ return `Error: ${error.code}: ${message}`;
189
+ }
190
+
191
+ /** 逐条失败串:稳定 code 在前,异常消息不带前缀时补上 */
192
+ function batchErrorText(error: unknown): string {
193
+ if (isCodedError(error)) {
194
+ const prefix = `${error.code}: `;
195
+ return error.message.startsWith(prefix) ? error.message : `${prefix}${error.message}`;
196
+ }
197
+ return errorText(error);
198
+ }
199
+
200
+ /**
201
+ * list 的工具输出剥掉 `body_history`(0.52)。
202
+ *
203
+ * `body_history` 是每具退役 body 的完整档案(session id / 绑定 / retired_at),给**人**排查
204
+ * rotate 用的;Agent 侧几乎用不到,却让每次 `list` 凭空多出 N 条噪声、把真正有用的
205
+ * `id` / `session_id` / `state` 挤到后面。所以只在工具序列化这一层剥掉,
206
+ * **不删 DTO 字段**:`agents.list` RPC 与 Web 成员详情照旧完整(那里正是给人看的)。
207
+ * 现存 body 用 `bodies` 表达,不受影响。
208
+ */
209
+ function withoutBodyHistory<T extends { body_history?: unknown }>(
210
+ entries: readonly T[],
211
+ ): Record<string, unknown>[] {
212
+ return entries.map((entry) => {
213
+ const copy = { ...entry } as Record<string, unknown>;
214
+ delete copy.body_history;
215
+ return copy;
216
+ });
217
+ }
218
+
219
+ /** dispatch / team.send / SendResult 的逐条结果映射到既有 batch 形状 */
220
+ type SendOutcome = DispatchResult | TeamAgentSendResult | SendResult;
221
+
222
+ function mapSendOutcome(result: SendOutcome): BatchItemResult<SendOutcome> {
223
+ // 带 status 的是 dispatch / TeamService 的业务结果。
224
+ if ('status' in result) {
225
+ if (result.status === 'queued' || result.status === 'notified') {
226
+ return { ok: true, status: result };
227
+ }
228
+ const code = result.code ?? result.status;
229
+ const reason = result.reason;
230
+ const error =
231
+ reason === undefined ? code : reason.startsWith(`${code}: `) ? reason : `${code}: ${reason}`;
232
+ return { ok: false, error };
233
+ }
234
+ // SendResult 只有成功(work queued:true / notify notified:true);失败会 throw。
235
+ return { ok: true, status: result };
236
+ }
237
+
238
+ /** 单条字段与 batch 字段不能同时给 */
239
+ function assertExclusive(
240
+ record: Record<string, unknown>,
241
+ singles: readonly string[],
242
+ batch: string,
243
+ action: string,
244
+ ): void {
245
+ if (record[batch] === undefined) return;
246
+ if (singles.some((key) => record[key] !== undefined)) {
247
+ throw invalid(`${action}: pass either single ${singles.join('/')} or ${batch}, not both`);
248
+ }
249
+ }
250
+
251
+ /** 读取 batch 数组参数;非数组或空数组直接拒绝 */
252
+ function readBatch(record: Record<string, unknown>, key: string, action: string): unknown[] {
253
+ const value = record[key];
254
+ if (!Array.isArray(value)) throw invalid(`${action}: ${key} must be an array`);
255
+ if (value.length === 0) throw invalid(`${action}: ${key} must not be empty`);
256
+ return value;
257
+ }
258
+
259
+ /**
260
+ * 成员派生入口(create / hire)的字段映射:只拷模型可指定的键;
261
+ * kind / owner / parentId / teamId / spawnedBy 由 handler 固定,模型不能伪造。
262
+ * 值不做类型校验:batch 要由 AgentService 逐条拒绝,不能在映射阶段整批抛错。
263
+ */
264
+ function mapDerived(
265
+ record: Record<string, unknown>,
266
+ fixed: Record<string, unknown>,
267
+ ): Record<string, unknown> {
268
+ const input: Record<string, unknown> = { ...fixed };
269
+ if (record.name !== undefined) input.name = record.name;
270
+ // q-session-naming:首会话显式标题(形状校验在 service 逐条做,batch 不整批抛错)。
271
+ if (record.title !== undefined) input.title = record.title;
272
+ if (record.model !== undefined) input.model = record.model;
273
+ // thinking 档位(q-thinking-agent-level-b2):形状/枚举校验在 service 逐条做。
274
+ if (record.thinking_level !== undefined) input.thinkingLevel = record.thinking_level;
275
+ if (record.system_prompt !== undefined) input.systemPrompt = record.system_prompt;
276
+ // q-hire-prompt:可选启动任务(形状校验在 service 逐条做,batch 不整批抛错)。
277
+ if (record.startup_prompt !== undefined) input.startup_prompt = record.startup_prompt;
278
+ // create 的 visibility 由 service 强制 team;传了非 team 值时由 service 逐条拒绝。
279
+ if (record.visibility !== undefined) input.visibility = record.visibility;
280
+ return input;
281
+ }
282
+
283
+ /** 非对象条目原样交给 service,由它逐条拒绝 */
284
+ function mapDerivedEntry(entry: unknown, fixed: Record<string, unknown>): unknown {
285
+ return isRecord(entry) ? mapDerived(entry, fixed) : entry;
286
+ }
287
+
288
+ /**
289
+ * 同名成员已存在时 service 复用而不是新建,返回体带 `reused: true`。
290
+ * 这里补一句 note 点明「没有再建一个」:否则调用方会以为刚创建了成员,
291
+ * 进而再发一次消息,而它其实是在给一个已有的成员派活。
292
+ * 正常创建时不加这个字段,避免每次调用多一段无用文本。
293
+ */
294
+ function withReusedNote<T extends { id: string; name?: string; reused?: boolean }>(
295
+ result: T,
296
+ ): T & { note?: string } {
297
+ if (result.reused !== true) return result;
298
+ return {
299
+ ...result,
300
+ note:
301
+ `a member named ${result.name ?? result.id} already exists in this team; ` +
302
+ 'reuse it with action=send',
303
+ };
304
+ }
305
+
306
+ /** `from` 不暴露:工具调用者恒为 owner,模型不能伪造发送者 */
307
+ function mapSend(record: Record<string, unknown>): Record<string, unknown> {
308
+ const input: Record<string, unknown> = {};
309
+ if (record.to !== undefined) input.to = record.to;
310
+ if (record.content !== undefined) input.content = record.content;
311
+ // 0.41 三档:interrupt / notify 互斥;message_id 仅与 interrupt 同用。
312
+ // notify 是 wire 名,进 handler 后立刻变成 inbox 的投递模式(见 sendSingle)。
313
+ if (record.interrupt !== undefined) input.interrupt = record.interrupt;
314
+ if (record.notify !== undefined) input.notify = record.notify;
315
+ if (record.message_id !== undefined) input.message_id = record.message_id;
316
+ // 块 P2 additive:附件引用原样透传(形状归一在 dispatch / TeamService 的
317
+ // normalizeRefs,与用户 send 同一份;这里不做第二套校验)。
318
+ if (record.refs !== undefined) input.refs = record.refs;
319
+ return input;
320
+ }
321
+
322
+ function readVisibility(value: unknown): MemberVisibility {
323
+ if (typeof value !== 'string' || !VISIBILITIES.includes(value as MemberVisibility)) {
324
+ throw invalid(`invalid visibility "${String(value)}" (expected private|team|tenant)`);
325
+ }
326
+ return value as MemberVisibility;
327
+ }
328
+
329
+ /**
330
+ * rotate: optional name for the new session. Trimmed, 1..MAX_SESSION_TITLE_LENGTH
331
+ * chars (120). Absent = keep the old behaviour (derived title, then AI naming).
332
+ * A named session is marked title_source: manual, so AI naming never overwrites it.
333
+ */
334
+ function readRotateTitle(value: unknown): string | undefined {
335
+ if (value === undefined) return undefined;
336
+ if (typeof value !== 'string') {
337
+ throw invalid('rotate title must be a string');
338
+ }
339
+ const title = value.trim();
340
+ if (title === '') {
341
+ throw invalid('rotate title must not be empty');
342
+ }
343
+ if (Array.from(title).length > MAX_SESSION_TITLE_LENGTH) {
344
+ throw invalid(`rotate title exceeds ${MAX_SESSION_TITLE_LENGTH} characters`);
345
+ }
346
+ return title;
347
+ }
348
+
349
+ function readState(value: unknown): MemberState {
350
+ if (typeof value !== 'string' || !MEMBER_STATES.includes(value as MemberState)) {
351
+ throw invalid(`invalid state "${String(value)}"`);
352
+ }
353
+ return value as MemberState;
354
+ }
355
+
356
+ /**
357
+ * `list + includeReleases` 的 limit / fields 入参形状校验。
358
+ *
359
+ * **只校验形状**:上限裁剪(默认 20 / 硬顶 200)、字段名白名单、截断标记都在服务层
360
+ * 的 `listReleasedMembers` 里 —— 同一份 clamp 只能有一处实现,否则 CLI / 工具 / RPC
361
+ * 迟早各说各话。
362
+ */
363
+ function readReleasedQuery(
364
+ record: Record<string, unknown>,
365
+ ): Pick<ReleasedMembersQuery, 'limit' | 'fields'> {
366
+ const query: Pick<ReleasedMembersQuery, 'limit' | 'fields'> = {};
367
+ if (record.limit !== undefined) query.limit = record.limit as number;
368
+ if (record.fields !== undefined) {
369
+ if (!Array.isArray(record.fields)) throw invalid('list: fields must be an array');
370
+ const fields: ReleasedMemberField[] = [];
371
+ for (const entry of record.fields) {
372
+ if (typeof entry !== 'string' || entry === '') {
373
+ throw invalid('list: fields entries must be non-empty strings');
374
+ }
375
+ // 字段名白名单在服务层(listReleasedMembers)统一校验;这里只收形状,
376
+ // 所以逐个 entry 在边界上收窄成联合类型,未知值由服务层报 invalid_input。
377
+ fields.push(entry as ReleasedMemberField);
378
+ }
379
+ query.fields = fields;
380
+ }
381
+ return query;
382
+ }
383
+
384
+ /** `read` 的 limit:缺省 20,1..50(封顶而不是报错:模型不该为了一个数字失败)。 */
385
+ function readMessageLimit(value: unknown): number {
386
+ if (value === undefined) return READ_MESSAGE_LIMIT_DEFAULT;
387
+ const parsed = typeof value === 'number' ? value : Number(value);
388
+ if (!Number.isFinite(parsed) || parsed < 1) return READ_MESSAGE_LIMIT_DEFAULT;
389
+ return Math.min(Math.floor(parsed), READ_MESSAGE_LIMIT_MAX);
390
+ }
391
+
392
+ /** 单条正文截断(按码点,避免切坏 emoji / 中文)。 */
393
+ function truncateText(text: string, max: number): string {
394
+ const chars = Array.from(text);
395
+ if (chars.length <= max) return text;
396
+ return `${chars.slice(0, max - 1).join('')}…`;
397
+ }
398
+
399
+ /** agent 工具选项 */
400
+ export interface AgentToolOptions {
401
+ /** 调用者(root owner)id;成员 owner / parent 与 list viewer 都用它 */
402
+ ownerId?: string;
403
+ /** root owner 自己的 session;用于区分 owner 调用与成员 ExecutionUnit 调用 */
404
+ ownerSessionId?: string;
405
+ /** 成员 ExecutionUnit 的 Team 能力(send / list);缺失时这些动作报错 */
406
+ team?: AgentTeamService;
407
+ /**
408
+ * 好友边投影(q-sub-unify-p1 M6,additive):返回 viewer 的好友成员 id 集。
409
+ * 装配层注入(读订阅状态 friend 块);缺省 ⇒ list 输出逐字不变(零回归)。
410
+ * canView 已由 rosterFor 管道保证;friend 标记是 canView ∧ friend 双过滤。
411
+ */
412
+ friendsOf?: (viewerId: string) => Promise<ReadonlySet<string>>;
413
+ /**
414
+ * `read` 的只读会话读取端口(装配层注入,与 `sessions.get` RPC 同一份 SessionState)。
415
+ *
416
+ * 不新增 RPC:只把已经落盘的会话消息读出来,供父级自己看成员报告(收口不再自动
417
+ * 回传正文之后,这是「父级要原文」的唯一入口)。缺省 = `read` 报不可用。
418
+ */
419
+ readSession?: (
420
+ sessionId: string,
421
+ ) => Promise<{ messages: ReadonlyArray<{ role: string; content: string }> } | null>;
422
+ /**
423
+ * 0.31:是否有能应答权限确认的人类通道(交互 REPL / serve;headless 为 false)。
424
+ *
425
+ * 只影响模型发起的 rotate:无人类通道时不发请求、不等待,直接
426
+ * `rotate_not_needed`,避免 bridge 收不到人类应答而挂死。
427
+ */
428
+ humanApproval?: boolean;
429
+ /**
430
+ * rotate 批准等待的上限(毫秒);缺省 {@link ROTATE_APPROVAL_TIMEOUT_MS}。
431
+ *
432
+ * `0` / 负数 = 不设上限(旧行为,只适合「通道确定通」的宿主)。装配层要给**别的**值
433
+ * 就走这里;测试用它把 2 分钟压到几十毫秒。
434
+ */
435
+ rotateApprovalTimeoutMs?: number;
436
+ }
437
+
438
+ /** 构造内置 `agent` 工具;生命周期全部委托给 AgentService */
439
+ export function createAgentTool(
440
+ service: AgentService,
441
+ options: AgentToolOptions = {},
442
+ ): ToolDefinition {
443
+ const ownerId = options.ownerId ?? DEFAULT_OWNER;
444
+
445
+ return {
446
+ name: 'agent',
447
+ // 不变量必须写在描述里:交接只有 startup_prompt 一条通道,新 body 一提交就开跑、
448
+ // 不继承本轮对话,所以「必填」不足以让模型写出下一个身体真正需要的信息。
449
+ description:
450
+ 'Long-lived member lifecycle tool. ' +
451
+ 'create: peer member(s) in the caller team (root owner: use hire). ' +
452
+ 'hire: contractor owned by the caller (any member may hire), bound to the caller team if it ' +
453
+ 'has one. ' +
454
+ 'create/hire accept an optional title for the first session (default: the member name). ' +
455
+ 'create/hire accept an optional startup_prompt: the first user message (the task), ' +
456
+ 'delivered at creation so the new member starts its first run at once — no follow-up ' +
457
+ 'send needed; omit = created idle, waiting for messages. ' +
458
+ 'send: dispatch a message (live queue now, gone resume first, rotating queue for the new ' +
459
+ 'body); returns immediately. This is the default channel for reporting to your parent: ' +
460
+ 'progress, blockers, a decision you made, or a question you cannot settle alone goes here ' +
461
+ 'instead of to the human (ask is the last resort). ' +
462
+ 'Add interrupt:true for urgent (cancel + front of queue) or ' +
463
+ 'notify:true to append to the inbox + summary wake without running. ' +
464
+ 'close: release member(s), idempotent. list: return the roster ' +
465
+ '(includeReleases: also list released members, read-only history). ' +
466
+ 'read: read the last messages of a member session (read-only; role + truncated text), so ' +
467
+ 'you can read a report yourself instead of waiting for it to be forwarded to you. ' +
468
+ 'rotate: move an agent into a fresh body (new session, epoch + 1) with startup_prompt first, ' +
469
+ 'plus an optional title that AI naming will not overwrite; ' +
470
+ 'a body may only rotate itself. ' +
471
+ 'rotate at/above the context threshold auto-allows; below threshold (or unknown ' +
472
+ 'context) asks a human first. ' +
473
+ 'On failure read reason (approval_timeout / denied_by_human / no_human_channel / ' +
474
+ 'approval_unavailable), not code — the legacy code rotate_not_needed covers every ' +
475
+ 'non-approval and does not mean the ratio was too low. ' +
476
+ 'startup_prompt is the only handoff: the new body starts at once and does not inherit ' +
477
+ 'this conversation, so it must carry everything the next body needs to know. ' +
478
+ 'Bodies may use create, hire, close, rotate, send, list and read. ' +
479
+ 'Closing a peer needs human approval; closing your own contractor or yourself does not. ' +
480
+ 'Cross-node: reply to a federated from by sending to that address; from is runtime-filled ' +
481
+ 'and must not be given. ' +
482
+ 'No team means no address send (no_team), owner included.',
483
+ inputSchema: {
484
+ type: 'object',
485
+ properties: {
486
+ action: {
487
+ type: 'string',
488
+ enum: [...OWNER_ACTIONS],
489
+ description: 'hire | send | close | list | rotate | read',
490
+ },
491
+ name: { type: 'string', description: 'create/hire: display name' },
492
+ model: {
493
+ type: 'string',
494
+ description: 'create/hire: explicit model pin (omit to follow the node default model)',
495
+ },
496
+ thinking_level: {
497
+ type: 'string',
498
+ description:
499
+ 'create/hire: explicit thinking level pin (auto | off | low | medium | high). ' +
500
+ 'Agent-level single source: sessions of this agent inherit it; omit or auto = ' +
501
+ 'follow the default chain (no key persisted). Change later via agents.update.',
502
+ },
503
+ system_prompt: { type: 'string', description: 'create/hire: optional system prompt' },
504
+ visibility: {
505
+ type: 'string',
506
+ enum: [...VISIBILITIES],
507
+ description:
508
+ 'create: team only; hire: visibility (default private for unbound, team with a team); ' +
509
+ 'list: filter by visibility',
510
+ },
511
+ members: {
512
+ type: 'array',
513
+ // items 必须显式声明(q-agent-close-tool-bug):纯 type:'array' 无 items 时,
514
+ // dashscope/qwen 的 schema 约束生成会抑制数组元素 —— journal 实证 members 恒
515
+ // 到达为 [](llm.response 原始输出只留空白骨架),close/hire/create 批量全灭。
516
+ // 异构条目(close 字符串 / create-hire 对象)用 type 数组:engine 机械校验
517
+ // (firstSchemaViolation)对非字符串 type 跳过,逐条拒绝语义留在 service 不变。
518
+ items: {
519
+ type: ['string', 'object'],
520
+ description:
521
+ 'close: a member id or session id string; ' +
522
+ 'create/hire: an object {name?, model?, thinking_level?, system_prompt?, visibility?, title?, startup_prompt?}',
523
+ },
524
+ description:
525
+ 'create/hire: [{name?, model?, thinking_level?, system_prompt?, visibility?, title?, startup_prompt?}] ' +
526
+ '(model = explicit pin, omit to follow the node default model; ' +
527
+ 'thinking_level = auto|off|low|medium|high, omit/auto to follow the default chain); ' +
528
+ 'close: [member id or session id]. ' +
529
+ 'Always emit the explicit entries; never an empty array',
530
+ },
531
+ to: {
532
+ type: 'string',
533
+ description:
534
+ 'send: member id or session id, or an address ' +
535
+ '<principal>@<node_id>:<team_id> (any value containing @ is treated as an address); ' +
536
+ 'a local sender gets a node segment too, so send the location value back as-is; ' +
537
+ 'rotate: target agent; read: member id, session id or name',
538
+ },
539
+ content: { type: 'string', description: 'send: message text' },
540
+ interrupt: {
541
+ type: 'boolean',
542
+ description:
543
+ 'send: urgent — cancel the target body active run and put this message first ' +
544
+ '(work/queued messages are preserved; cannot combine with notify)',
545
+ },
546
+ notify: {
547
+ type: 'boolean',
548
+ description:
549
+ 'send: append to the target inbox as unread and wake it with a summary notice; ' +
550
+ 'does not run, queue, or cancel anything (cannot combine with interrupt)',
551
+ },
552
+ message_id: {
553
+ type: 'string',
554
+ description:
555
+ 'send: with interrupt, deliver an existing inbox message id instead of new content',
556
+ },
557
+ refs: {
558
+ type: 'array',
559
+ description:
560
+ 'send: file/image references attached to the message (same shape as user-send refs: ' +
561
+ '{kind: file|image|document, path: absolute local path, name?, mime?, sha256?, bytes?}; ' +
562
+ 'max 32, invalid entries dropped). Local member targets only — not addresses, ' +
563
+ 'not with message_id. The receiver sees reference chips and reads files on demand',
564
+ items: {
565
+ type: 'object',
566
+ properties: {
567
+ kind: { type: 'string', enum: ['file', 'image', 'document'] },
568
+ path: { type: 'string' },
569
+ name: { type: 'string' },
570
+ mime: { type: 'string' },
571
+ sha256: { type: 'string' },
572
+ bytes: { type: 'integer' },
573
+ },
574
+ },
575
+ },
576
+ messages: {
577
+ type: 'array',
578
+ // items 显式声明(q-agent-close-tool-bug 同病同修):无 items 的数组在
579
+ // dashscope/qwen 约束生成下元素被抑制恒空。properties 只校形状不标 required:
580
+ // 缺字段的业务拒绝仍逐条在 dispatch / TeamService,结构错误整体拒绝与
581
+ // RPC requireObjectEntries 同口径。
582
+ items: {
583
+ type: 'object',
584
+ properties: {
585
+ to: { type: 'string' },
586
+ content: { type: 'string' },
587
+ interrupt: { type: 'boolean' },
588
+ notify: { type: 'boolean' },
589
+ message_id: { type: 'string' },
590
+ refs: { type: 'array' },
591
+ },
592
+ },
593
+ description: 'send: [{to, content, interrupt?, notify?, message_id?, refs?}]',
594
+ },
595
+ limit: {
596
+ type: 'integer',
597
+ minimum: 1,
598
+ // 不设字段级 maximum:read 封顶 50(readMessageLimit)、list+includeReleases
599
+ // 封顶 200(服务层 releasedLimit)——两个动作上限不同,单一 maximum 必谎报其一
600
+ // (旧值 200 让模型以为 read 能拿 200 条)。真实上限按动作写在 description,
601
+ // clamp 各只一处实现(形状校验只收形状,见 readReleasedQuery 注释)。
602
+ description:
603
+ `read: how many trailing messages to return (default ${READ_MESSAGE_LIMIT_DEFAULT}, max ${READ_MESSAGE_LIMIT_MAX}); ` +
604
+ `list + includeReleases: how many released members to return (default ${RELEASED_MEMBER_LIMIT_DEFAULT}, max ${RELEASED_MEMBER_LIMIT_MAX})`,
605
+ },
606
+ includeReleases: {
607
+ type: 'boolean',
608
+ description:
609
+ 'list: also list released members (closed / left) as a read-only history view; ' +
610
+ 'default false — the plain roster never includes released members',
611
+ },
612
+ fields: {
613
+ type: 'array',
614
+ items: { type: 'string', enum: [...RELEASED_MEMBER_FIELDS] },
615
+ description:
616
+ 'list + includeReleases: which fields each released member carries ' +
617
+ `(default ${RELEASED_MEMBER_DEFAULT_FIELDS.join(', ')})`,
618
+ },
619
+ member: { type: 'string', description: 'close: member id or session id' },
620
+ startup_prompt: {
621
+ type: 'string',
622
+ // 成员侧 schema 沿用这一份(runtime 的 MEMBER_AGENT_PROPERTIES 只做 fallback),
623
+ // 所以「唯一交接通道」这句话写在这里对两侧同时生效。
624
+ description:
625
+ 'create/hire: optional first user message (the task), delivered at creation — ' +
626
+ 'the new member starts its first run at once, no follow-up send needed; ' +
627
+ 'omit = created idle. Cannot be combined with members at the top level. ' +
628
+ 'rotate: required; the new body first message and the only handoff channel — ' +
629
+ 'it does not inherit this conversation, so write everything the next body needs',
630
+ },
631
+ title: {
632
+ type: 'string',
633
+ maxLength: MAX_SESSION_TITLE_LENGTH,
634
+ description: `create/hire/rotate: optional session title (1-${MAX_SESSION_TITLE_LENGTH} chars); omitted = the member name for agent-spawned members and tool rotate; AI titling never renames a named session`,
635
+ },
636
+ state: {
637
+ type: 'string',
638
+ enum: [...MEMBER_STATES],
639
+ description: 'list: filter by member state',
640
+ },
641
+ parent_id: { type: 'string', description: 'list: filter by parent member id' },
642
+ },
643
+ required: ['action'],
644
+ },
645
+ /**
646
+ * close 的审批在权限层完成(批准后 handler 照常执行 service.close)。
647
+ * - owner 调用 / 非 close 动作:放行;
648
+ * - self-close:放行;
649
+ * - temporary:雇佣者或同 Team 成员放行,其它拒绝;
650
+ * - member:需要人类审批(ask)—— 含 `main`。0.28 删除了「single 记录直接 deny」
651
+ * 这条:`main` 现在是 member,成员关它要让人类看到并有明确答复,而不是静默拒绝。
652
+ * 批量 close 中只要含 member 就整体 ask 一次。
653
+ */
654
+ checkPermission: async (args: unknown, ctx: ToolContext): Promise<'allow' | 'deny' | 'ask'> => {
655
+ const record = isRecord(args) ? args : {};
656
+ if (record.action !== 'close') return 'allow';
657
+ const callerSession = ctx.session_id;
658
+ if (
659
+ callerSession === undefined ||
660
+ options.ownerSessionId === undefined ||
661
+ callerSession === options.ownerSessionId
662
+ ) {
663
+ return 'allow';
664
+ }
665
+
666
+ const refs: string[] = [];
667
+ if (Array.isArray(record.members)) {
668
+ for (const entry of record.members) {
669
+ if (typeof entry === 'string' && entry !== '') refs.push(entry);
670
+ }
671
+ }
672
+ if (typeof record.member === 'string' && record.member !== '') refs.push(record.member);
673
+ // 无目标时交给 handler 报参数错,权限层不额外拦截。
674
+ if (refs.length === 0) return 'allow';
675
+
676
+ const caller = await service.identify(callerSession);
677
+ if (caller === undefined) return 'deny';
678
+
679
+ let needAsk = false;
680
+ for (const ref of refs) {
681
+ const target = await service.identify(ref);
682
+ // 无法解析的目标由 handler 报 unknown_member。
683
+ if (target === undefined) continue;
684
+ if (target.id === caller.id) continue;
685
+ // member 关闭需要人类审批(`main` 也是 member,同样走审批而不是被静默拒绝)。
686
+ if (target.role === 'member') {
687
+ needAsk = true;
688
+ continue;
689
+ }
690
+ // temporary:雇佣者的、或同 Team 的可直接关闭。
691
+ if (target.owner !== undefined && target.owner === caller.id) continue;
692
+ if (target.team_id !== undefined && target.team_id === caller.team_id) continue;
693
+ return 'deny';
694
+ }
695
+ return needAsk ? 'ask' : 'allow';
696
+ },
697
+ handler: async (args: unknown, ctx): Promise<string> => {
698
+ try {
699
+ const record = isRecord(args) ? args : {};
700
+ const action = record.action;
701
+ const callerSession = ctx?.session_id;
702
+ // 成员 ExecutionUnit 调用(有 session 且不是 root owner 的 session)只能 rotate 自己。
703
+ const isOwnerCaller =
704
+ callerSession === undefined ||
705
+ options.ownerSessionId === undefined ||
706
+ callerSession === options.ownerSessionId;
707
+
708
+ /**
709
+ * 成员派生入口的调用者:session 必须能解析出所属 Team,否则 no_team。
710
+ * 只有 create(peer)要求 Team;hire 对任意成员开放,team 可选。
711
+ */
712
+ const requireTeamCaller = async (): Promise<MemberStatus & { team_id: string }> => {
713
+ if (callerSession === undefined) {
714
+ throw invalid('no_team: create requires a member session');
715
+ }
716
+ const caller = await service.identify(callerSession);
717
+ if (caller === undefined || caller.team_id === undefined) {
718
+ throw invalid('no_team: create requires a member with a team');
719
+ }
720
+ return caller as MemberStatus & { team_id: string };
721
+ };
722
+
723
+ if (action === 'rotate') {
724
+ if (callerSession === undefined) {
725
+ throw invalid('rotate requires a calling body');
726
+ }
727
+ if (typeof record.startup_prompt !== 'string' || record.startup_prompt === '') {
728
+ throw invalid('rotate requires startup_prompt');
729
+ }
730
+ const rotateTitle = readRotateTitle(record.title);
731
+ // 0.31:模型发起的 rotate 须先经人类权限确认;用户裁定(q-rotate-threshold)
732
+ // 加一档:**达到/超过阈值(percent >= warningLine)自动允许,不发批准卡**;
733
+ // 低于阈值 / 未知仍走人工批准。CLI / 人工 RPC 直接走 service.createSession,
734
+ // 不经过这里,因此不会被询问。
735
+ const ratio = service.contextRatio(callerSession);
736
+ // 0.52:取整口径必须与界面一致 —— TUI 状态栏 / 会话列表 / core 的
737
+ // `context.pressure` 全是 `Math.round(ratio * 100)`;这里若用 floor,就会出现
738
+ // 「界面 50%、提示 49%」这种比不给数更糟的错觉。
739
+ // 「高于/低于阈值线」也按同一个整数判,否则 49.6% 会显示成「50%(低于 50% 线)」。
740
+ // 阈值线与 runtime 的 rotate 压力提示同源(CONTEXT_PRESSURE_WARN_RATIO,
741
+ // 用户裁定 0.5):提示让模型 50% 就考虑换 body,批准卡不能反着说「90% 以下不必」。
742
+ const warningLine = Math.round(CONTEXT_PRESSURE_WARN_RATIO * 100);
743
+ const percent = ratio === undefined ? undefined : Math.round(ratio * 100);
744
+ const warning =
745
+ ratio === undefined || percent === undefined
746
+ ? 'Context usage is unknown; rotate only with human approval.'
747
+ : percent >= warningLine
748
+ ? `Context is at ${percent}% (at or above the ${warningLine}% line); rotation is recommended.`
749
+ : `Context is at ${percent}% (below the ${warningLine}% line); rotation is usually unnecessary.`;
750
+
751
+ let approved = false;
752
+ let denial = 'no_human_channel';
753
+ /** 只在自动允许档有值('threshold'):进结果与审计事件,区分「人批准的」与「阈值放行的」。 */
754
+ let autoAllowReason: 'threshold' | undefined;
755
+ /** 只在超时档有值:写进结果让调用方知道等了多少(不是「人拒绝了」)。 */
756
+ let approvalTimeoutMs: number | undefined;
757
+ // 用户裁定(q-rotate-threshold):达到/超过阈值自动允许,不需 permission、
758
+ // 不发批准卡。判据与 warning 文案 / 界面同一个整数(percent >= warningLine);
759
+ // 未知(percent === undefined)不能证明到线,fail-closed 走下面的人工分支。
760
+ if (percent !== undefined && percent >= warningLine) {
761
+ approved = true;
762
+ autoAllowReason = 'threshold';
763
+ // 审计事实:与批准卡同通道(emitFact → journal → 时间线,同下方 P-A
764
+ // 先例);事实端口缺省(旧装配 / harness)退回裸流。runtime.notice 是
765
+ // 已知可渲染类型(scope=permission),时间线可见「rotate 自动允许 N%≥50%」。
766
+ const publishAutoAllow: (event: RunEvent) => void =
767
+ ctx.emitFact ?? ((event) => ctx.events.publish(event));
768
+ publishAutoAllow({
769
+ type: 'runtime.notice',
770
+ run_id: ctx.run_id,
771
+ data: {
772
+ scope: 'permission',
773
+ summary:
774
+ `rotate auto-allowed: context at ${percent}% (>= ${warningLine}% threshold); ` +
775
+ 'no human approval required',
776
+ ok: true,
777
+ tool: 'agent.rotate',
778
+ session_id: callerSession,
779
+ context_percent: percent,
780
+ auto_allow_reason: autoAllowReason,
781
+ },
782
+ ts: Date.now(),
783
+ });
784
+ } else if (options.humanApproval === true && service.canConfirm(callerSession)) {
785
+ // 入口有人类 + 该 body 真有 bridge,两个条件都成立才发请求;否则
786
+ // fail-closed。只检查入口标志会在 permissionMode=allow 的无 team body
787
+ // 上把请求发进无人订阅的事件流并永久等待。
788
+ const requestId = randomUUID();
789
+ const waitLimitMs = options.rotateApprovalTimeoutMs ?? ROTATE_APPROVAL_TIMEOUT_MS;
790
+ // q-card-robust P-A:审批请求 / 超时收卡信号改走**事实通道**(装配方
791
+ // publishEvent → journal → 时间线),与内置 PermissionPolicy 同构 ——
792
+ // 裸流发布不进会话时间线,时间线订阅的 Web 连接 live 永远收不到这张卡
793
+ // (根因见 docs/dev/plans/envcard-run-visibility-research.md Part II)。
794
+ // 事实端口缺省(旧装配 / harness)退回裸流,行为不变;waitFor 仍走
795
+ // ctx.events(同一条流,应答照旧到达)。
796
+ const publishApproval: (event: RunEvent) => void =
797
+ ctx.emitFact ?? ((event) => ctx.events.publish(event));
798
+ publishApproval({
799
+ type: 'tool.permission.request',
800
+ run_id: ctx.run_id,
801
+ data: {
802
+ requestId,
803
+ tool: 'agent.rotate',
804
+ input: {
805
+ action: 'rotate',
806
+ to: (record.to ?? callerSession) as string,
807
+ ...(ratio !== undefined
808
+ ? { context_ratio: ratio, context_percent: percent }
809
+ : {}),
810
+ warning,
811
+ },
812
+ session_id: callerSession,
813
+ ...(ctx.tool_call_id !== undefined ? { tool_call_id: ctx.tool_call_id } : {}),
814
+ source: ctx.source ?? 'runtime',
815
+ },
816
+ ts: Date.now(),
817
+ });
818
+ try {
819
+ const response = await ctx.events.waitFor('tool.permission.response', {
820
+ requestId,
821
+ // 超时兜底:卡片到不了人时不能无限挂(见 ROTATE_APPROVAL_TIMEOUT_MS)。
822
+ // `waitLimitMs <= 0` = 显式要求不设上限(旧行为)。
823
+ ...(waitLimitMs > 0 ? { timeout: waitLimitMs } : {}),
824
+ ...(ctx.signal !== undefined ? { signal: ctx.signal } : {}),
825
+ });
826
+ const data = isRecord(response) ? response : {};
827
+ // 缺 answered_by = legacy human(TUI);policy / auto_allow 不是人类。
828
+ const human = data.answered_by === undefined || data.answered_by === 'human';
829
+ const decision =
830
+ data.decision ?? (data.allowed === false ? ('deny' as const) : ('allow' as const));
831
+ approved = human && decision === 'allow';
832
+ if (!human) denial = 'no_human_channel';
833
+ else if (!approved) denial = 'denied_by_human';
834
+ } catch (error) {
835
+ // 取消优先:run 被中止时原样抛出(由兜底包装成 `cancelled` 码),
836
+ // 不能被下面的「批准不可用」吞掉。
837
+ if (ctx.signal?.aborted) throw error;
838
+ if (isApprovalTimeout(error)) {
839
+ denial = ROTATE_APPROVAL_TIMEOUT_REASON;
840
+ approvalTimeoutMs = waitLimitMs;
841
+ // 超时后这张卡在界面上已经**没有意义**了:请求还在服务端 pending,
842
+ // 用户看到的是一张「能点」的卡 —— 点下去要么无人订阅(静默无效),
843
+ // 要么报 expired。这里显式发过期事件,让界面把卡收起来并说清原因。
844
+ // P-A:收卡信号与请求卡同通道(事实端口),时间线订阅同样可达。
845
+ publishApproval({
846
+ type: 'tool.permission.expired',
847
+ run_id: ctx.run_id,
848
+ data: {
849
+ requestId,
850
+ reason: ROTATE_APPROVAL_TIMEOUT_REASON,
851
+ tool: 'agent.rotate',
852
+ session_id: callerSession,
853
+ wait_ms: waitLimitMs,
854
+ },
855
+ ts: Date.now(),
856
+ });
857
+ } else denial = 'approval_unavailable';
858
+ }
859
+ }
860
+
861
+ const decisionData = {
862
+ ...(ratio !== undefined ? { context_ratio: ratio } : {}),
863
+ ...(percent !== undefined ? { context_percent: percent } : {}),
864
+ warning,
865
+ };
866
+ if (!approved) {
867
+ service.noteAgentEvent('agent.rotate.denied', callerSession, {
868
+ ...decisionData,
869
+ reason: denial,
870
+ ...(approvalTimeoutMs !== undefined ? { timeout_ms: approvalTimeoutMs } : {}),
871
+ });
872
+ return JSON.stringify({
873
+ status: 'failed',
874
+ // 码名是历史遗留(冻结契约,不改):它装的是「未获批准」的全部档位
875
+ // (超时 / 人拒绝 / 无人类通道 / 审批不可用)。q-rotate-threshold 起
876
+ // 达到/超过阈值自动允许、不会走到这里;此码只出现在低于阈值 / 未知的
877
+ // 人工批准档,且**不代表「ratio 太低」**(未知 ratio 也走这条路)。
878
+ // 调用方必须看 `reason` 分辨档位,不能把 `rotate_not_needed` 读成
879
+ // 「工具认为不需要 rotate」(口径统一审查 §2.4 的误读实锤)。工具描述里已同步澄清。
880
+ code: 'rotate_not_needed',
881
+ reason: denial,
882
+ // 超时档把等过的时限写结果里:调用方据此分辨「人点了拒绝」与「根本没人答」。
883
+ ...(approvalTimeoutMs !== undefined ? { timeout_ms: approvalTimeoutMs } : {}),
884
+ ...decisionData,
885
+ });
886
+ }
887
+
888
+ const caller = await service.identify(callerSession);
889
+ if (caller === undefined) {
890
+ throw invalid('rotate requires a known calling body');
891
+ }
892
+ service.noteAgentEvent('agent.rotate.approved', callerSession, {
893
+ ...decisionData,
894
+ ...(autoAllowReason !== undefined
895
+ ? { auto_allowed: true, auto_allow_reason: autoAllowReason }
896
+ : {}),
897
+ });
898
+ // CREATE-0.39:rotate 下沉到 sessions.create(无来源 + startup_prompt)。
899
+ const result = await service.createSession(
900
+ {
901
+ agent_id: caller.id,
902
+ startup_prompt: record.startup_prompt,
903
+ ...(rotateTitle !== undefined ? { title: rotateTitle } : {}),
904
+ },
905
+ // 工具在调用者自身 active run 内执行;RPC 路径不传此内部选项。
906
+ { allowActiveRun: true },
907
+ );
908
+ const created = await service.identify(result.session_id);
909
+ const rotated = {
910
+ status: 'rotated',
911
+ agent_id: result.agent_id,
912
+ from_session_id: callerSession,
913
+ to_session_id: result.session_id,
914
+ epoch: created?.epoch,
915
+ ...(result.title !== undefined ? { title: result.title } : {}),
916
+ // 自动允许档(用户裁定 q-rotate-threshold):结果里报 context_percent +
917
+ // auto_allowed:true,让调用方 / 父级知道这具新 body 是阈值放行、非人批准。
918
+ ...(autoAllowReason !== undefined
919
+ ? { auto_allowed: true, auto_allow_reason: autoAllowReason, context_percent: percent }
920
+ : {}),
921
+ };
922
+ // 文案必须是真的(0.52 B′):交棒的那一轮**正常记账**——agent 终态、
923
+ // 父级通知、正文采用都照常走,只有 failed / 正文为空时才补一条 notice。
924
+ // 所以模型可以放心把这一轮说完;`startup_prompt` 仍然是唯一交接通道,
925
+ // 因为新 body 不会继承这段对话(它只读 startup_prompt + 旧队列)。
926
+ return (
927
+ `${JSON.stringify(rotated)}\n` +
928
+ 'rotation committed; the new body is already running and this conversation is ' +
929
+ 'no longer yours. Finish the current turn: its closing reply is recorded normally ' +
930
+ '(agent state + parent notice), not fenced. startup_prompt remains the only handoff ' +
931
+ 'channel — the new body does not inherit this conversation, so everything it must ' +
932
+ 'know still has to go there.'
933
+ );
934
+ }
935
+
936
+ if (!isOwnerCaller && !BODY_ACTIONS.includes(action as string)) {
937
+ throw invalid('agent bodies may only use create|hire|close|rotate|send|list|read');
938
+ }
939
+
940
+ if (action === 'create' || action === 'hire') {
941
+ // create 只给成员(peer 必须绑定调用者 Team);root 没有 Team,只能用 hire。
942
+ if (action === 'create' && isOwnerCaller) {
943
+ throw invalid('create requires a team member caller; owner should use hire');
944
+ }
945
+ let fixed: Record<string, unknown>;
946
+ if (action === 'create') {
947
+ const caller = await requireTeamCaller();
948
+ fixed = {
949
+ kind: 'peer',
950
+ teamId: caller.team_id,
951
+ spawnedBy: caller.id,
952
+ };
953
+ } else if (isOwnerCaller) {
954
+ // root owner:unbound contractor,沿用旧 new 的 owner/parent 语义。
955
+ fixed = {
956
+ kind: 'contractor',
957
+ owner: ownerId,
958
+ parentId: ownerId,
959
+ spawnedBy: ownerId,
960
+ };
961
+ } else {
962
+ // 任意成员(含 contractor,是否有 Team 均可)都能 hire:owner / parent 固定为调用者,
963
+ // 模型不能伪造。调用者有 Team 时绑定该 Team(计入上限 / 冻结),否则 unbound。
964
+ if (callerSession === undefined) {
965
+ throw invalid('hire requires a member session');
966
+ }
967
+ const caller = await service.identify(callerSession);
968
+ if (caller === undefined) {
969
+ throw invalid('hire requires a member session');
970
+ }
971
+ fixed = {
972
+ kind: 'contractor',
973
+ owner: caller.id,
974
+ parentId: caller.id,
975
+ spawnedBy: caller.id,
976
+ ...(caller.team_id !== undefined ? { teamId: caller.team_id } : {}),
977
+ };
978
+ }
979
+ const singles = [
980
+ 'name',
981
+ 'model',
982
+ 'thinking_level',
983
+ 'system_prompt',
984
+ 'visibility',
985
+ 'startup_prompt',
986
+ ];
987
+ if (record.members !== undefined) {
988
+ assertExclusive(record, singles, 'members', action);
989
+ const entries = readBatch(record, 'members', action).map((entry) =>
990
+ mapDerivedEntry(entry, fixed),
991
+ );
992
+ const result = await service.create({
993
+ members: entries as unknown as CreateMemberInput[],
994
+ });
995
+ // batch 逐条标注复用:命中同名成员的条目要说明「没新建」
996
+ const results = entries.map((entry, index) => {
997
+ const item = result.results[index];
998
+ if (item === undefined || !item.ok || !isRecord(entry)) return item;
999
+ return { ...item, status: withReusedNote(item.status) };
1000
+ });
1001
+ return JSON.stringify({ ...result, results });
1002
+ }
1003
+ const created = await service.create(
1004
+ mapDerived(record, fixed) as unknown as CreateMemberInput,
1005
+ );
1006
+ return JSON.stringify(withReusedNote(created));
1007
+ }
1008
+
1009
+ if (action === 'send') {
1010
+ // owner 走统一 dispatch;成员 ExecutionUnit 用自己的 session 走 TeamService.send
1011
+ // (from 恒由入口决定,模型不能伪造)。
1012
+ // 0.41:一批 send 生成一个 wake 边计数 key;整批 await 完后释放(内部、非 wire)。
1013
+ const releaseWakeBatch = (batchKey: string): void => {
1014
+ service.releaseWakeBatch(batchKey);
1015
+ };
1016
+ const sendSingle = async (
1017
+ entry: unknown,
1018
+ batchKey?: string,
1019
+ ): Promise<DispatchResult | TeamAgentSendResult | SendResult> => {
1020
+ // 0.41:important 已全链路删除;显式传入按非法输入拒绝,不静默忽略。
1021
+ if (isRecord(entry) && entry.important !== undefined) {
1022
+ throw invalid('send does not accept important');
1023
+ }
1024
+ const mapped = isRecord(entry) ? mapSend(entry) : {};
1025
+ const to = mapped.to as string;
1026
+ const content = mapped.content as string;
1027
+ const interrupt = mapped.interrupt === true;
1028
+ // 工具参数 `notify` 是 wire 名:映射成 inbox 的投递模式再往下传,
1029
+ // 内部(TeamService / dispatch)不再二传布尔。
1030
+ const delivery = deliveryFromNotify(mapped.notify === true);
1031
+ const wakes = delivery === 'wake';
1032
+ const messageId = typeof mapped.message_id === 'string' ? mapped.message_id : undefined;
1033
+ // 块 P2 additive:refs 只支持本机成员投递路 —— 地址目标(含跨节点)携带不了
1034
+ // node-local 路径;message_id 重投用既有消息自带的 refs,不接受新 refs。
1035
+ // 形状归一在 dispatch / TeamService 的 normalizeRefs(与用户 send 同一份)。
1036
+ const refs = mapped.refs as MessageRef[] | undefined;
1037
+ if (refs !== undefined) {
1038
+ if (!Array.isArray(refs)) throw invalid('send refs must be an array');
1039
+ if (typeof to === 'string' && to.includes('@')) {
1040
+ throw invalid(
1041
+ 'send refs are only supported for local member targets, not addresses',
1042
+ );
1043
+ }
1044
+ if (messageId !== undefined) {
1045
+ throw invalid('send refs cannot combine with message_id');
1046
+ }
1047
+ }
1048
+ if (!isOwnerCaller) {
1049
+ if (options.team === undefined) throw invalid('send requires a team service');
1050
+ return options.team.send({
1051
+ from_session_id: callerSession as string,
1052
+ to,
1053
+ content,
1054
+ ...(interrupt ? { interrupt: true } : {}),
1055
+ delivery,
1056
+ ...(messageId !== undefined ? { message_id: messageId } : {}),
1057
+ ...(refs !== undefined && refs.length > 0 ? { refs } : {}),
1058
+ origin_run_id: ctx.run_id,
1059
+ ...(batchKey !== undefined ? { batch_key: batchKey } : {}),
1060
+ });
1061
+ }
1062
+ // owner 的会话就是人类直接看的那个 session,每轮回复的文本人类直接能看到。
1063
+ // 所以 owner 没有「把话递给人类」这个动作可做 ——
1064
+ // 那是给 Team 成员用的(成员在 Team 里跑,人类不在它的 session 里)。
1065
+ // 两条拒绝理由不同,文案必须分开,否则模型会去追一个不存在的动作:
1066
+ // - `human`:回复本身就是回答,不需要 send;
1067
+ // - 地址形式:owner 所在 Team 的构型不允许它从这里发地址。
1068
+ // 旧文案让模型「用 vessel federation post --from ...」——那是 CLI,模型没有
1069
+ // 这条工具调用可发,属于不可执行的死提示。错误消息给的替代动作必须真能用。
1070
+ if (typeof to === 'string' && (to.includes('@') || to === HUMAN_PRINCIPAL)) {
1071
+ // 0.41:地址 / 跨节点目标不支持 urgent / wake 投递。
1072
+ if (interrupt || wakes) {
1073
+ return {
1074
+ status: 'rejected',
1075
+ code: 'invalid_input',
1076
+ reason: 'unsupported_delivery',
1077
+ logged: false,
1078
+ };
1079
+ }
1080
+ const reason =
1081
+ to === HUMAN_PRINCIPAL
1082
+ ? 'owner has no team: your reply text is shown to the human directly, ' +
1083
+ 'so no send is needed. To reach an agent, send to its id.'
1084
+ : 'owner has no team, so an address cannot be delivered from here; ' +
1085
+ 'to reach an agent, send to its id instead of an address.';
1086
+ return { status: 'rejected', code: 'no_team', reason, logged: false };
1087
+ }
1088
+ return service.dispatch({
1089
+ to,
1090
+ content,
1091
+ from: ownerId,
1092
+ ...(interrupt ? { interrupt: true } : {}),
1093
+ // wire 边界:dispatch 只认 notify 布尔,wake 模式在这里转回去。
1094
+ ...(wakes ? { notify: true } : {}),
1095
+ ...(messageId !== undefined ? { message_id: messageId } : {}),
1096
+ // 块 P2 additive:引用随投递(dispatch normalizeRefs 既有路)。
1097
+ ...(refs !== undefined && refs.length > 0 ? { refs } : {}),
1098
+ // 内部(非 wire):tool 路径按调用者 session 继承会话 / 按 run 去重边。
1099
+ ...(callerSession !== undefined ? { origin_session_id: callerSession } : {}),
1100
+ origin_run_id: ctx.run_id,
1101
+ ...(batchKey !== undefined ? { batch_key: batchKey } : {}),
1102
+ });
1103
+ };
1104
+
1105
+ if (record.important !== undefined) {
1106
+ throw invalid('send does not accept important');
1107
+ }
1108
+ if (record.messages !== undefined) {
1109
+ // 三档 flag 是逐条投递语义:与 messages 数组同用会被静默丢弃,必须显式拒绝。
1110
+ assertExclusive(
1111
+ record,
1112
+ ['to', 'content', 'interrupt', 'notify', 'message_id'],
1113
+ 'messages',
1114
+ 'send',
1115
+ );
1116
+ const entries = readBatch(record, 'messages', 'send');
1117
+ // 一次 messages 数组共享一个 wake 边计数 key(内部、非 wire)。
1118
+ const batchKey = randomUUID();
1119
+ try {
1120
+ const results = await Promise.all(
1121
+ entries.map(async (entry) => {
1122
+ try {
1123
+ return mapSendOutcome(await sendSingle(entry, batchKey));
1124
+ } catch (error) {
1125
+ return { ok: false as const, error: batchErrorText(error) };
1126
+ }
1127
+ }),
1128
+ );
1129
+ return JSON.stringify({ results });
1130
+ } finally {
1131
+ releaseWakeBatch(batchKey);
1132
+ }
1133
+ }
1134
+ const batchKey = randomUUID();
1135
+ try {
1136
+ return JSON.stringify(await sendSingle(record, batchKey));
1137
+ } finally {
1138
+ releaseWakeBatch(batchKey);
1139
+ }
1140
+ }
1141
+
1142
+ if (action === 'close') {
1143
+ if (record.members !== undefined) {
1144
+ assertExclusive(record, ['member'], 'members', 'close');
1145
+ const members = readBatch(record, 'members', 'close') as string[];
1146
+ return JSON.stringify(await service.close({ members }));
1147
+ }
1148
+ const input: CloseInput = {};
1149
+ if (record.member !== undefined) input.member = record.member as string;
1150
+ return JSON.stringify(await service.close(input));
1151
+ }
1152
+
1153
+ if (action === 'list') {
1154
+ const visibility =
1155
+ record.visibility === undefined ? undefined : readVisibility(record.visibility);
1156
+ const state = record.state === undefined ? undefined : readState(record.state);
1157
+ const includeReleases = record.includeReleases === true;
1158
+
1159
+ if (includeReleases) {
1160
+ // 历史视图(0.53):只读,默认关闭。visibility / state / parent_id 是 roster 的
1161
+ // 过滤条件,对「已释放成员」没有意义 —— 组合使用一律拒绝,而不是静默忽略
1162
+ // (静默忽略会让人以为筛选生效了)。
1163
+ if (visibility !== undefined || state !== undefined || record.parent_id !== undefined) {
1164
+ throw invalid(
1165
+ 'list: includeReleases cannot be combined with visibility / state / parent_id',
1166
+ );
1167
+ }
1168
+ const released = readReleasedQuery(record);
1169
+ if (!isOwnerCaller) {
1170
+ // 成员只该看自己 Team 的历史:不传 teamId 就是把别的 Team 的已释放成员
1171
+ // 也交出去。调用者自身解析不到 Team 时明确报错(不猜、不漏)。
1172
+ if (callerSession === undefined) {
1173
+ throw invalid('list: includeReleases requires a calling member');
1174
+ }
1175
+ const caller = await service.identify(callerSession);
1176
+ if (caller === undefined || caller.team_id === undefined) {
1177
+ throw invalid('no_team: list includeReleases requires a member with a team');
1178
+ }
1179
+ return JSON.stringify(
1180
+ await service.listReleasedMembers({
1181
+ ...released,
1182
+ viewer: caller.id,
1183
+ teamId: caller.team_id,
1184
+ }),
1185
+ );
1186
+ }
1187
+ // root owner:租户级历史(private 记录仍按 owner 判定可见性)。
1188
+ return JSON.stringify(
1189
+ await service.listReleasedMembers({ ...released, viewer: ownerId }),
1190
+ );
1191
+ }
1192
+
1193
+ if (!isOwnerCaller) {
1194
+ // 成员只看调用者所属 Team 的 roster;filter 在本地做,parent_id 不适用。
1195
+ const team = options.team;
1196
+ if (team === undefined) throw invalid('list requires a team service');
1197
+ let roster = await team.listForCaller(callerSession as string);
1198
+ if (visibility !== undefined) {
1199
+ roster = roster.filter((entry) => entry.visibility === visibility);
1200
+ }
1201
+ if (state !== undefined) {
1202
+ roster = roster.filter((entry) => entry.state === state);
1203
+ }
1204
+ // 好友区(q-sub-unify-p1 M6,additive):canView ∧ friend 双过滤。
1205
+ // 无 port / 无好友 ⇒ 输出逐字不变(零回归);有好友 ⇒ 条目加 friend:true。
1206
+ if (options.friendsOf !== undefined) {
1207
+ const caller = await service.identify(callerSession as string);
1208
+ if (caller !== undefined) {
1209
+ const friends = await options.friendsOf(caller.id);
1210
+ if (friends.size > 0) {
1211
+ roster = roster.map((entry) =>
1212
+ friends.has(entry.agent_id) ? { ...entry, friend: true } : entry,
1213
+ );
1214
+ }
1215
+ }
1216
+ }
1217
+ return JSON.stringify(withoutBodyHistory(roster));
1218
+ }
1219
+
1220
+ // private 成员只有 owner 可见;工具调用者就是 owner
1221
+ const filter: ListFilter = { viewer: ownerId };
1222
+ if (visibility !== undefined) filter.visibility = visibility;
1223
+ if (state !== undefined) filter.state = state;
1224
+ if (record.parent_id !== undefined) {
1225
+ if (typeof record.parent_id !== 'string' || record.parent_id === '') {
1226
+ throw invalid('parent_id must be a non-empty string');
1227
+ }
1228
+ filter.parentId = record.parent_id;
1229
+ }
1230
+ return JSON.stringify(withoutBodyHistory(await service.list(filter)));
1231
+ }
1232
+
1233
+ if (action === 'read') {
1234
+ // 只读:解析目标 → 取该成员当前 primary body 的 session → 读最近 N 条消息。
1235
+ // 不新增 RPC,也不改 sessions.get 的形状:同一份 SessionState 只读一份。
1236
+ const target = typeof record.to === 'string' ? record.to.trim() : '';
1237
+ if (target === '') throw invalid('read requires to');
1238
+ // 跨节点 / 地址形态读不到对方的本地会话:显式拒绝,不猜。
1239
+ if (target.includes('@')) {
1240
+ throw invalid(
1241
+ 'read: only local members are readable; address targets live on another node',
1242
+ );
1243
+ }
1244
+ const visible: { id: string; session_id: string; name?: string }[] = [];
1245
+ if (!isOwnerCaller) {
1246
+ const team = options.team;
1247
+ if (team === undefined) throw invalid('read requires a team service');
1248
+ for (const entry of await team.listForCaller(callerSession as string)) {
1249
+ visible.push({
1250
+ id: entry.agent_id,
1251
+ session_id: entry.session_id,
1252
+ ...(entry.name !== undefined ? { name: entry.name } : {}),
1253
+ });
1254
+ }
1255
+ } else {
1256
+ for (const entry of await service.list({ viewer: ownerId })) {
1257
+ visible.push({
1258
+ id: entry.id,
1259
+ session_id: entry.session_id,
1260
+ ...(entry.name !== undefined ? { name: entry.name } : {}),
1261
+ });
1262
+ }
1263
+ }
1264
+ const hit =
1265
+ visible.find((entry) => entry.id === target) ??
1266
+ visible.find((entry) => entry.session_id === target) ??
1267
+ visible.find((entry) => entry.name === target);
1268
+ if (hit === undefined) {
1269
+ throw new AgentError('unknown_member', `unknown_member: ${target}`);
1270
+ }
1271
+ const readSession = options.readSession;
1272
+ if (readSession === undefined) {
1273
+ throw invalid('read: no session store is attached to this entry');
1274
+ }
1275
+ // 当前 primary body 的 session:rotate 之后旧 session 是历史,读新的那具。
1276
+ const current = await service.identify(hit.id);
1277
+ const sessionId = current?.session_id ?? hit.session_id;
1278
+ const state = await readSession(sessionId);
1279
+ if (state === null) {
1280
+ throw invalid(`read: no session state for ${sessionId}`);
1281
+ }
1282
+ const limit = readMessageLimit(record.limit);
1283
+ const all = state.messages;
1284
+ const selected = all.slice(Math.max(0, all.length - limit));
1285
+ const messages = selected.map((message) => ({
1286
+ role: message.role,
1287
+ content: truncateText(message.content, READ_MESSAGE_MAX_CHARS),
1288
+ }));
1289
+ return JSON.stringify({
1290
+ agent_id: hit.id,
1291
+ ...(hit.name !== undefined ? { name: hit.name } : {}),
1292
+ session_id: sessionId,
1293
+ state: current?.state,
1294
+ messages_total: all.length,
1295
+ returned: messages.length,
1296
+ messages,
1297
+ });
1298
+ }
1299
+
1300
+ throw invalid(`unknown action "${String(action)}" (expected ${ACTIONS.join('|')})`);
1301
+ } catch (error) {
1302
+ return errorResult(error, ctx?.signal);
1303
+ }
1304
+ },
1305
+ };
1306
+ }