@ai-zen/agents-sdk 1.0.0-alpha.23 → 1.0.0-alpha.25

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,142 @@
1
+ ## [1.0.0-alpha.25] - 2026-11-02
2
+
3
+ > Endpoint capability bits are now backfilled on migration. Since alpha.12 the
4
+ > `capabilities.filesApi` bit decides whether local media is uploaded (Files API) or
5
+ > inlined as base64 — but endpoints are never factory-managed, and migration did not
6
+ > touch them either, so any config written before alpha.12 kept `deepseek` without the
7
+ > bit. For those users the promised "deepseek goes through the Files API" never took
8
+ > effect: images, `view_image` and MCP media silently degraded to base64 inline, and
9
+ > the request body grew with every turn of history.
10
+ >
11
+ > Alongside it, entity ids are now confined to their repository directory: a hostile id
12
+ > could previously make `AgentRepository` read / write / delete JSON files outside of
13
+ > `agents/`.
14
+
15
+ ### 🛡️ Fixed — `Endpoint.capabilities` is backfilled when missing
16
+
17
+ - **`normalizeEndpointCapabilities()`** (in `config/migrate.ts`, wired into
18
+ `migrateConfig()`) fills in `capabilities` **only when the whole field is absent**,
19
+ taking the values from the factory endpoint with the same id. Nothing else is touched:
20
+ - an endpoint that already has `capabilities` — even `{}` or `{"filesApi": false}` — is
21
+ left byte-for-byte alone; an explicit `false` is a decision, not a gap;
22
+ - endpoints whose id is not in the factory list (user-built) are left alone, because
23
+ guessing would send uploads to a `/files` endpoint that may not exist.
24
+ - The migration lands on disk through the usual `ensureDefaultConfig()` path, so it runs
25
+ exactly once per config: a second start finds nothing to change.
26
+ - Verified end to end against a legacy-shaped config: `deepseek` gains
27
+ `{ filesApi: true }` in memory **and** on disk, a user-written `filesApi: false` on
28
+ `openai` survives, a self-built endpoint stays untouched, and the second start does not
29
+ rewrite the file.
30
+
31
+ ### 🔒 Fixed — entity ids can no longer escape their repository directory
32
+
33
+ - **`EntityRepository.path()`** now validates the resolved target:
34
+ `resolve()` + a `root + sep` prefix check, instead of `join(dir, `${id}.json`)`.
35
+ - A bare `startsWith(root)` would not have been enough: `../agents-evil/x` normalizes to
36
+ `<root>-evil/x.json`, which still *starts with* `<root>`.
37
+ - `join` cannot normalize absolute paths, so `/etc/passwd` used to land in
38
+ `<dir>/etc/passwd.json`; `resolve` catches it.
39
+ - The check lives in `path()` rather than in `write()` / `delete()`: `read`, `write` and
40
+ `delete` all go through it, and `list()` only ever passes single-segment names coming
41
+ from `readdir`, so it cannot break listing — one gate, read/write/delete consistent.
42
+ - Affected callers that pass a user-supplied id straight through: `AgentRepository`
43
+ (agent / sub-agent definitions) and the CLI's conversation repository (`/save`, `/load`).
44
+ A hostile id now fails loudly (`Invalid entity id: …`) instead of writing outside the
45
+ directory.
46
+ - Known and accepted: `a/../b` normalizes back inside `<root>/b.json` and is therefore
47
+ still allowed — the only remaining effect is overwriting another definition, and
48
+ `config.json` is out of reach.
49
+
50
+ ### ✅ Tests
51
+
52
+ - `AgentRepository.test.ts` +5: `../escaped` rejected *and* no file written outside,
53
+ `../agents-evil/x` rejected, `read` / `delete` share the same gate, absolute path
54
+ rejected, normal id unaffected. Uses a two-level temp directory so an escape would land
55
+ inside the test's own tmpdir instead of `/tmp`.
56
+ - `migrate.test.ts` +7: backfill on a legacy config, explicit `false` respected,
57
+ existing-but-empty `capabilities` untouched, user-built endpoint untouched, factory
58
+ endpoint without the bit untouched, idempotency, and "no side effects on the caller's
59
+ object".
60
+ - Full suite: **57 files / 629 tests passing** (6 skipped), `tsc --noEmit` clean.
61
+
62
+ ### 🔧 Toolchain — TypeScript 5.9.3 → 7.0.2
63
+
64
+ - **`packages/sdk/tsconfig.json`**: added `"types": ["node"]`. TypeScript 7 no longer
65
+ picks global types up from `node_modules/@types` automatically (at least under this
66
+ repo's pnpm symlink layout), so `"node:fs"` / `process` / `Buffer` all turn into
67
+ `TS2591`. Naming the types explicitly is also what `@ai-zen/cli` already does.
68
+ - **`packages/core/tsconfig.json`**: `moduleResolution: "Node"` → `"Bundler"`. The
69
+ `node10` resolution mode was **removed** in TypeScript 7 (`TS5108`); `Bundler` is the
70
+ closest equivalent for a package compiled with `module: ESNext`.
71
+ - Verified after the upgrade: `tsc --noEmit` clean for both packages, both `build`
72
+ scripts succeed, core **150 passed / 17 skipped**, sdk **624 passed / 6 skipped**
73
+ at that point (629 after the entity-id hardening above), and `dist/index.js` still
74
+ loads at runtime (84 exports).
75
+
1
76
  # Changelog
2
77
 
78
+ ## [1.0.0-alpha.24] - 2026-10-29
79
+
80
+ > User tool files can no longer damage the host. `tools/` holds code that the SDK
81
+ > **evaluates in-process**, so a stray script in that directory used to be able to
82
+ > kill the process, hang startup, or silently rewrite project files.
83
+
84
+ ### 💥 Breaking Changes
85
+
86
+ - **`tools/` is now explicitly a trusted-extension directory.** Files there are
87
+ still `import()`-ed in-process, so the SDK cannot sandbox them: a top-level
88
+ synchronous infinite loop or a native `process.kill()` still takes the host
89
+ down. Anything untrusted belongs in an MCP server, which is the out-of-process
90
+ extension path. This is documented in `discover.ts` next to the guards.
91
+
92
+ ### 🛡️ Fixed — user tool loading is now fail-safe
93
+
94
+ Real-world incident that motivated this release: a one-off developer script
95
+ (`process.exit(2)` when called without arguments) was dropped into
96
+ `.ai-zen/tools/`. Every startup imported it during session creation, so the CLI
97
+ process was killed mid-initialization and the last drawn frame stayed on screen —
98
+ it looked like a hang. Another script in the same directory rewrote PNG assets at
99
+ module top level on every startup. All four such files are now skipped or
100
+ neutralised.
101
+
102
+ - **Static pre-check: files without `export` are never evaluated.** A module with
103
+ no `export` cannot export a `Tool`, so `normalizeToolExport()` was already going
104
+ to discard it — the only difference is that the old code found out *after*
105
+ evaluating it, i.e. after the side effects had happened. Reading the source
106
+ first costs one `fs.readFile` and buys complete immunity from that class of
107
+ file. Read failures fail open (the file is still imported) so an unreadable but
108
+ valid tool is never silently dropped.
109
+ - **`process.exit` / `process.abort` are suppressed during evaluation.** They are
110
+ swapped for a thrown `UserToolExitError`, which lands in the existing
111
+ `try/catch` and rejects just that one file. The originals are restored in a
112
+ `finally` — the guard must never outlive the import, or the host itself could
113
+ not exit. What was saved is the *current* value, not the value at module load,
114
+ so nested/concurrent discoveries restore correctly.
115
+ - **`console.log` / `info` / `debug` are redirected to stderr while evaluating.**
116
+ stdout belongs to the host's UI; a tool file writing to it tears an Ink frame
117
+ apart. This is also why the stray scripts visibly corrupted the TUI.
118
+ - **Per-file import timeout (`importTimeoutMs`, default 5000).** A module whose
119
+ top-level `await` never settles no longer blocks startup. A timeout only stops
120
+ *waiting* — ESM evaluation cannot be cancelled, so the module may still finish
121
+ later; this is stated at the call site rather than pretended away.
122
+
123
+ ### 🔧 Changed
124
+
125
+ - Rejections are reported through `getLogger().warn/error` (previously the
126
+ failure path logged at `error` only). No new notification API was added: hosts
127
+ that want these on screen should tee their `Logger`, which is a single hook that
128
+ covers every SDK subsystem at once instead of one callback per feature.
129
+
130
+ ### ✅ Tests
131
+
132
+ - `discover.test.ts` 16 → 21 cases. The five new ones pin each hazard: a file
133
+ without `export` is skipped **without being evaluated** (asserted via a
134
+ side-effect marker file), a top-level `process.exit(2)` neither kills the host
135
+ nor prevents later files from loading, top-level `console.log` does not reach
136
+ stdout, a never-settling top-level `await` times out, and `process.exit` /
137
+ `console.log` are restored afterwards.
138
+ - Full suite: 57 files / 617 passed / 6 skipped.
139
+
3
140
  ## [1.0.0-alpha.23] - 2026-10-29
4
141
 
5
142
  > The SDK is now English-only. Every model-facing and user-facing string is a
@@ -15,6 +15,8 @@
15
15
  * `reasoningPreset` 而默默失去调档能力。这里删掉旧字段,并按**同 id 的出厂模型**
16
16
  * 补上正确的策略名(同一 id 即同一厂商型号,协议能力不会因用户改过参数而变)。
17
17
  *
18
+ * 另有一类「缺省值缺位」的迁移:`Endpoint.capabilities`(见 `normalizeEndpointCapabilities`)。
19
+ *
18
20
  * 迁移时机:`ConfigManager.read()` 读出即迁(内存里永远是当前形状);
19
21
  * 落盘由 `ensureDefaultConfig()` 负责 —— 它比较迁移结果与磁盘原文,不同才写回,
20
22
  * 因此迁移只发生一次,且不会在每次启动时无谓地改写文件。
@@ -73,3 +75,32 @@ export declare const ABORTED_MESSAGE_STRATEGIES: readonly ["keep", "drop"];
73
75
  export declare const ABORTED_TOOL_ROUND_STRATEGIES: readonly ["fill", "drop"];
74
76
  /** 缺失 / 非法 → 出厂默认;返回是否有改动(直接改写传入对象) */
75
77
  export declare function normalizeAbortStrategies(config: AppConfig): boolean;
78
+ /**
79
+ * 补齐端点**缺失**的能力位声明(`Endpoint.capabilities`)。
80
+ *
81
+ * ## 这个问题是怎么来的
82
+ *
83
+ * `capabilities.filesApi` 是 alpha.12 才引入的能力位 —— 同一版把 `view_image` 的判定
84
+ * 从「端点 id 是不是 `deepseek`」改成「看这一位」,并只给**出厂 deepseek** 打了 `true`。
85
+ * 但端点**不参与出厂托管**(`ConfigManager.syncManagedModels` 明写「保持用户配置」),
86
+ * 迁移此前也完全不碰 `endpoints` —— 于是 alpha.12 之前就已写下的配置,其 deepseek
87
+ * 端点永远缺 `capabilities`,`supportsFilesApi()` 恒为 `false`:
88
+ *
89
+ * · 出厂承诺的「deepseek 走 Files API」对这些用户从未生效;
90
+ * · 而且**全程静默** —— 「未声明能力位」和「缺 apiKey」两个分支都不发 warning,
91
+ * 图片 / `view_image` / MCP 媒体就悄悄退化成 base64 内联,请求体随历史膨胀。
92
+ *
93
+ * 这是「默认值缺位」,不是「用户选择」,所以由迁移补 —— 与模型清单不同,端点本身仍然
94
+ * 归用户所有,我们只往**空位**里放出厂默认。
95
+ *
96
+ * ## 边界:只补整体缺失,绝不覆盖
97
+ *
98
+ * - `capabilities` **整体缺失** → 按**同 id 的出厂端点**补上整块;
99
+ * - `capabilities` 已存在(哪怕是 `{}`、哪怕写着 `filesApi: false`)→ 一个字段都不动:
100
+ * 用户已经表过态,`false` 就是「我不走 Files API」;
101
+ * - 端点 id 不在出厂清单(用户自建)→ 不动:我们不知道它是否真有 `/files`,
102
+ * 猜错会把上传请求打到不存在的接口上。
103
+ *
104
+ * @returns 是否有改动(直接改写传入对象)
105
+ */
106
+ export declare function normalizeEndpointCapabilities(config: AppConfig): boolean;
@@ -15,6 +15,8 @@
15
15
  * `reasoningPreset` 而默默失去调档能力。这里删掉旧字段,并按**同 id 的出厂模型**
16
16
  * 补上正确的策略名(同一 id 即同一厂商型号,协议能力不会因用户改过参数而变)。
17
17
  *
18
+ * 另有一类「缺省值缺位」的迁移:`Endpoint.capabilities`(见 `normalizeEndpointCapabilities`)。
19
+ *
18
20
  * 迁移时机:`ConfigManager.read()` 读出即迁(内存里永远是当前形状);
19
21
  * 落盘由 `ensureDefaultConfig()` 负责 —— 它比较迁移结果与磁盘原文,不同才写回,
20
22
  * 因此迁移只发生一次,且不会在每次启动时无谓地改写文件。
@@ -118,7 +120,12 @@ export function migrateConfig(config) {
118
120
  changed = true;
119
121
  return reasoning.model;
120
122
  });
121
- const next = { ...config, models };
123
+ const next = {
124
+ ...config,
125
+ models,
126
+ // 端点数组浅拷贝:能力位补齐会改元素,不把副作用浇到调用方手里的旧对象上
127
+ endpoints: (config.endpoints ?? []).map((endpoint) => ({ ...endpoint })),
128
+ };
122
129
  // 已废弃字段:不参与运行,也不允许再写回磁盘
123
130
  if ("defaultModel" in next) {
124
131
  delete next.defaultModel;
@@ -126,6 +133,8 @@ export function migrateConfig(config) {
126
133
  }
127
134
  if (normalizeAbortStrategies(next))
128
135
  changed = true;
136
+ if (normalizeEndpointCapabilities(next))
137
+ changed = true;
129
138
  if (!changed)
130
139
  return { config, changed };
131
140
  return { config: next, changed };
@@ -146,3 +155,44 @@ export function normalizeAbortStrategies(config) {
146
155
  }
147
156
  return changed;
148
157
  }
158
+ /**
159
+ * 补齐端点**缺失**的能力位声明(`Endpoint.capabilities`)。
160
+ *
161
+ * ## 这个问题是怎么来的
162
+ *
163
+ * `capabilities.filesApi` 是 alpha.12 才引入的能力位 —— 同一版把 `view_image` 的判定
164
+ * 从「端点 id 是不是 `deepseek`」改成「看这一位」,并只给**出厂 deepseek** 打了 `true`。
165
+ * 但端点**不参与出厂托管**(`ConfigManager.syncManagedModels` 明写「保持用户配置」),
166
+ * 迁移此前也完全不碰 `endpoints` —— 于是 alpha.12 之前就已写下的配置,其 deepseek
167
+ * 端点永远缺 `capabilities`,`supportsFilesApi()` 恒为 `false`:
168
+ *
169
+ * · 出厂承诺的「deepseek 走 Files API」对这些用户从未生效;
170
+ * · 而且**全程静默** —— 「未声明能力位」和「缺 apiKey」两个分支都不发 warning,
171
+ * 图片 / `view_image` / MCP 媒体就悄悄退化成 base64 内联,请求体随历史膨胀。
172
+ *
173
+ * 这是「默认值缺位」,不是「用户选择」,所以由迁移补 —— 与模型清单不同,端点本身仍然
174
+ * 归用户所有,我们只往**空位**里放出厂默认。
175
+ *
176
+ * ## 边界:只补整体缺失,绝不覆盖
177
+ *
178
+ * - `capabilities` **整体缺失** → 按**同 id 的出厂端点**补上整块;
179
+ * - `capabilities` 已存在(哪怕是 `{}`、哪怕写着 `filesApi: false`)→ 一个字段都不动:
180
+ * 用户已经表过态,`false` 就是「我不走 Files API」;
181
+ * - 端点 id 不在出厂清单(用户自建)→ 不动:我们不知道它是否真有 `/files`,
182
+ * 猜错会把上传请求打到不存在的接口上。
183
+ *
184
+ * @returns 是否有改动(直接改写传入对象)
185
+ */
186
+ export function normalizeEndpointCapabilities(config) {
187
+ let changed = false;
188
+ for (const endpoint of config.endpoints ?? []) {
189
+ if (endpoint.capabilities != null)
190
+ continue;
191
+ const factory = (DEFAULT_APP_CONFIG.endpoints ?? []).find((item) => item.id === endpoint.id);
192
+ if (!factory?.capabilities)
193
+ continue;
194
+ endpoint.capabilities = { ...factory.capabilities };
195
+ changed = true;
196
+ }
197
+ return changed;
198
+ }
@@ -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] Failed to load tool file: ${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
  // 导出格式归一化
@@ -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() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-zen/agents-sdk",
3
- "version": "1.0.0-alpha.23",
3
+ "version": "1.0.0-alpha.25",
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",
@@ -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": [