@ai-zen/agents-sdk 1.0.0-alpha.9 → 1.1.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 +691 -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 +26 -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 +288 -0
  25. package/dist/runtime/HandoffService.js +538 -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,17 +3,17 @@ import { SdkCallbackTool } from "./SdkCallbackTool.js";
3
3
  export class MkdirTool extends SdkCallbackTool {
4
4
  function = {
5
5
  name: "mkdir",
6
- description: "创建目录",
6
+ description: "Create a directory",
7
7
  parameters: {
8
8
  type: "object",
9
9
  properties: {
10
10
  path: {
11
11
  type: "string",
12
- description: "目录路径",
12
+ description: "Directory path",
13
13
  },
14
14
  recursive: {
15
15
  type: "boolean",
16
- description: "是否递归创建子目录",
16
+ description: "Whether to create parent directories recursively",
17
17
  },
18
18
  },
19
19
  required: ["path"],
@@ -4,18 +4,18 @@ import { DEFAULT_MAX_TOOL_OUTPUT, guardOutput } from "./outputGuard.js";
4
4
  export class ReadTool extends SdkCallbackTool {
5
5
  function = {
6
6
  name: "read",
7
- description: "读取文件",
7
+ description: "Read a file",
8
8
  parameters: {
9
9
  type: "object",
10
10
  properties: {
11
11
  path: {
12
12
  type: "string",
13
- description: "文件路径",
13
+ description: "File path",
14
14
  },
15
15
  range: {
16
16
  type: "array",
17
- description: "读取范围 [起始行, 起始列, 结束行, 结束列],行列均从 0 开始,-1 表示末位;" +
18
- "例如 [0, 0, 100, -1] 表示从第 0 行第 0 列读到第 100 行最后一列。省略则读取整个文件。",
17
+ description: "Read range [startLine, startCol, endLine, endCol]; rows and columns are 0-based, -1 means the last position. " +
18
+ "For example, [0, 0, 100, -1] reads from line 0, column 0 through the last column of line 100; omit it to read the whole file.",
19
19
  items: {
20
20
  type: "number",
21
21
  },
@@ -34,7 +34,7 @@ export class ReadTool extends SdkCallbackTool {
34
34
  const stats = await fsp.stat(filePath);
35
35
  // 读取阈值:文件过大时拒绝读取(与输出阈值 maxToolOutput 无关)
36
36
  if (stats.size > 300 * 1024) {
37
- throw new Error(`文件过大,无法读取,当前文件大小 ${stats.size} 字节`);
37
+ throw new Error(`File too large to read: ${stats.size} bytes`);
38
38
  }
39
39
  const content = await fsp.readFile(filePath, "utf-8");
40
40
  const output = input.range ? sliceByRange(content, input.range) : content;
@@ -44,9 +44,9 @@ export class ReadTool extends SdkCallbackTool {
44
44
  tool: "read",
45
45
  content: output,
46
46
  isOverLimit: (text) => text.length > limit,
47
- buildWarning: () => `读取内容过大:本次输出 ${output.length} 字符,超过上限 ${limit} 字符,未落盘。` +
48
- `文件共 ${countLines(content)} 行、${content.length} 字符,` +
49
- `请用 range 参数分范围读取(形如 [起始行, 起始列, 结束行, 结束列],行列从 0 开始,-1 表示末位)。`,
47
+ buildWarning: () => `Output too large: this read returned ${output.length} characters, exceeding the limit of ${limit} characters; not written to disk. ` +
48
+ `The file has ${countLines(content)} lines and ${content.length} characters. ` +
49
+ `Use the range parameter to read it in chunks (format [startLine, startCol, endLine, endCol], 0-based, -1 means the last position).`,
50
50
  });
51
51
  }
52
52
  catch (error) {
@@ -3,17 +3,17 @@ import { SdkCallbackTool } from "./SdkCallbackTool.js";
3
3
  export class RenameTool extends SdkCallbackTool {
4
4
  function = {
5
5
  name: "rename",
6
- description: "重命名或移动文件/目录(相当于 mv 命令)",
6
+ description: "Rename or move a file/directory (equivalent to the mv command)",
7
7
  parameters: {
8
8
  type: "object",
9
9
  properties: {
10
10
  oldPath: {
11
11
  type: "string",
12
- description: "原路径",
12
+ description: "Original path",
13
13
  },
14
14
  newPath: {
15
15
  type: "string",
16
- description: "新路径",
16
+ description: "New path",
17
17
  },
18
18
  },
19
19
  required: ["oldPath", "newPath"],
@@ -3,17 +3,17 @@ import { SdkCallbackTool } from "./SdkCallbackTool.js";
3
3
  export class RmTool extends SdkCallbackTool {
4
4
  function = {
5
5
  name: "rm",
6
- description: "删除文件或目录",
6
+ description: "Delete a file or directory",
7
7
  parameters: {
8
8
  type: "object",
9
9
  properties: {
10
10
  path: {
11
11
  type: "string",
12
- description: "文件或目录路径",
12
+ description: "File or directory path",
13
13
  },
14
14
  recursive: {
15
15
  type: "boolean",
16
- description: "是否递归删除子目录",
16
+ description: "Whether to delete subdirectories recursively",
17
17
  },
18
18
  },
19
19
  required: ["path"],
@@ -2,13 +2,13 @@ import { SdkCallbackTool } from "./SdkCallbackTool.js";
2
2
  export class SleepTool extends SdkCallbackTool {
3
3
  function = {
4
4
  name: "sleep",
5
- description: "等待指定的时间(毫秒)。用于需要延迟执行的场景,例如等待其他操作完成、操作间隔控制等。注意:过长的等待时间会影响响应速度,建议不超过 30000 毫秒(30 秒)。",
5
+ description: "Wait for the specified time in milliseconds. Use it when a delay is needed, for example to wait for another operation to finish or to space out actions. Note: long waits slow down responses; keep it at or below 30000 milliseconds (30 seconds).",
6
6
  parameters: {
7
7
  type: "object",
8
8
  properties: {
9
9
  ms: {
10
10
  type: "number",
11
- description: "等待的毫秒数(1 秒 = 1000 毫秒)。建议不超过 30000(30 秒)。",
11
+ description: "Milliseconds to wait (1 second = 1000 milliseconds). Values above 30000 (30 seconds) are not recommended.",
12
12
  },
13
13
  },
14
14
  required: ["ms"],
@@ -23,14 +23,14 @@ export class SleepTool extends SdkCallbackTool {
23
23
  if (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0) {
24
24
  return JSON.stringify({
25
25
  success: false,
26
- error: "ms 必须是正整数",
26
+ error: "ms must be a positive integer",
27
27
  });
28
28
  }
29
29
  if (ms > 300_000) {
30
30
  // 超过 5 分钟给出警告
31
31
  return JSON.stringify({
32
32
  success: false,
33
- error: `等待时间 ${ms}ms 过长,建议不超过 300000ms(5 分钟)。如需长时间等待请分段执行。`,
33
+ error: `Wait time ${ms}ms is too long, keep it at or below 300000ms (5 minutes). For longer waits, split them into shorter steps`,
34
34
  });
35
35
  }
36
36
  // 若 signal 已处于 aborted,直接返回中断结果,避免不必要的等待
@@ -53,14 +53,14 @@ export class SleepTool extends SdkCallbackTool {
53
53
  return JSON.stringify({
54
54
  success: false,
55
55
  aborted: true,
56
- error: "等待被中断(aborted)",
56
+ error: "Wait aborted",
57
57
  });
58
58
  }
59
59
  return JSON.stringify({
60
60
  success: true,
61
61
  waitedMs: ms,
62
62
  waitedSeconds: (ms / 1000).toFixed(1),
63
- message: `已等待 ${ms}ms(${(ms / 1000).toFixed(1)} 秒)`,
63
+ message: `Waited ${ms}ms (${(ms / 1000).toFixed(1)} seconds)`,
64
64
  });
65
65
  }
66
66
  }
@@ -3,21 +3,21 @@ import { SdkCallbackTool } from "./SdkCallbackTool.js";
3
3
  export class SpawnTool extends SdkCallbackTool {
4
4
  function = {
5
5
  name: "spawn",
6
- description: "异步执行命令,启动程序后立即返回,不等待执行结果。适用于启动长期运行的进程(如服务器、监听程序、GUI应用等)或不需要等待结果的命令。注意:该工具本身不捕获命令的输出;若需获取/留存输出,可在命令中使用 shell 重定向写入文件(如 `> /path/file`,支持 `>>` 追加、`|` 管道)。命令经 shell 解析执行。",
6
+ description: "Spawn a command asynchronously and return immediately without waiting for the result. Use it for long-running processes (servers, watchers, GUI apps, etc.) or commands whose result you do not need to wait for. Note: this tool does not capture the command's output itself; to retain or inspect output, use shell redirection to a file inside the command (e.g. `> /path/file`; `>>` append and `|` pipes are supported). The command is parsed and executed by the shell.",
7
7
  parameters: {
8
8
  type: "object",
9
9
  properties: {
10
10
  command: {
11
11
  type: "string",
12
- description: "要执行的命令(含参数)",
12
+ description: "Command to execute (including arguments)",
13
13
  },
14
14
  cwd: {
15
15
  type: "string",
16
- description: "工作目录(可选,默认当前工作目录)",
16
+ description: "Working directory (optional, defaults to the current working directory)",
17
17
  },
18
18
  detached: {
19
19
  type: "boolean",
20
- description: "是否完全脱离当前进程组(可选,默认 false)。设为 true 时,即使当前 Agent 进程退出,启动的程序仍会继续运行。适用于需要独立运行的守护进程或 GUI 程序。",
20
+ description: "Whether to fully detach from the current process group (optional, defaults to false). When true, the spawned program keeps running even after the current Agent process exits. Use it for daemons or GUI programs that must run independently.",
21
21
  },
22
22
  },
23
23
  required: ["command"],
@@ -31,7 +31,13 @@ export class SpawnTool extends SdkCallbackTool {
31
31
  const command = input.command;
32
32
  const cwd = input.cwd ? this.resolve(input.cwd) : this.env.cwd;
33
33
  const detached = input.detached ?? false;
34
- // 统一走 shell:允许 shell 语法(重定向 > / >>、管道 | 等)
34
+ /**
35
+ * 本工具只回答「进程是否已启动」,**不跟踪退出状态**。
36
+ *
37
+ * 它 spawn 后立刻返回,输出也走 `stdio: "ignore"` 丢弃;因此命令不存在、语法错误、
38
+ * 脚本起来就崩这类「早退失败」在这里一律看不见 —— 以前会把它们报成 `success: true`,
39
+ * 现在如实命名为 `started`,并在 note 里说清。需要成败/输出/退出码请用 exec。
40
+ */
35
41
  return new Promise((resolve) => {
36
42
  const child = spawn(command, [], {
37
43
  cwd,
@@ -41,57 +47,34 @@ export class SpawnTool extends SdkCallbackTool {
41
47
  windowsHide: true,
42
48
  });
43
49
  let resolved = false;
44
- child.on("error", (err) => {
50
+ let timer;
51
+ const done = (payload) => {
45
52
  if (resolved)
46
53
  return;
47
54
  resolved = true;
48
- resolve(JSON.stringify({
49
- success: false,
50
- pid: null,
51
- message: `启动失败: ${err.message}`,
52
- }));
55
+ if (timer)
56
+ clearTimeout(timer);
57
+ resolve(JSON.stringify(payload));
58
+ };
59
+ const startedPayload = () => ({
60
+ started: true,
61
+ pid: child.pid ?? null,
62
+ message: `Process started (PID: ${child.pid ?? "unknown"})`,
63
+ note: "This tool only reports that the process was started; it does not track the exit status. Use exec if you need the exit code or the output.",
53
64
  });
54
- child.on("spawn", () => {
55
- if (resolved)
56
- return;
57
- resolved = true;
58
- resolve(JSON.stringify({
59
- success: true,
60
- pid: child.pid ?? null,
61
- message: `进程已启动 (PID: ${child.pid ?? "unknown"})`,
62
- }));
65
+ child.on("error", (err) => {
66
+ done({ started: false, pid: null, message: `Failed to start: ${err.message}` });
63
67
  });
64
- child.on("exit", (code) => {
65
- if (resolved)
66
- return;
67
- resolved = true;
68
- resolve(JSON.stringify({
69
- success: code === 0,
70
- pid: child.pid ?? null,
71
- exitCode: code,
72
- message: code === null
73
- ? `进程已退出 (PID: ${child.pid ?? "unknown"})`
74
- : `进程已退出 (PID: ${child.pid ?? "unknown"}, 退出码: ${code})`,
75
- }));
68
+ child.on("spawn", () => {
69
+ child.unref();
70
+ done(startedPayload());
76
71
  });
77
- const timeout = setTimeout(() => {
78
- if (resolved)
79
- return;
80
- resolved = true;
81
- resolve(JSON.stringify({
82
- success: true,
83
- pid: child.pid ?? null,
84
- message: `进程已启动 (PID: ${child.pid ?? "unknown"})`,
85
- }));
72
+ // 兜底:`spawn` 事件理论上必然触发,这里保证工具不会挂住
73
+ timer = setTimeout(() => {
74
+ child.unref();
75
+ done(startedPayload());
86
76
  }, 500);
87
- const cleanup = () => {
88
- clearTimeout(timeout);
89
- child.removeAllListeners();
90
- };
91
- child.on("spawn", cleanup);
92
- child.on("error", cleanup);
93
- child.on("exit", cleanup);
94
- child.unref();
77
+ timer.unref?.();
95
78
  });
96
79
  }
97
80
  }
@@ -7,11 +7,13 @@ import type { AgentDefinition, AppConfig, ToolEnv } from "../../../types/index.j
7
7
  * buildTools 阶段按声明过滤——非视觉模型不会拿到该工具,故无需运行时重复校验。
8
8
  *
9
9
  * 输入 `path_or_url`:
10
- * - http(s) URL → 直接以 `image_url` 内容块返回,模型直接查看;
11
- * - 本地路径 → 自动通过 Files API(DeepSeek)上传,以 `file` 内容块(file_id)返回。
10
+ * - http(s) URL → 直接以 `image_url` 内容块返回;
11
+ * - 本地路径 → 交给 `fileToContentSection()` 统一处理:
12
+ * 端点声明 `capabilities.filesApi`(出厂仅 deepseek)→ Files API 上传,`file` 块(file_id);
13
+ * 其余端点 → base64 data URL 内联(`image_url`),不再要求必须配置 deepseek。
12
14
  *
13
- * 不使用 base64 内联(本地图片走 Files API,符合 DeepSeek 推荐与 48 MiB 请求体限制)。
14
- * 依赖配置中的 deepseek 端点(Files API 能力);URL 场景不依赖上传。
15
+ * 端点按**当前模型**反查(`ctx.agent.model`),不硬编码端点 id——`file_id` 是端点维度
16
+ * 资源,传错端点会返回 not found。
15
17
  */
16
18
  export declare class ViewImageTool extends SdkCallbackTool {
17
19
  /** 仅视觉模型可用:从 definition.modelId 解析当前模型,非视觉模型由 buildTools 过滤 */
@@ -1,8 +1,7 @@
1
- import OpenAI, { toFile } from "openai";
2
- import { promises as fs } from "node:fs";
3
1
  import path from "node:path";
2
+ import { promises as fs } from "node:fs";
4
3
  import { SdkCallbackTool } from "./SdkCallbackTool.js";
5
- const SUPPORTED_EXT = [".jpg", ".jpeg", ".png", ".gif", ".webp"];
4
+ import { fileToContentSection, mimeOf, resolveModelAndEndpoint, } from "../../../shared/content-blocks.js";
6
5
  /**
7
6
  * 是否为"本地 URL"——指向本地/回环地址,API 服务商无法下载访问。
8
7
  * 覆盖 file:// 等本地协议,以及指向本机的 http(s) 地址(localhost、127.0.0.1、[::1]、0.0.0.0)。
@@ -19,28 +18,30 @@ function isLocalUrl(value) {
19
18
  * buildTools 阶段按声明过滤——非视觉模型不会拿到该工具,故无需运行时重复校验。
20
19
  *
21
20
  * 输入 `path_or_url`:
22
- * - http(s) URL → 直接以 `image_url` 内容块返回,模型直接查看;
23
- * - 本地路径 → 自动通过 Files API(DeepSeek)上传,以 `file` 内容块(file_id)返回。
21
+ * - http(s) URL → 直接以 `image_url` 内容块返回;
22
+ * - 本地路径 → 交给 `fileToContentSection()` 统一处理:
23
+ * 端点声明 `capabilities.filesApi`(出厂仅 deepseek)→ Files API 上传,`file` 块(file_id);
24
+ * 其余端点 → base64 data URL 内联(`image_url`),不再要求必须配置 deepseek。
24
25
  *
25
- * 不使用 base64 内联(本地图片走 Files API,符合 DeepSeek 推荐与 48 MiB 请求体限制)。
26
- * 依赖配置中的 deepseek 端点(Files API 能力);URL 场景不依赖上传。
26
+ * 端点按**当前模型**反查(`ctx.agent.model`),不硬编码端点 id——`file_id` 是端点维度
27
+ * 资源,传错端点会返回 not found。
27
28
  */
28
29
  export class ViewImageTool extends SdkCallbackTool {
29
30
  /** 仅视觉模型可用:从 definition.modelId 解析当前模型,非视觉模型由 buildTools 过滤 */
30
31
  isAvailable(config, definition) {
31
- const modelId = definition.modelId ?? config.defaultModel;
32
+ const modelId = definition.modelId;
32
33
  const model = (config.models ?? []).find((m) => m.id === modelId);
33
34
  return model?.vision === true;
34
35
  }
35
36
  function = {
36
37
  name: "view_image",
37
- description: "查看一张图片并分析其内容。传入本地图片路径或 http(s) 图片 URL。本地图片会自动上传(Files API)后引用,网络图片直接引用。不支持本地 URL(如 file:// 协议、指向本机 localhost/127.0.0.1 的 http(s) 地址),本地图片请使用文件路径。适合识别图片文字、描述图片内容、分析图表等。",
38
+ description: "View an image and analyze its content. Pass a local image path or an http(s) image URL. Local images are uploaded when the endpoint supports the Files API and are otherwise referenced as inline base64; remote images are referenced directly. Local URLs are not supported (such as the file:// protocol, or http(s) addresses pointing to localhost/127.0.0.1 on this machine); use a file path for local images. Suitable for reading text in images, describing image content and analyzing charts.",
38
39
  parameters: {
39
40
  type: "object",
40
41
  properties: {
41
42
  path_or_url: {
42
43
  type: "string",
43
- description: "本地图片路径(相对/绝对)或 http(s) 图片 URL。支持的格式:JPEG、PNG、GIF、WebP。不支持本地 URL(如 file:// 协议、指向本机 localhost/127.0.0.1 的 http(s) 地址),本地图片请使用文件路径。",
44
+ description: "Local image path (relative or absolute) or an http(s) image URL. Supported formats: JPEG, PNG, GIF, WebP. Local URLs are not supported (such as the file:// protocol, or http(s) addresses pointing to localhost/127.0.0.1 on this machine); use a file path for local images.",
44
45
  },
45
46
  },
46
47
  required: ["path_or_url"],
@@ -54,70 +55,57 @@ export class ViewImageTool extends SdkCallbackTool {
54
55
  const signal = ctx?.signal;
55
56
  const target = input?.path_or_url;
56
57
  if (!target || !target.trim()) {
57
- return "view_image 需要提供 path_or_url 参数(本地图片路径或 http(s) URL)。";
58
+ return "view_image requires the path_or_url parameter (a local image path or an http(s) URL)";
58
59
  }
59
60
  const value = target.trim();
60
- // 拒绝服务商无法访问的"本地 URL":file:// 等本地协议,或指向本机回环地址(localhost/127.0.0.1/[::1]/0.0.0.0)的 http(s) 地址
61
+ // 拒绝服务商无法访问的"本地 URL":file:// 等本地协议,或指向本机回环地址的 http(s) 地址
61
62
  if (isLocalUrl(value)) {
62
- return "不支持本地 URL(API 服务商无法下载访问)。本地图片请使用文件路径,而不是本地链接。";
63
+ return "Local URLs are not supported (the API provider cannot download them). Use a file path for local images, not a local link";
63
64
  }
65
+ // 按当前模型定位端点:决定走 Files API 上传还是 base64 内联
66
+ const { model, endpoint } = resolveModelAndEndpoint(this.env.config, ctx?.agent?.model);
64
67
  try {
65
- // 网络图片:直接返回 image_url 内容块(无需上传)
66
- if (/^https?:\/\//i.test(value)) {
67
- return [
68
- {
69
- type: "text",
70
- text: `已获取网络图片:${value}`,
71
- },
72
- { type: "image_url", image_url: { url: value } },
73
- ];
74
- }
75
- // 本地图片:解析路径 + 校验 + Files API 上传
76
- const absPath = path.isAbsolute(value)
77
- ? value
78
- : path.join(this.env.cwd, value);
79
- let stat;
80
- try {
81
- stat = await fs.stat(absPath);
82
- }
83
- catch {
84
- return `本地图片不存在: ${absPath}`;
85
- }
86
- if (!stat.isFile()) {
87
- return `"${absPath}" 不是文件。`;
68
+ const isUrl = /^https?:\/\//i.test(value);
69
+ // 本工具只处理图片:先按扩展名把关,给出比通用入口更贴切的提示
70
+ if (!isUrl) {
71
+ const abs = this.resolve(value);
72
+ // 先 stat 一次,把 ENOENT 变成对人友好的提示(通用入口的报错面向任意文件)
73
+ try {
74
+ await fs.stat(abs);
75
+ }
76
+ catch {
77
+ return `Local image not found: ${abs}`;
78
+ }
79
+ const mime = mimeOf(abs);
80
+ if (!mime || !mime.startsWith("image/")) {
81
+ return `Unsupported image format "${path.extname(abs) || "(no extension)"}". Supported formats: JPEG, PNG, GIF, WebP`;
82
+ }
88
83
  }
89
- const ext = path.extname(absPath).toLowerCase();
90
- if (!SUPPORTED_EXT.includes(ext)) {
91
- return `不支持的图片格式 "${ext || "(无扩展名)"}"。支持的格式:JPEG、PNG、GIF、WebP。`;
92
- }
93
- // 上传端点:deepseek(Files API 能力)
94
- const endpoint = (this.env.config.endpoints ?? []).find((e) => e.id === "deepseek");
95
- if (!endpoint) {
96
- return "未配置 deepseek 端点,无法上传本地图片(Files API)。如需查看本地图片,请先配置 deepseek 端点;网络图片 URL 可直接使用。";
97
- }
98
- if (!endpoint.apiKey) {
99
- return `端点 "${endpoint.name}" 的 API Key 未设置,无法上传本地图片。`;
100
- }
101
- const client = new OpenAI({
102
- apiKey: endpoint.apiKey,
103
- baseURL: endpoint.baseUrl,
84
+ const result = await fileToContentSection({
85
+ source: isUrl ? { url: value } : { path: this.resolve(value) },
86
+ endpoint,
87
+ model,
88
+ signal,
89
+ // 出网动作走注入的 deps(缺省时 content-blocks 自己调 OpenAI SDK)
90
+ deps: this.env.deps,
104
91
  });
105
- const file = await toFile(await fs.readFile(absPath), path.basename(absPath));
106
- const uploaded = await client.files.create({ file, purpose: "user_data" }, { signal });
107
- return [
108
- {
109
- type: "text",
110
- text: `图片已上传(${path.basename(absPath)}),file_id: ${uploaded.id}`,
111
- },
112
- { type: "file", file_id: uploaded.id },
113
- ];
92
+ const label = isUrl
93
+ ? `Fetched remote image: ${value}`
94
+ : `Fetched local image (${path.basename(value)})`;
95
+ const how = result.transport === "files-api"
96
+ ? `, uploaded to the Files API (file_id: ${result.section.file_id ?? "?"})`
97
+ : result.transport === "inline"
98
+ ? `, inlined as base64 (${(result.bytes / 1024).toFixed(0)} KB)`
99
+ : "";
100
+ const extra = result.warning ? ` (fallback: ${result.warning})` : "";
101
+ return [{ type: "text", text: `${label}${how}${extra}` }, result.section];
114
102
  }
115
103
  catch (error) {
116
104
  // 中断(abort)时返回明确的中断结果
117
105
  if (signal?.aborted) {
118
- return "图片查看被中断(aborted)";
106
+ return "Image view aborted";
119
107
  }
120
- return `查看图片失败: ${error instanceof Error ? error.message : String(error)}`;
108
+ return `Failed to view image: ${error instanceof Error ? error.message : String(error)}`;
121
109
  }
122
110
  }
123
111
  }
@@ -4,17 +4,17 @@ import { SdkCallbackTool } from "./SdkCallbackTool.js";
4
4
  export class WriteTool extends SdkCallbackTool {
5
5
  function = {
6
6
  name: "write",
7
- description: "写入文件",
7
+ description: "Write a file",
8
8
  parameters: {
9
9
  type: "object",
10
10
  properties: {
11
11
  path: {
12
12
  type: "string",
13
- description: "文件路径",
13
+ description: "File path",
14
14
  },
15
15
  content: {
16
16
  type: "string",
17
- description: "文件内容",
17
+ description: "File content",
18
18
  },
19
19
  },
20
20
  required: ["path", "content"],
@@ -0,0 +1,9 @@
1
+ /**
2
+ * 校验遍历/搜索的基目录。
3
+ *
4
+ * 没有这层校验时,`fsp.glob()` 对不存在的目录只会安静地返回空结果,模型会据此得出
5
+ * 「这些文件不存在」的错误结论(`ls` 在同场景下是抛 `ENOENT` 的)。
6
+ *
7
+ * 返回错误文本;目录正常时返回 `null`。
8
+ */
9
+ export declare function checkBaseDirectory(dir: string): Promise<string | null>;
@@ -0,0 +1,17 @@
1
+ import * as fsp from "fs/promises";
2
+ /**
3
+ * 校验遍历/搜索的基目录。
4
+ *
5
+ * 没有这层校验时,`fsp.glob()` 对不存在的目录只会安静地返回空结果,模型会据此得出
6
+ * 「这些文件不存在」的错误结论(`ls` 在同场景下是抛 `ENOENT` 的)。
7
+ *
8
+ * 返回错误文本;目录正常时返回 `null`。
9
+ */
10
+ export async function checkBaseDirectory(dir) {
11
+ const stat = await fsp.stat(dir).catch(() => null);
12
+ if (!stat)
13
+ return `Path does not exist: ${dir}`;
14
+ if (!stat.isDirectory())
15
+ return `Not a directory: ${dir}`;
16
+ return null;
17
+ }
@@ -1,3 +1,3 @@
1
- import type { AppConfig, ToolEnv } from "../../../types/index.js";
2
- /** 构造测试用 ToolEnv */
3
- export declare function makeEnv(cwd?: string, config?: AppConfig): ToolEnv;
1
+ import type { AppConfig, ToolEnv, ToolEnvDeps } from "../../../types/index.js";
2
+ /** 构造测试用 ToolEnv(deps 用于注入出网依赖,避免 mock openai 模块) */
3
+ export declare function makeEnv(cwd?: string, config?: AppConfig, deps?: ToolEnvDeps): ToolEnv;
@@ -1,4 +1,4 @@
1
- /** 构造测试用 ToolEnv */
2
- export function makeEnv(cwd = process.cwd(), config = {}) {
3
- return { cwd, config };
1
+ /** 构造测试用 ToolEnv(deps 用于注入出网依赖,避免 mock openai 模块) */
2
+ export function makeEnv(cwd = process.cwd(), config = {}, deps) {
3
+ return deps ? { cwd, config, deps } : { cwd, config };
4
4
  }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * 文本替换的公共实现(`edit` / `batch_edit` 共用)。
3
+ */
4
+ /** 统计 `text` 在 `content` 中非重叠的出现次数(`text` 为空时返回 0) */
5
+ export declare function countOccurrences(content: string, text: string): number;
6
+ /**
7
+ * 执行一次替换,返回新内容与**实际替换次数**。
8
+ *
9
+ * 必须用回调式 replacer:字符串形式的替换值里,`$&`、`` $` ``、`$'`、`$$` 会被
10
+ * `String.replace` 当作替换模式展开(写入的不再是字面量),而回调的返回值一律按字面量处理。
11
+ *
12
+ * `oldText` 为空时不做替换(空串会匹配每一个位置):替换次数恒为 0,由调用方给出提示。
13
+ */
14
+ export declare function replaceText(content: string, oldText: string, newText: string, isReplaceAll: boolean): {
15
+ content: string;
16
+ replacedCount: number;
17
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * 文本替换的公共实现(`edit` / `batch_edit` 共用)。
3
+ */
4
+ /** 统计 `text` 在 `content` 中非重叠的出现次数(`text` 为空时返回 0) */
5
+ export function countOccurrences(content, text) {
6
+ if (text === "")
7
+ return 0;
8
+ let count = 0;
9
+ let pos = 0;
10
+ while (true) {
11
+ pos = content.indexOf(text, pos);
12
+ if (pos === -1)
13
+ break;
14
+ count++;
15
+ pos += text.length;
16
+ }
17
+ return count;
18
+ }
19
+ /**
20
+ * 执行一次替换,返回新内容与**实际替换次数**。
21
+ *
22
+ * 必须用回调式 replacer:字符串形式的替换值里,`$&`、`` $` ``、`$'`、`$$` 会被
23
+ * `String.replace` 当作替换模式展开(写入的不再是字面量),而回调的返回值一律按字面量处理。
24
+ *
25
+ * `oldText` 为空时不做替换(空串会匹配每一个位置):替换次数恒为 0,由调用方给出提示。
26
+ */
27
+ export function replaceText(content, oldText, newText, isReplaceAll) {
28
+ const matches = countOccurrences(content, oldText);
29
+ if (matches === 0)
30
+ return { content, replacedCount: 0 };
31
+ return {
32
+ content: isReplaceAll
33
+ ? content.replaceAll(oldText, () => newText)
34
+ : content.replace(oldText, () => newText),
35
+ replacedCount: isReplaceAll ? matches : 1,
36
+ };
37
+ }
@@ -2,8 +2,10 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
2
  import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
3
3
  import type { McpServerConfig, McpServerManifest, McpConnectionState } from "../../../types/index.js";
4
4
  export interface McpConnectOptions {
5
- /** 空闲超时(毫秒),默认 stdio: 30min, http: 5min */
5
+ /** 空闲超时(毫秒),默认 stdio: 30min, http/sse: 5min */
6
6
  idleTimeoutMs?: number;
7
+ /** 建连超时(毫秒),默认 60s;超时即断开并抛错,避免工具永久挂起 */
8
+ connectTimeoutMs?: number;
7
9
  /** 失败时自动重连 */
8
10
  autoReconnect?: boolean;
9
11
  /** 最大重试次数,默认 3 */
@@ -26,8 +28,14 @@ export declare class McpConnectionManager {
26
28
  getManifest(name: string): McpServerManifest | undefined;
27
29
  getClient(name: string): Client | undefined;
28
30
  connect(name: string, config: McpServerConfig, options?: McpConnectOptions): Promise<McpServerManifest>;
31
+ /** 给建连套上超时:超时即取消连接并清掉半成品状态 */
32
+ private withConnectTimeout;
29
33
  private connectWithRetry;
30
34
  private doConnect;
35
+ /** 静默关闭连接资源(断开/取消路径共用) */
36
+ private closeQuietly;
37
+ /** 运行期断线:标记 disconnected 并记日志(已在连接状态才处理,避免重复日志) */
38
+ private markDisconnected;
31
39
  /**
32
40
  * 根据配置创建对应的 Transport 实例。
33
41
  * 如果设置了自定义工厂(测试用),则使用自定义工厂。