@ai-zen/agents-sdk 1.0.0-alpha.8 → 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 +661 -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
@@ -8,7 +8,7 @@ import { createModel } from "../../../runtime/createModel.js";
8
8
  */
9
9
  export function createSubAgentTool(def, scope) {
10
10
  if (!def.function) {
11
- throw new Error(`Agent "${def.id}" 没有 function 字段,不能作为 SubAgent 工具`);
11
+ throw new Error(`Agent "${def.id}" has no function field, so it cannot be used as a SubAgent tool`);
12
12
  }
13
13
  const selfName = def.function.name;
14
14
  const lazy = new AgentToolLazy({
@@ -24,7 +24,8 @@ export function createSubAgentTool(def, scope) {
24
24
  let model;
25
25
  let modelConfig;
26
26
  if (def.modelId) {
27
- const m = createModel(scope, def.modelId);
27
+ // SubAgent 可声明自己的模型与参数覆盖(与主 Agent 同一套规则:直接合并)
28
+ const m = createModel(scope, def.modelId, def.modelParams);
28
29
  client = m.client;
29
30
  model = m.model;
30
31
  modelConfig = m.modelConfig;
@@ -32,7 +33,7 @@ export function createSubAgentTool(def, scope) {
32
33
  else {
33
34
  const parent = ctx.agent;
34
35
  if (!parent) {
35
- throw new Error(`SubAgent "${selfName}" 未指定 modelId,且父 Agent 没有可复用的模型`);
36
+ throw new Error(`SubAgent "${selfName}" does not specify a modelId, and the parent Agent has no reusable model`);
36
37
  }
37
38
  client = parent.client;
38
39
  model = parent.model;
@@ -1,4 +1,11 @@
1
1
  import { Tool } from "@ai-zen/agents-core";
2
+ /** 单个用户工具文件的加载参数 */
3
+ export interface DiscoverUserToolsOptions {
4
+ /** 静默:不写日志(测试 / 批量探测用) */
5
+ silent?: boolean;
6
+ /** 单文件 import 的超时(毫秒),默认 {@link DEFAULT_IMPORT_TIMEOUT_MS};`0` 表示不限 */
7
+ importTimeoutMs?: number;
8
+ }
2
9
  /**
3
10
  * 扫描多个 tools/ 目录,发现所有 .js / .mjs 文件,动态加载为 Tool 实例。
4
11
  * 使用原生 dynamic import() 加载(在 "type": "module" 下 .js 也是 ESM),
@@ -7,6 +14,4 @@ import { Tool } from "@ai-zen/agents-core";
7
14
  * 按优先级从高到低传入路径列表,同名工具靠前的路径优先(先到先得)。
8
15
  * 按文件名排序以保证确定性。
9
16
  */
10
- export declare function discoverUserTools(paths: string[], options?: {
11
- silent?: boolean;
12
- }): Promise<Tool[]>;
17
+ export declare function discoverUserTools(paths: string[], options?: DiscoverUserToolsOptions): Promise<Tool[]>;
@@ -3,6 +3,114 @@ import { join } from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { Tool, CallbackTool } from "@ai-zen/agents-core";
5
5
  import { getLogger } from "../../../shared/logger.js";
6
+ /** 默认的单文件 import 超时:工具目录里不该有需要长过它的模块求值 */
7
+ const DEFAULT_IMPORT_TIMEOUT_MS = 5000;
8
+ // ==================================================================
9
+ // 宿主护栏
10
+ // ==================================================================
11
+ //
12
+ // `import()` 是把文件当模块**求值**,不是把文件当配置读——顶层代码因此拥有宿主进程
13
+ // 的全部权限。这里是有过真实事故的:用户把一个一次性开发脚本(无参数时
14
+ // `process.exit(2)`)放进了 tools 目录,于是**每次启动都在初始化途中被这个脚本杀掉**,
15
+ // 界面上只剩最后一帧,看着像「卡住不启动」;另有脚本在顶层直接 `writeFileSync`,
16
+ // 每次启动都在静默重写项目资产。
17
+ //
18
+ // 能挡住的:
19
+ // · `process.exit` / `process.abort` → 换成抛异常,落进 `loadToolFile` 的 try/catch;
20
+ // · `console.log / info / debug` → 改指 stderr,不撕宿主的 stdout(TUI 画面);
21
+ // · 顶层 await 永不 settle(异步挂死)→ 超时放弃该文件。
22
+ //
23
+ // **挡不住**的(只有进程隔离能解,而那正是 MCP 的职责):
24
+ // · 顶层同步死循环——事件循环被占,连超时定时器都不会跑;
25
+ // · `process.kill(process.pid)` 这类原生自杀。
26
+ //
27
+ // 所以 tools/ 的定位是**可信的本地扩展**;不可信的代码请写成 MCP 服务器。
28
+ /** 正在被 import 的文件(护栏回报错误时用它定位) */
29
+ let importingFile = null;
30
+ /** 用户文件里调 `process.exit()` / `process.abort()` 时抛这个 —— 落进 loadToolFile 的 catch */
31
+ class UserToolExitError extends Error {
32
+ constructor(code) {
33
+ super(`process.exit(${code ?? "?"}) was called while evaluating a user tool file` +
34
+ (importingFile ? `: ${importingFile}` : "") +
35
+ " — the call was suppressed to keep the host process alive");
36
+ this.name = "UserToolExitError";
37
+ }
38
+ }
39
+ /**
40
+ * 工具模块的静态判据:ESM 里没有 `export` 就**不可能**导出 Tool。
41
+ *
42
+ * 这个预检能把「放错目录的普通脚本」挡在求值之前——没有 export 的模块本来也会被
43
+ * `normalizeToolExport` 判成 null,区别只在于:那时它已经被求值、副作用已经发生了。
44
+ * 实测那 4 个一次性脚本的 export 计数全为 0。
45
+ *
46
+ * 读不出来(权限 / 编码 / 不是普通文件)时放行:预检只为省掉明显的白跑,
47
+ * 不该因为读不了文件就把正常工具挡住。
48
+ */
49
+ const TOOL_MODULE_HINT = /\bexport\b/;
50
+ async function mayExportTool(filepath) {
51
+ try {
52
+ return TOOL_MODULE_HINT.test(await fs.readFile(filepath, "utf-8"));
53
+ }
54
+ catch {
55
+ return true;
56
+ }
57
+ }
58
+ /**
59
+ * 装上宿主护栏,返回还原函数。
60
+ *
61
+ * 保存的是**当前**值而非模块加载时的值,且由调用方在 finally 里还原——
62
+ * 不能常驻,否则宿主自己也永远退不出去。
63
+ */
64
+ function installHostGuards() {
65
+ const realExit = process.exit;
66
+ const realAbort = process.abort;
67
+ const realLog = console.log;
68
+ const realInfo = console.info;
69
+ const realDebug = console.debug;
70
+ process.exit = ((code) => {
71
+ throw new UserToolExitError(code);
72
+ });
73
+ process.abort = (() => {
74
+ throw new UserToolExitError();
75
+ });
76
+ // 用户脚本的输出一律走 stderr:stdout 属于宿主的界面(Ink 的帧),不能让扩展写
77
+ console.log = (...args) => console.error(...args);
78
+ console.info = console.log;
79
+ console.debug = console.log;
80
+ return () => {
81
+ process.exit = realExit;
82
+ process.abort = realAbort;
83
+ console.log = realLog;
84
+ console.info = realInfo;
85
+ console.debug = realDebug;
86
+ };
87
+ }
88
+ /**
89
+ * `import()` + 超时。
90
+ *
91
+ * 超时只是「不再等它」:ESM 求值**不可取消**,该模块随后仍可能被求值完并产生副作用,
92
+ * 因此超时只记告警、不声称已终止。真正的隔离需要独立进程(即 MCP)。
93
+ */
94
+ async function importWithTimeout(url, timeoutMs) {
95
+ if (timeoutMs <= 0)
96
+ return import(url);
97
+ let timer;
98
+ const timeout = new Promise((_, reject) => {
99
+ timer = setTimeout(() => reject(new Error(`import timed out after ${timeoutMs}ms`)), timeoutMs);
100
+ });
101
+ try {
102
+ return await Promise.race([import(url), timeout]);
103
+ }
104
+ finally {
105
+ if (timer)
106
+ clearTimeout(timer);
107
+ }
108
+ }
109
+ /** 「这个文件被拒了」的出口:只走 logger,怎么展示是宿主的事 */
110
+ function reportReject(file, reason, opts, level = "warn") {
111
+ if (!opts.silent)
112
+ getLogger()[level](`[usertools] ${file} — ${reason}`);
113
+ }
6
114
  /**
7
115
  * 扫描多个 tools/ 目录,发现所有 .js / .mjs 文件,动态加载为 Tool 实例。
8
116
  * 使用原生 dynamic import() 加载(在 "type": "module" 下 .js 也是 ESM),
@@ -11,8 +119,7 @@ import { getLogger } from "../../../shared/logger.js";
11
119
  * 按优先级从高到低传入路径列表,同名工具靠前的路径优先(先到先得)。
12
120
  * 按文件名排序以保证确定性。
13
121
  */
14
- export async function discoverUserTools(paths, options) {
15
- const silent = options?.silent ?? false;
122
+ export async function discoverUserTools(paths, options = {}) {
16
123
  const seen = new Set();
17
124
  const tools = [];
18
125
  for (const dir of paths) {
@@ -35,7 +142,7 @@ export async function discoverUserTools(paths, options) {
35
142
  if (!seen.has(name)) {
36
143
  seen.add(name);
37
144
  try {
38
- const tool = await loadToolFile(join(dir, name + ext), silent);
145
+ const tool = await loadToolFile(join(dir, name + ext), options);
39
146
  if (tool) {
40
147
  tools.push(tool);
41
148
  }
@@ -60,24 +167,38 @@ export async function discoverUserTools(paths, options) {
60
167
  *
61
168
  * 使用原生 dynamic import() 加载 ESM 模块。每次调用添加时间戳 querystring
62
169
  * 防止模块缓存,确保 refresh() 能重新加载。
170
+ *
171
+ * 三道护栏(顺序有意义):
172
+ * 1. **先做静态预检**:没有 `export` 的文件根本不 import(连求值的机会都不给);
173
+ * 2. **再装宿主护栏**:import 期间 `process.exit` / console 输出被接管;
174
+ * 3. **超时**:异步挂死的文件不再拖住启动。
63
175
  */
64
- async function loadToolFile(filepath, silent) {
176
+ async function loadToolFile(filepath, opts) {
177
+ if (!(await mayExportTool(filepath))) {
178
+ reportReject(filepath, "no `export` in source — not a tool module, skipped without evaluating", opts);
179
+ return null;
180
+ }
181
+ const restore = installHostGuards();
182
+ const outerImporting = importingFile;
183
+ importingFile = filepath;
65
184
  try {
66
185
  const url = `${pathToFileURL(filepath).href}?t=${Date.now()}`;
67
- const mod = await import(url);
186
+ const mod = (await importWithTimeout(url, opts.importTimeoutMs ?? DEFAULT_IMPORT_TIMEOUT_MS));
68
187
  // import() 返回模块命名空间对象,取其 default 导出
69
188
  const exported = mod.default ?? mod;
70
189
  if (!exported || (typeof exported === "object" && Object.keys(exported).length === 0)) {
71
190
  return null;
72
191
  }
73
- return normalizeToolExport({ default: exported }, filepath, silent);
192
+ return normalizeToolExport({ default: exported }, filepath, opts.silent);
74
193
  }
75
194
  catch (err) {
76
- if (!silent) {
77
- getLogger().error(`[usertools] 加载工具文件失败: ${filepath} — ${err?.message ?? err}`);
78
- }
195
+ reportReject(filepath, `failed to load — ${err?.message ?? err}`, opts, "error");
79
196
  return null;
80
197
  }
198
+ finally {
199
+ importingFile = outerImporting;
200
+ restore();
201
+ }
81
202
  }
82
203
  // ==================================================================
83
204
  // 导出格式归一化
@@ -96,21 +217,27 @@ function normalizeToolExport(exported, filepath, silent) {
96
217
  return target;
97
218
  }
98
219
  // 情况 3:{ function, exec } 格式 → 适配为 CallbackTool
99
- if (target && typeof target === "object" && target.function && typeof target.exec === "function") {
220
+ if (target &&
221
+ typeof target === "object" &&
222
+ target.function &&
223
+ typeof target.exec === "function") {
100
224
  return new CallbackTool({
101
225
  function: target.function,
102
226
  callback: target.exec,
103
227
  });
104
228
  }
105
229
  // 情况 4:{ function, callback } 格式 → 适配为 CallbackTool
106
- if (target && typeof target === "object" && target.function && typeof target.callback === "function") {
230
+ if (target &&
231
+ typeof target === "object" &&
232
+ target.function &&
233
+ typeof target.callback === "function") {
107
234
  return new CallbackTool({
108
235
  function: target.function,
109
236
  callback: target.callback,
110
237
  });
111
238
  }
112
239
  if (!silent) {
113
- getLogger().error(`[usertools] 无法识别的工具格式: ${filepath}`);
240
+ getLogger().error(`[usertools] Unrecognized tool format: ${filepath}`);
114
241
  }
115
242
  return null;
116
243
  }
@@ -11,7 +11,16 @@ export declare class EntityRepository<T extends {
11
11
  }> {
12
12
  private dir;
13
13
  constructor(dir: string);
14
- /** 获取实体的文件路径 */
14
+ /**
15
+ * 获取实体的文件路径;`id` 必须落在本仓储目录内,否则抛错。
16
+ *
17
+ * 这是**唯一**的落盘口(read / write / delete 全走这里,`list()` 的 id 来自
18
+ * `readdir` 的单层文件名、不可能逃逸),所以校验放这里读写删天然自洽。
19
+ *
20
+ * 两个细节都是必需的:
21
+ * - 用 `resolve` 而不是 `join`:只有 `resolve` 会把绝对路径(`/etc/passwd`)归一化拦下;
22
+ * - 比较 `root + sep` 而不是裸 `startsWith(root)`:`<root>-evil/x` 也以 `<root>` 开头。
23
+ */
15
24
  protected path(id: string): string;
16
25
  /** 列出目录下所有实体(跳过解析失败的文件) */
17
26
  list(): Promise<T[]>;
@@ -1,5 +1,5 @@
1
1
  import { promises as fs } from "node:fs";
2
- import { join } from "node:path";
2
+ import { resolve, sep } from "node:path";
3
3
  /**
4
4
  * 通用实体仓储 — 对磁盘 JSON 文件的 CRUD 操作。
5
5
  *
@@ -13,9 +13,23 @@ export class EntityRepository {
13
13
  constructor(dir) {
14
14
  this.dir = dir;
15
15
  }
16
- /** 获取实体的文件路径 */
16
+ /**
17
+ * 获取实体的文件路径;`id` 必须落在本仓储目录内,否则抛错。
18
+ *
19
+ * 这是**唯一**的落盘口(read / write / delete 全走这里,`list()` 的 id 来自
20
+ * `readdir` 的单层文件名、不可能逃逸),所以校验放这里读写删天然自洽。
21
+ *
22
+ * 两个细节都是必需的:
23
+ * - 用 `resolve` 而不是 `join`:只有 `resolve` 会把绝对路径(`/etc/passwd`)归一化拦下;
24
+ * - 比较 `root + sep` 而不是裸 `startsWith(root)`:`<root>-evil/x` 也以 `<root>` 开头。
25
+ */
17
26
  path(id) {
18
- return join(this.dir, `${id}.json`);
27
+ const root = resolve(this.dir);
28
+ const target = resolve(root, `${id}.json`);
29
+ if (!target.startsWith(root + sep)) {
30
+ throw new Error(`Invalid entity id: ${JSON.stringify(id)}`);
31
+ }
32
+ return target;
19
33
  }
20
34
  /** 列出目录下所有实体(跳过解析失败的文件) */
21
35
  async list() {
@@ -26,9 +40,7 @@ export class EntityRepository {
26
40
  return [];
27
41
  }
28
42
  const entries = await fs.readdir(this.dir);
29
- const ids = entries
30
- .filter((f) => f.endsWith(".json"))
31
- .map((f) => f.replace(/\.json$/, ""));
43
+ const ids = entries.filter((f) => f.endsWith(".json")).map((f) => f.replace(/\.json$/, ""));
32
44
  const entities = [];
33
45
  for (const id of ids) {
34
46
  const entity = await this.read(id);
@@ -0,0 +1,101 @@
1
+ /**
2
+ * 本地文件 → 消息内容块的唯一转换入口。
3
+ *
4
+ * 背景:这段逻辑原先散落三处,且各自为政 ——
5
+ * 1. `ViewImageTool` 自己判断 `endpoint.id === "deepseek"` 再上传(端点 id 一变就失效);
6
+ * 2. `mcp/mcpTools.ts` 自己把 MCP 的 base64 归一成 `image_url` / `file` 块;
7
+ * 3. CLI 侧又实现了一遍「上传 or base64」。
8
+ *
9
+ * 现在统一到这里,调用方只提供「文件 + 当前端点/模型」,传输方式由本模块决定:
10
+ *
11
+ * | 条件 | 结果 |
12
+ * |------|------|
13
+ * | http(s) URL | 直接 `image_url`(不上传、不内联) |
14
+ * | 端点声明 `capabilities.filesApi` | 上传 Files API → `file` 块(`file_id`),失败降级为内联 |
15
+ * | 其余端点 + 图片 | `image_url` + base64 data URL |
16
+ * | 其余端点 + 非图片 | `file` 块 + `file_data`(base64 data URL) |
17
+ * | 模型明确不支持视觉(`vision === false`)且是图片 | 退化为 `text`,只给路径提示 |
18
+ * | 内联体积超过上限且无法上传 | 抛错(不静默塞进请求体) |
19
+ */
20
+ import type { AgentNS } from "@ai-zen/agents-core";
21
+ import type { AppConfig, Endpoint, Model, ToolEnvDeps, UploadFn } from "../types/index.js";
22
+ /** 上传函数类型(定义在 types,此处再导出方便既有引用) */
23
+ export type { UploadFn };
24
+ /** 扩展名 → MIME。图片走视觉通道,其余走 `file` 块 */
25
+ export declare const MIME_BY_EXT: Record<string, string>;
26
+ /** 按扩展名推断 MIME;未知扩展名返回 undefined */
27
+ export declare function mimeOf(filePath: string): string | undefined;
28
+ /** base64 二进制转 data URL(`image_url` 与 `file.file_data` 均接受) */
29
+ export declare function toDataUrl(base64: string, mime: string): string;
30
+ /**
31
+ * base64 字符串对应的字节数(不含空白)。
32
+ *
33
+ * 用于「只看体积、不想解码」的场景:内联上限检查与日志统计。
34
+ */
35
+ export declare function base64ByteLength(base64: string): number;
36
+ /** 内联(base64)体积上限,默认 8 MiB;超过且端点不支持上传时直接报错 */
37
+ export declare const DEFAULT_MAX_INLINE_BYTES: number;
38
+ /** 实际采用的传输方式(供调用方组织提示文案 / 日志) */
39
+ export type ContentTransport = "url" | "files-api" | "inline" | "text";
40
+ /** 文件来源:本地路径 / 网络 URL / 已在内存里的字节 */
41
+ export type FileSource = {
42
+ path: string;
43
+ } | {
44
+ url: string;
45
+ } | {
46
+ data: Uint8Array;
47
+ mime: string;
48
+ filename?: string;
49
+ }
50
+ /** 已经是 base64 的字节(MCP 等协议给的就是 base64):内联时原样透传,不做解码再编码 */
51
+ | {
52
+ base64: string;
53
+ mime: string;
54
+ filename?: string;
55
+ };
56
+ export interface FileToSectionInput {
57
+ source: FileSource;
58
+ /** 当前模型所用端点:决定能否走 Files API */
59
+ endpoint?: Endpoint | null;
60
+ /** 当前模型:`vision === false` 时图片退化为文本提示 */
61
+ model?: Model | null;
62
+ signal?: AbortSignal;
63
+ /** 覆盖内联体积上限 */
64
+ maxInlineBytes?: number;
65
+ /** 依赖注入(测试 / 宿主用),缺省走 OpenAI SDK 的 Files API */
66
+ deps?: ToolEnvDeps;
67
+ }
68
+ export interface FileToSectionResult {
69
+ section: AgentNS.MessageContentSection;
70
+ transport: ContentTransport;
71
+ /** 实际处理的字节数(URL 来源为 0) */
72
+ bytes: number;
73
+ /** 降级 / 退化时的人类可读说明,供上层拼提示 */
74
+ warning?: string;
75
+ }
76
+ /**
77
+ * 由「发给 API 的模型名」反查它绑定的模型定义与端点。
78
+ *
79
+ * 工具在 `call()` 阶段拿不到 Agent 定义,但 `ctx.agent.model` 就是发给 API 的
80
+ * 模型名(`Model.modelName ?? Model.id`)。必须按**当前实际使用的模型**定位端点:
81
+ * `file_id` 是端点维度资源,传错端点会得到 not found。
82
+ */
83
+ export declare function resolveModelAndEndpoint(config: AppConfig, apiModelName?: string): {
84
+ model?: Model;
85
+ endpoint?: Endpoint | null;
86
+ };
87
+ /** 端点是否声明了 Files API 能力 */
88
+ export declare function supportsFilesApi(endpoint?: Endpoint | null): boolean;
89
+ /** 清空上传缓存(测试用;进程内长期运行无需清理,条目有上限) */
90
+ export declare function clearUploadCache(): void;
91
+ /** 内容哈希(sha256),用于给「内存里的字节」做上传缓存键 */
92
+ export declare function contentHash(bytes: Uint8Array): string;
93
+ /**
94
+ * 把文件转成内容块。
95
+ *
96
+ * 抛错场景(均由调用方决定如何呈现给模型):
97
+ * - `source.url` 不是 http(s)(本地 URL 服务商访问不到)
98
+ * - 本地文件不存在 / 不是文件 / 扩展名不支持
99
+ * - 需要内联但体积超过上限,且端点不支持上传
100
+ */
101
+ export declare function fileToContentSection(input: FileToSectionInput): Promise<FileToSectionResult>;
@@ -0,0 +1,253 @@
1
+ /**
2
+ * 本地文件 → 消息内容块的唯一转换入口。
3
+ *
4
+ * 背景:这段逻辑原先散落三处,且各自为政 ——
5
+ * 1. `ViewImageTool` 自己判断 `endpoint.id === "deepseek"` 再上传(端点 id 一变就失效);
6
+ * 2. `mcp/mcpTools.ts` 自己把 MCP 的 base64 归一成 `image_url` / `file` 块;
7
+ * 3. CLI 侧又实现了一遍「上传 or base64」。
8
+ *
9
+ * 现在统一到这里,调用方只提供「文件 + 当前端点/模型」,传输方式由本模块决定:
10
+ *
11
+ * | 条件 | 结果 |
12
+ * |------|------|
13
+ * | http(s) URL | 直接 `image_url`(不上传、不内联) |
14
+ * | 端点声明 `capabilities.filesApi` | 上传 Files API → `file` 块(`file_id`),失败降级为内联 |
15
+ * | 其余端点 + 图片 | `image_url` + base64 data URL |
16
+ * | 其余端点 + 非图片 | `file` 块 + `file_data`(base64 data URL) |
17
+ * | 模型明确不支持视觉(`vision === false`)且是图片 | 退化为 `text`,只给路径提示 |
18
+ * | 内联体积超过上限且无法上传 | 抛错(不静默塞进请求体) |
19
+ */
20
+ import OpenAI, { toFile } from "openai";
21
+ import { createHash } from "node:crypto";
22
+ import { promises as fs } from "node:fs";
23
+ import path from "node:path";
24
+ /** 扩展名 → MIME。图片走视觉通道,其余走 `file` 块 */
25
+ export const MIME_BY_EXT = {
26
+ ".png": "image/png",
27
+ ".jpg": "image/jpeg",
28
+ ".jpeg": "image/jpeg",
29
+ ".gif": "image/gif",
30
+ ".webp": "image/webp",
31
+ ".pdf": "application/pdf",
32
+ ".txt": "text/plain",
33
+ ".md": "text/markdown",
34
+ ".json": "application/json",
35
+ };
36
+ /** 按扩展名推断 MIME;未知扩展名返回 undefined */
37
+ export function mimeOf(filePath) {
38
+ const dot = filePath.lastIndexOf(".");
39
+ if (dot < 0)
40
+ return undefined;
41
+ return MIME_BY_EXT[filePath.slice(dot).toLowerCase()];
42
+ }
43
+ /** base64 二进制转 data URL(`image_url` 与 `file.file_data` 均接受) */
44
+ export function toDataUrl(base64, mime) {
45
+ return `data:${mime};base64,${base64}`;
46
+ }
47
+ /**
48
+ * base64 字符串对应的字节数(不含空白)。
49
+ *
50
+ * 用于「只看体积、不想解码」的场景:内联上限检查与日志统计。
51
+ */
52
+ export function base64ByteLength(base64) {
53
+ const len = base64.replace(/\s/g, "").length;
54
+ if (len === 0)
55
+ return 0;
56
+ const pad = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
57
+ return Math.max(0, Math.floor((len * 3) / 4) - pad);
58
+ }
59
+ /** 内联(base64)体积上限,默认 8 MiB;超过且端点不支持上传时直接报错 */
60
+ export const DEFAULT_MAX_INLINE_BYTES = 8 * 1024 * 1024;
61
+ /**
62
+ * 由「发给 API 的模型名」反查它绑定的模型定义与端点。
63
+ *
64
+ * 工具在 `call()` 阶段拿不到 Agent 定义,但 `ctx.agent.model` 就是发给 API 的
65
+ * 模型名(`Model.modelName ?? Model.id`)。必须按**当前实际使用的模型**定位端点:
66
+ * `file_id` 是端点维度资源,传错端点会得到 not found。
67
+ */
68
+ export function resolveModelAndEndpoint(config, apiModelName) {
69
+ const models = config.models ?? [];
70
+ const endpoints = config.endpoints ?? [];
71
+ const findEndpoint = (id) => (id ? (endpoints.find((e) => e.id === id) ?? null) : null);
72
+ const byApiName = apiModelName
73
+ ? models.find((m) => (m.modelName ?? m.id) === apiModelName)
74
+ : undefined;
75
+ if (byApiName)
76
+ return { model: byApiName, endpoint: findEndpoint(byApiName.endpointId) };
77
+ return { endpoint: null };
78
+ }
79
+ /** 端点是否声明了 Files API 能力 */
80
+ export function supportsFilesApi(endpoint) {
81
+ return endpoint?.capabilities?.filesApi === true;
82
+ }
83
+ /**
84
+ * 上传缓存:`端点id + 绝对路径 + mtime + size` → `file_id`。
85
+ *
86
+ * file_id 是**端点维度**的资源,所以 key 必须带端点 id —— 同一张图传到两个端点
87
+ * 会得到两个不同的 id,混用会让另一端返回 not found。
88
+ */
89
+ const uploadCache = new Map();
90
+ /** 清空上传缓存(测试用;进程内长期运行无需清理,条目有上限) */
91
+ export function clearUploadCache() {
92
+ uploadCache.clear();
93
+ }
94
+ const UPLOAD_CACHE_LIMIT = 200;
95
+ /** 内容哈希(sha256),用于给「内存里的字节」做上传缓存键 */
96
+ export function contentHash(bytes) {
97
+ return createHash("sha256").update(bytes).digest("hex");
98
+ }
99
+ function cacheKey(endpoint, absPath, stat) {
100
+ return `${endpoint.id}\u0000${absPath}\u0000${stat.mtimeMs}\u0000${stat.size}`;
101
+ }
102
+ /** 内存来源的缓存键:没有路径与 mtime,改用内容哈希(同一张图不会重复上传) */
103
+ function contentCacheKey(endpoint, hash) {
104
+ return `${endpoint.id}\u0000sha256:${hash}`;
105
+ }
106
+ function rememberUpload(key, fileId) {
107
+ uploadCache.set(key, fileId);
108
+ while (uploadCache.size > UPLOAD_CACHE_LIMIT) {
109
+ const oldest = uploadCache.keys().next();
110
+ if (oldest.done)
111
+ break;
112
+ uploadCache.delete(oldest.value);
113
+ }
114
+ }
115
+ /** 默认上传实现:OpenAI 兼容的 `POST {baseUrl}/files`(`purpose=user_data`) */
116
+ const defaultUpload = async ({ endpoint, data, filename, signal }) => {
117
+ const client = new OpenAI({ apiKey: endpoint.apiKey, baseURL: endpoint.baseUrl });
118
+ const file = await toFile(Buffer.from(data), filename);
119
+ const uploaded = await client.files.create({ file, purpose: "user_data" }, { signal });
120
+ return uploaded.id;
121
+ };
122
+ function isRemoteUrl(value) {
123
+ return /^https?:\/\//i.test(value);
124
+ }
125
+ function textSection(text) {
126
+ return { type: "text", text };
127
+ }
128
+ /**
129
+ * 把文件转成内容块。
130
+ *
131
+ * 抛错场景(均由调用方决定如何呈现给模型):
132
+ * - `source.url` 不是 http(s)(本地 URL 服务商访问不到)
133
+ * - 本地文件不存在 / 不是文件 / 扩展名不支持
134
+ * - 需要内联但体积超过上限,且端点不支持上传
135
+ */
136
+ export async function fileToContentSection(input) {
137
+ const { source, endpoint, model, signal } = input;
138
+ const maxInline = input.maxInlineBytes ?? DEFAULT_MAX_INLINE_BYTES;
139
+ // ---- 1. 网络 URL:直接引用,不经上传/内联 ----
140
+ if ("url" in source) {
141
+ if (!isRemoteUrl(source.url)) {
142
+ throw new Error(`Unsupported local URL (${source.url}): the API provider cannot access it. For local files pass a file path, not a local link`);
143
+ }
144
+ return {
145
+ section: { type: "image_url", image_url: { url: source.url } },
146
+ transport: "url",
147
+ bytes: 0,
148
+ };
149
+ }
150
+ // ---- 2. 取得字节与 MIME ----
151
+ // 已经是 base64 的来源(MCP):先不解码,内联时原样透传,只有真要上传/算哈希时才解码
152
+ let base64 = null;
153
+ let bytes = null;
154
+ let byteLength;
155
+ let mime;
156
+ let filename;
157
+ let absPath = null;
158
+ let stat = null;
159
+ if ("path" in source) {
160
+ absPath = path.isAbsolute(source.path) ? source.path : path.resolve(source.path);
161
+ const st = await fs.stat(absPath);
162
+ if (!st.isFile())
163
+ throw new Error(`"${absPath}" is not a file`);
164
+ const inferred = mimeOf(absPath);
165
+ if (!inferred) {
166
+ throw new Error(`Unsupported file type: "${absPath}" (known types: ${Object.keys(MIME_BY_EXT).join(" ")})`);
167
+ }
168
+ mime = inferred;
169
+ stat = { mtimeMs: st.mtimeMs, size: st.size };
170
+ bytes = new Uint8Array(await fs.readFile(absPath));
171
+ byteLength = bytes.byteLength;
172
+ filename = path.basename(absPath);
173
+ }
174
+ else if ("base64" in source) {
175
+ mime = source.mime;
176
+ base64 = source.base64;
177
+ byteLength = base64ByteLength(base64);
178
+ filename = source.filename ?? "file";
179
+ }
180
+ else {
181
+ mime = source.mime;
182
+ bytes = source.data;
183
+ byteLength = bytes.byteLength;
184
+ filename = source.filename ?? "file";
185
+ }
186
+ /** 需要真实字节时才解码(上传、算内容哈希) */
187
+ const ensureBytes = () => {
188
+ if (!bytes)
189
+ bytes = new Uint8Array(Buffer.from(base64 ?? "", "base64"));
190
+ return bytes;
191
+ };
192
+ const isImage = mime.startsWith("image/");
193
+ // ---- 3. 模型看不见图:退化为文本提示 ----
194
+ // 判定口径与 `ViewImageTool.isAvailable` 一致:只有 `vision === true` 才算视觉模型,
195
+ // 缺省视为不支持(模型未提供 model 时不做判断,交给调用方)。
196
+ // 对任何来源都生效(本地路径给路径,内存来源给文件名):非视觉模型收到 image_url
197
+ // 可能直接 4xx,宁可退化成一行提示。
198
+ if (isImage && model && model.vision !== true) {
199
+ const label = absPath ?? filename;
200
+ return {
201
+ section: textSection(`[Image] ${label} (the current model does not support image input; use a vision-capable model to view it)`),
202
+ transport: "text",
203
+ bytes: byteLength,
204
+ warning: "The current model does not support image input; degraded to a text hint",
205
+ };
206
+ }
207
+ // ---- 4. 端点支持 Files API:上传(带缓存),失败降级内联 ----
208
+ let warning;
209
+ if (supportsFilesApi(endpoint) && endpoint?.apiKey) {
210
+ const key = absPath && stat
211
+ ? cacheKey(endpoint, absPath, stat)
212
+ : contentCacheKey(endpoint, contentHash(ensureBytes()));
213
+ const cached = uploadCache.get(key);
214
+ if (cached) {
215
+ return {
216
+ section: { type: "file", file_id: cached },
217
+ transport: "files-api",
218
+ bytes: byteLength,
219
+ };
220
+ }
221
+ try {
222
+ const upload = input.deps?.upload ?? defaultUpload;
223
+ const fileId = await upload({ endpoint, data: ensureBytes(), filename, signal });
224
+ rememberUpload(key, fileId);
225
+ return {
226
+ section: { type: "file", file_id: fileId },
227
+ transport: "files-api",
228
+ bytes: byteLength,
229
+ };
230
+ }
231
+ catch (error) {
232
+ if (signal?.aborted)
233
+ throw error;
234
+ warning = `Files API upload failed, falling back to base64 inline: ${error?.message ?? error}`;
235
+ }
236
+ }
237
+ // ---- 5. 内联(base64 data URL)----
238
+ if (byteLength > maxInline) {
239
+ throw new Error(`File size ${(byteLength / 1024 / 1024).toFixed(1)} MiB exceeds the inline limit of ` +
240
+ `${(maxInline / 1024 / 1024).toFixed(1)} MiB and the endpoint does not declare the Files API capability ` +
241
+ `(capabilities.filesApi), so it cannot be sent`);
242
+ }
243
+ // base64 来源直接透传,不重新编码(保证字节级一致,也省一次编解码)
244
+ const dataUrl = toDataUrl(base64 ?? Buffer.from(ensureBytes()).toString("base64"), mime);
245
+ return {
246
+ section: isImage
247
+ ? { type: "image_url", image_url: { url: dataUrl } }
248
+ : { type: "file", file_data: dataUrl, filename },
249
+ transport: "inline",
250
+ bytes: byteLength,
251
+ warning,
252
+ };
253
+ }