@ai-zen/agents-sdk 1.0.0-alpha.9 → 1.0.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 (86) hide show
  1. package/CHANGELOG.md +651 -2
  2. package/README.md +22 -6
  3. package/README.zh.md +23 -7
  4. package/dist/agent-plugins/AutoMigratePlugin.d.ts +35 -9
  5. package/dist/agent-plugins/AutoMigratePlugin.js +21 -10
  6. package/dist/agent-plugins/AutoRefreshToolsPlugin.js +1 -3
  7. package/dist/agent-plugins/ContextGuardPlugin.d.ts +28 -16
  8. package/dist/agent-plugins/ContextGuardPlugin.js +23 -17
  9. package/dist/agent-plugins/UnknownToolHintPlugin.js +4 -4
  10. package/dist/config/ConfigManager.d.ts +57 -8
  11. package/dist/config/ConfigManager.js +167 -26
  12. package/dist/config/constants.d.ts +7 -0
  13. package/dist/config/constants.js +70 -43
  14. package/dist/config/factory-skills.d.ts +33 -0
  15. package/dist/config/factory-skills.js +126 -0
  16. package/dist/config/migrate.d.ts +106 -0
  17. package/dist/config/migrate.js +196 -0
  18. package/dist/config/reasoning-presets.d.ts +37 -0
  19. package/dist/config/reasoning-presets.js +64 -0
  20. package/dist/index.d.ts +13 -7
  21. package/dist/index.js +11 -3
  22. package/dist/runtime/HandoffGuardPlugin.d.ts +35 -0
  23. package/dist/runtime/HandoffGuardPlugin.js +65 -0
  24. package/dist/runtime/HandoffService.d.ts +246 -0
  25. package/dist/runtime/HandoffService.js +475 -0
  26. package/dist/runtime/SdkAgent.d.ts +7 -1
  27. package/dist/runtime/SdkAgent.js +3 -0
  28. package/dist/runtime/createAgent.d.ts +20 -1
  29. package/dist/runtime/createAgent.js +14 -9
  30. package/dist/runtime/createModel.d.ts +8 -4
  31. package/dist/runtime/createModel.js +22 -5
  32. package/dist/scope/PermissionEvaluator.js +1 -1
  33. package/dist/scope/Scope.d.ts +3 -1
  34. package/dist/scope/Scope.js +4 -2
  35. package/dist/scope/plugins/builtin/BatchEditTool.js +24 -14
  36. package/dist/scope/plugins/builtin/CopyTool.js +4 -4
  37. package/dist/scope/plugins/builtin/CwdTool.js +1 -1
  38. package/dist/scope/plugins/builtin/DownloadFileTool.d.ts +1 -0
  39. package/dist/scope/plugins/builtin/DownloadFileTool.js +58 -34
  40. package/dist/scope/plugins/builtin/EditTool.js +25 -25
  41. package/dist/scope/plugins/builtin/ExecTool.js +134 -25
  42. package/dist/scope/plugins/builtin/ExistTool.js +2 -2
  43. package/dist/scope/plugins/builtin/FindTextTool.js +15 -10
  44. package/dist/scope/plugins/builtin/GenerateImageTool.js +91 -25
  45. package/dist/scope/plugins/builtin/GlobTool.js +10 -5
  46. package/dist/scope/plugins/builtin/InspectFileTool.js +7 -7
  47. package/dist/scope/plugins/builtin/LsTool.js +5 -5
  48. package/dist/scope/plugins/builtin/MkdirTool.js +3 -3
  49. package/dist/scope/plugins/builtin/ReadTool.js +8 -8
  50. package/dist/scope/plugins/builtin/RenameTool.js +3 -3
  51. package/dist/scope/plugins/builtin/RmTool.js +3 -3
  52. package/dist/scope/plugins/builtin/SleepTool.js +6 -6
  53. package/dist/scope/plugins/builtin/SpawnTool.js +32 -49
  54. package/dist/scope/plugins/builtin/ViewImageTool.d.ts +6 -4
  55. package/dist/scope/plugins/builtin/ViewImageTool.js +50 -62
  56. package/dist/scope/plugins/builtin/WriteTool.js +3 -3
  57. package/dist/scope/plugins/builtin/searchBase.d.ts +9 -0
  58. package/dist/scope/plugins/builtin/searchBase.js +17 -0
  59. package/dist/scope/plugins/builtin/test-helpers.d.ts +3 -3
  60. package/dist/scope/plugins/builtin/test-helpers.js +3 -3
  61. package/dist/scope/plugins/builtin/textEdit.d.ts +17 -0
  62. package/dist/scope/plugins/builtin/textEdit.js +37 -0
  63. package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +9 -1
  64. package/dist/scope/plugins/mcp/McpConnectionManager.js +95 -16
  65. package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +1 -1
  66. package/dist/scope/plugins/mcp/McpScopePlugin.js +8 -6
  67. package/dist/scope/plugins/mcp/discover.js +1 -1
  68. package/dist/scope/plugins/mcp/mcpTools.d.ts +9 -3
  69. package/dist/scope/plugins/mcp/mcpTools.js +247 -37
  70. package/dist/scope/plugins/skills/SkillsScopePlugin.js +2 -3
  71. package/dist/scope/plugins/skills/discover.js +28 -9
  72. package/dist/scope/plugins/skills/skillTools.js +30 -20
  73. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +1 -3
  74. package/dist/scope/plugins/subagents/subAgentTools.js +4 -3
  75. package/dist/scope/plugins/usertools/discover.d.ts +8 -3
  76. package/dist/scope/plugins/usertools/discover.js +139 -12
  77. package/dist/shared/EntityRepository.d.ts +10 -1
  78. package/dist/shared/EntityRepository.js +18 -6
  79. package/dist/shared/content-blocks.d.ts +101 -0
  80. package/dist/shared/content-blocks.js +253 -0
  81. package/dist/shared/errors.d.ts +4 -8
  82. package/dist/shared/errors.js +8 -14
  83. package/dist/types/index.d.ts +170 -8
  84. package/package.json +16 -7
  85. package/dist/runtime/TaskMigrationService.d.ts +0 -128
  86. package/dist/runtime/TaskMigrationService.js +0 -211
@@ -3,6 +3,13 @@ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
3
3
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
4
4
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
5
5
  import { getLogger } from "../../../shared/logger.js";
6
+ /**
7
+ * 建连超时缺省值(毫秒)。
8
+ *
9
+ * 没有上限时,配置错误的 SSE / HTTP 端点会让 `load_mcp` 永久挂起(SSE 在服务端不发
10
+ * 响应头时尤其如此,fetch 只对建链有兜底,对"连上了但永不回话"没有)。与请求超时同口径。
11
+ */
12
+ const DEFAULT_CONNECT_TIMEOUT_MS = 60_000;
6
13
  const DEFAULT_IDLE_TIMEOUT = {
7
14
  stdio: 30 * 60 * 1000,
8
15
  http: 5 * 60 * 1000,
@@ -56,9 +63,14 @@ export class McpConnectionManager {
56
63
  timeoutMs,
57
64
  cancelled: false,
58
65
  });
66
+ const connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
59
67
  try {
60
- await pendingPromise;
68
+ await this.withConnectTimeout(name, pendingPromise, connectTimeoutMs);
61
69
  const entry = this.servers.get(name);
70
+ // 建连期间被 disconnect()/dispose():不要复活连接
71
+ if (entry.cancelled || entry.state === "disconnected") {
72
+ throw new Error(`Connection to "${name}" was cancelled`);
73
+ }
62
74
  this.servers.set(name, {
63
75
  ...entry,
64
76
  state: "connected",
@@ -77,6 +89,30 @@ export class McpConnectionManager {
77
89
  throw err;
78
90
  }
79
91
  }
92
+ /** 给建连套上超时:超时即取消连接并清掉半成品状态 */
93
+ async withConnectTimeout(name, promise, timeoutMs) {
94
+ let timer;
95
+ const timeout = new Promise((_resolve, reject) => {
96
+ timer = setTimeout(() => {
97
+ reject(new Error(`MCP server "${name}" connection timed out after ${timeoutMs}ms (check the transport config: command/url/headers)`));
98
+ }, timeoutMs);
99
+ timer.unref?.();
100
+ });
101
+ try {
102
+ await Promise.race([promise, timeout]);
103
+ }
104
+ catch (err) {
105
+ if (String(err?.message ?? "").includes("timed out")) {
106
+ // 取消挂着的建连,并清掉它可能建好的资源
107
+ await this.disconnect(name).catch(() => { });
108
+ }
109
+ throw err;
110
+ }
111
+ finally {
112
+ if (timer)
113
+ clearTimeout(timer);
114
+ }
115
+ }
80
116
  async connectWithRetry(name, config, options, attempt) {
81
117
  try {
82
118
  await this.doConnect(name, config);
@@ -141,7 +177,7 @@ export class McpConnectionManager {
141
177
  }));
142
178
  }
143
179
  catch (err) {
144
- getLogger().error(`[McpConnectionManager] 获取 "${name}" 工具列表失败: ${err?.message ?? err}`);
180
+ getLogger().error(`[McpConnectionManager] Failed to list tools for "${name}": ${err?.message ?? err}`);
145
181
  }
146
182
  }
147
183
  if (serverCaps?.resources) {
@@ -155,7 +191,7 @@ export class McpConnectionManager {
155
191
  }));
156
192
  }
157
193
  catch (err) {
158
- getLogger().error(`[McpConnectionManager] 获取 "${name}" 资源列表失败: ${err?.message ?? err}`);
194
+ getLogger().error(`[McpConnectionManager] Failed to list resources for "${name}": ${err?.message ?? err}`);
159
195
  }
160
196
  }
161
197
  if (serverCaps?.prompts) {
@@ -167,10 +203,28 @@ export class McpConnectionManager {
167
203
  }));
168
204
  }
169
205
  catch (err) {
170
- getLogger().error(`[McpConnectionManager] 获取 "${name}" 提示列表失败: ${err?.message ?? err}`);
206
+ getLogger().error(`[McpConnectionManager] Failed to list prompts for "${name}": ${err?.message ?? err}`);
171
207
  }
172
208
  }
173
209
  const entry = this.servers.get(name) ?? { state: "connecting" };
210
+ // 建连期间被 disconnect()/dispose()(启动即退出是正常序列):关掉刚建好的资源,
211
+ // 绝不写回 connected,否则连接会"复活"、stdio 子进程也再没人关。
212
+ if (entry.cancelled) {
213
+ await this.closeQuietly(client, transport);
214
+ throw new Error(`Connection to "${name}" was cancelled`);
215
+ }
216
+ // 断线检测:运行期 transport 关掉时把状态标回 disconnected,避免 load_mcp / 状态栏
217
+ // 一直展示过期清单(不做自动重连:重连策略属于上层)。
218
+ const prevOnClose = transport.onclose;
219
+ transport.onclose = () => {
220
+ prevOnClose?.();
221
+ this.markDisconnected(name);
222
+ };
223
+ const prevOnError = transport.onerror;
224
+ transport.onerror = (error) => {
225
+ prevOnError?.(error);
226
+ getLogger().error(`[McpConnectionManager] Transport error for "${name}": ${error?.message ?? error}`);
227
+ };
174
228
  this.servers.set(name, {
175
229
  ...entry,
176
230
  state: "connected",
@@ -180,6 +234,26 @@ export class McpConnectionManager {
180
234
  cancelled: false,
181
235
  });
182
236
  }
237
+ /** 静默关闭连接资源(断开/取消路径共用) */
238
+ async closeQuietly(client, transport) {
239
+ try {
240
+ await client?.close();
241
+ }
242
+ catch { }
243
+ try {
244
+ await transport?.close();
245
+ }
246
+ catch { }
247
+ }
248
+ /** 运行期断线:标记 disconnected 并记日志(已在连接状态才处理,避免重复日志) */
249
+ markDisconnected(name) {
250
+ const entry = this.servers.get(name);
251
+ if (!entry || entry.state !== "connected")
252
+ return;
253
+ getLogger().error(`[McpConnectionManager] MCP server "${name}" disconnected`);
254
+ this.clearTimeout(name);
255
+ this.servers.set(name, { state: "disconnected" });
256
+ }
183
257
  /**
184
258
  * 根据配置创建对应的 Transport 实例。
185
259
  * 如果设置了自定义工厂(测试用),则使用自定义工厂。
@@ -190,7 +264,7 @@ export class McpConnectionManager {
190
264
  }
191
265
  if (config.transport === "stdio") {
192
266
  if (!config.command) {
193
- throw new Error(`MCP stdio server 缺少 command`);
267
+ throw new Error(`MCP stdio server is missing command`);
194
268
  }
195
269
  return new StdioClientTransport({
196
270
  command: config.command,
@@ -201,7 +275,7 @@ export class McpConnectionManager {
201
275
  // http 使用 Streamable HTTP 传输(POST + 可选 SSE 流)
202
276
  if (config.transport === "http") {
203
277
  if (!config.url) {
204
- throw new Error(`MCP http server 缺少 url`);
278
+ throw new Error(`MCP http server is missing url`);
205
279
  }
206
280
  return new StreamableHTTPClientTransport(new URL(config.url), {
207
281
  requestInit: config.headers ? { headers: config.headers } : undefined,
@@ -210,13 +284,13 @@ export class McpConnectionManager {
210
284
  // sse 使用旧版 HTTP+SSE 传输(GET 建立 SSE 流,POST 发送消息)
211
285
  if (config.transport === "sse") {
212
286
  if (!config.url) {
213
- throw new Error(`MCP sse server 缺少 url`);
287
+ throw new Error(`MCP sse server is missing url`);
214
288
  }
215
289
  return new SSEClientTransport(new URL(config.url), {
216
290
  requestInit: config.headers ? { headers: config.headers } : undefined,
217
291
  });
218
292
  }
219
- throw new Error(`不支持的 MCP transport 类型: ${config.transport}`);
293
+ throw new Error(`Unsupported MCP transport type: ${config.transport}`);
220
294
  }
221
295
  // ---- 断开 ----
222
296
  async disconnect(name) {
@@ -233,14 +307,19 @@ export class McpConnectionManager {
233
307
  entry.retryTimer = undefined;
234
308
  }
235
309
  this.clearTimeout(name);
236
- try {
237
- await entry.client?.close();
238
- await entry.transport?.close();
239
- }
240
- catch {
241
- // 断开失败也清理状态
242
- }
243
- this.servers.set(name, { state: "disconnected" });
310
+ // 断开失败也清理状态。注意保留 `cancelled`:建连中的 await 回来后要据此放弃写入。
311
+ await this.closeQuietly(entry.client, entry.transport);
312
+ this.servers.set(name, {
313
+ ...entry,
314
+ state: "disconnected",
315
+ client: undefined,
316
+ transport: undefined,
317
+ manifest: undefined,
318
+ pendingPromise: undefined,
319
+ timeoutTimer: undefined,
320
+ retryTimer: undefined,
321
+ cancelRetryWait: undefined,
322
+ });
244
323
  }
245
324
  async disconnectAll() {
246
325
  const names = Array.from(this.servers.keys());
@@ -24,6 +24,6 @@ export declare class McpScopePlugin implements ScopePlugin {
24
24
  /** 是否配置了 MCP(供外部代码判定,如 UnknownToolHintPlugin) */
25
25
  hasConfig(): boolean;
26
26
  candidates(): ScopeCandidates;
27
- instantiate(_scope: Scope, filtered: FilterOutput): Tool[];
27
+ instantiate(scope: Scope, filtered: FilterOutput): Tool[];
28
28
  dispose(): Promise<void>;
29
29
  }
@@ -1,6 +1,6 @@
1
1
  import { isAbsolute, join } from "node:path";
2
2
  import { discoverMcpServers } from "./discover.js";
3
- import { createCallMcpTool, createLoadMcpTool, createReadMcpResourceTool, } from "./mcpTools.js";
3
+ import { createCallMcpTool, createLoadMcpTool, createReadMcpResourceTool } from "./mcpTools.js";
4
4
  import { McpConnectionManager } from "./McpConnectionManager.js";
5
5
  /**
6
6
  * MCP 插件 —— 发现 mcp.json + 自持连接管理器 + 装配渐进式披露元工具。
@@ -20,8 +20,7 @@ export class McpScopePlugin {
20
20
  servers = [];
21
21
  constructor(options) {
22
22
  this.paths = options?.paths ?? [];
23
- this.mcpManager =
24
- this.paths.length > 0 ? new McpConnectionManager() : undefined;
23
+ this.mcpManager = this.paths.length > 0 ? new McpConnectionManager() : undefined;
25
24
  }
26
25
  async discover(scope) {
27
26
  const files = this.paths.map((p) => (isAbsolute(p) ? p : join(scope.cwd, p)));
@@ -37,20 +36,23 @@ export class McpScopePlugin {
37
36
  tools: ["load_mcp", "call_mcp_tool", "read_mcp_resource"],
38
37
  };
39
38
  }
40
- instantiate(_scope, filtered) {
39
+ instantiate(scope, filtered) {
41
40
  const allow = new Set(filtered.tools);
42
41
  const allowedMcps = new Set(filtered.mcps);
43
42
  const filteredMcps = this.servers.filter((s) => allowedMcps.has(s.id));
43
+ const mcps = filteredMcps.map((s) => s.id);
44
44
  const m = this.mcpManager;
45
45
  const result = [];
46
46
  if (allow.has("load_mcp") && m && filteredMcps.length > 0) {
47
47
  result.push(createLoadMcpTool(m, filteredMcps));
48
48
  }
49
49
  if (allow.has("call_mcp_tool") && m) {
50
- result.push(createCallMcpTool(m));
50
+ // env 供 call_mcp_tool 读取 maxToolOutput,与内置工具共用同一上限口径;
51
+ // filteredMcps 是权限白名单(连接管理器全局共享,必须按 Scope 过滤)
52
+ result.push(createCallMcpTool(m, scope.env, mcps));
51
53
  }
52
54
  if (allow.has("read_mcp_resource") && m) {
53
- result.push(createReadMcpResourceTool(m));
55
+ result.push(createReadMcpResourceTool(m, scope.env, mcps));
54
56
  }
55
57
  return result;
56
58
  }
@@ -82,7 +82,7 @@ export async function discoverMcpServers(paths) {
82
82
  }
83
83
  }
84
84
  catch (err) {
85
- getLogger().warn(`[sdk] 解析 MCP 配置失败: ${path} — ${err?.message ?? err}`);
85
+ getLogger().warn(`[sdk] Failed to parse MCP config: ${path} — ${err?.message ?? err}`);
86
86
  }
87
87
  }
88
88
  return items;
@@ -1,6 +1,6 @@
1
1
  import { CallbackTool } from "@ai-zen/agents-core";
2
2
  import type { McpConnectionManager } from "./McpConnectionManager.js";
3
- import type { McpServerConfig } from "../../../types/index.js";
3
+ import type { McpServerConfig, ToolEnv } from "../../../types/index.js";
4
4
  /**
5
5
  * 创建 load_mcp 工具。
6
6
  * server 枚举由 filteredMcps (完整 McpServerConfig[])自动推导,
@@ -10,9 +10,15 @@ export declare function createLoadMcpTool(mcpManager: McpConnectionManager, filt
10
10
  /**
11
11
  * 创建 call_mcp_tool 工具。
12
12
  * 通过官方 Client.callTool() API 调用 MCP 服务器上的工具。
13
+ *
14
+ * 返回形态:
15
+ * - 仅文本 → 纯字符串(与历史行为一致);
16
+ * - 含媒体 → 内容块数组:首块为受保护的文本,其后原样透传 image / file 块。
17
+ *
18
+ * env 仅用于读取 maxToolOutput(文本输出保护上限),与内置工具口径一致。
13
19
  */
14
- export declare function createCallMcpTool(mcpManager: McpConnectionManager): CallbackTool;
20
+ export declare function createCallMcpTool(mcpManager: McpConnectionManager, env: ToolEnv, filteredMcps: string[]): CallbackTool;
15
21
  /**
16
22
  * 创建 read_mcp_resource 工具。
17
23
  */
18
- export declare function createReadMcpResourceTool(mcpManager: McpConnectionManager): CallbackTool;
24
+ export declare function createReadMcpResourceTool(mcpManager: McpConnectionManager, env: ToolEnv, filteredMcps: string[]): CallbackTool;