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

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,67 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.0.0-alpha.24] - 2026-10-29
4
+
5
+ > User tool files can no longer damage the host. `tools/` holds code that the SDK
6
+ > **evaluates in-process**, so a stray script in that directory used to be able to
7
+ > kill the process, hang startup, or silently rewrite project files.
8
+
9
+ ### 💥 Breaking Changes
10
+
11
+ - **`tools/` is now explicitly a trusted-extension directory.** Files there are
12
+ still `import()`-ed in-process, so the SDK cannot sandbox them: a top-level
13
+ synchronous infinite loop or a native `process.kill()` still takes the host
14
+ down. Anything untrusted belongs in an MCP server, which is the out-of-process
15
+ extension path. This is documented in `discover.ts` next to the guards.
16
+
17
+ ### 🛡️ Fixed — user tool loading is now fail-safe
18
+
19
+ Real-world incident that motivated this release: a one-off developer script
20
+ (`process.exit(2)` when called without arguments) was dropped into
21
+ `.ai-zen/tools/`. Every startup imported it during session creation, so the CLI
22
+ process was killed mid-initialization and the last drawn frame stayed on screen —
23
+ it looked like a hang. Another script in the same directory rewrote PNG assets at
24
+ module top level on every startup. All four such files are now skipped or
25
+ neutralised.
26
+
27
+ - **Static pre-check: files without `export` are never evaluated.** A module with
28
+ no `export` cannot export a `Tool`, so `normalizeToolExport()` was already going
29
+ to discard it — the only difference is that the old code found out *after*
30
+ evaluating it, i.e. after the side effects had happened. Reading the source
31
+ first costs one `fs.readFile` and buys complete immunity from that class of
32
+ file. Read failures fail open (the file is still imported) so an unreadable but
33
+ valid tool is never silently dropped.
34
+ - **`process.exit` / `process.abort` are suppressed during evaluation.** They are
35
+ swapped for a thrown `UserToolExitError`, which lands in the existing
36
+ `try/catch` and rejects just that one file. The originals are restored in a
37
+ `finally` — the guard must never outlive the import, or the host itself could
38
+ not exit. What was saved is the *current* value, not the value at module load,
39
+ so nested/concurrent discoveries restore correctly.
40
+ - **`console.log` / `info` / `debug` are redirected to stderr while evaluating.**
41
+ stdout belongs to the host's UI; a tool file writing to it tears an Ink frame
42
+ apart. This is also why the stray scripts visibly corrupted the TUI.
43
+ - **Per-file import timeout (`importTimeoutMs`, default 5000).** A module whose
44
+ top-level `await` never settles no longer blocks startup. A timeout only stops
45
+ *waiting* — ESM evaluation cannot be cancelled, so the module may still finish
46
+ later; this is stated at the call site rather than pretended away.
47
+
48
+ ### 🔧 Changed
49
+
50
+ - Rejections are reported through `getLogger().warn/error` (previously the
51
+ failure path logged at `error` only). No new notification API was added: hosts
52
+ that want these on screen should tee their `Logger`, which is a single hook that
53
+ covers every SDK subsystem at once instead of one callback per feature.
54
+
55
+ ### ✅ Tests
56
+
57
+ - `discover.test.ts` 16 → 21 cases. The five new ones pin each hazard: a file
58
+ without `export` is skipped **without being evaluated** (asserted via a
59
+ side-effect marker file), a top-level `process.exit(2)` neither kills the host
60
+ nor prevents later files from loading, top-level `console.log` does not reach
61
+ stdout, a never-settling top-level `await` times out, and `process.exit` /
62
+ `console.log` are restored afterwards.
63
+ - Full suite: 57 files / 617 passed / 6 skipped.
64
+
3
65
  ## [1.0.0-alpha.23] - 2026-10-29
4
66
 
5
67
  > The SDK is now English-only. Every model-facing and user-facing string is a
@@ -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
  // 导出格式归一化
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.24",
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",