@ai-zen/agents-sdk 1.2.0-alpha.2 → 2.0.0-alpha.1

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 (131) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +397 -113
  3. package/README.zh.md +314 -112
  4. package/dist/agent-plugins/AssetTransportPlugin.d.ts +51 -0
  5. package/dist/agent-plugins/AssetTransportPlugin.js +145 -0
  6. package/dist/agent-plugins/AutoMigratePlugin.d.ts +56 -6
  7. package/dist/agent-plugins/AutoMigratePlugin.js +64 -15
  8. package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +12 -9
  9. package/dist/agent-plugins/AutoRefreshToolsPlugin.js +6 -7
  10. package/dist/agent-plugins/ContextGuardPlugin.d.ts +32 -24
  11. package/dist/agent-plugins/ContextGuardPlugin.js +37 -22
  12. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +38 -46
  13. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +37 -50
  14. package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +15 -1
  15. package/dist/agent-plugins/UnknownToolHintPlugin.js +15 -1
  16. package/dist/config/ConfigManager.d.ts +13 -5
  17. package/dist/config/ConfigManager.js +58 -39
  18. package/dist/config/constants.d.ts +1 -1
  19. package/dist/config/constants.js +2 -2
  20. package/dist/config/factory-skills.js +2 -2
  21. package/dist/config/normalize.d.ts +93 -0
  22. package/dist/config/normalize.js +158 -0
  23. package/dist/crud/AgentRepository.d.ts +3 -1
  24. package/dist/crud/AgentRepository.js +4 -2
  25. package/dist/index.d.ts +22 -9
  26. package/dist/index.js +16 -6
  27. package/dist/runtime/AgentRuntime.d.ts +293 -0
  28. package/dist/runtime/AgentRuntime.js +457 -0
  29. package/dist/runtime/HandoffGuardPlugin.d.ts +85 -16
  30. package/dist/runtime/HandoffGuardPlugin.js +140 -19
  31. package/dist/runtime/HandoffService.d.ts +255 -91
  32. package/dist/runtime/HandoffService.js +392 -177
  33. package/dist/runtime/RuntimePeerSessions.d.ts +34 -0
  34. package/dist/runtime/RuntimePeerSessions.js +50 -0
  35. package/dist/runtime/Scopes.d.ts +123 -0
  36. package/dist/runtime/Scopes.js +169 -0
  37. package/dist/runtime/SdkAgent.d.ts +21 -11
  38. package/dist/runtime/SdkAgent.js +24 -8
  39. package/dist/runtime/completeOnce.d.ts +3 -3
  40. package/dist/runtime/completeOnce.js +3 -3
  41. package/dist/runtime/createAgent.d.ts +29 -7
  42. package/dist/runtime/createAgent.js +57 -12
  43. package/dist/runtime/createModel.d.ts +4 -4
  44. package/dist/runtime/createModel.js +6 -6
  45. package/dist/runtime/lastPromptTokens.d.ts +18 -0
  46. package/dist/runtime/lastPromptTokens.js +26 -0
  47. package/dist/runtime/resolveModel.d.ts +9 -9
  48. package/dist/runtime/resolveModel.js +8 -8
  49. package/dist/scope/Scope.d.ts +42 -14
  50. package/dist/scope/Scope.js +55 -16
  51. package/dist/scope/ScopePlugin.d.ts +2 -8
  52. package/dist/scope/disclosure.d.ts +1 -1
  53. package/dist/scope/disclosure.js +1 -1
  54. package/dist/scope/plugins/allInOne.d.ts +13 -1
  55. package/dist/scope/plugins/allInOne.js +9 -5
  56. package/dist/scope/plugins/builtin/AsyncExecTool.d.ts +12 -0
  57. package/dist/scope/plugins/builtin/AsyncExecTool.js +103 -0
  58. package/dist/scope/plugins/builtin/AsyncTimeoutTool.d.ts +10 -0
  59. package/dist/scope/plugins/builtin/AsyncTimeoutTool.js +90 -0
  60. package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.d.ts +1 -1
  61. package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.js +1 -1
  62. package/dist/scope/plugins/builtin/DownloadFileTool.js +1 -1
  63. package/dist/scope/plugins/builtin/ExecTool.js +10 -199
  64. package/dist/scope/plugins/builtin/FindTextTool.d.ts +1 -1
  65. package/dist/scope/plugins/builtin/FindTextTool.js +1 -1
  66. package/dist/scope/plugins/builtin/GenerateImageTool.d.ts +1 -4
  67. package/dist/scope/plugins/builtin/GenerateImageTool.js +2 -8
  68. package/dist/scope/plugins/builtin/InspectFileTool.js +1 -1
  69. package/dist/scope/plugins/builtin/SdkCallbackTool.d.ts +4 -4
  70. package/dist/scope/plugins/builtin/SdkCallbackTool.js +3 -3
  71. package/dist/scope/plugins/builtin/SleepTool.js +2 -3
  72. package/dist/scope/plugins/builtin/ViewImageTool.d.ts +2 -4
  73. package/dist/scope/plugins/builtin/ViewImageTool.js +4 -6
  74. package/dist/scope/plugins/builtin/WriteTool.d.ts +7 -0
  75. package/dist/scope/plugins/builtin/WriteTool.js +8 -1
  76. package/dist/scope/plugins/builtin/asyncTasks.d.ts +41 -0
  77. package/dist/scope/plugins/builtin/asyncTasks.js +97 -0
  78. package/dist/scope/plugins/builtin/commandOutput.d.ts +22 -0
  79. package/dist/scope/plugins/builtin/commandOutput.js +55 -0
  80. package/dist/scope/plugins/builtin/commandRun.d.ts +48 -0
  81. package/dist/scope/plugins/builtin/commandRun.js +169 -0
  82. package/dist/scope/plugins/builtin/discover.d.ts +1 -3
  83. package/dist/scope/plugins/builtin/discover.js +1 -3
  84. package/dist/scope/plugins/builtin/index.d.ts +5 -7
  85. package/dist/scope/plugins/builtin/index.js +7 -7
  86. package/dist/scope/plugins/builtin/outputGuard.d.ts +1 -5
  87. package/dist/scope/plugins/builtin/outputGuard.js +1 -5
  88. package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +61 -9
  89. package/dist/scope/plugins/mcp/McpConnectionManager.js +174 -72
  90. package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +37 -4
  91. package/dist/scope/plugins/mcp/McpScopePlugin.js +100 -9
  92. package/dist/scope/plugins/mcp/discover.d.ts +9 -2
  93. package/dist/scope/plugins/mcp/discover.js +12 -14
  94. package/dist/scope/plugins/mcp/mcpTaskNotice.d.ts +52 -0
  95. package/dist/scope/plugins/mcp/mcpTaskNotice.js +8 -0
  96. package/dist/scope/plugins/mcp/mcpTools.d.ts +20 -2
  97. package/dist/scope/plugins/mcp/mcpTools.js +220 -39
  98. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.d.ts +25 -0
  99. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +32 -0
  100. package/dist/scope/plugins/peers/peerSessionTools.d.ts +173 -0
  101. package/dist/scope/plugins/peers/peerSessionTools.js +292 -0
  102. package/dist/scope/plugins/skills/SkillsScopePlugin.d.ts +4 -0
  103. package/dist/scope/plugins/skills/SkillsScopePlugin.js +10 -4
  104. package/dist/scope/plugins/skills/discover.d.ts +15 -8
  105. package/dist/scope/plugins/skills/discover.js +15 -26
  106. package/dist/scope/plugins/skills/skillTools.d.ts +9 -8
  107. package/dist/scope/plugins/skills/skillTools.js +21 -13
  108. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.d.ts +4 -0
  109. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +4 -1
  110. package/dist/scope/plugins/subagents/discover.d.ts +7 -1
  111. package/dist/scope/plugins/subagents/discover.js +7 -3
  112. package/dist/scope/plugins/subagents/subAgentTools.d.ts +0 -1
  113. package/dist/scope/plugins/subagents/subAgentTools.js +14 -1
  114. package/dist/scope/plugins/usertools/UserToolsScopePlugin.d.ts +4 -0
  115. package/dist/scope/plugins/usertools/UserToolsScopePlugin.js +4 -1
  116. package/dist/scope/plugins/usertools/discover.d.ts +7 -8
  117. package/dist/scope/plugins/usertools/discover.js +17 -27
  118. package/dist/shared/EntityRepository.d.ts +22 -5
  119. package/dist/shared/EntityRepository.js +45 -29
  120. package/dist/shared/content-blocks.d.ts +9 -3
  121. package/dist/shared/content-blocks.js +12 -19
  122. package/dist/shared/errors.d.ts +8 -3
  123. package/dist/shared/errors.js +9 -4
  124. package/dist/shared/logger.d.ts +21 -10
  125. package/dist/shared/logger.js +9 -15
  126. package/dist/types/index.d.ts +38 -13
  127. package/package.json +2 -2
  128. package/dist/config/migrate.d.ts +0 -115
  129. package/dist/config/migrate.js +0 -200
  130. package/dist/scope/plugins/builtin/test-helpers.d.ts +0 -3
  131. package/dist/scope/plugins/builtin/test-helpers.js +0 -4
@@ -1,7 +1,13 @@
1
1
  import type { AgentDefinition } from "../../../types/index.js";
2
+ import { type LogSink } from "../../../shared/logger.js";
3
+ /** 发现 SubAgent 时的选项 */
4
+ export interface DiscoverSubAgentsOptions {
5
+ /** 日志口(可选):有文件读不出来、被跳过时报一句;不注入就不记(库缺省沉默) */
6
+ logger?: LogSink;
7
+ }
2
8
  /**
3
9
  * 扫描多个目录中发现的所有 SubAgent 完整定义。
4
10
  * 按优先级从高到低传入路径列表,同名 function.name 靠前的路径优先(先到先得)。
5
11
  * 跳过无 function 的普通 Agent 和解析失败的文件。
6
12
  */
7
- export declare function discoverSubAgents(paths: string[]): Promise<AgentDefinition[]>;
13
+ export declare function discoverSubAgents(paths: string[], options?: DiscoverSubAgentsOptions): Promise<AgentDefinition[]>;
@@ -1,11 +1,13 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { SILENT_LOG } from "../../../shared/logger.js";
3
4
  /**
4
5
  * 扫描多个目录中发现的所有 SubAgent 完整定义。
5
6
  * 按优先级从高到低传入路径列表,同名 function.name 靠前的路径优先(先到先得)。
6
7
  * 跳过无 function 的普通 Agent 和解析失败的文件。
7
8
  */
8
- export async function discoverSubAgents(paths) {
9
+ export async function discoverSubAgents(paths, options = {}) {
10
+ const logger = options.logger ?? SILENT_LOG;
9
11
  const seen = new Set();
10
12
  const agents = [];
11
13
  for (const dir of paths) {
@@ -35,8 +37,10 @@ export async function discoverSubAgents(paths) {
35
37
  }
36
38
  }
37
39
  }
38
- catch {
39
- // 跳过解析失败的文件
40
+ catch (error) {
41
+ // 跳过坏文件是对的(一个坏文件不该让整张 SubAgent 列表读不出来),但要留一行:
42
+ // 文件读不出来是个事实,静默跳过会让配置看着像生效了
43
+ logger.warn(`[subagents] ${join(dir, file)} 读不出来或不是合法定义,跳过:${String(error)}`);
40
44
  }
41
45
  }
42
46
  }
@@ -5,6 +5,5 @@ import type { Scope } from "../../Scope.js";
5
5
  * 创建 SubAgent 工具(AgentToolLazy)。
6
6
  *
7
7
  * SubAgent 是有 `function` 字段的 Agent,可被其他 Agent 作为工具调用。
8
- * 使用延迟构建(AgentToolLazy)避免工具列表构建阶段的递归创建问题。
9
8
  */
10
9
  export declare function createSubAgentTool(def: AgentDefinition, scope: Scope): Tool;
@@ -1,10 +1,11 @@
1
1
  import { Agent, AgentToolLazy } from "@ai-zen/agents-core";
2
2
  import { createModel } from "../../../runtime/createModel.js";
3
+ import { PEER_SESSION_TOOL_NAMES } from "../peers/peerSessionTools.js";
4
+ import { ASYNC_TASK_TOOL_NAMES } from "../builtin/asyncTasks.js";
3
5
  /**
4
6
  * 创建 SubAgent 工具(AgentToolLazy)。
5
7
  *
6
8
  * SubAgent 是有 `function` 字段的 Agent,可被其他 Agent 作为工具调用。
7
- * 使用延迟构建(AgentToolLazy)避免工具列表构建阶段的递归创建问题。
8
9
  */
9
10
  export function createSubAgentTool(def, scope) {
10
11
  if (!def.function) {
@@ -43,6 +44,15 @@ export function createSubAgentTool(def, scope) {
43
44
  const subFiltered = scope.filter(def, {
44
45
  exclude: {
45
46
  subagents: def.function?.name ? [def.function.name] : undefined,
47
+ // 平级会话那三个工具是会话级能力,被派出去的执行体手上不该有:它不属于任何一段
48
+ // 会话 —— 没有可以署名的身份(发话要写「来自哪一段会话」),也开不出有人认领的新
49
+ // 会话,所以这三个工具在它手上只有必错的路(发话在端口层直接抛,创建被判
50
+ // depth_exceeded)。取 exclude 而不动定义里的 permissions:定义文件是用户可编辑的
51
+ // 配置,这条规矩不长在那儿;而 filter 先按 exclude 剔除、再按权限过滤,定义写
52
+ // `allow: ["*"]` 也照样剔得掉。
53
+ //
54
+ // 两个后台工具同理:被派出去的是个一次性执行体,结果回来时它的调用栈已经退了。
55
+ tools: [...PEER_SESSION_TOOL_NAMES, ...ASYNC_TASK_TOOL_NAMES],
46
56
  },
47
57
  });
48
58
  const tools = scope.instantiate(subFiltered);
@@ -51,6 +61,9 @@ export function createSubAgentTool(def, scope) {
51
61
  model,
52
62
  modelConfig,
53
63
  tools,
64
+ // 委派就是「干一件已经看得见结果的活」:`buildAgent` 造出来的必须是**一次性**
65
+ // (`CORE.md` §9)。常驻子节点不能走这条路 —— 它得有人给它定地址、有人负责 stop。
66
+ lifetime: "one-shot",
54
67
  });
55
68
  return subAgent;
56
69
  },
@@ -1,5 +1,6 @@
1
1
  import type { Tool } from "@ai-zen/agents-core";
2
2
  import type { AgentDefinition } from "../../../types/index.js";
3
+ import type { LogSink } from "../../../shared/logger.js";
3
4
  import type { Scope, FilterOutput } from "../../Scope.js";
4
5
  import type { ScopeCandidates, ScopePlugin } from "../../ScopePlugin.js";
5
6
  /**
@@ -13,8 +14,11 @@ export declare class UserToolsScopePlugin implements ScopePlugin {
13
14
  readonly id = "user-tools";
14
15
  private readonly paths;
15
16
  private tools;
17
+ /** 日志口(可选):某个文件被拒了报一句;不注入就不记 */
18
+ private readonly logger?;
16
19
  constructor(options?: {
17
20
  paths?: string[];
21
+ logger?: LogSink;
18
22
  });
19
23
  discover(scope: Scope, options?: {
20
24
  silent?: boolean;
@@ -11,12 +11,15 @@ export class UserToolsScopePlugin {
11
11
  id = UserToolsScopePlugin.ID;
12
12
  paths;
13
13
  tools = [];
14
+ /** 日志口(可选):某个文件被拒了报一句;不注入就不记 */
15
+ logger;
14
16
  constructor(options) {
15
17
  this.paths = options?.paths ?? [];
18
+ this.logger = options?.logger;
16
19
  }
17
20
  async discover(scope, options) {
18
21
  const dirs = this.paths.map((p) => (isAbsolute(p) ? p : join(scope.cwd, p)));
19
- this.tools = await discoverUserTools(dirs, options);
22
+ this.tools = await discoverUserTools(dirs, { silent: options?.silent, logger: this.logger });
20
23
  }
21
24
  candidates(_scope, _definition) {
22
25
  return { tools: this.tools.map((t) => t.function.name) };
@@ -1,8 +1,11 @@
1
1
  import { Tool } from "@ai-zen/agents-core";
2
+ import { type LogSink } from "../../../shared/logger.js";
2
3
  /** 单个用户工具文件的加载参数 */
3
4
  export interface DiscoverUserToolsOptions {
4
5
  /** 静默:不写日志(测试 / 批量探测用) */
5
6
  silent?: boolean;
7
+ /** 日志口(可选):某个文件被拒了从它报一句;不注入就不记(库缺省沉默) */
8
+ logger?: LogSink;
6
9
  /** 单文件 import 的超时(毫秒),默认 {@link DEFAULT_IMPORT_TIMEOUT_MS};`0` 表示不限 */
7
10
  importTimeoutMs?: number;
8
11
  }
@@ -10,8 +13,8 @@ export interface DiscoverUserToolsOptions {
10
13
  * 一个用户工具文件(加载成功的那一个):文件身份 + 加载出来的实例。
11
14
  *
12
15
  * 为什么要成对给:`Tool` 自己不记「我是从哪个文件来的」(它只是 core 的一个工具对象),
13
- * 而 `asset.list` 那类「把发现结果报给客户端看」的调用方需要的正是**文件**(路径、
14
- * 文件名)。让调用方拿着工具名去某个目录里找同名文件,就是第二套扫描规则。
16
+ * 而把发现结果报给上层的调用方(宿主 `DiscoveryService` 列配置层)需要的正是**文件**。
17
+ * 让调用方拿着工具名去某个目录里找同名文件,就是第二套扫描规则。
15
18
  */
16
19
  export interface UserToolFile {
17
20
  /** 文件名(不含扩展名):同一条扫描里的唯一键,也是发现顺序的依据 */
@@ -22,20 +25,16 @@ export interface UserToolFile {
22
25
  }
23
26
  /**
24
27
  * 扫描多个 tools/ 目录,发现所有 .js / .mjs 文件,动态加载为 Tool 实例。
25
- * 使用原生 dynamic import() 加载(在 "type": "module" 下 .js 也是 ESM),
26
- * 每次添加时间戳 querystring 防止缓存。
27
28
  *
28
29
  * 按优先级从高到低传入路径列表,同名工具靠前的路径优先(先到先得)。
29
30
  * 按文件名排序以保证确定性。
30
31
  *
31
- * 本体在 {@link discoverUserToolFiles}:两个出口共用同一条扫描规则(顺序、去重、导入护栏、
32
- * 超时都在那一处),否则「Agent 装了哪些工具」与「资产清单里列了哪些」迟早对不上。
32
+ * 本体在 {@link discoverUserToolFiles},这里只是取出 `tool`。
33
33
  */
34
34
  export declare function discoverUserTools(paths: string[], options?: DiscoverUserToolsOptions): Promise<Tool[]>;
35
35
  /**
36
36
  * 同 {@link discoverUserTools},但把**文件**也一起交出来(路径 / 文件名)。
37
37
  *
38
- * 发现规则只有一份:目录顺序、同名去重、扩展名、导入护栏、超时全部写在本函数里,
39
- * 另一个出口只是上面的 `map`。
38
+ * 扫描规则只写在本函数里,另一个出口只是上面的 `map`。
40
39
  */
41
40
  export declare function discoverUserToolFiles(paths: string[], options?: DiscoverUserToolsOptions): Promise<UserToolFile[]>;
@@ -2,8 +2,8 @@ import { promises as fs } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { Tool, CallbackTool } from "@ai-zen/agents-core";
5
- import { getLogger } from "../../../shared/logger.js";
6
- /** 默认的单文件 import 超时:工具目录里不该有需要长过它的模块求值 */
5
+ import { SILENT_LOG } from "../../../shared/logger.js";
6
+ /** 默认的单文件 import 超时(毫秒) */
7
7
  const DEFAULT_IMPORT_TIMEOUT_MS = 5000;
8
8
  // ==================================================================
9
9
  // 宿主护栏
@@ -20,11 +20,9 @@ const DEFAULT_IMPORT_TIMEOUT_MS = 5000;
20
20
  // · `console.log / info / debug` → 改指 stderr,不撕宿主的 stdout(TUI 画面);
21
21
  // · 顶层 await 永不 settle(异步挂死)→ 超时放弃该文件。
22
22
  //
23
- // **挡不住**的(只有进程隔离能解,而那正是 MCP 的职责):
23
+ // **挡不住**的(只有进程隔离能解,那正是 MCP 的职责):
24
24
  // · 顶层同步死循环——事件循环被占,连超时定时器都不会跑;
25
25
  // · `process.kill(process.pid)` 这类原生自杀。
26
- //
27
- // 所以 tools/ 的定位是**可信的本地扩展**;不可信的代码请写成 MCP 服务器。
28
26
  /** 正在被 import 的文件(护栏回报错误时用它定位) */
29
27
  let importingFile = null;
30
28
  /** 用户文件里调 `process.exit()` / `process.abort()` 时抛这个 —— 落进 loadToolFile 的 catch */
@@ -88,7 +86,7 @@ function installHostGuards() {
88
86
  * `import()` + 超时。
89
87
  *
90
88
  * 超时只是「不再等它」:ESM 求值**不可取消**,该模块随后仍可能被求值完并产生副作用,
91
- * 因此超时只记告警、不声称已终止。真正的隔离需要独立进程(即 MCP)。
89
+ * 因此超时只记告警、不声称已终止。
92
90
  */
93
91
  async function importWithTimeout(url, timeoutMs) {
94
92
  if (timeoutMs <= 0)
@@ -105,21 +103,18 @@ async function importWithTimeout(url, timeoutMs) {
105
103
  clearTimeout(timer);
106
104
  }
107
105
  }
108
- /** 「这个文件被拒了」的出口:只走 logger,怎么展示是宿主的事 */
106
+ /** 「这个文件被拒了」的出口:只走注入进来的日志,怎么展示是宿主的事 */
109
107
  function reportReject(file, reason, opts, level = "warn") {
110
108
  if (!opts.silent)
111
- getLogger()[level](`[usertools] ${file} — ${reason}`);
109
+ (opts.logger ?? SILENT_LOG)[level](`[usertools] ${file} — ${reason}`);
112
110
  }
113
111
  /**
114
112
  * 扫描多个 tools/ 目录,发现所有 .js / .mjs 文件,动态加载为 Tool 实例。
115
- * 使用原生 dynamic import() 加载(在 "type": "module" 下 .js 也是 ESM),
116
- * 每次添加时间戳 querystring 防止缓存。
117
113
  *
118
114
  * 按优先级从高到低传入路径列表,同名工具靠前的路径优先(先到先得)。
119
115
  * 按文件名排序以保证确定性。
120
116
  *
121
- * 本体在 {@link discoverUserToolFiles}:两个出口共用同一条扫描规则(顺序、去重、导入护栏、
122
- * 超时都在那一处),否则「Agent 装了哪些工具」与「资产清单里列了哪些」迟早对不上。
117
+ * 本体在 {@link discoverUserToolFiles},这里只是取出 `tool`。
123
118
  */
124
119
  export async function discoverUserTools(paths, options = {}) {
125
120
  return (await discoverUserToolFiles(paths, options)).map((item) => item.tool);
@@ -127,8 +122,7 @@ export async function discoverUserTools(paths, options = {}) {
127
122
  /**
128
123
  * 同 {@link discoverUserTools},但把**文件**也一起交出来(路径 / 文件名)。
129
124
  *
130
- * 发现规则只有一份:目录顺序、同名去重、扩展名、导入护栏、超时全部写在本函数里,
131
- * 另一个出口只是上面的 `map`。
125
+ * 扫描规则只写在本函数里,另一个出口只是上面的 `map`。
132
126
  */
133
127
  export async function discoverUserToolFiles(paths, options = {}) {
134
128
  const seen = new Set();
@@ -153,14 +147,10 @@ export async function discoverUserToolFiles(paths, options = {}) {
153
147
  if (!seen.has(name)) {
154
148
  seen.add(name);
155
149
  const path = join(dir, name + ext);
156
- try {
157
- const tool = await loadToolFile(path, options);
158
- if (tool) {
159
- items.push({ name, path, tool });
160
- }
161
- }
162
- catch {
163
- // 跳过加载失败的文件
150
+ // 不必再包一层:`loadToolFile()` 自己 catch-all,加载失败会走 `reportReject` 上报并回 null
151
+ const tool = await loadToolFile(path, options);
152
+ if (tool) {
153
+ items.push({ name, path, tool });
164
154
  }
165
155
  }
166
156
  }
@@ -196,12 +186,12 @@ async function loadToolFile(filepath, opts) {
196
186
  try {
197
187
  const url = `${pathToFileURL(filepath).href}?t=${Date.now()}`;
198
188
  const mod = (await importWithTimeout(url, opts.importTimeoutMs ?? DEFAULT_IMPORT_TIMEOUT_MS));
199
- // import() 返回模块命名空间对象,取其 default 导出
189
+ // import() 返回模块命名空间对象,优先取 default 导出;没有 default 时整个命名空间当导出
200
190
  const exported = mod.default ?? mod;
201
191
  if (!exported || (typeof exported === "object" && Object.keys(exported).length === 0)) {
202
192
  return null;
203
193
  }
204
- return normalizeToolExport({ default: exported }, filepath, opts.silent);
194
+ return normalizeToolExport({ default: exported }, filepath, opts);
205
195
  }
206
196
  catch (err) {
207
197
  reportReject(filepath, `failed to load — ${err?.message ?? err}`, opts, "error");
@@ -218,7 +208,7 @@ async function loadToolFile(filepath, opts) {
218
208
  /**
219
209
  * 统一各种导出格式为 Tool 实例。
220
210
  */
221
- function normalizeToolExport(exported, filepath, silent) {
211
+ function normalizeToolExport(exported, filepath, opts = {}) {
222
212
  // 情况 1:直接是 Tool 实例
223
213
  if (exported instanceof Tool) {
224
214
  return exported;
@@ -248,8 +238,8 @@ function normalizeToolExport(exported, filepath, silent) {
248
238
  callback: target.callback,
249
239
  });
250
240
  }
251
- if (!silent) {
252
- getLogger().error(`[usertools] Unrecognized tool format: ${filepath}`);
241
+ if (!opts.silent) {
242
+ (opts.logger ?? SILENT_LOG).error(`[usertools] Unrecognized tool format: ${filepath}`);
253
243
  }
254
244
  return null;
255
245
  }
@@ -1,16 +1,23 @@
1
+ import { type LogSink } from "./logger.js";
1
2
  /**
2
3
  * 通用实体仓储 — 对磁盘 JSON 文件的 CRUD 操作。
3
4
  *
4
5
  * 约定:
5
6
  * - 每个实体一个 JSON 文件,文件名 = `${id}.json`
6
7
  * - 目录不存在时自动创建
7
- * - 解析失败的文件会被跳过(list 时)
8
+ * - `read()` 只把「文件不在」答成 `null`;文件在但读不出来(不是 JSON、没权限)照抛
9
+ * - `list()` 跳过读不出来的那**一条**并报一句
8
10
  */
9
11
  export declare class EntityRepository<T extends {
10
12
  id: string;
11
13
  }> {
12
14
  private dir;
13
- constructor(dir: string);
15
+ protected readonly logger: LogSink;
16
+ /**
17
+ * @param dir 实体目录
18
+ * @param logger 日志口(可选):`list()` 跳过读不出来的那一条时从它报一句。缺省 `SILENT_LOG`
19
+ */
20
+ constructor(dir: string, logger?: LogSink);
14
21
  /**
15
22
  * 获取实体的文件路径;`id` 必须落在本仓储目录内,否则抛错。
16
23
  *
@@ -22,12 +29,22 @@ export declare class EntityRepository<T extends {
22
29
  * - 比较 `root + sep` 而不是裸 `startsWith(root)`:`<root>-evil/x` 也以 `<root>` 开头。
23
30
  */
24
31
  protected path(id: string): string;
25
- /** 列出目录下所有实体(跳过解析失败的文件) */
32
+ /**
33
+ * 列出目录下所有实体。
34
+ *
35
+ * 一个坏文件只影响它自己那一行(宿主的「这个模型被哪个助手引用」读的是整张表),所以
36
+ * 这里接住并报一句:跳过的是这一条,不是整张表。
37
+ */
26
38
  list(): Promise<T[]>;
27
- /** 读取单个实体,不存在返回 null */
39
+ /**
40
+ * 读取单个实体:**只有文件不在才回 `null`**。
41
+ *
42
+ * 「没有这一条」与「这一条坏了」(不是 JSON、EACCES、EIO)是两个答案。折叠成一个 `null`
43
+ * 会让读者对坏文件说假话。要把它当成「没有」的调用方自己接住,并在那一处写明为什么。
44
+ */
28
45
  read(id: string): Promise<T | null>;
29
46
  /** 写入实体(创建或更新) */
30
47
  write(entity: T): Promise<void>;
31
- /** 删除实体,不存在时不抛异常 */
48
+ /** 删除实体;本来就不存在算成功,删不掉(权限等)照抛 */
32
49
  delete(id: string): Promise<void>;
33
50
  }
@@ -1,17 +1,25 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import { resolve, sep } from "node:path";
3
+ import { SILENT_LOG } from "./logger.js";
3
4
  /**
4
5
  * 通用实体仓储 — 对磁盘 JSON 文件的 CRUD 操作。
5
6
  *
6
7
  * 约定:
7
8
  * - 每个实体一个 JSON 文件,文件名 = `${id}.json`
8
9
  * - 目录不存在时自动创建
9
- * - 解析失败的文件会被跳过(list 时)
10
+ * - `read()` 只把「文件不在」答成 `null`;文件在但读不出来(不是 JSON、没权限)照抛
11
+ * - `list()` 跳过读不出来的那**一条**并报一句
10
12
  */
11
13
  export class EntityRepository {
12
14
  dir;
13
- constructor(dir) {
15
+ logger;
16
+ /**
17
+ * @param dir 实体目录
18
+ * @param logger 日志口(可选):`list()` 跳过读不出来的那一条时从它报一句。缺省 `SILENT_LOG`
19
+ */
20
+ constructor(dir, logger = SILENT_LOG) {
14
21
  this.dir = dir;
22
+ this.logger = logger;
15
23
  }
16
24
  /**
17
25
  * 获取实体的文件路径;`id` 必须落在本仓储目录内,否则抛错。
@@ -31,7 +39,12 @@ export class EntityRepository {
31
39
  }
32
40
  return target;
33
41
  }
34
- /** 列出目录下所有实体(跳过解析失败的文件) */
42
+ /**
43
+ * 列出目录下所有实体。
44
+ *
45
+ * 一个坏文件只影响它自己那一行(宿主的「这个模型被哪个助手引用」读的是整张表),所以
46
+ * 这里接住并报一句:跳过的是这一条,不是整张表。
47
+ */
35
48
  async list() {
36
49
  try {
37
50
  await fs.access(this.dir);
@@ -43,48 +56,51 @@ export class EntityRepository {
43
56
  const ids = entries.filter((f) => f.endsWith(".json")).map((f) => f.replace(/\.json$/, ""));
44
57
  const entities = [];
45
58
  for (const id of ids) {
46
- const entity = await this.read(id);
47
- if (entity)
48
- entities.push(entity);
59
+ try {
60
+ const entity = await this.read(id);
61
+ if (entity !== null)
62
+ entities.push(entity);
63
+ }
64
+ catch (error) {
65
+ this.logger.warn(`[entity] 读不出来,列表里跳过这一条:${this.path(id)}(${String(error)})`);
66
+ }
49
67
  }
50
68
  return entities;
51
69
  }
52
- /** 读取单个实体,不存在返回 null */
70
+ /**
71
+ * 读取单个实体:**只有文件不在才回 `null`**。
72
+ *
73
+ * 「没有这一条」与「这一条坏了」(不是 JSON、EACCES、EIO)是两个答案。折叠成一个 `null`
74
+ * 会让读者对坏文件说假话。要把它当成「没有」的调用方自己接住,并在那一处写明为什么。
75
+ */
53
76
  async read(id) {
77
+ // `path()` 留在 try 外面:id 逃出目录是调用方的错,该抛,不该被当成「没有这一条」
54
78
  const p = this.path(id);
55
79
  try {
56
- await fs.access(p);
57
- }
58
- catch {
59
- return null;
60
- }
61
- try {
62
- const raw = await fs.readFile(p, "utf-8");
63
- return JSON.parse(raw);
80
+ return JSON.parse(await fs.readFile(p, "utf-8"));
64
81
  }
65
- catch {
66
- return null;
82
+ catch (error) {
83
+ if (error.code === "ENOENT")
84
+ return null;
85
+ throw error;
67
86
  }
68
87
  }
69
88
  /** 写入实体(创建或更新) */
70
89
  async write(entity) {
71
- try {
72
- await fs.access(this.dir);
73
- }
74
- catch {
75
- await fs.mkdir(this.dir, { recursive: true });
76
- }
90
+ // `mkdir(recursive)` 幂等,不必先探测目录在不在
91
+ await fs.mkdir(this.dir, { recursive: true });
77
92
  await fs.writeFile(this.path(entity.id), JSON.stringify(entity, null, 2), "utf-8");
78
93
  }
79
- /** 删除实体,不存在时不抛异常 */
94
+ /** 删除实体;本来就不存在算成功,删不掉(权限等)照抛 */
80
95
  async delete(id) {
81
- const p = this.path(id);
82
96
  try {
83
- await fs.access(p);
84
- await fs.unlink(p);
97
+ await fs.unlink(this.path(id));
85
98
  }
86
- catch {
87
- // 文件不存在,忽略
99
+ catch (error) {
100
+ // 只有 ENOENT 可以当「已经没有了」;EACCES / EPERM / EISDIR 必须报 ——
101
+ // 吞了它们,调用方会把「没删掉」当成「删掉了」(宿主那边就会回 `removed: true`)
102
+ if (error.code !== "ENOENT")
103
+ throw error;
88
104
  }
89
105
  }
90
106
  }
@@ -6,10 +6,10 @@
6
6
  * | 条件 | 结果 |
7
7
  * |------|------|
8
8
  * | http(s) URL | 直接 `image_url`(不上传、不内联) |
9
- * | 端点声明 `capabilities.filesApi` | 上传 Files API → `file` 块(`file_id`),失败降级为内联 |
9
+ * | 端点声明 `capabilities.filesApi` 且有 `apiKey` | 上传 Files API → `file` 块(`file_id`);上传失败即抛,不换传输方式 |
10
10
  * | 其余端点 + 图片 | `image_url` + base64 data URL |
11
11
  * | 其余端点 + 非图片 | `file` 块 + `file_data`(base64 data URL) |
12
- * | 模型明确不支持视觉(`vision === false`)且是图片 | 退化为 `text`,只给路径提示 |
12
+ * | 图片且模型不是视觉模型(`vision !== true`) | 退化为 `text`,只给路径提示 |
13
13
  * | 内联体积超过上限且无法上传 | 抛错(不静默塞进请求体) |
14
14
  *
15
15
  * 本模块只负责**选路**与**上传这一个 HTTP 动作**:需要 `file_id` 时每次调用都真上传,
@@ -69,7 +69,11 @@ export interface FileToSectionResult {
69
69
  transport: ContentTransport;
70
70
  /** 实际处理的字节数(URL 来源为 0) */
71
71
  bytes: number;
72
- /** 降级 / 退化时的人类可读说明,供上层拼提示 */
72
+ /**
73
+ * 退化为文本提示时的人类可读说明,供上层拼提示。
74
+ *
75
+ * 唯一产生者是下面「模型看不见图 → 退化为文本」那一支(上传失败直接抛错,不走这里)。
76
+ */
73
77
  warning?: string;
74
78
  }
75
79
  /**
@@ -93,6 +97,8 @@ export declare function contentHash(bytes: Uint8Array): string;
93
97
  * 抛错场景(均由调用方决定如何呈现给模型):
94
98
  * - `source.url` 不是 http(s)(本地 URL 服务商访问不到)
95
99
  * - 本地文件不存在 / 不是文件 / 扩展名不支持
100
+ * - 端点声明了 Files API 但上传失败(HTTP 非 2xx、网络错误、取消):不换成 base64 内联,
101
+ * 原错误原样抛——换传输方式是调用方该知道的事,不该在这里静默发生
96
102
  * - 需要内联但体积超过上限,且端点不支持上传
97
103
  */
98
104
  export declare function fileToContentSection(input: FileToSectionInput): Promise<FileToSectionResult>;
@@ -6,10 +6,10 @@
6
6
  * | 条件 | 结果 |
7
7
  * |------|------|
8
8
  * | http(s) URL | 直接 `image_url`(不上传、不内联) |
9
- * | 端点声明 `capabilities.filesApi` | 上传 Files API → `file` 块(`file_id`),失败降级为内联 |
9
+ * | 端点声明 `capabilities.filesApi` 且有 `apiKey` | 上传 Files API → `file` 块(`file_id`);上传失败即抛,不换传输方式 |
10
10
  * | 其余端点 + 图片 | `image_url` + base64 data URL |
11
11
  * | 其余端点 + 非图片 | `file` 块 + `file_data`(base64 data URL) |
12
- * | 模型明确不支持视觉(`vision === false`)且是图片 | 退化为 `text`,只给路径提示 |
12
+ * | 图片且模型不是视觉模型(`vision !== true`) | 退化为 `text`,只给路径提示 |
13
13
  * | 内联体积超过上限且无法上传 | 抛错(不静默塞进请求体) |
14
14
  *
15
15
  * 本模块只负责**选路**与**上传这一个 HTTP 动作**:需要 `file_id` 时每次调用都真上传,
@@ -125,6 +125,8 @@ function textSection(text) {
125
125
  * 抛错场景(均由调用方决定如何呈现给模型):
126
126
  * - `source.url` 不是 http(s)(本地 URL 服务商访问不到)
127
127
  * - 本地文件不存在 / 不是文件 / 扩展名不支持
128
+ * - 端点声明了 Files API 但上传失败(HTTP 非 2xx、网络错误、取消):不换成 base64 内联,
129
+ * 原错误原样抛——换传输方式是调用方该知道的事,不该在这里静默发生
128
130
  * - 需要内联但体积超过上限,且端点不支持上传
129
131
  */
130
132
  export async function fileToContentSection(input) {
@@ -196,23 +198,15 @@ export async function fileToContentSection(input) {
196
198
  warning: "The current model does not support image input; degraded to a text hint",
197
199
  };
198
200
  }
199
- // ---- 4. 端点支持 Files API:上传(每次调用都真上传),失败降级内联 ----
200
- let warning;
201
+ // ---- 4. 端点支持 Files API:上传(每次调用都真上传),失败原样抛 ----
201
202
  if (supportsFilesApi(endpoint) && endpoint?.apiKey) {
202
- try {
203
- const upload = input.deps?.upload ?? defaultUpload;
204
- const fileId = await upload({ endpoint, data: ensureBytes(), filename, signal });
205
- return {
206
- section: { type: "file", file_id: fileId },
207
- transport: "files-api",
208
- bytes: byteLength,
209
- };
210
- }
211
- catch (error) {
212
- if (signal?.aborted)
213
- throw error;
214
- warning = `Files API upload failed, falling back to base64 inline: ${error?.message ?? error}`;
215
- }
203
+ const upload = input.deps?.upload ?? defaultUpload;
204
+ const fileId = await upload({ endpoint, data: ensureBytes(), filename, signal });
205
+ return {
206
+ section: { type: "file", file_id: fileId },
207
+ transport: "files-api",
208
+ bytes: byteLength,
209
+ };
216
210
  }
217
211
  // ---- 5. 内联(base64 data URL)----
218
212
  if (byteLength > maxInline) {
@@ -228,6 +222,5 @@ export async function fileToContentSection(input) {
228
222
  : { type: "file", file_data: dataUrl, filename },
229
223
  transport: "inline",
230
224
  bytes: byteLength,
231
- warning,
232
225
  };
233
226
  }
@@ -7,12 +7,17 @@ export declare class SdkError extends Error {
7
7
  constructor(code: string, message: string, cause?: Error);
8
8
  }
9
9
  /**
10
- * 上下文超限错误。由 ContextGuardPlugin 在请求前抛出,用于中断对话。
10
+ * 上下文超限错误。由 ContextGuardPlugin 在请求前**用来拼拒绝理由**(返回它的 `message`)。
11
+ *
12
+ * 它自己不被抛出:钩子里抛错会穿到 `start()` 外面把整个循环打死(agent 变成僵尸),所以
13
+ * 护栏改成「返回字符串 = 拒这一次请求」(`onInnerLoopStart`)。拒绝理由只有字符串这一种
14
+ * 形状,用量 / 阈值这两个字段便于就地拼文案。
15
+ *
11
16
  * 触发条件通常是上下文 token 用量超过硬线(如读入超大文件),
12
- * 继续对话已无意义且会持续放大费用/延迟,故由上层捕获后向用户显式报错。
17
+ * 继续会话已无意义且会持续放大费用/延迟。
13
18
  */
14
19
  export declare class ContextOverflowError extends Error {
15
- /** 触发中断时的刚用量(usage.prompt_tokens) */
20
+ /** 触发拦截时的用量(usage.prompt_tokens) */
16
21
  readonly promptTokens: number;
17
22
  /** 被越过的强行阻断阈值(`tokenThresholds.guard`,绝对值) */
18
23
  readonly guardTokens: number;
@@ -14,18 +14,23 @@ export class SdkError extends Error {
14
14
  }
15
15
  }
16
16
  /**
17
- * 上下文超限错误。由 ContextGuardPlugin 在请求前抛出,用于中断对话。
17
+ * 上下文超限错误。由 ContextGuardPlugin 在请求前**用来拼拒绝理由**(返回它的 `message`)。
18
+ *
19
+ * 它自己不被抛出:钩子里抛错会穿到 `start()` 外面把整个循环打死(agent 变成僵尸),所以
20
+ * 护栏改成「返回字符串 = 拒这一次请求」(`onInnerLoopStart`)。拒绝理由只有字符串这一种
21
+ * 形状,用量 / 阈值这两个字段便于就地拼文案。
22
+ *
18
23
  * 触发条件通常是上下文 token 用量超过硬线(如读入超大文件),
19
- * 继续对话已无意义且会持续放大费用/延迟,故由上层捕获后向用户显式报错。
24
+ * 继续会话已无意义且会持续放大费用/延迟。
20
25
  */
21
26
  export class ContextOverflowError extends Error {
22
- /** 触发中断时的刚用量(usage.prompt_tokens) */
27
+ /** 触发拦截时的用量(usage.prompt_tokens) */
23
28
  promptTokens;
24
29
  /** 被越过的强行阻断阈值(`tokenThresholds.guard`,绝对值) */
25
30
  guardTokens;
26
31
  constructor(promptTokens, guardTokens) {
27
32
  super(`🛑 Context critically over the limit: ${promptTokens} tokens used, above the blocking threshold of ${guardTokens}.` +
28
- ` The conversation may have run away after reading an oversized file, so it has been interrupted — please inspect and start over.` +
33
+ ` The session may have run away after reading an oversized file, so it has been interrupted — please inspect and start over.` +
29
34
  ` (If you really need a longer context, raise tokenThresholds.guard for this model in config.json.)`);
30
35
  this.name = "ContextOverflowError";
31
36
  this.promptTokens = promptTokens;
@@ -1,14 +1,25 @@
1
- export interface LogFunctions {
2
- info: (message: string) => void;
3
- warn: (message: string) => void;
4
- error: (message: string) => void;
5
- }
6
- export type Logger = LogFunctions;
7
1
  /**
8
- * 获取全局 Logger 实例。
2
+ * 日志口:一个三方法的结构类型 + 一份什么都不做的缺省实现。
3
+ *
4
+ * 库**不持有**日志出口:这里没有模块级的可变单例。谁要打日志,谁就从自己的参数里收一个
5
+ * {@link LogSink} 往下传;不注入就什么都不写({@link SILENT_LOG})。
6
+ *
7
+ * 为什么不在这里放一份「缺省写 stdout」的实现:库默认往标准输出写,等于把「日志落到哪里」
8
+ * 这件属于进程的事替调用方定了 —— 宿主被拉起时 stdout / stderr 归谁、落到哪个文件,只有
9
+ * 进程自己知道。库缺省沉默,嵌入方(宿主 / 命令行)把自己那一份注入进来。
10
+ *
11
+ * 与 `@ai-zen/agents-logger` 的同名类型**结构相容**,但本包不依赖那个包:「三方法」不值得
12
+ * 让库去认下一个文件日志包。
9
13
  */
10
- export declare function getLogger(): Logger;
14
+ export interface LogSink {
15
+ info(message: string, detail?: unknown): void;
16
+ warn(message: string, detail?: unknown): void;
17
+ error(message: string, detail?: unknown): void;
18
+ }
11
19
  /**
12
- * 设置全局 Logger 实例,替换默认的 console 输出。
20
+ * 什么都不做的 {@link LogSink}:所有「可选日志」参数的缺省值。
21
+ *
22
+ * 一份实例、一处定义:缺省值在构造里写成 `logger ?? SILENT_LOG`,不在每个调用点现拼一个
23
+ * 空对象 —— 那样每一处都是新的一份,且「不注入日志时会发生什么」得读遍调用点才能答上来。
13
24
  */
14
- export declare function setLogger(log: Logger): void;
25
+ export declare const SILENT_LOG: LogSink;