@ai-zen/agents-sdk 1.2.0-alpha.1 → 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 (40) 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/config/ConfigManager.d.ts +21 -16
  15. package/dist/config/ConfigManager.js +47 -25
  16. package/dist/index.d.ts +5 -2
  17. package/dist/index.js +3 -0
  18. package/dist/runtime/HandoffGuardPlugin.d.ts +7 -5
  19. package/dist/runtime/HandoffGuardPlugin.js +8 -6
  20. package/dist/runtime/HandoffService.d.ts +51 -12
  21. package/dist/runtime/HandoffService.js +112 -19
  22. package/dist/runtime/SdkAgent.d.ts +2 -3
  23. package/dist/runtime/SdkAgent.js +1 -2
  24. package/dist/scope/Scope.d.ts +35 -8
  25. package/dist/scope/Scope.js +50 -11
  26. package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +7 -0
  27. package/dist/scope/plugins/mcp/McpConnectionManager.js +7 -0
  28. package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +23 -0
  29. package/dist/scope/plugins/mcp/McpScopePlugin.js +68 -1
  30. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.d.ts +28 -0
  31. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +35 -0
  32. package/dist/scope/plugins/peers/peerSessionTools.d.ts +122 -0
  33. package/dist/scope/plugins/peers/peerSessionTools.js +266 -0
  34. package/dist/scope/plugins/skills/skillTools.d.ts +1 -1
  35. package/dist/scope/plugins/skills/skillTools.js +6 -2
  36. package/dist/scope/plugins/subagents/subAgentTools.js +3 -0
  37. package/dist/shared/errors.d.ts +10 -3
  38. package/dist/shared/errors.js +10 -3
  39. package/dist/types/index.d.ts +6 -4
  40. package/package.json +2 -2
@@ -25,6 +25,15 @@ export interface ExcludeOptions {
25
25
  export interface FilterOptions {
26
26
  exclude?: ExcludeOptions;
27
27
  }
28
+ /**
29
+ * 取配置的端口 —— `Scope` 不再收一份配置快照,而是收「怎么拿到当下这一份」。
30
+ *
31
+ * 配置的本质是磁盘上那几个 json:改完之后该由下一次 `refresh()` 现读读到,
32
+ * 而不是把整个 Scope 拆掉重建(拆掉会连带别的能力一起重来,且正在跑的那一轮
33
+ * 会被抽掉能力)。端口可以是同步的(测试里给一份常量),也可以是异步的
34
+ * (宿主给 `ConfigManager.read()`)。
35
+ */
36
+ export type ScopeConfigSource = () => AppConfig | Promise<AppConfig>;
28
37
  /**
29
38
  * Scope — 全局上下文 + 能力装配编排容器。
30
39
  *
@@ -36,7 +45,7 @@ export interface FilterOptions {
36
45
  *
37
46
  * 装配方式(插件必须显式注入,Scope 不装任何默认插件):
38
47
  * ```ts
39
- * const scope = new Scope({ config, cwd, agentsDir })
48
+ * const scope = new Scope({ getConfig, cwd, agentsDir })
40
49
  * .use(...allInOne({ skillsPaths, toolsPaths, subAgentsPaths, mcpPaths }));
41
50
  * await scope.init();
42
51
  * ```
@@ -44,14 +53,21 @@ export interface FilterOptions {
44
53
  * 设计原则:
45
54
  * - Scope 只做编排:三阶段管线骨架(发现 → 过滤 → 实例化)+ 生命周期
46
55
  * - 能力来源(内置/用户工具、Skill、MCP、SubAgent)全部疏散到 ScopePlugin,各自自持
47
- * - Scope 实例一旦创建,config/cwd/agentsDir/env 不变;refresh() 只让插件重新发现
56
+ * - config 随 `refresh()` 更新(每轮现读端口),cwd / agentsDir 创建之后不变
48
57
  */
49
58
  export declare class Scope {
50
- /** 应用配置(端点、模型等) */
51
- readonly config: AppConfig;
59
+ /** 取配置的端口:每次 `refresh()` 都问它要一份 */
60
+ private readonly getConfig;
61
+ /**
62
+ * 当下这一份配置。
63
+ *
64
+ * 只有一个字段、一个来源:`scope.config` 与 `scope.env.config` 读的都是它,
65
+ * 于是「按新配置算出来的东西」与「工具 exec 时看到的配置」不会分叉。
66
+ */
67
+ private current?;
52
68
  /** 当前工作目录 — 相对路径解析基准,也是 ToolEnv.cwd 的来源 */
53
69
  readonly cwd: string;
54
- /** 工具环境 — 插件实例化内置工具时注入 */
70
+ /** 工具环境 — 插件实例化内置工具时注入(`config` 是活的,见构造函数的注释) */
55
71
  readonly env: ToolEnv;
56
72
  /** Agent 定义目录(createAgent 用) */
57
73
  readonly agentsDir: string;
@@ -60,12 +76,20 @@ export declare class Scope {
60
76
  /** 是否已 init(init 之后禁止再 use) */
61
77
  private _initialized;
62
78
  constructor(options: {
63
- config: AppConfig;
79
+ /** 取配置的端口:配置改了不必重建 Scope,下一次 `refresh()` 就会读到新的那一份 */
80
+ getConfig: ScopeConfigSource;
64
81
  agentsDir: string;
65
82
  cwd?: string;
66
83
  /** 出网/外部依赖的注入点(缺省全部走真实 OpenAI SDK),会透传到 ToolEnv.deps */
67
84
  deps?: ToolEnvDeps;
68
85
  });
86
+ /**
87
+ * 应用配置(端点、模型等)。
88
+ *
89
+ * 同步读,读到的是**当下**那一份:`refresh()` 之后就是磁盘上的新配置。
90
+ * 配置端口是异步的且还没 `init()` 过时抛错(那时确实还没有「当下这一份」)。
91
+ */
92
+ get config(): AppConfig;
69
93
  /** 已注册插件(只读视图) */
70
94
  get plugins(): readonly ScopePlugin[];
71
95
  /**
@@ -81,11 +105,14 @@ export declare class Scope {
81
105
  /** 按 id 查找插件(供外部代码/其它插件查询插件状态) */
82
106
  getPluginById<T extends ScopePlugin>(id: string): T | undefined;
83
107
  /**
84
- * 初始化:执行首次全局能力发现(遍历插件 discover()),随后锁定插件注册。
108
+ * 初始化:取一次配置 + 执行首次全局能力发现(遍历插件 discover()),随后锁定插件注册。
85
109
  */
86
110
  init(): Promise<void>;
87
111
  /**
88
- * 重新执行全局发现(遍历插件 discover())。
112
+ * 重新取配置 + 重新执行全局发现(遍历插件 discover())。
113
+ *
114
+ * 顺序不能反:插件发现可能要用新配置算路径 / 开关(如内置工具的可用性、
115
+ * MCP 的连接对账),所以先把 `current` 换掉,再让插件看世界。
89
116
  */
90
117
  refresh(options?: {
91
118
  silent?: boolean;
@@ -10,7 +10,7 @@ import { PermissionEvaluator } from "./PermissionEvaluator.js";
10
10
  *
11
11
  * 装配方式(插件必须显式注入,Scope 不装任何默认插件):
12
12
  * ```ts
13
- * const scope = new Scope({ config, cwd, agentsDir })
13
+ * const scope = new Scope({ getConfig, cwd, agentsDir })
14
14
  * .use(...allInOne({ skillsPaths, toolsPaths, subAgentsPaths, mcpPaths }));
15
15
  * await scope.init();
16
16
  * ```
@@ -18,14 +18,21 @@ import { PermissionEvaluator } from "./PermissionEvaluator.js";
18
18
  * 设计原则:
19
19
  * - Scope 只做编排:三阶段管线骨架(发现 → 过滤 → 实例化)+ 生命周期
20
20
  * - 能力来源(内置/用户工具、Skill、MCP、SubAgent)全部疏散到 ScopePlugin,各自自持
21
- * - Scope 实例一旦创建,config/cwd/agentsDir/env 不变;refresh() 只让插件重新发现
21
+ * - config 随 `refresh()` 更新(每轮现读端口),cwd / agentsDir 创建之后不变
22
22
  */
23
23
  export class Scope {
24
- /** 应用配置(端点、模型等) */
25
- config;
24
+ /** 取配置的端口:每次 `refresh()` 都问它要一份 */
25
+ getConfig;
26
+ /**
27
+ * 当下这一份配置。
28
+ *
29
+ * 只有一个字段、一个来源:`scope.config` 与 `scope.env.config` 读的都是它,
30
+ * 于是「按新配置算出来的东西」与「工具 exec 时看到的配置」不会分叉。
31
+ */
32
+ current;
26
33
  /** 当前工作目录 — 相对路径解析基准,也是 ToolEnv.cwd 的来源 */
27
34
  cwd;
28
- /** 工具环境 — 插件实例化内置工具时注入 */
35
+ /** 工具环境 — 插件实例化内置工具时注入(`config` 是活的,见构造函数的注释) */
29
36
  env;
30
37
  /** Agent 定义目录(createAgent 用) */
31
38
  agentsDir;
@@ -34,12 +41,36 @@ export class Scope {
34
41
  /** 是否已 init(init 之后禁止再 use) */
35
42
  _initialized = false;
36
43
  constructor(options) {
37
- this.config = options.config;
44
+ this.getConfig = options.getConfig;
38
45
  this.cwd = options.cwd ?? process.cwd();
39
- this.env = options.deps
40
- ? { cwd: this.cwd, config: this.config, deps: options.deps }
41
- : { cwd: this.cwd, config: this.config };
42
46
  this.agentsDir = options.agentsDir;
47
+ // 端口给的是现成的一份(同步)时,构造完就能读 config;给的是 Promise 时
48
+ // 留到 init() / refresh() 填 —— 那时候读之前先等一次即可。
49
+ const seeded = options.getConfig();
50
+ if (!isPromiseLike(seeded))
51
+ this.current = seeded;
52
+ const scope = this;
53
+ this.env = {
54
+ cwd: this.cwd,
55
+ // 活的 config:工具在 exec 时读到的永远是「当下这一份」,refresh 之后就是新的。
56
+ // 不在这里另存一份,否则 env.config 与 scope.config 会分叉。
57
+ get config() {
58
+ return scope.config;
59
+ },
60
+ ...(options.deps ? { deps: options.deps } : {}),
61
+ };
62
+ }
63
+ /**
64
+ * 应用配置(端点、模型等)。
65
+ *
66
+ * 同步读,读到的是**当下**那一份:`refresh()` 之后就是磁盘上的新配置。
67
+ * 配置端口是异步的且还没 `init()` 过时抛错(那时确实还没有「当下这一份」)。
68
+ */
69
+ get config() {
70
+ if (this.current === undefined) {
71
+ throw new Error("Scope.config is not loaded yet: the config port is async, await init() / refresh() first");
72
+ }
73
+ return this.current;
43
74
  }
44
75
  // ==================================================================
45
76
  // 插件注册与生命周期
@@ -71,17 +102,21 @@ export class Scope {
71
102
  return this._plugins.find((p) => p.id === id);
72
103
  }
73
104
  /**
74
- * 初始化:执行首次全局能力发现(遍历插件 discover()),随后锁定插件注册。
105
+ * 初始化:取一次配置 + 执行首次全局能力发现(遍历插件 discover()),随后锁定插件注册。
75
106
  */
76
107
  async init() {
77
108
  await this.refresh();
78
109
  this._initialized = true;
79
110
  }
80
111
  /**
81
- * 重新执行全局发现(遍历插件 discover())。
112
+ * 重新取配置 + 重新执行全局发现(遍历插件 discover())。
113
+ *
114
+ * 顺序不能反:插件发现可能要用新配置算路径 / 开关(如内置工具的可用性、
115
+ * MCP 的连接对账),所以先把 `current` 换掉,再让插件看世界。
82
116
  */
83
117
  async refresh(options) {
84
118
  const opts = { silent: options?.silent ?? false };
119
+ this.current = await this.getConfig();
85
120
  for (const plugin of this._plugins) {
86
121
  await plugin.discover?.(this, opts);
87
122
  }
@@ -153,6 +188,10 @@ export class Scope {
153
188
  return dedupTools(result);
154
189
  }
155
190
  }
191
+ /** 端口返回值是不是 Promise(同步端口因此可以省掉一次 await 的语义差别) */
192
+ function isPromiseLike(value) {
193
+ return typeof value?.then === "function";
194
+ }
156
195
  function dedupTools(tools) {
157
196
  const seen = new Set();
158
197
  const result = [];
@@ -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[];