@ai-zen/agents-sdk 1.2.0-alpha.2 → 2.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +3 -3
  3. package/README.zh.md +3 -3
  4. package/dist/agent-plugins/AutoMigratePlugin.d.ts +34 -5
  5. package/dist/agent-plugins/AutoMigratePlugin.js +56 -7
  6. package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +8 -5
  7. package/dist/agent-plugins/AutoRefreshToolsPlugin.js +5 -6
  8. package/dist/agent-plugins/ContextGuardPlugin.d.ts +15 -3
  9. package/dist/agent-plugins/ContextGuardPlugin.js +16 -2
  10. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +18 -16
  11. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +16 -14
  12. package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +12 -3
  13. package/dist/agent-plugins/UnknownToolHintPlugin.js +16 -4
  14. package/dist/index.d.ts +5 -2
  15. package/dist/index.js +3 -0
  16. package/dist/runtime/HandoffGuardPlugin.d.ts +7 -5
  17. package/dist/runtime/HandoffGuardPlugin.js +8 -6
  18. package/dist/runtime/HandoffService.d.ts +51 -12
  19. package/dist/runtime/HandoffService.js +112 -19
  20. package/dist/runtime/SdkAgent.d.ts +2 -3
  21. package/dist/runtime/SdkAgent.js +1 -2
  22. package/dist/scope/Scope.d.ts +35 -8
  23. package/dist/scope/Scope.js +50 -11
  24. package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +7 -0
  25. package/dist/scope/plugins/mcp/McpConnectionManager.js +7 -0
  26. package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +23 -0
  27. package/dist/scope/plugins/mcp/McpScopePlugin.js +68 -1
  28. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.d.ts +28 -0
  29. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +35 -0
  30. package/dist/scope/plugins/peers/peerSessionTools.d.ts +122 -0
  31. package/dist/scope/plugins/peers/peerSessionTools.js +266 -0
  32. package/dist/scope/plugins/skills/skillTools.d.ts +1 -1
  33. package/dist/scope/plugins/skills/skillTools.js +6 -2
  34. package/dist/scope/plugins/subagents/subAgentTools.js +3 -0
  35. package/dist/shared/errors.d.ts +10 -3
  36. package/dist/shared/errors.js +10 -3
  37. package/dist/types/index.d.ts +6 -4
  38. package/package.json +2 -2
@@ -41,6 +41,13 @@ export declare class McpConnectionManager {
41
41
  * 如果设置了自定义工厂(测试用),则使用自定义工厂。
42
42
  */
43
43
  private createTransport;
44
+ /**
45
+ * 断开**单个** server(不影响别的 server)。
46
+ *
47
+ * 状态与清单一起失效:断开之后 `getState()` 回到 `disconnected`、`getManifest()` 为空,
48
+ * 下一次 `connect()` 会按新的定义重新建链(懒连)。MCP 插件的发现对账就靠它落地 ——
49
+ * 声明变了而旧连接还在,等于「配置改了但实际没生效」。
50
+ */
44
51
  disconnect(name: string): Promise<void>;
45
52
  disconnectAll(): Promise<void>;
46
53
  touch(name: string): void;
@@ -293,6 +293,13 @@ export class McpConnectionManager {
293
293
  throw new Error(`Unsupported MCP transport type: ${config.transport}`);
294
294
  }
295
295
  // ---- 断开 ----
296
+ /**
297
+ * 断开**单个** server(不影响别的 server)。
298
+ *
299
+ * 状态与清单一起失效:断开之后 `getState()` 回到 `disconnected`、`getManifest()` 为空,
300
+ * 下一次 `connect()` 会按新的定义重新建链(懒连)。MCP 插件的发现对账就靠它落地 ——
301
+ * 声明变了而旧连接还在,等于「配置改了但实际没生效」。
302
+ */
296
303
  async disconnect(name) {
297
304
  const entry = this.servers.get(name);
298
305
  if (!entry || entry.state === "disconnected")
@@ -1,4 +1,5 @@
1
1
  import type { Tool } from "@ai-zen/agents-core";
2
+ import type { McpServerConfig } from "../../../types/index.js";
2
3
  import type { Scope, FilterOutput } from "../../Scope.js";
3
4
  import type { ScopeCandidates, ScopePlugin } from "../../ScopePlugin.js";
4
5
  /**
@@ -10,6 +11,9 @@ import type { ScopeCandidates, ScopePlugin } from "../../ScopePlugin.js";
10
11
  * - `read_mcp_resource` 读取已连接 server 的资源
11
12
  * 三个元工具名恒上报 `tools` 维度;`mcpManager` 由本插件私有持有,
12
13
  * 有配置路径时在构造时创建,`dispose()` 时统一断开。
14
+ *
15
+ * 每次 `discover()` 除了重读 mcp 文件,还会把连接与发现结果对账一次(`reconcileConnections`):
16
+ * 于是「改了 mcp 配置」= 刷一次 Scope,不需要把 Scope 拆掉重建。
13
17
  */
14
18
  export declare class McpScopePlugin implements ScopePlugin {
15
19
  static readonly ID = "mcp";
@@ -21,9 +25,28 @@ export declare class McpScopePlugin implements ScopePlugin {
21
25
  paths?: string[];
22
26
  });
23
27
  discover(scope: Scope): Promise<void>;
28
+ /**
29
+ * 让连接跟着发现结果对账。
30
+ *
31
+ * 连接是按**定义**建立的:声明改了而连接不动,等于「配置改了但实际没生效」。所以
32
+ * - 这次发现里消失的 server → 断开它的连接(连同缓存的状态 / 清单一起失效);
33
+ * - 定义变了的 server → 断开旧连接,下一次调用时按新定义懒连;
34
+ * - 新增的 server → 不主动连(保持懒连接:没人调用就不起进程 / 不建链);
35
+ * - 定义没变的 → 一个字节都不动(连接与清单原样留着)。
36
+ *
37
+ * 对账在 `refresh()` / `init()` 里跑,于是「配置改了」只需刷一次 Scope,不必重建它。
38
+ */
39
+ private reconcileConnections;
24
40
  /** 是否配置了 MCP(供外部代码判定,如 UnknownToolHintPlugin) */
25
41
  hasConfig(): boolean;
26
42
  candidates(): ScopeCandidates;
27
43
  instantiate(scope: Scope, filtered: FilterOutput): Tool[];
28
44
  dispose(): Promise<void>;
29
45
  }
46
+ /**
47
+ * 对账结论:这些 server 的连接必须断掉。
48
+ *
49
+ * 两类:已经不在这次发现里的(配置里删了 / 被禁用),以及定义变了的(连接不能再按旧定义用)。
50
+ * 新增的不在结论里 —— 新增不主动连,保持懒连接。
51
+ */
52
+ export declare function staleMcpConnections(previous: readonly McpServerConfig[], discovered: readonly McpServerConfig[]): string[];
@@ -11,6 +11,9 @@ import { McpConnectionManager } from "./McpConnectionManager.js";
11
11
  * - `read_mcp_resource` 读取已连接 server 的资源
12
12
  * 三个元工具名恒上报 `tools` 维度;`mcpManager` 由本插件私有持有,
13
13
  * 有配置路径时在构造时创建,`dispose()` 时统一断开。
14
+ *
15
+ * 每次 `discover()` 除了重读 mcp 文件,还会把连接与发现结果对账一次(`reconcileConnections`):
16
+ * 于是「改了 mcp 配置」= 刷一次 Scope,不需要把 Scope 拆掉重建。
14
17
  */
15
18
  export class McpScopePlugin {
16
19
  static ID = "mcp";
@@ -24,7 +27,28 @@ export class McpScopePlugin {
24
27
  }
25
28
  async discover(scope) {
26
29
  const files = this.paths.map((p) => (isAbsolute(p) ? p : join(scope.cwd, p)));
27
- this.servers = await discoverMcpServers(files);
30
+ const discovered = await discoverMcpServers(files);
31
+ await this.reconcileConnections(discovered);
32
+ this.servers = discovered;
33
+ }
34
+ /**
35
+ * 让连接跟着发现结果对账。
36
+ *
37
+ * 连接是按**定义**建立的:声明改了而连接不动,等于「配置改了但实际没生效」。所以
38
+ * - 这次发现里消失的 server → 断开它的连接(连同缓存的状态 / 清单一起失效);
39
+ * - 定义变了的 server → 断开旧连接,下一次调用时按新定义懒连;
40
+ * - 新增的 server → 不主动连(保持懒连接:没人调用就不起进程 / 不建链);
41
+ * - 定义没变的 → 一个字节都不动(连接与清单原样留着)。
42
+ *
43
+ * 对账在 `refresh()` / `init()` 里跑,于是「配置改了」只需刷一次 Scope,不必重建它。
44
+ */
45
+ async reconcileConnections(discovered) {
46
+ const manager = this.mcpManager;
47
+ if (!manager)
48
+ return;
49
+ for (const id of staleMcpConnections(this.servers, discovered)) {
50
+ await manager.disconnect(id);
51
+ }
28
52
  }
29
53
  /** 是否配置了 MCP(供外部代码判定,如 UnknownToolHintPlugin) */
30
54
  hasConfig() {
@@ -60,3 +84,46 @@ export class McpScopePlugin {
60
84
  await this.mcpManager?.disconnectAll();
61
85
  }
62
86
  }
87
+ /**
88
+ * 对账结论:这些 server 的连接必须断掉。
89
+ *
90
+ * 两类:已经不在这次发现里的(配置里删了 / 被禁用),以及定义变了的(连接不能再按旧定义用)。
91
+ * 新增的不在结论里 —— 新增不主动连,保持懒连接。
92
+ */
93
+ export function staleMcpConnections(previous, discovered) {
94
+ const nextById = new Map(discovered.map((config) => [config.id, config]));
95
+ const stale = [];
96
+ for (const before of previous) {
97
+ const after = nextById.get(before.id);
98
+ if (!after || definitionFingerprint(before) !== definitionFingerprint(after)) {
99
+ stale.push(before.id);
100
+ }
101
+ }
102
+ return stale;
103
+ }
104
+ /**
105
+ * 「定义」的指纹:哪些字段变了就算连接不能再用。
106
+ *
107
+ * 算进来的是**连接事实**:transport 以及各 transport 的落地参数(command / args / env /
108
+ * url / headers / oauth)。不算 `description` —— 它只影响 `load_mcp` 给人看的那段文字,
109
+ * 与怎么连无关,改它不该把一条好连接断掉(新描述下一次实例化就带上了)。
110
+ * `id` 也不进指纹:按 id 配对的,同一 id 才比。
111
+ *
112
+ * 键顺序用排序后的规范化 JSON 抹平(同一份配置不同写法不该被当成「变了」)。
113
+ */
114
+ function definitionFingerprint(config) {
115
+ const { id: _id, description: _description, ...definition } = config;
116
+ return canonicalJson(definition);
117
+ }
118
+ /** 递归按键名排序的 JSON:对象字段顺序不算差异 */
119
+ function canonicalJson(value) {
120
+ if (Array.isArray(value))
121
+ return `[${value.map(canonicalJson).join(",")}]`;
122
+ if (value && typeof value === "object") {
123
+ const entries = Object.entries(value)
124
+ .filter(([, item]) => item !== undefined)
125
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
126
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
127
+ }
128
+ return JSON.stringify(value) ?? "null";
129
+ }
@@ -0,0 +1,28 @@
1
+ import type { Tool } from "@ai-zen/agents-core";
2
+ import type { PeerSessionPort } from "./peerSessionTools.js";
3
+ import type { Scope, FilterOutput } from "../../Scope.js";
4
+ import type { ScopeCandidates, ScopePlugin } from "../../ScopePlugin.js";
5
+ /**
6
+ * 平级会话插件 —— 把宿主给的端口装成三个工具(`create_session` / `read_session_status` /
7
+ * `send_to_session`)。
8
+ *
9
+ * 与 `SubAgentsScopePlugin` 同构(`id` / `candidates` / `instantiate`):自己不发现任何东西
10
+ * (平级会话不是磁盘上的定义,是宿主的运行时能力),候选名是固定的三个。
11
+ *
12
+ * **不给端口就什么都不产出**:`candidates()` 回空、`instantiate()` 回空数组 —— 没有宿主接线
13
+ * 的 SDK 用户(CLI 脚本、用例、只有 Scope 的库使用者)看到的能力面一个字都不变。
14
+ *
15
+ * 为什么能力从端口进来而不是 SDK 自己实现:会话是宿主的财产(id、落库、模型解析、跑一轮、
16
+ * 把结果投回去全在那边),SDK 这一层只认识 Scope 与 Agent 定义。端口是唯一的一处接线,
17
+ * 于是「SDK 不依赖 host」这条分层不用破例。
18
+ */
19
+ export declare class PeerSessionsScopePlugin implements ScopePlugin {
20
+ static readonly ID = "peer-sessions";
21
+ readonly id = "peer-sessions";
22
+ private readonly port?;
23
+ /** 不传端口 = 这个 Scope 没有平级会话能力(老行为) */
24
+ constructor(port?: PeerSessionPort);
25
+ candidates(): ScopeCandidates;
26
+ instantiate(_scope: Scope, filtered: FilterOutput): Tool[];
27
+ }
28
+ export type { PeerSessionPort };
@@ -0,0 +1,35 @@
1
+ import { createPeerSessionTools, PEER_SESSION_TOOL_NAMES } from "./peerSessionTools.js";
2
+ /**
3
+ * 平级会话插件 —— 把宿主给的端口装成三个工具(`create_session` / `read_session_status` /
4
+ * `send_to_session`)。
5
+ *
6
+ * 与 `SubAgentsScopePlugin` 同构(`id` / `candidates` / `instantiate`):自己不发现任何东西
7
+ * (平级会话不是磁盘上的定义,是宿主的运行时能力),候选名是固定的三个。
8
+ *
9
+ * **不给端口就什么都不产出**:`candidates()` 回空、`instantiate()` 回空数组 —— 没有宿主接线
10
+ * 的 SDK 用户(CLI 脚本、用例、只有 Scope 的库使用者)看到的能力面一个字都不变。
11
+ *
12
+ * 为什么能力从端口进来而不是 SDK 自己实现:会话是宿主的财产(id、落库、模型解析、跑一轮、
13
+ * 把结果投回去全在那边),SDK 这一层只认识 Scope 与 Agent 定义。端口是唯一的一处接线,
14
+ * 于是「SDK 不依赖 host」这条分层不用破例。
15
+ */
16
+ export class PeerSessionsScopePlugin {
17
+ static ID = "peer-sessions";
18
+ id = PeerSessionsScopePlugin.ID;
19
+ port;
20
+ /** 不传端口 = 这个 Scope 没有平级会话能力(老行为) */
21
+ constructor(port) {
22
+ this.port = port;
23
+ }
24
+ candidates() {
25
+ if (!this.port)
26
+ return {};
27
+ return { tools: [...PEER_SESSION_TOOL_NAMES] };
28
+ }
29
+ instantiate(_scope, filtered) {
30
+ if (!this.port)
31
+ return [];
32
+ const allow = new Set(filtered.tools);
33
+ return createPeerSessionTools(this.port).filter((tool) => allow.has(tool.function.name));
34
+ }
35
+ }
@@ -0,0 +1,122 @@
1
+ import type { Agent, Tool } from "@ai-zen/agents-core";
2
+ /**
3
+ * 平级会话(peer session)的三个工具 —— **只负责把模型的话翻译成端口调用**。
4
+ *
5
+ * 端口({@link PeerSessionPort})由宿主实现:开一段会话、开跑、之后接着跟它说话、跑完把结果投回
6
+ * 发起者,全都是宿主的事(会话是宿主的财产,SDK 不认识会话)。SDK 这一侧只有三件东西:参数说明,
7
+ * 以及**给模型看的那几句话**(结果会自动推回来别轮询;接着发的话排在哪;记不住 `sessionId` 就靠
8
+ * `label`)。
9
+ *
10
+ * 为什么这几句话必须同时出现在 description 与返回文案两处:模型只读它拿到的东西 —— 第一次只看
11
+ * 得到 description,之后每次调用只看得到返回值。少写一处,模型就会开始忙等轮询
12
+ * (`read_session_status` 一个接一个),而每轮轮询都要烧一次模型调用。
13
+ */
14
+ /** `create_session`:开一段平级会话,受理即回 */
15
+ export declare const CREATE_SESSION_TOOL = "create_session";
16
+ /** `read_session_status`:只问状态 + 一条摘要,绝不返回全量消息 */
17
+ export declare const READ_SESSION_STATUS_TOOL = "read_session_status";
18
+ /** `send_to_session`:继续跟已经存在的那段平级会话说一句(不等结果) */
19
+ export declare const SEND_TO_SESSION_TOOL = "send_to_session";
20
+ /** 本插件向 `tools` 维度贡献的候选名(顺序即展示顺序) */
21
+ export declare const PEER_SESSION_TOOL_NAMES: readonly ["create_session", "read_session_status", "send_to_session"];
22
+ /**
23
+ * 平级会话的状态。
24
+ *
25
+ * 前四个是记录里的状态;`gone` 只出现在 `read_session_status` 的答案里:这段会话的记录
26
+ * 找不到了(被删掉,或者宿主重启之后那份进程内记录没了 —— 那时它就是一段普通会话)。
27
+ */
28
+ export type PeerSessionState = "running" | "idle" | "failed" | "aborted" | "gone";
29
+ /**
30
+ * `create_session` 被**结构化拒绝**的原因。
31
+ *
32
+ * 拒绝是返回结果而不是异常:模型要能读懂并改变策略(「这层不能开分身了,那我自己做」
33
+ * 「这个助手没有可用模型,换一个」「先等已有的跑完」),异常只会把它这一轮打断。
34
+ */
35
+ export type PeerSessionRejectReason = "depth_exceeded" | "model_unresolved" | "too_many_peers";
36
+ /**
37
+ * `create_session` 的答案。
38
+ *
39
+ * 成功只给两个字段:`sessionId`(子会话的 conversationId)与可读的 `label`。**没有结果** ——
40
+ * 「建完即回,不等子会话跑完」是整个方案的定盘星:等待就等于子代理,那已经存在了。
41
+ */
42
+ export type PeerSessionCreated = {
43
+ ok: true;
44
+ sessionId: string;
45
+ label: string;
46
+ } | {
47
+ ok: false;
48
+ reason: PeerSessionRejectReason;
49
+ hint?: string;
50
+ };
51
+ /**
52
+ * `read_session_status` 的答案。
53
+ *
54
+ * `lastMessage` 是子会话最后一条助手消息的**截断摘要**(宿主侧 ~300 字),不是全量消息:
55
+ * 给了原文,模型就会把它当上下文搬运,token 立刻炸,而且绕过了我们自己的上下文管理。
56
+ */
57
+ export interface PeerSessionStatus {
58
+ state: PeerSessionState;
59
+ label?: string;
60
+ startedAt?: string;
61
+ lastMessage?: string;
62
+ }
63
+ /**
64
+ * `send_to_session` 的答案。
65
+ *
66
+ * 成功只给 `state`:**投递那一刻**对方处于什么状态(`running` = 这一条排在它这一轮末尾;
67
+ * `idle` = 这一条会把它叫起来;`settling` = 它正在收尾,这一条排在后面)。不是「已经跑完了」——
68
+ * 本工具从不等结果。
69
+ *
70
+ * 两种拒绝:`gone`(这段会话没有了:被删了,或者宿主重启之后那份进程内记录没了)、
71
+ * `not_allowed`(它与我之间没有父子关系:平级会话之间不许互发)。
72
+ */
73
+ export type PeerSessionSent = {
74
+ ok: true;
75
+ state: "running" | "idle" | "settling";
76
+ } | {
77
+ ok: false;
78
+ reason: "gone" | "not_allowed";
79
+ };
80
+ /** `send_to_session` 的入参(`caller` 由插件从 `ToolCallContext` 取,不由模型给) */
81
+ export interface PeerSessionSendInput {
82
+ /** 谁在调这个工具(`ctx.agent`)—— 宿主据此认领「哪一段会话在说话」与消息署名 */
83
+ caller: Agent;
84
+ sessionId: string;
85
+ content: string;
86
+ }
87
+ /** `create_session` 的入参(`caller` 由插件从 `ToolCallContext` 取,不由模型给) */
88
+ export interface PeerSessionCreateInput {
89
+ /** 谁在调这个工具(`ctx.agent`)—— 宿主据此认领「哪一段会话在开分身」 */
90
+ caller: Agent;
91
+ prompt: string;
92
+ agentId?: string;
93
+ modelId?: string;
94
+ label?: string;
95
+ }
96
+ /**
97
+ * 宿主实现给 SDK 的端口(**SDK 不依赖宿主**:这个接口是唯一的一处接线)。
98
+ *
99
+ * 不给端口时插件不产出任何工具 —— 老行为一个字不变。
100
+ */
101
+ export interface PeerSessionPort {
102
+ create(input: PeerSessionCreateInput): Promise<PeerSessionCreated>;
103
+ status(input: {
104
+ caller: Agent;
105
+ sessionId: string;
106
+ }): Promise<PeerSessionStatus>;
107
+ /**
108
+ * 继续跟一段已有的平级会话说一句(不返回结果:结果跑完会自己推回来)。
109
+ *
110
+ * 与 `create` / `status` 同构:**只收 `caller`**,不收来源名 / label —— 正文那行「来自 会话「…」
111
+ * 自动推送」由宿主按调用方解析(模型说自己是谁不算数)。
112
+ */
113
+ send(input: PeerSessionSendInput): Promise<PeerSessionSent>;
114
+ }
115
+ /** `send_to_session` 成功回执里的 `state`(与宿主的 `DeliveryOutcome.state` 同义) */
116
+ export type PeerSessionSendState = "running" | "idle" | "settling";
117
+ /**
118
+ * 造三个工具(顺序即返回顺序)。
119
+ *
120
+ * 三个工具都是即时返回的 `CallbackTool`:真正的等待在宿主那一侧(子会话自己跑)。
121
+ */
122
+ export declare function createPeerSessionTools(port: PeerSessionPort): Tool[];
@@ -0,0 +1,266 @@
1
+ import { CallbackTool } from "@ai-zen/agents-core";
2
+ /**
3
+ * 平级会话(peer session)的三个工具 —— **只负责把模型的话翻译成端口调用**。
4
+ *
5
+ * 端口({@link PeerSessionPort})由宿主实现:开一段会话、开跑、之后接着跟它说话、跑完把结果投回
6
+ * 发起者,全都是宿主的事(会话是宿主的财产,SDK 不认识会话)。SDK 这一侧只有三件东西:参数说明,
7
+ * 以及**给模型看的那几句话**(结果会自动推回来别轮询;接着发的话排在哪;记不住 `sessionId` 就靠
8
+ * `label`)。
9
+ *
10
+ * 为什么这几句话必须同时出现在 description 与返回文案两处:模型只读它拿到的东西 —— 第一次只看
11
+ * 得到 description,之后每次调用只看得到返回值。少写一处,模型就会开始忙等轮询
12
+ * (`read_session_status` 一个接一个),而每轮轮询都要烧一次模型调用。
13
+ */
14
+ /** `create_session`:开一段平级会话,受理即回 */
15
+ export const CREATE_SESSION_TOOL = "create_session";
16
+ /** `read_session_status`:只问状态 + 一条摘要,绝不返回全量消息 */
17
+ export const READ_SESSION_STATUS_TOOL = "read_session_status";
18
+ /** `send_to_session`:继续跟已经存在的那段平级会话说一句(不等结果) */
19
+ export const SEND_TO_SESSION_TOOL = "send_to_session";
20
+ /** 本插件向 `tools` 维度贡献的候选名(顺序即展示顺序) */
21
+ export const PEER_SESSION_TOOL_NAMES = [
22
+ CREATE_SESSION_TOOL,
23
+ READ_SESSION_STATUS_TOOL,
24
+ SEND_TO_SESSION_TOOL,
25
+ ];
26
+ /** ① 结果会自动推回来、别轮询;② 记不住 `sessionId` 就靠 `label` */
27
+ const CREATE_HINT = "The result of this session is pushed back to me automatically when it settles — that push " +
28
+ "wakes me up, so do not poll it (and do not call read_session_status in a loop). Keep `label` " +
29
+ "next to `sessionId`: if I forget the id later, `label` is how I name this session.";
30
+ /** 拒绝各自的一句话:说清「为什么」与「接下来能做什么」(宿主没给 hint 时用它) */
31
+ const REJECT_HINTS = {
32
+ depth_exceeded: "This conversation is itself a peer session, and peer sessions cannot open further peer " +
33
+ "sessions (one level only). Do the work here instead, or report back and let the conversation " +
34
+ "that started this one spawn it.",
35
+ model_unresolved: "No model could be resolved for that peer session (no session override, no modelId on the " +
36
+ "agent definition, no global default model). Pass `modelId`, or pass an `agentId` that has a " +
37
+ "model bound.",
38
+ too_many_peers: "This conversation already has the maximum number of peer sessions running at the same time. " +
39
+ "Wait for some of them to finish (their results are pushed back to me automatically), or give " +
40
+ "the work to fewer sessions instead of opening another one.",
41
+ };
42
+ /**
43
+ * `send_to_session` 被拒绝的两种原因各自的一句话(端口只回原因,不给文案)。
44
+ *
45
+ * `gone` 要说清「不会再有回音」(否则模型会等一条永远不会到的结果),`not_allowed` 要说清
46
+ * 「自己把活干掉」,两者都不建议重试。
47
+ */
48
+ const SEND_REJECT_HINTS = {
49
+ gone: "There is no record of this session any more: it was deleted, or the host restarted and that " +
50
+ "in-process record is gone (it is now an ordinary conversation that still shows up in the " +
51
+ "session list). Nothing was sent and no result will arrive — do the work here instead.",
52
+ not_allowed: "That session is not related to this one: only a conversation and the peer sessions it " +
53
+ "started can talk to each other, and peer sessions cannot message each other. Nothing was " +
54
+ "sent — handle it here, or report back and let the conversation that started this one relay.",
55
+ };
56
+ /**
57
+ * `send_to_session` 成功时每个 `state` 一句给模型的话。
58
+ *
59
+ * 三句必须都在(少一句模型就会开始忙等,或者记不住是哪段会话):
60
+ * ① 对方在跑 → 这一条排在它这一轮末尾;对方空闲 → 这一条会把它叫起来;
61
+ * ② **不要等结果**,跑完会自动推回来;
62
+ * ③ 记不住 `sessionId` 就靠 `label` 认。
63
+ * 「排在末尾 / 叫起来 / 先攒着」只差头一句,后两句三支一模一样。
64
+ */
65
+ const SEND_TAIL = "Do not wait for a result: this message does not come back here, the result of that session " +
66
+ "is pushed back to me automatically when it settles and that push wakes me up. If I forget the " +
67
+ "`sessionId`, the `label` returned by create_session is how I name this session.";
68
+ function sendHint(state) {
69
+ switch (state) {
70
+ case "running":
71
+ return ("It is running, so this message waits in line and is picked up at the end of its current " +
72
+ `turn. ${SEND_TAIL}`);
73
+ case "idle":
74
+ return `It was idle, so this message wakes it up and it starts a new turn. ${SEND_TAIL}`;
75
+ case "settling":
76
+ return ("It is finishing its current turn, so this message is held and delivered as soon as that " +
77
+ `turn settles. ${SEND_TAIL}`);
78
+ }
79
+ }
80
+ /** 每个状态一句给模型的话(同样带着「别轮询」与「靠 label」两句) */
81
+ function statusHint(state) {
82
+ switch (state) {
83
+ case "running":
84
+ return ("It is still running. Its result will be pushed to me automatically when it settles — do " +
85
+ "not poll it. If I forget the `sessionId`, the `label` identifies this session.");
86
+ case "idle":
87
+ return ("It finished and its result was already pushed to me automatically. Do not poll it again. " +
88
+ "If I forget the `sessionId`, the `label` identifies this session.");
89
+ case "failed":
90
+ case "aborted":
91
+ return ("It stopped without finishing; the result (including why it stopped) was already pushed " +
92
+ "to me automatically. Do not poll it again. If I forget the `sessionId`, the `label` " +
93
+ "identifies this session.");
94
+ case "gone":
95
+ return ("There is no record of this session any more: it was deleted, or the host restarted and " +
96
+ "that in-process record is gone (in that case it is now an ordinary conversation that " +
97
+ "still shows up in the session list). Do not wait for a result that will never arrive; if " +
98
+ "I only remember the `label`, that session can no longer be looked up by it.");
99
+ }
100
+ }
101
+ /**
102
+ * 造三个工具(顺序即返回顺序)。
103
+ *
104
+ * 三个工具都是即时返回的 `CallbackTool`:真正的等待在宿主那一侧(子会话自己跑)。
105
+ */
106
+ export function createPeerSessionTools(port) {
107
+ return [createSessionTool(port), readSessionStatusTool(port), sendToSessionTool(port)];
108
+ }
109
+ /** `create_session({ prompt, agentId?, modelId?, label? })` → `{ sessionId, label }` */
110
+ function createSessionTool(port) {
111
+ return new CallbackTool({
112
+ function: {
113
+ name: CREATE_SESSION_TOOL,
114
+ description: [
115
+ "Open a PEER SESSION: a separate, full conversation with its own agent that works on",
116
+ "`prompt` in parallel with me (own context, own usage, and it stays readable in the",
117
+ "session list afterwards). Use it for work that can happen alongside this conversation",
118
+ "instead of blocking it.",
119
+ "This call returns as soon as the session is accepted — it does NOT wait for the work to",
120
+ "finish, so do not expect the result here.",
121
+ "The result is pushed back to me automatically when that session settles, and that push",
122
+ "wakes me up so I can carry on: do not poll it repeatedly.",
123
+ "Remember the returned `label` as well as `sessionId`: in a long conversation I may no",
124
+ "longer recall the id, and the label is how I refer to this session.",
125
+ ].join(" "),
126
+ parameters: {
127
+ type: "object",
128
+ properties: {
129
+ prompt: {
130
+ type: "string",
131
+ description: "What that session should do. Write it as a self-contained task: the peer session " +
132
+ "starts from an empty context and cannot see this conversation.",
133
+ },
134
+ agentId: {
135
+ type: "string",
136
+ description: "Agent (by id) that runs the peer session (optional, defaults to the agent of this " +
137
+ "conversation)",
138
+ },
139
+ modelId: {
140
+ type: "string",
141
+ description: "Model id for the peer session (optional, defaults to the usual resolution: session " +
142
+ "> agent definition > global default)",
143
+ },
144
+ label: {
145
+ type: "string",
146
+ description: 'Short readable name for this session (optional, e.g. "run the tests"). It is what ' +
147
+ "the pushed-back result says and what read_session_status shows.",
148
+ },
149
+ },
150
+ required: ["prompt"],
151
+ additionalProperties: false,
152
+ },
153
+ },
154
+ callback: async (input, ctx) => {
155
+ const created = await port.create({
156
+ caller: ctx.agent,
157
+ prompt: typeof input.prompt === "string" ? input.prompt : String(input.prompt ?? ""),
158
+ ...optionalString("agentId", input.agentId),
159
+ ...optionalString("modelId", input.modelId),
160
+ ...optionalString("label", input.label),
161
+ });
162
+ // 结构化拒绝:模型能按字段分支,不用去读自由文本(宿主没给 hint 时用 SDK 这一份)
163
+ if (!created.ok)
164
+ return { rejected: created.reason, hint: created.hint ?? REJECT_HINTS[created.reason] };
165
+ return { sessionId: created.sessionId, label: created.label, hint: CREATE_HINT };
166
+ },
167
+ });
168
+ }
169
+ /** `read_session_status({ sessionId })` → `{ state, label?, startedAt?, lastMessage?, hint }` */
170
+ function readSessionStatusTool(port) {
171
+ return new CallbackTool({
172
+ function: {
173
+ name: READ_SESSION_STATUS_TOOL,
174
+ description: [
175
+ "Check a peer session created earlier: its state (running / idle / failed / aborted /",
176
+ "gone) plus a short digest of its last assistant message — never the full conversation,",
177
+ "so do not use it to fetch results or context.",
178
+ "The result is pushed back to me automatically when that session settles and that push",
179
+ "wakes me up: this tool is for a single check (is it still running? is it gone?), not for",
180
+ "polling in a loop.",
181
+ "If I no longer remember the `sessionId`, the `label` returned by create_session is what",
182
+ "identifies the session — it comes back in the answer, so I can tell them apart.",
183
+ ].join(" "),
184
+ parameters: {
185
+ type: "object",
186
+ properties: {
187
+ sessionId: {
188
+ type: "string",
189
+ description: "The sessionId returned by create_session (that id is also the conversation id of " +
190
+ "that session)",
191
+ },
192
+ },
193
+ required: ["sessionId"],
194
+ additionalProperties: false,
195
+ },
196
+ },
197
+ callback: async (input, ctx) => {
198
+ const status = await port.status({
199
+ caller: ctx.agent,
200
+ sessionId: typeof input.sessionId === "string" ? input.sessionId : "",
201
+ });
202
+ // 键的出现与否本身就是信息:`label` / `startedAt` / `lastMessage` 拿不到就不出现
203
+ return {
204
+ state: status.state,
205
+ ...(status.label === undefined ? {} : { label: status.label }),
206
+ ...(status.startedAt === undefined ? {} : { startedAt: status.startedAt }),
207
+ ...(status.lastMessage === undefined ? {} : { lastMessage: status.lastMessage }),
208
+ hint: statusHint(status.state),
209
+ };
210
+ },
211
+ });
212
+ }
213
+ /** `send_to_session({ sessionId, content })` → `{ accepted, state }` / `{ rejected, hint }` */
214
+ function sendToSessionTool(port) {
215
+ return new CallbackTool({
216
+ function: {
217
+ name: SEND_TO_SESSION_TOOL,
218
+ description: [
219
+ "Send another message to a PEER SESSION created earlier by create_session — it is how I",
220
+ "carry on with that session instead of starting a new one.",
221
+ "If that session is running, this message is queued and picked up at the end of its",
222
+ "current turn; if it is idle, this message wakes it up and it starts a new turn. Either",
223
+ "way the call returns immediately.",
224
+ "Do not wait for a result here: this message does not come back, and the result of that",
225
+ "session is pushed back to me automatically when it settles (that push wakes me up), so do",
226
+ "not poll it.",
227
+ "If I no longer remember the `sessionId`, the `label` returned by create_session is how I",
228
+ "identify that session.",
229
+ ].join(" "),
230
+ parameters: {
231
+ type: "object",
232
+ properties: {
233
+ sessionId: {
234
+ type: "string",
235
+ description: "The sessionId returned by create_session (that id is also the conversation id of " +
236
+ "that session)",
237
+ },
238
+ content: {
239
+ type: "string",
240
+ description: "What to say to that session. Write it as a self-contained instruction: it cannot " +
241
+ "see this conversation, it only has its own history.",
242
+ },
243
+ },
244
+ required: ["sessionId", "content"],
245
+ additionalProperties: false,
246
+ },
247
+ },
248
+ callback: async (input, ctx) => {
249
+ const sent = await port.send({
250
+ caller: ctx.agent,
251
+ sessionId: typeof input.sessionId === "string" ? input.sessionId : "",
252
+ content: typeof input.content === "string" ? input.content : String(input.content ?? ""),
253
+ });
254
+ // 结构化拒绝:模型能按字段分支,不用去读自由文本
255
+ if (!sent.ok)
256
+ return { rejected: sent.reason, hint: SEND_REJECT_HINTS[sent.reason] };
257
+ return { accepted: true, state: sent.state, hint: sendHint(sent.state) };
258
+ },
259
+ });
260
+ }
261
+ /** 可选的字符串参数:空串与非字符串都当作「没给」,不往端口里塞一个假值 */
262
+ function optionalString(key, value) {
263
+ if (typeof value !== "string" || value.length === 0)
264
+ return {};
265
+ return { [key]: value };
266
+ }
@@ -10,7 +10,7 @@ export declare function createLoadSkillTool(skillDirs: string[], filteredSkills:
10
10
  * 只展示 subAgent: true 的 Skill,枚举中自动排除不支持子 Agent 模式的 skill。
11
11
  *
12
12
  * 工具由 AgentToolLazy 承载:子 Agent 在 exec 时构建,从而复用统一的委派边界
13
- * (onSubAgentStart / onSubAgentEnd 钩子与 sub-agent-start / sub-agent-end 事件)。
13
+ * (onSubAgentStart / onSubAgentEnd 钩子与 subAgentStarted / subAgentFinished 事件)。
14
14
  * 子 Agent 沿用父 Agent 的工具能力(不做权限过滤),但剔除 call_skill_sub_agent 自身,
15
15
  * 避免 skill 链式自递归。
16
16
  */
@@ -75,7 +75,7 @@ export function createLoadSkillTool(skillDirs, filteredSkills) {
75
75
  * 只展示 subAgent: true 的 Skill,枚举中自动排除不支持子 Agent 模式的 skill。
76
76
  *
77
77
  * 工具由 AgentToolLazy 承载:子 Agent 在 exec 时构建,从而复用统一的委派边界
78
- * (onSubAgentStart / onSubAgentEnd 钩子与 sub-agent-start / sub-agent-end 事件)。
78
+ * (onSubAgentStart / onSubAgentEnd 钩子与 subAgentStarted / subAgentFinished 事件)。
79
79
  * 子 Agent 沿用父 Agent 的工具能力(不做权限过滤),但剔除 call_skill_sub_agent 自身,
80
80
  * 避免 skill 链式自递归。
81
81
  */
@@ -112,7 +112,8 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
112
112
  },
113
113
  },
114
114
  // 初始消息依赖运行时参数(skill_id → SKILL.md 内容),故不传 messages 模板,
115
- // 由 buildAgent 读取 SKILL.md 后自行决定;abort 联动与委派边界由 AgentToolLazy 统一处理
115
+ // 由 buildAgent 读取 SKILL.md 后自行决定;中断信号与委派边界由 AgentToolLazy 统一处理
116
+ // (父的 `abort` 直接把 signal 交给子 agent 的 `runOnce`,不再有手工联动)
116
117
  buildAgent: async (parsedArgs, ctx) => {
117
118
  const skillId = parsedArgs.skill_id;
118
119
  const task = parsedArgs.task;
@@ -136,6 +137,9 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
136
137
  modelConfig: parentAgent.modelConfig,
137
138
  messages: [Message.System(skill.content), Message.User(task)],
138
139
  tools,
140
+ // 技能子 Agent 同样走委派:`buildAgent` 造出来的必须是**一次性**
141
+ // (`CORE.md` §9)。它跑完就死透,不与父会话共用寿命。
142
+ lifetime: "one-shot",
139
143
  });
140
144
  },
141
145
  });