@ai-zen/agents-sdk 1.0.0-alpha.24 → 1.0.0-alpha.26

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 (50) hide show
  1. package/CHANGELOG.md +209 -0
  2. package/README.md +5 -5
  3. package/README.zh.md +5 -5
  4. package/dist/agent-plugins/AutoMigratePlugin.js +1 -3
  5. package/dist/agent-plugins/AutoRefreshToolsPlugin.js +1 -3
  6. package/dist/agent-plugins/ContextGuardPlugin.d.ts +15 -1
  7. package/dist/agent-plugins/ContextGuardPlugin.js +11 -1
  8. package/dist/config/ConfigManager.js +1 -1
  9. package/dist/config/constants.js +5 -8
  10. package/dist/config/migrate.d.ts +31 -0
  11. package/dist/config/migrate.js +52 -4
  12. package/dist/index.d.ts +5 -5
  13. package/dist/index.js +3 -3
  14. package/dist/runtime/HandoffService.d.ts +5 -4
  15. package/dist/runtime/HandoffService.js +17 -14
  16. package/dist/runtime/createAgent.js +1 -3
  17. package/dist/scope/Scope.d.ts +3 -1
  18. package/dist/scope/Scope.js +3 -1
  19. package/dist/scope/plugins/builtin/BatchEditTool.js +15 -8
  20. package/dist/scope/plugins/builtin/DownloadFileTool.d.ts +1 -0
  21. package/dist/scope/plugins/builtin/DownloadFileTool.js +54 -30
  22. package/dist/scope/plugins/builtin/EditTool.js +13 -18
  23. package/dist/scope/plugins/builtin/ExecTool.js +127 -18
  24. package/dist/scope/plugins/builtin/FindTextTool.js +6 -1
  25. package/dist/scope/plugins/builtin/GenerateImageTool.js +80 -14
  26. package/dist/scope/plugins/builtin/GlobTool.js +6 -1
  27. package/dist/scope/plugins/builtin/SpawnTool.js +28 -45
  28. package/dist/scope/plugins/builtin/ViewImageTool.js +6 -2
  29. package/dist/scope/plugins/builtin/searchBase.d.ts +9 -0
  30. package/dist/scope/plugins/builtin/searchBase.js +17 -0
  31. package/dist/scope/plugins/builtin/test-helpers.d.ts +3 -3
  32. package/dist/scope/plugins/builtin/test-helpers.js +3 -3
  33. package/dist/scope/plugins/builtin/textEdit.d.ts +17 -0
  34. package/dist/scope/plugins/builtin/textEdit.js +37 -0
  35. package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +9 -1
  36. package/dist/scope/plugins/mcp/McpConnectionManager.js +88 -9
  37. package/dist/scope/plugins/mcp/McpScopePlugin.js +7 -6
  38. package/dist/scope/plugins/mcp/mcpTools.d.ts +2 -2
  39. package/dist/scope/plugins/mcp/mcpTools.js +42 -10
  40. package/dist/scope/plugins/skills/SkillsScopePlugin.js +2 -3
  41. package/dist/scope/plugins/skills/discover.js +25 -5
  42. package/dist/scope/plugins/skills/skillTools.js +13 -1
  43. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +1 -3
  44. package/dist/scope/plugins/usertools/discover.js +8 -2
  45. package/dist/shared/EntityRepository.d.ts +10 -1
  46. package/dist/shared/EntityRepository.js +18 -6
  47. package/dist/shared/content-blocks.d.ts +5 -12
  48. package/dist/shared/content-blocks.js +1 -1
  49. package/dist/types/index.d.ts +48 -0
  50. package/package.json +5 -6
@@ -1,5 +1,5 @@
1
1
  import { CallbackTool } from "@ai-zen/agents-core";
2
- import { fileToContentSection, resolveModelAndEndpoint } from "../../../shared/content-blocks.js";
2
+ import { fileToContentSection, resolveModelAndEndpoint, } from "../../../shared/content-blocks.js";
3
3
  import { createDisclosureParam } from "../../disclosure.js";
4
4
  import { DEFAULT_MAX_TOOL_OUTPUT, guardOutput, headTailPreview } from "../builtin/outputGuard.js";
5
5
  import { getLogger } from "../../../shared/logger.js";
@@ -111,6 +111,7 @@ async function mediaSection(data, mime, media) {
111
111
  endpoint: media.endpoint,
112
112
  model: media.model,
113
113
  signal: media.signal,
114
+ deps: media.deps,
114
115
  });
115
116
  return section;
116
117
  }
@@ -229,9 +230,7 @@ async function protectCallOutput(output, env) {
229
230
  const hasMedia = sections.some((s) => s.type !== "text");
230
231
  if (!hasMedia)
231
232
  return isError ? `❌ Tool execution failed:\n${fullText}` : fullText;
232
- return isError
233
- ? [{ type: "text", text: "❌ Tool execution failed:" }, ...sections]
234
- : sections;
233
+ return isError ? [{ type: "text", text: "❌ Tool execution failed:" }, ...sections] : sections;
235
234
  }
236
235
  /**
237
236
  * 创建 call_mcp_tool 工具。
@@ -243,7 +242,11 @@ async function protectCallOutput(output, env) {
243
242
  *
244
243
  * env 仅用于读取 maxToolOutput(文本输出保护上限),与内置工具口径一致。
245
244
  */
246
- export function createCallMcpTool(mcpManager, env) {
245
+ export function createCallMcpTool(mcpManager, env, filteredMcps) {
246
+ // 权限白名单:`filteredMcps` 是本 Scope 允许的 server。
247
+ // 连接管理器是全局共享的,只按"是否 connected"判断会让任一 Agent 连上的 server 对其他 Scope 敞开。
248
+ const allowed = new Set(filteredMcps);
249
+ const allowList = filteredMcps.join(", ") || "(none)";
247
250
  return new CallbackTool({
248
251
  function: {
249
252
  name: "call_mcp_tool",
@@ -261,6 +264,9 @@ export function createCallMcpTool(mcpManager, env) {
261
264
  },
262
265
  callback: async (input, ctx) => {
263
266
  const serverName = input.server;
267
+ if (!allowed.has(serverName)) {
268
+ return `❌ MCP server "${serverName}" is not available here. Available servers: ${allowList}`;
269
+ }
264
270
  const state = mcpManager.getState(serverName);
265
271
  if (state !== "connected") {
266
272
  return `Call load_mcp to connect "${serverName}" first`;
@@ -281,11 +287,21 @@ export function createCallMcpTool(mcpManager, env) {
281
287
  // 没有 content 时退回原始 JSON(既有兜底)
282
288
  if (contents.length === 0) {
283
289
  const json = JSON.stringify(result);
284
- return await protectCallOutput({ sections: [{ type: "text", text: json }], fullText: json, chars: json.length, isError }, env);
290
+ return await protectCallOutput({
291
+ sections: [{ type: "text", text: json }],
292
+ fullText: json,
293
+ chars: json.length,
294
+ isError,
295
+ }, env);
285
296
  }
286
297
  // 按当前模型定位端点:决定媒体走 Files API 上传还是 base64 内联
287
298
  const { model, endpoint } = resolveModelAndEndpoint(env.config, ctx?.agent?.model);
288
- const mediaContext = { endpoint, model, signal: ctx?.signal };
299
+ const mediaContext = {
300
+ endpoint,
301
+ model,
302
+ signal: ctx?.signal,
303
+ deps: env.deps,
304
+ };
289
305
  // Promise.all 保序:文本与媒体的相对位置不变
290
306
  const sections = await Promise.all(contents.map((block) => toMessageSection(block, mediaContext)));
291
307
  const textSections = sections.filter((s) => s.type === "text");
@@ -302,7 +318,10 @@ export function createCallMcpTool(mcpManager, env) {
302
318
  /**
303
319
  * 创建 read_mcp_resource 工具。
304
320
  */
305
- export function createReadMcpResourceTool(mcpManager, env) {
321
+ export function createReadMcpResourceTool(mcpManager, env, filteredMcps) {
322
+ // 与 call_mcp_tool 同一白名单口径(见该工具的说明)
323
+ const allowed = new Set(filteredMcps);
324
+ const allowList = filteredMcps.join(", ") || "(none)";
306
325
  return new CallbackTool({
307
326
  function: {
308
327
  name: "read_mcp_resource",
@@ -319,6 +338,9 @@ export function createReadMcpResourceTool(mcpManager, env) {
319
338
  },
320
339
  callback: async (input, ctx) => {
321
340
  const serverName = input.server;
341
+ if (!allowed.has(serverName)) {
342
+ return `❌ MCP server "${serverName}" is not available here. Available servers: ${allowList}`;
343
+ }
322
344
  const state = mcpManager.getState(serverName);
323
345
  if (state !== "connected") {
324
346
  return `Call load_mcp to connect "${serverName}" first`;
@@ -332,14 +354,24 @@ export function createReadMcpResourceTool(mcpManager, env) {
332
354
  const result = await client.readResource({ uri: input.uri }, { signal: ctx?.signal });
333
355
  const contents = result?.contents ?? [];
334
356
  const { model, endpoint } = resolveModelAndEndpoint(env.config, ctx?.agent?.model);
335
- const mediaContext = { endpoint, model, signal: ctx?.signal };
357
+ const mediaContext = {
358
+ endpoint,
359
+ model,
360
+ signal: ctx?.signal,
361
+ deps: env.deps,
362
+ };
336
363
  // 与 call_mcp_tool 同一套映射:文本归一为 text 块,媒体按端点能力上传或内联,
337
364
  // 不再把二进制资源(图片 / PDF)静默丢掉。
338
365
  const sections = await Promise.all(contents.map((content) => resourceToMessageSection(content, mediaContext)));
339
366
  // 没有 contents 时退回原始 JSON(与 call_mcp_tool 同一兜底)
340
367
  if (sections.length === 0) {
341
368
  const json = JSON.stringify(result);
342
- return await protectCallOutput({ sections: [{ type: "text", text: json }], fullText: json, chars: json.length, isError: false }, env);
369
+ return await protectCallOutput({
370
+ sections: [{ type: "text", text: json }],
371
+ fullText: json,
372
+ chars: json.length,
373
+ isError: false,
374
+ }, env);
343
375
  }
344
376
  // 与 call_mcp_tool 共用同一套输出保护:文本超限落盘 result.txt,
345
377
  // 媒体块原位保留;未超限时纯文本退化为字符串、含媒体返回块数组。
@@ -1,6 +1,6 @@
1
1
  import { isAbsolute, join } from "node:path";
2
2
  import { discoverSkills } from "./discover.js";
3
- import { createCallSkillSubAgentTool, createLoadSkillTool, } from "./skillTools.js";
3
+ import { createCallSkillSubAgentTool, createLoadSkillTool } from "./skillTools.js";
4
4
  /**
5
5
  * Skill 插件 —— 发现 SKILL.md + 装配渐进式披露元工具。
6
6
  *
@@ -39,8 +39,7 @@ export class SkillsScopePlugin {
39
39
  result.push(createLoadSkillTool(this.dirs, filteredSkills));
40
40
  }
41
41
  // call_skill_sub_agent:只要有支持子 Agent 的 skill 就注册
42
- if (allow.has("call_skill_sub_agent") &&
43
- filteredSkills.some((s) => s.subAgent)) {
42
+ if (allow.has("call_skill_sub_agent") && filteredSkills.some((s) => s.subAgent)) {
44
43
  result.push(createCallSkillSubAgentTool(this.dirs, filteredSkills));
45
44
  }
46
45
  return result;
@@ -169,23 +169,43 @@ export function validateSkill(skillId, fm) {
169
169
  }
170
170
  else {
171
171
  if (fm.name.length > 64) {
172
- errors.push({ skillId, field: "name", message: `Exceeds 64 characters (currently ${fm.name.length})` });
172
+ errors.push({
173
+ skillId,
174
+ field: "name",
175
+ message: `Exceeds 64 characters (currently ${fm.name.length})`,
176
+ });
173
177
  }
174
178
  if (!VALID_NAME_RE.test(fm.name)) {
175
- errors.push({ skillId, field: "name", message: `"${fm.name}" is not valid: only lowercase letters, digits and hyphens are allowed, and it must not start, end or contain consecutive hyphens` });
179
+ errors.push({
180
+ skillId,
181
+ field: "name",
182
+ message: `"${fm.name}" is not valid: only lowercase letters, digits and hyphens are allowed, and it must not start, end or contain consecutive hyphens`,
183
+ });
176
184
  }
177
185
  if (fm.name !== skillId) {
178
- errors.push({ skillId, field: "name", message: `"${fm.name}" does not match the directory name "${skillId}"` });
186
+ errors.push({
187
+ skillId,
188
+ field: "name",
189
+ message: `"${fm.name}" does not match the directory name "${skillId}"`,
190
+ });
179
191
  }
180
192
  }
181
193
  if (!fm.description || fm.description.length === 0) {
182
194
  errors.push({ skillId, field: "description", message: "Must be present and non-empty" });
183
195
  }
184
196
  else if (fm.description.length > 1024) {
185
- errors.push({ skillId, field: "description", message: `Exceeds 1024 characters (currently ${fm.description.length})` });
197
+ errors.push({
198
+ skillId,
199
+ field: "description",
200
+ message: `Exceeds 1024 characters (currently ${fm.description.length})`,
201
+ });
186
202
  }
187
203
  if (fm.compatibility && fm.compatibility.length > 500) {
188
- errors.push({ skillId, field: "compatibility", message: `Exceeds 500 characters (currently ${fm.compatibility.length})` });
204
+ errors.push({
205
+ skillId,
206
+ field: "compatibility",
207
+ message: `Exceeds 500 characters (currently ${fm.compatibility.length})`,
208
+ });
189
209
  }
190
210
  return errors;
191
211
  }
@@ -1,4 +1,4 @@
1
- import { CallbackTool, Agent, AgentToolLazy, Message } from "@ai-zen/agents-core";
1
+ import { CallbackTool, Agent, AgentToolLazy, Message, } from "@ai-zen/agents-core";
2
2
  import { createDisclosureParam } from "../../disclosure.js";
3
3
  import { readSkill } from "./discover.js";
4
4
  import { promises as fs } from "node:fs";
@@ -9,6 +9,7 @@ const EMPTY_HINT = "(No Skills are currently available, please ask the user to a
9
9
  */
10
10
  export function createLoadSkillTool(skillDirs, filteredSkills) {
11
11
  const ids = filteredSkills.map((s) => s.id);
12
+ const allowedIds = new Set(ids);
12
13
  const param = createDisclosureParam(ids, "Select a Skill", EMPTY_HINT);
13
14
  // 拼接各 skill 的描述供 LLM 参考
14
15
  const skillDescriptions = filteredSkills
@@ -34,6 +35,12 @@ export function createLoadSkillTool(skillDirs, filteredSkills) {
34
35
  },
35
36
  callback: async function (input) {
36
37
  const skillId = input.skill_id;
38
+ // 权限白名单:`filteredSkills` 才是本 Scope 允许的技能。
39
+ // 只靠枚举 + 描述里列名字不算限制(deny 的技能照样能被点名加载),
40
+ // 顺带堵掉 "../../etc" 这类越出 skillDirs 的 id。
41
+ if (!allowedIds.has(skillId)) {
42
+ return `❌ Skill "${skillId}" is not available here. Available skills: ${ids.join(", ") || "(none)"}`;
43
+ }
37
44
  const skill = await readSkill(skillDirs, skillId);
38
45
  if (!skill) {
39
46
  return `❌ Skill "${skillId}" not found, please verify the name`;
@@ -76,6 +83,7 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
76
83
  // 只保留支持子 Agent 模式的 skill
77
84
  const subAgentSkills = filteredSkills.filter((s) => s.subAgent);
78
85
  const ids = subAgentSkills.map((s) => s.id);
86
+ const allowedIds = new Set(ids);
79
87
  const param = createDisclosureParam(ids, "Select a Skill that supports SubAgent mode", EMPTY_HINT);
80
88
  // 拼接各 skill 的描述供 LLM 参考
81
89
  const skillDescriptions = subAgentSkills
@@ -108,6 +116,10 @@ export function createCallSkillSubAgentTool(skillDirs, filteredSkills) {
108
116
  buildAgent: async (parsedArgs, ctx) => {
109
117
  const skillId = parsedArgs.skill_id;
110
118
  const task = parsedArgs.task;
119
+ // 与 load_skill 同一白名单口径:被权限过滤掉的技能不能被点名启动
120
+ if (!allowedIds.has(skillId)) {
121
+ throw new Error(`❌ Skill "${skillId}" is not available here. Available SubAgent skills: ${ids.join(", ") || "(none)"}`);
122
+ }
111
123
  const skill = await readSkill(skillDirs, skillId);
112
124
  if (!skill) {
113
125
  throw new Error(`❌ Skill "${skillId}" not found, please verify the name`);
@@ -20,9 +20,7 @@ export class SubAgentsScopePlugin {
20
20
  }
21
21
  candidates() {
22
22
  return {
23
- subagents: this.subagents
24
- .filter((d) => d.function)
25
- .map((d) => d.function.name),
23
+ subagents: this.subagents.filter((d) => d.function).map((d) => d.function.name),
26
24
  };
27
25
  }
28
26
  instantiate(scope, filtered) {
@@ -217,14 +217,20 @@ function normalizeToolExport(exported, filepath, silent) {
217
217
  return target;
218
218
  }
219
219
  // 情况 3:{ function, exec } 格式 → 适配为 CallbackTool
220
- 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") {
221
224
  return new CallbackTool({
222
225
  function: target.function,
223
226
  callback: target.exec,
224
227
  });
225
228
  }
226
229
  // 情况 4:{ function, callback } 格式 → 适配为 CallbackTool
227
- 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") {
228
234
  return new CallbackTool({
229
235
  function: target.function,
230
236
  callback: target.callback,
@@ -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);
@@ -18,7 +18,9 @@
18
18
  * | 内联体积超过上限且无法上传 | 抛错(不静默塞进请求体) |
19
19
  */
20
20
  import type { AgentNS } from "@ai-zen/agents-core";
21
- import type { AppConfig, Endpoint, Model } from "../types/index.js";
21
+ import type { AppConfig, Endpoint, Model, ToolEnvDeps, UploadFn } from "../types/index.js";
22
+ /** 上传函数类型(定义在 types,此处再导出方便既有引用) */
23
+ export type { UploadFn };
22
24
  /** 扩展名 → MIME。图片走视觉通道,其余走 `file` 块 */
23
25
  export declare const MIME_BY_EXT: Record<string, string>;
24
26
  /** 按扩展名推断 MIME;未知扩展名返回 undefined */
@@ -51,13 +53,6 @@ export type FileSource = {
51
53
  mime: string;
52
54
  filename?: string;
53
55
  };
54
- /** Files API 上传函数签名(可注入,便于测试与替换实现) */
55
- export type UploadFn = (input: {
56
- endpoint: Endpoint;
57
- data: Uint8Array;
58
- filename: string;
59
- signal?: AbortSignal;
60
- }) => Promise<string>;
61
56
  export interface FileToSectionInput {
62
57
  source: FileSource;
63
58
  /** 当前模型所用端点:决定能否走 Files API */
@@ -67,10 +62,8 @@ export interface FileToSectionInput {
67
62
  signal?: AbortSignal;
68
63
  /** 覆盖内联体积上限 */
69
64
  maxInlineBytes?: number;
70
- /** 依赖注入(测试用),默认走 OpenAI SDK 的 Files API */
71
- deps?: {
72
- upload?: UploadFn;
73
- };
65
+ /** 依赖注入(测试 / 宿主用),缺省走 OpenAI SDK 的 Files API */
66
+ deps?: ToolEnvDeps;
74
67
  }
75
68
  export interface FileToSectionResult {
76
69
  section: AgentNS.MessageContentSection;
@@ -68,7 +68,7 @@ export const DEFAULT_MAX_INLINE_BYTES = 8 * 1024 * 1024;
68
68
  export function resolveModelAndEndpoint(config, apiModelName) {
69
69
  const models = config.models ?? [];
70
70
  const endpoints = config.endpoints ?? [];
71
- const findEndpoint = (id) => (id ? endpoints.find((e) => e.id === id) ?? null : null);
71
+ const findEndpoint = (id) => (id ? (endpoints.find((e) => e.id === id) ?? null) : null);
72
72
  const byApiName = apiModelName
73
73
  ? models.find((m) => (m.modelName ?? m.id) === apiModelName)
74
74
  : undefined;
@@ -222,6 +222,52 @@ export interface AppConfig {
222
222
  */
223
223
  abortedToolRoundStrategy?: AbortedToolRoundStrategy;
224
224
  }
225
+ /**
226
+ * Files API 上传函数签名(默认实现走 OpenAI SDK 的 `POST {baseUrl}/files`)。
227
+ *
228
+ * 出网动作做成可注入的依赖,而不是让测试去 mock `openai` 模块:模块级 mock 在
229
+ * `isolate: false` 的共享模块图里会因加载顺序失效(谁先把真实 SDK 拉进缓存,
230
+ * 后注册的 mock 就再也不生效)。
231
+ */
232
+ export type UploadFn = (input: {
233
+ endpoint: Endpoint;
234
+ data: Uint8Array;
235
+ filename: string;
236
+ signal?: AbortSignal;
237
+ }) => Promise<string>;
238
+ /** 图片生成函数签名(默认实现走 OpenAI SDK 的 `images.generate`) */
239
+ export type GenerateImageFn = (input: {
240
+ endpoint: Endpoint;
241
+ /** 发给端点的图片模型名(`ImageModel.modelName ?? id`) */
242
+ model: string;
243
+ prompt: string;
244
+ size?: string;
245
+ quality?: string;
246
+ signal?: AbortSignal;
247
+ }) => Promise<{
248
+ created?: number;
249
+ /**
250
+ * 端点返回的图片列表。二选一:
251
+ * - `url`:临时图片链接(多数厂商);
252
+ * - `b64_json`:base64 内联(部分模型只返回它),由工具落盘后给出本地路径。
253
+ */
254
+ data?: {
255
+ url?: string;
256
+ b64_json?: string;
257
+ }[];
258
+ }>;
259
+ /**
260
+ * 外部依赖注入点 — 所有出网动作的唯一出口。
261
+ *
262
+ * 缺省(不传)时全部走真实 OpenAI SDK;测试与宿主(CLI / Desktop)可按需替换,
263
+ * 这样业务代码里的网络调用不再需要 `vi.mock("openai")` 之类打穿模块图的技巧。
264
+ */
265
+ export interface ToolEnvDeps {
266
+ /** 上传文件到端点 Files API,默认 `POST {baseUrl}/files`(purpose=user_data) */
267
+ upload?: UploadFn;
268
+ /** 调用端点生成图片,默认 `client.images.generate` */
269
+ generateImage?: GenerateImageFn;
270
+ }
225
271
  /**
226
272
  * 工具环境 — Scope 的能力插件在实例化内置工具时注入的环境信息。
227
273
  *
@@ -233,6 +279,8 @@ export interface ToolEnv {
233
279
  cwd: string;
234
280
  /** 应用配置 */
235
281
  config: AppConfig;
282
+ /** 外部依赖注入点(默认全部走真实 OpenAI SDK) */
283
+ deps?: ToolEnvDeps;
236
284
  }
237
285
  /** MCP 连接状态 */
238
286
  export type McpConnectionState = "disconnected" | "connecting" | "connected" | "error";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-zen/agents-sdk",
3
- "version": "1.0.0-alpha.24",
3
+ "version": "1.0.0-alpha.26",
4
4
  "description": "AI-Zen Agents SDK — shared business logic for CLI and Desktop",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -25,7 +25,7 @@
25
25
  "author": "LZQCN",
26
26
  "license": "MIT",
27
27
  "dependencies": {
28
- "@ai-zen/agents-core": "^4.5.3",
28
+ "@ai-zen/agents-core": "^4.5.4",
29
29
  "@modelcontextprotocol/sdk": "^1.29.0",
30
30
  "dayjs": "^1.11.21",
31
31
  "openai": "^7.5.0"
@@ -35,7 +35,7 @@
35
35
  "dotenv": "^17.4.2",
36
36
  "prettier": "^3.9.5",
37
37
  "rimraf": "^6.0.0",
38
- "typescript": "^5.3.3",
38
+ "typescript": "^7.0.2",
39
39
  "vitest": "^4.1.9"
40
40
  },
41
41
  "files": [
@@ -48,10 +48,9 @@
48
48
  "build": "tsc",
49
49
  "format": "prettier --write .",
50
50
  "format:check": "prettier --check .",
51
- "pretest": "tsc --noEmit",
51
+ "pretest": "tsc --noEmit -p tsconfig.test.json",
52
52
  "test": "vitest run",
53
- "test:integration": "npm run pretest && vitest run --config vitest.integration.config.ts",
54
53
  "test:e2e": "npm run pretest && vitest run --config vitest.e2e.config.ts",
55
- "test:all": "npm run pretest && vitest run && vitest run --config vitest.integration.config.ts && vitest run --config vitest.e2e.config.ts"
54
+ "test:all": "npm run pretest && vitest run && npm run build && vitest run --config vitest.e2e.config.ts"
56
55
  }
57
56
  }