@armadra/agent 0.17.3 → 0.19.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 (157) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/CHANGELOG.zh-CN.md +50 -0
  3. package/README.md +4 -0
  4. package/README.zh-CN.md +4 -0
  5. package/THIRD_PARTY_NOTICES.md +6 -0
  6. package/assets/quickjs/LICENSE +57 -0
  7. package/assets/quickjs/README.md +14 -0
  8. package/assets/quickjs/quickjs.wasm +0 -0
  9. package/dist/agent/recovery-reminder.js +6 -1
  10. package/dist/agent/schema-coerce.d.ts +24 -0
  11. package/dist/agent/schema-coerce.js +157 -0
  12. package/dist/agent/schema.d.ts +1 -1
  13. package/dist/agent/schema.js +1 -1
  14. package/dist/agent/session-cache.js +12 -0
  15. package/dist/agent/tool-runner.js +57 -28
  16. package/dist/agent/types.d.ts +4 -0
  17. package/dist/ai/apis/anthropic-compat.d.ts +3 -1
  18. package/dist/ai/apis/anthropic-compat.js +8 -1
  19. package/dist/ai/apis/anthropic-messages.js +54 -2
  20. package/dist/ai/apis/anthropic-request.d.ts +3 -0
  21. package/dist/ai/apis/anthropic-request.js +7 -1
  22. package/dist/ai/apis/anthropic-threads.d.ts +64 -0
  23. package/dist/ai/apis/anthropic-threads.js +192 -0
  24. package/dist/ai/providers/catalog-data.js +5 -5
  25. package/dist/ai/providers/models-dev-data.js +22 -22
  26. package/dist/ai/types.d.ts +16 -0
  27. package/dist/bundle/ama-sandbox.cjs +96 -2
  28. package/dist/bundle/ama.cjs +29964 -27673
  29. package/dist/cli/bootstrap.js +32 -6
  30. package/dist/cli/compose-agents.js +2 -1
  31. package/dist/cli/compose-extensions-load.d.ts +20 -0
  32. package/dist/cli/compose-extensions-load.js +38 -0
  33. package/dist/cli/compose.js +1 -0
  34. package/dist/cli/deps.d.ts +11 -0
  35. package/dist/cli/runtime.d.ts +7 -0
  36. package/dist/cli/subcommands/config.d.ts +3 -0
  37. package/dist/cli/subcommands/config.js +22 -7
  38. package/dist/cli/subcommands/doctor.js +34 -0
  39. package/dist/cli/subcommands/models-discover.js +6 -2
  40. package/dist/codemode/capability.d.ts +14 -2
  41. package/dist/codemode/capability.js +19 -2
  42. package/dist/codemode/host-side.d.ts +14 -0
  43. package/dist/codemode/host-side.js +81 -10
  44. package/dist/codemode/inner-calls.d.ts +19 -0
  45. package/dist/codemode/inner-calls.js +24 -0
  46. package/dist/codemode/protocol.d.ts +14 -0
  47. package/dist/codemode/protocol.js +9 -1
  48. package/dist/codemode/quickjs/host.d.ts +15 -0
  49. package/dist/codemode/quickjs/host.js +243 -0
  50. package/dist/codemode/quickjs/wasm.d.ts +21 -0
  51. package/dist/codemode/quickjs/wasm.js +39 -0
  52. package/dist/codemode/quickjs/worker.d.ts +55 -0
  53. package/dist/codemode/quickjs/worker.js +457 -0
  54. package/dist/codemode/sandbox-entry.d.ts +4 -0
  55. package/dist/codemode/sandbox-entry.js +95 -3
  56. package/dist/codemode/script-images.d.ts +18 -0
  57. package/dist/codemode/script-images.js +38 -0
  58. package/dist/codemode/script-output.d.ts +19 -0
  59. package/dist/codemode/script-output.js +67 -0
  60. package/dist/codemode/search-tools.d.ts +27 -0
  61. package/dist/codemode/search-tools.js +83 -0
  62. package/dist/codemode/tool.d.ts +4 -0
  63. package/dist/codemode/tool.js +60 -9
  64. package/dist/codemode/worker-pool.d.ts +65 -0
  65. package/dist/codemode/worker-pool.js +131 -0
  66. package/dist/config/extension-tree-hash.d.ts +31 -0
  67. package/dist/config/extension-tree-hash.js +88 -0
  68. package/dist/config/extension-trust.d.ts +70 -0
  69. package/dist/config/extension-trust.js +112 -0
  70. package/dist/config/json-schema.js +3 -1
  71. package/dist/config/key-docs.js +7 -1
  72. package/dist/config/profile.d.ts +2 -0
  73. package/dist/config/profile.js +1 -0
  74. package/dist/config/schema-trust.d.ts +7 -0
  75. package/dist/config/schema-trust.js +46 -0
  76. package/dist/config/schema.d.ts +4 -5
  77. package/dist/config/schema.js +7 -27
  78. package/dist/config/settings-registry.js +2 -0
  79. package/dist/config/trust.d.ts +2 -0
  80. package/dist/config/trust.js +5 -1
  81. package/dist/config/types.d.ts +23 -0
  82. package/dist/config/types.js +1 -0
  83. package/dist/drivers/host-runners.d.ts +15 -4
  84. package/dist/drivers/host-runners.js +31 -17
  85. package/dist/errors.d.ts +1 -1
  86. package/dist/host/api-impl.d.ts +47 -4
  87. package/dist/host/api-impl.js +181 -20
  88. package/dist/host/commands.d.ts +23 -0
  89. package/dist/host/commands.js +76 -0
  90. package/dist/host/extensions.d.ts +43 -0
  91. package/dist/host/extensions.js +117 -0
  92. package/dist/host/resources.d.ts +2 -0
  93. package/dist/host/resources.js +5 -0
  94. package/dist/host/types.d.ts +41 -2
  95. package/dist/host/types.js +4 -2
  96. package/dist/i18n/catalog.d.ts +39 -0
  97. package/dist/i18n/messages/cli.d.ts +24 -0
  98. package/dist/i18n/messages/cli.js +24 -0
  99. package/dist/i18n/messages/config-keys.d.ts +4 -0
  100. package/dist/i18n/messages/config-keys.js +6 -2
  101. package/dist/i18n/messages/config.d.ts +4 -0
  102. package/dist/i18n/messages/drivers.d.ts +22 -0
  103. package/dist/i18n/messages/drivers.js +22 -0
  104. package/dist/i18n/messages/errors.d.ts +1 -1
  105. package/dist/i18n/messages/interactive-startup.d.ts +4 -0
  106. package/dist/i18n/messages/interactive-startup.js +4 -0
  107. package/dist/i18n/messages/interactive-view.d.ts +2 -0
  108. package/dist/i18n/messages/interactive-view.js +2 -0
  109. package/dist/i18n/messages/interactive.d.ts +6 -0
  110. package/dist/i18n/messages/report.d.ts +14 -0
  111. package/dist/i18n/messages/report.js +14 -0
  112. package/dist/i18n/messages/subcommands-config.d.ts +8 -0
  113. package/dist/i18n/messages/subcommands-config.js +8 -0
  114. package/dist/i18n/messages/subcommands.d.ts +8 -0
  115. package/dist/modes/acp/acp-config.d.ts +4 -2
  116. package/dist/modes/acp/acp-config.js +17 -3
  117. package/dist/modes/acp/acp-events.d.ts +2 -0
  118. package/dist/modes/acp/acp-events.js +4 -0
  119. package/dist/modes/acp/acp-server.js +6 -2
  120. package/dist/modes/acp/acp-sessions.d.ts +8 -1
  121. package/dist/modes/acp/acp-sessions.js +18 -0
  122. package/dist/modes/commands-core.d.ts +14 -1
  123. package/dist/modes/commands-core.js +34 -2
  124. package/dist/modes/interactive/startup-ui.js +21 -0
  125. package/dist/modes/interactive/status-area.js +1 -1
  126. package/dist/modes/interactive/tool-view.d.ts +8 -2
  127. package/dist/modes/interactive/tool-view.js +12 -5
  128. package/dist/modes/print/print-mode.d.ts +3 -0
  129. package/dist/modes/print/print-mode.js +35 -8
  130. package/dist/modes/rpc/commands.d.ts +2 -0
  131. package/dist/modes/rpc/commands.js +22 -7
  132. package/dist/modes/rpc/rpc-mode.js +3 -0
  133. package/dist/modes/startup-ui-text.js +11 -0
  134. package/dist/rpc.d.ts +2 -1
  135. package/dist/session/unclean-end.d.ts +8 -0
  136. package/dist/session/unclean-end.js +39 -7
  137. package/dist/tools/registry.d.ts +6 -0
  138. package/dist/tools/registry.js +13 -0
  139. package/dist/tools/types.d.ts +7 -0
  140. package/docs/README.md +1 -1
  141. package/docs/en/README.md +3 -3
  142. package/docs/en/guides/extensions.md +141 -0
  143. package/docs/en/guides/providers.md +27 -7
  144. package/docs/en/guides/tui.md +1 -1
  145. package/docs/en/reference/acp.md +1 -1
  146. package/docs/en/reference/host-api.md +55 -27
  147. package/docs/en/reference/rpc.md +12 -8
  148. package/docs/guides/codemode.md +52 -12
  149. package/docs/guides/extensions.md +136 -0
  150. package/docs/guides/providers.md +21 -1
  151. package/docs/guides/sandbox.md +2 -0
  152. package/docs/guides/tui.md +1 -1
  153. package/docs/reference/acp.md +1 -1
  154. package/docs/reference/host-api.md +55 -27
  155. package/docs/reference/rpc.md +12 -8
  156. package/docs/reference/session-format.md +10 -9
  157. package/package.json +5 -2
@@ -13,6 +13,8 @@
13
13
  * (完整门禁);名字是 `codemode` 直接拒绝。脚本结束时 abort 仍在跑的调用。
14
14
  * - 超时:父进程计时,到点杀子进程树(POSIX 进程组 / Windows taskkill);外层 abort:先发
15
15
  * `abort`,宽限后杀树。
16
+ * - 名额:进程内同时存活的子进程数受 `worker-pool.ts` 限制,排队最多 60 s 且计入 `timeout_ms`;名额在子进程
17
+ * `close` 时归还,不是结果落定时。
16
18
  * - OS 沙箱(docs/guides/sandbox.md):有可用的 sandbox-exec / bwrap / unshare 时,整条命令行经它启动,拒绝
17
19
  * 网络与一切写入(`CODEMODE_OS_POLICY`;子进程本来就没有写权限)。Node 22 / 24 的 strict 依赖这一层
18
20
  * (`requireOsSandbox`),包装不了就报错,不裸跑;Node ≥ 25 是叠加的纵深防御。
@@ -25,7 +27,8 @@ import { osSandboxStatus } from "../sandbox/detect.js";
25
27
  import { wrapCommand } from "../sandbox/wrap.js";
26
28
  import { killProcessTree, trackProcessGroup, untrackProcessGroup } from "../tools/process-tree.js";
27
29
  import { detectSandboxCapability } from "./capability.js";
28
- import { LineSplitter, SANDBOX_MAIN_FLAG, decodeChildLine, encodeLine, } from "./protocol.js";
30
+ import { DEFAULT_MAX_WORKERS, MAX_WORKER_WAIT_MS, codemodeWorkerPool, } from "./worker-pool.js";
31
+ import { LineSplitter, MAX_SCRIPT_IMAGES, SANDBOX_MAIN_FLAG, SEARCH_TOOLS_CALL, decodeChildLine, encodeLine, } from "./protocol.js";
29
32
  /** 父进程累积的输出上限(字符);超出后丢弃中段(给模型的再按 max_output_tokens 截)。 */
30
33
  export const MAX_COLLECTED_OUTPUT_CHARS = 16 * 1024 * 1024;
31
34
  /** 外层 abort 后等子进程自行结束的宽限。 */
@@ -94,6 +97,7 @@ export async function runSandbox(request) {
94
97
  const heapMb = Math.floor(request.maxHeapMb ?? DEFAULT_CODEMODE_HEAP_MB);
95
98
  const base = {
96
99
  outputs: [],
100
+ images: [],
97
101
  timedOut: false,
98
102
  aborted: false,
99
103
  toolCalls: 0,
@@ -119,13 +123,51 @@ export async function runSandbox(request) {
119
123
  elapsedMs: 0,
120
124
  };
121
125
  }
122
- const isWindows = process.platform === "win32";
123
- const child = spawn(command.command, command.args, {
124
- env: sandboxEnv(),
125
- stdio: ["pipe", "pipe", "pipe"],
126
- detached: !isWindows,
127
- windowsHide: true,
126
+ const timeoutMs = request.options.timeoutMs;
127
+ const pool = request.workerPool ?? codemodeWorkerPool;
128
+ const limit = request.maxWorkers ?? DEFAULT_MAX_WORKERS;
129
+ const slot = await pool.acquire({
130
+ limit,
131
+ waitMs: Math.min(MAX_WORKER_WAIT_MS, timeoutMs),
132
+ signal: request.signal,
128
133
  });
134
+ if (slot.status === "aborted") {
135
+ return { ...base, ok: false, error: "Script aborted", aborted: true, elapsedMs: 0 };
136
+ }
137
+ if (slot.status === "timeout") {
138
+ const ownDeadline = timeoutMs <= MAX_WORKER_WAIT_MS;
139
+ return {
140
+ ...base,
141
+ ok: false,
142
+ timedOut: ownDeadline,
143
+ error: ownDeadline
144
+ ? `Script timed out after ${timeoutMs} ms waiting for a free codemode sandbox slot (${slot.active} of ${limit} in use); it was not run`
145
+ : `Script was not run: all ${limit} codemode sandbox slots stayed busy for ${MAX_WORKER_WAIT_MS / 1000} s; try again when other scripts finish`,
146
+ elapsedMs: slot.waitedMs,
147
+ };
148
+ }
149
+ const lease = slot.lease;
150
+ // 等名额的时间计入脚本的 timeout_ms
151
+ const runTimeoutMs = Math.max(1, timeoutMs - slot.waitedMs);
152
+ const isWindows = process.platform === "win32";
153
+ let child;
154
+ try {
155
+ child = spawn(command.command, command.args, {
156
+ env: sandboxEnv(),
157
+ stdio: ["pipe", "pipe", "pipe"],
158
+ detached: !isWindows,
159
+ windowsHide: true,
160
+ });
161
+ }
162
+ catch (error) {
163
+ lease.release();
164
+ return {
165
+ ...base,
166
+ ok: false,
167
+ error: `Failed to start codemode sandbox: ${error.message}`,
168
+ elapsedMs: slot.waitedMs,
169
+ };
170
+ }
129
171
  const pid = child.pid;
130
172
  if (pid !== undefined && !isWindows)
131
173
  trackProcessGroup(pid);
@@ -166,10 +208,10 @@ export async function runSandbox(request) {
166
208
  settle({
167
209
  ok: false,
168
210
  timedOut: true,
169
- error: `Script timed out after ${request.options.timeoutMs} ms`,
211
+ error: `Script timed out after ${timeoutMs} ms`,
170
212
  });
171
213
  kill();
172
- }, request.options.timeoutMs);
214
+ }, runTimeoutMs);
173
215
  let graceTimer;
174
216
  const onAbort = () => {
175
217
  write({ type: "abort" });
@@ -211,8 +253,31 @@ export async function runSandbox(request) {
211
253
  request.onOutput?.(text);
212
254
  return;
213
255
  }
256
+ case "image":
257
+ if (typeof message.data === "string" &&
258
+ typeof message.mimeType === "string" &&
259
+ result.images.length < MAX_SCRIPT_IMAGES) {
260
+ result.images.push({ data: message.data, mimeType: message.mimeType });
261
+ }
262
+ return;
214
263
  case "tool_call": {
215
264
  const { id, name, input } = message;
265
+ if (name === SEARCH_TOOLS_CALL) {
266
+ const args = (input ?? {});
267
+ try {
268
+ const value = request.searchTools?.(args.query, args.options) ?? [];
269
+ write({ type: "tool_result", id, ok: true, value });
270
+ }
271
+ catch (error) {
272
+ write({
273
+ type: "tool_result",
274
+ id,
275
+ ok: false,
276
+ error: error instanceof Error ? error.message : String(error),
277
+ });
278
+ }
279
+ return;
280
+ }
216
281
  result.toolCalls++;
217
282
  if (name === "codemode") {
218
283
  write({
@@ -261,8 +326,14 @@ export async function runSandbox(request) {
261
326
  for (const line of splitter.push(chunk))
262
327
  onLine(line);
263
328
  });
264
- child.on("error", (error) => settle({ ok: false, error: `Failed to start codemode sandbox: ${error.message}` }));
329
+ child.on("error", (error) => {
330
+ settle({ ok: false, error: `Failed to start codemode sandbox: ${error.message}` });
331
+ // 没起来的进程不会再有 close
332
+ if (child.pid === undefined)
333
+ lease.release();
334
+ });
265
335
  child.on("close", (code, signal) => {
336
+ lease.release();
266
337
  for (const line of splitter.flush())
267
338
  onLine(line);
268
339
  if (pid !== undefined && !isWindows)
@@ -0,0 +1,19 @@
1
+ /**
2
+ * 脚本内层调用的落盘记录(恢复用)。
3
+ *
4
+ * 脚本跑几分钟、中途进程被杀时,转录里只有外层 `codemode` 调用悬空,已经执行完的内层调用(写了文件、
5
+ * 推了分支)不在任何地方。每个内层调用完成后追加一条 `custom{customType:"ama.codemode-call"}`
6
+ * (不进上下文):外层调用 id、工具名、目标(与恢复提醒共用 `toolTarget`,bash 只取命令第一个词、
7
+ * 不带参数与结果正文)、是否成功。`session/unclean-end.ts` 在外层调用没有结果时把它们列进恢复提醒。
8
+ * 只记已完成的;被脚本结束取消的不记。记录失败不影响调用本身。
9
+ */
10
+ import type { ToolContext } from "../tools/types.js";
11
+ export declare const INNER_CALL_CUSTOM_TYPE = "ama.codemode-call";
12
+ export interface InnerCallData {
13
+ /** 外层 `codemode` 调用的 toolCallId。 */
14
+ parent: string;
15
+ name: string;
16
+ target?: string;
17
+ ok: boolean;
18
+ }
19
+ export declare function recordInnerCall(session: ToolContext["session"], parent: string, name: string, args: unknown, ok: boolean): void;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * 脚本内层调用的落盘记录(恢复用)。
3
+ *
4
+ * 脚本跑几分钟、中途进程被杀时,转录里只有外层 `codemode` 调用悬空,已经执行完的内层调用(写了文件、
5
+ * 推了分支)不在任何地方。每个内层调用完成后追加一条 `custom{customType:"ama.codemode-call"}`
6
+ * (不进上下文):外层调用 id、工具名、目标(与恢复提醒共用 `toolTarget`,bash 只取命令第一个词、
7
+ * 不带参数与结果正文)、是否成功。`session/unclean-end.ts` 在外层调用没有结果时把它们列进恢复提醒。
8
+ * 只记已完成的;被脚本结束取消的不记。记录失败不影响调用本身。
9
+ */
10
+ import { toolTarget } from "../session/unclean-end.js";
11
+ export const INNER_CALL_CUSTOM_TYPE = "ama.codemode-call";
12
+ export function recordInnerCall(session, parent, name, args, ok) {
13
+ try {
14
+ const record = typeof args === "object" && args !== null && !Array.isArray(args)
15
+ ? args
16
+ : {};
17
+ const target = toolTarget(name, record);
18
+ const data = { parent, name, ok, ...(target !== undefined ? { target } : {}) };
19
+ session.appendCustom(INNER_CALL_CUSTOM_TYPE, data);
20
+ }
21
+ catch {
22
+ // 记录只用于恢复提醒,不能让调用失败
23
+ }
24
+ }
@@ -9,6 +9,7 @@
9
9
  * 子 → 父(子进程 stdout):
10
10
  * - `tool_call`:脚本里的 `tools.<name>(input)`;
11
11
  * - `output`:`text()` / `console.log()` / `return` 产出的一段输出;
12
+ * - `image`:`image(v)` 产出的一张图(子进程先按文件头校验);
12
13
  * - `store`:脚本成功结束且写过 store 时的完整快照,父进程只在 `done.ok` 时提交;
13
14
  * - `done`:脚本结束(成功或失败),带用时。
14
15
  *
@@ -27,6 +28,13 @@ export declare const DEFAULT_SCRIPT_TIMEOUT_MS = 300000;
27
28
  export declare const MAX_SCRIPT_TIMEOUT_MS = 3600000;
28
29
  /** 父进程启动子进程时附加的参数(sandbox-entry.ts 见到它才启动)。 */
29
30
  export declare const SANDBOX_MAIN_FLAG = "--ama-codemode-sandbox";
31
+ /**
32
+ * 脚本里 `searchTools()` 走 `tool_call` 通道的保留名(不是工具名:工具名不含 `@`)。沙箱入口不能
33
+ * import 本文件的运行时代码,引导脚本里写的是同一个字面量。
34
+ */
35
+ export declare const SEARCH_TOOLS_CALL = "@searchTools";
36
+ /** 单个脚本最多附几张图(与 sandbox-entry.ts 的 MAX_SCRIPT_IMAGES 一致)。 */
37
+ export declare const MAX_SCRIPT_IMAGES = 8;
30
38
  /** 同一脚本内并发工具调用上限。 */
31
39
  export declare const MAX_CONCURRENT_TOOL_CALLS = 8;
32
40
  export declare const DEFAULT_SCRIPT_OPTIONS: Readonly<ScriptOptions>;
@@ -64,6 +72,12 @@ export type ChildMessage = {
64
72
  type: "output";
65
73
  text: string;
66
74
  }
75
+ /** `image(v)` 校验过的图片(base64,MIME 由文件头得出);父进程再校验一次,不信任子进程。 */
76
+ | {
77
+ type: "image";
78
+ data: string;
79
+ mimeType: string;
80
+ }
67
81
  /** 脚本成功结束且写过 store 时发:结束时的完整快照(父进程整体替换)。 */
68
82
  | {
69
83
  type: "store";
@@ -9,6 +9,7 @@
9
9
  * 子 → 父(子进程 stdout):
10
10
  * - `tool_call`:脚本里的 `tools.<name>(input)`;
11
11
  * - `output`:`text()` / `console.log()` / `return` 产出的一段输出;
12
+ * - `image`:`image(v)` 产出的一张图(子进程先按文件头校验);
12
13
  * - `store`:脚本成功结束且写过 store 时的完整快照,父进程只在 `done.ok` 时提交;
13
14
  * - `done`:脚本结束(成功或失败),带用时。
14
15
  *
@@ -21,6 +22,13 @@ export const DEFAULT_SCRIPT_TIMEOUT_MS = 300_000;
21
22
  export const MAX_SCRIPT_TIMEOUT_MS = 3_600_000;
22
23
  /** 父进程启动子进程时附加的参数(sandbox-entry.ts 见到它才启动)。 */
23
24
  export const SANDBOX_MAIN_FLAG = "--ama-codemode-sandbox";
25
+ /**
26
+ * 脚本里 `searchTools()` 走 `tool_call` 通道的保留名(不是工具名:工具名不含 `@`)。沙箱入口不能
27
+ * import 本文件的运行时代码,引导脚本里写的是同一个字面量。
28
+ */
29
+ export const SEARCH_TOOLS_CALL = "@searchTools";
30
+ /** 单个脚本最多附几张图(与 sandbox-entry.ts 的 MAX_SCRIPT_IMAGES 一致)。 */
31
+ export const MAX_SCRIPT_IMAGES = 8;
24
32
  /** 同一脚本内并发工具调用上限。 */
25
33
  export const MAX_CONCURRENT_TOOL_CALLS = 8;
26
34
  export const DEFAULT_SCRIPT_OPTIONS = Object.freeze({
@@ -73,7 +81,7 @@ export function encodeLine(message) {
73
81
  .replace(/\u2028/g, "\\u2028")
74
82
  .replace(/\u2029/g, "\\u2029")}\n`;
75
83
  }
76
- const CHILD_TYPES = new Set(["tool_call", "output", "store", "done"]);
84
+ const CHILD_TYPES = new Set(["tool_call", "output", "image", "store", "done"]);
77
85
  const PARENT_TYPES = new Set(["run", "tool_result", "abort"]);
78
86
  function decode(line, types) {
79
87
  let value;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * codemode 的 QuickJS 引擎:主线程一侧(设计 §5.5)。[#290]
3
+ *
4
+ * 与 `runSandbox`(Node 子进程引擎)同一个请求 / 结果形状,tool.ts 按引擎二选一:每次执行起一个
5
+ * worker 线程(worker.ts),脚本跑在 WebAssembly 里的 QuickJS 中,只能经 `tools.*` 触达外界。
6
+ *
7
+ * - `tool_call` → `callTool`(完整门禁,同 host-side.ts);`codemode` 自己直接拒绝;
8
+ * - 超时 / 外层 abort:先写共享的中断标志(QuickJS 的中断处理器读它,空转的脚本会被打断),再 `abort`
9
+ * 消息(脚本在等工具结果时用),宽限后 `worker.terminate()`;结束后一律 terminate;
10
+ * - 内存:`codemode.maxHeapMb`(缺省 256)→ QuickJS 的内存上限;超出时脚本抛 out of memory,映射成与
11
+ * Node 引擎相同的文案;
12
+ * - worker 崩溃 / 非预期退出 → 失败结果,不影响宿主。
13
+ */
14
+ import { type SandboxRunRequest, type SandboxRunResult } from "../host-side.js";
15
+ export declare function runQuickjs(request: SandboxRunRequest): Promise<SandboxRunResult>;
@@ -0,0 +1,243 @@
1
+ /**
2
+ * codemode 的 QuickJS 引擎:主线程一侧(设计 §5.5)。[#290]
3
+ *
4
+ * 与 `runSandbox`(Node 子进程引擎)同一个请求 / 结果形状,tool.ts 按引擎二选一:每次执行起一个
5
+ * worker 线程(worker.ts),脚本跑在 WebAssembly 里的 QuickJS 中,只能经 `tools.*` 触达外界。
6
+ *
7
+ * - `tool_call` → `callTool`(完整门禁,同 host-side.ts);`codemode` 自己直接拒绝;
8
+ * - 超时 / 外层 abort:先写共享的中断标志(QuickJS 的中断处理器读它,空转的脚本会被打断),再 `abort`
9
+ * 消息(脚本在等工具结果时用),宽限后 `worker.terminate()`;结束后一律 terminate;
10
+ * - 内存:`codemode.maxHeapMb`(缺省 256)→ QuickJS 的内存上限;超出时脚本抛 out of memory,映射成与
11
+ * Node 引擎相同的文案;
12
+ * - worker 崩溃 / 非预期退出 → 失败结果,不影响宿主。
13
+ */
14
+ import { Worker } from "node:worker_threads";
15
+ import { BOOTSTRAP, MAX_CONCURRENT, MAX_STORE_TOTAL_CHARS, MAX_STORE_VALUE_CHARS, } from "../sandbox-entry.js";
16
+ import { ABORT_GRACE_MS, DEFAULT_CODEMODE_HEAP_MB, MAX_COLLECTED_OUTPUT_CHARS, heapLimitError, } from "../host-side.js";
17
+ import { MAX_SCRIPT_IMAGES, SEARCH_TOOLS_CALL } from "../protocol.js";
18
+ import { DEFAULT_MAX_WORKERS, MAX_WORKER_WAIT_MS, codemodeWorkerPool } from "../worker-pool.js";
19
+ import { quickjsModule, resolveQuickjsWorker } from "./wasm.js";
20
+ const realTimers = {
21
+ set: (fn, ms) => setTimeout(fn, ms),
22
+ clear: (handle) => clearTimeout(handle),
23
+ };
24
+ export async function runQuickjs(request) {
25
+ const started = Date.now();
26
+ const heapMb = Math.floor(request.maxHeapMb ?? DEFAULT_CODEMODE_HEAP_MB);
27
+ const result = {
28
+ ok: false,
29
+ outputs: [],
30
+ images: [],
31
+ timedOut: false,
32
+ aborted: false,
33
+ toolCalls: 0,
34
+ droppedChars: 0,
35
+ elapsedMs: 0,
36
+ };
37
+ if (request.signal.aborted) {
38
+ return { ...result, error: "Script aborted", aborted: true };
39
+ }
40
+ // 进程级名额(与 Node 引擎共用同一个池):排队 ≤ 60 s 且计入 timeout_ms;名额在 worker 真正退出时归还
41
+ const timeoutMs = request.options.timeoutMs;
42
+ const limit = request.maxWorkers ?? DEFAULT_MAX_WORKERS;
43
+ const slot = await (request.workerPool ?? codemodeWorkerPool).acquire({
44
+ limit,
45
+ waitMs: Math.min(MAX_WORKER_WAIT_MS, timeoutMs),
46
+ signal: request.signal,
47
+ });
48
+ if (slot.status === "aborted") {
49
+ return { ...result, error: "Script aborted", aborted: true };
50
+ }
51
+ if (slot.status === "timeout") {
52
+ const ownDeadline = timeoutMs <= MAX_WORKER_WAIT_MS;
53
+ return {
54
+ ...result,
55
+ timedOut: ownDeadline,
56
+ error: ownDeadline
57
+ ? `Script timed out after ${timeoutMs} ms waiting for a free codemode sandbox slot (${slot.active} of ${limit} in use); it was not run`
58
+ : `Script was not run: all ${limit} codemode sandbox slots stayed busy for ${MAX_WORKER_WAIT_MS / 1000} s; try again when other scripts finish`,
59
+ elapsedMs: slot.waitedMs,
60
+ };
61
+ }
62
+ const lease = slot.lease;
63
+ const runTimeoutMs = Math.max(1, timeoutMs - slot.waitedMs);
64
+ let module;
65
+ let source;
66
+ try {
67
+ module = await quickjsModule();
68
+ source = resolveQuickjsWorker();
69
+ }
70
+ catch (error) {
71
+ lease.release();
72
+ return { ...result, error: `Failed to start codemode sandbox: ${error.message}` };
73
+ }
74
+ const flag = new SharedArrayBuffer(4);
75
+ const flagView = new Int32Array(flag);
76
+ const data = {
77
+ module,
78
+ bootstrap: BOOTSTRAP,
79
+ script: request.script,
80
+ tools: request.tools,
81
+ store: request.store,
82
+ limits: {
83
+ maxConcurrent: MAX_CONCURRENT,
84
+ maxValueChars: MAX_STORE_VALUE_CHARS,
85
+ maxTotalChars: MAX_STORE_TOTAL_CHARS,
86
+ maxImages: MAX_SCRIPT_IMAGES,
87
+ },
88
+ memoryLimitBytes: heapMb > 0 ? heapMb * 1024 * 1024 : 0,
89
+ flag,
90
+ };
91
+ // execArgv 清空:不继承宿主的 --input-type / --inspect 等只对主线程有意义的开关
92
+ const options = { workerData: data, env: {}, execArgv: [], name: "codemode-quickjs" };
93
+ let worker;
94
+ try {
95
+ worker = source.eval
96
+ ? new Worker(source.code, { ...options, eval: true })
97
+ : new Worker(source.file, options);
98
+ }
99
+ catch (error) {
100
+ lease.release();
101
+ return { ...result, error: `Failed to start codemode sandbox: ${error.message}` };
102
+ }
103
+ const calls = new AbortController();
104
+ let collected = 0;
105
+ let settled = false;
106
+ let finish;
107
+ const finished = new Promise((resolve) => (finish = resolve));
108
+ const send = (message) => {
109
+ if (!settled)
110
+ worker.postMessage(message);
111
+ };
112
+ const settle = (patch) => {
113
+ if (settled)
114
+ return;
115
+ settled = true;
116
+ Object.assign(result, patch);
117
+ result.elapsedMs = patch.elapsedMs ?? Date.now() - started;
118
+ calls.abort();
119
+ finish();
120
+ };
121
+ /** 先拉中断标志(空转的脚本据此停下),随后由收尾的 terminate 兜底。 */
122
+ const interrupt = () => {
123
+ Atomics.store(flagView, 0, 1);
124
+ };
125
+ const timers = request.timeoutTimers ?? realTimers;
126
+ const timer = timers.set(() => {
127
+ interrupt();
128
+ settle({
129
+ ok: false,
130
+ timedOut: true,
131
+ error: `Script timed out after ${timeoutMs} ms`,
132
+ });
133
+ }, runTimeoutMs);
134
+ let graceTimer;
135
+ const onAbort = () => {
136
+ interrupt();
137
+ send({ type: "abort" });
138
+ graceTimer = setTimeout(() => settle({ ok: false, aborted: true, error: "Script aborted" }), ABORT_GRACE_MS);
139
+ };
140
+ request.signal.addEventListener("abort", onAbort, { once: true });
141
+ worker.on("message", (message) => {
142
+ if (settled)
143
+ return;
144
+ switch (message.type) {
145
+ case "output": {
146
+ const text = message.text;
147
+ if (collected + text.length > MAX_COLLECTED_OUTPUT_CHARS) {
148
+ result.droppedChars += text.length;
149
+ return;
150
+ }
151
+ collected += text.length;
152
+ result.outputs.push(text);
153
+ request.onOutput?.(text);
154
+ return;
155
+ }
156
+ case "image":
157
+ if (typeof message.data === "string" &&
158
+ typeof message.mimeType === "string" &&
159
+ result.images.length < MAX_SCRIPT_IMAGES) {
160
+ result.images.push({ data: message.data, mimeType: message.mimeType });
161
+ }
162
+ return;
163
+ case "tool_call": {
164
+ const { id, name, input } = message;
165
+ if (name === SEARCH_TOOLS_CALL) {
166
+ const args = (input ?? {});
167
+ try {
168
+ const value = request.searchTools?.(args.query, args.options) ?? [];
169
+ send({ type: "tool_result", id, ok: true, json: JSON.stringify(value) });
170
+ }
171
+ catch (error) {
172
+ send({
173
+ type: "tool_result",
174
+ id,
175
+ ok: false,
176
+ error: error instanceof Error ? error.message : String(error),
177
+ });
178
+ }
179
+ return;
180
+ }
181
+ result.toolCalls++;
182
+ if (name === "codemode") {
183
+ send({
184
+ type: "tool_result",
185
+ id,
186
+ ok: false,
187
+ error: "codemode cannot be called from a codemode script",
188
+ });
189
+ return;
190
+ }
191
+ request.callTool(name, input, calls.signal).then((value) => {
192
+ let json;
193
+ try {
194
+ json = JSON.stringify(value ?? null);
195
+ }
196
+ catch (error) {
197
+ send({ type: "tool_result", id, ok: false, error: error.message });
198
+ return;
199
+ }
200
+ send({ type: "tool_result", id, ok: true, json });
201
+ }, (error) => send({
202
+ type: "tool_result",
203
+ id,
204
+ ok: false,
205
+ error: error instanceof Error ? error.message : String(error),
206
+ }));
207
+ return;
208
+ }
209
+ case "store":
210
+ result.store = message.entries;
211
+ return;
212
+ case "done": {
213
+ const patch = { ok: message.ok, elapsedMs: message.elapsedMs };
214
+ if (message.error !== undefined) {
215
+ patch.error =
216
+ heapMb > 0 && /^InternalError: out of memory/i.test(message.error)
217
+ ? heapLimitError(heapMb)
218
+ : message.error;
219
+ }
220
+ if (request.signal.aborted) {
221
+ patch.ok = false;
222
+ patch.aborted = true;
223
+ }
224
+ if (patch.ok !== true)
225
+ delete result.store;
226
+ settle(patch);
227
+ return;
228
+ }
229
+ }
230
+ });
231
+ worker.on("error", (error) => settle({ ok: false, error: `codemode QuickJS engine crashed: ${error.message}` }));
232
+ worker.on("exit", (code) => {
233
+ lease.release();
234
+ settle({ ok: false, error: `codemode QuickJS engine exited unexpectedly (code ${code})` });
235
+ });
236
+ await finished;
237
+ timers.clear(timer);
238
+ if (graceTimer !== undefined)
239
+ clearTimeout(graceTimer);
240
+ request.signal.removeEventListener("abort", onAbort);
241
+ void worker.terminate();
242
+ return result;
243
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * QuickJS 引擎的资源定位:编译好的 `WebAssembly.Module`(进程内缓存,传给每个 worker)与 worker 入口。[#290]
3
+ *
4
+ * - bundle(ama.cjs):构建脚本把 wasm 的 base64 与 worker 的单文件源码定义成 `__AMA_QUICKJS_WASM_B64__` /
5
+ * `__AMA_QUICKJS_WORKER_SOURCE__`,运行时不需要任何旁路文件;
6
+ * - tsc 产物与源码树:`assets/quickjs/quickjs.wasm`(相对本文件三级目录上去,npm 包的 `files` 带着它)
7
+ * 与同目录的 `worker.js` / `worker.ts`。
8
+ */
9
+ /** wasm 字节:bundle 内嵌,否则读 assets 目录。 */
10
+ export declare function readQuickjsWasm(moduleUrl?: string): Buffer;
11
+ /** 编译一次,之后每个 worker 复用(`WebAssembly.Module` 可经 workerData 结构化克隆)。 */
12
+ export declare function quickjsModule(): Promise<WebAssembly.Module>;
13
+ /** worker 的启动方式:bundle 里是内嵌源码(eval worker),否则是文件。 */
14
+ export type WorkerSource = {
15
+ eval: true;
16
+ code: string;
17
+ } | {
18
+ eval: false;
19
+ file: URL;
20
+ };
21
+ export declare function resolveQuickjsWorker(moduleUrl?: string): WorkerSource;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * QuickJS 引擎的资源定位:编译好的 `WebAssembly.Module`(进程内缓存,传给每个 worker)与 worker 入口。[#290]
3
+ *
4
+ * - bundle(ama.cjs):构建脚本把 wasm 的 base64 与 worker 的单文件源码定义成 `__AMA_QUICKJS_WASM_B64__` /
5
+ * `__AMA_QUICKJS_WORKER_SOURCE__`,运行时不需要任何旁路文件;
6
+ * - tsc 产物与源码树:`assets/quickjs/quickjs.wasm`(相对本文件三级目录上去,npm 包的 `files` 带着它)
7
+ * 与同目录的 `worker.js` / `worker.ts`。
8
+ */
9
+ import { existsSync, readFileSync } from "node:fs";
10
+ import { dirname, join } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ let compiled;
13
+ /** wasm 字节:bundle 内嵌,否则读 assets 目录。 */
14
+ export function readQuickjsWasm(moduleUrl = import.meta.url) {
15
+ if (typeof __AMA_QUICKJS_WASM_B64__ !== "undefined") {
16
+ return Buffer.from(__AMA_QUICKJS_WASM_B64__, "base64");
17
+ }
18
+ const here = dirname(fileURLToPath(moduleUrl));
19
+ return readFileSync(join(here, "..", "..", "..", "assets", "quickjs", "quickjs.wasm"));
20
+ }
21
+ /** 编译一次,之后每个 worker 复用(`WebAssembly.Module` 可经 workerData 结构化克隆)。 */
22
+ export function quickjsModule() {
23
+ compiled ??= WebAssembly.compile(readQuickjsWasm()).catch((error) => {
24
+ compiled = undefined;
25
+ throw error;
26
+ });
27
+ return compiled;
28
+ }
29
+ export function resolveQuickjsWorker(moduleUrl = import.meta.url) {
30
+ if (typeof __AMA_QUICKJS_WORKER_SOURCE__ !== "undefined") {
31
+ return { eval: true, code: __AMA_QUICKJS_WORKER_SOURCE__ };
32
+ }
33
+ const here = dirname(fileURLToPath(moduleUrl));
34
+ for (const name of ["worker.js", "worker.ts"]) {
35
+ if (existsSync(join(here, name)))
36
+ return { eval: false, file: new URL(name, moduleUrl) };
37
+ }
38
+ throw new Error("codemode QuickJS worker not found (build the package first)");
39
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * codemode 的 QuickJS 引擎:worker 线程入口(设计 §5.5)。[#290]
3
+ *
4
+ * 每次执行一个 worker:用主线程编译好的 `WebAssembly.Module` 实例化 QuickJS(WASI reactor),在 VM 里
5
+ * 先冻结内建对象,再跑与 Node 引擎同一份引导脚本(`BOOTSTRAP`,由主线程经 `workerData` 传入),最后跑
6
+ * 模型写的脚本。VM 里没有 require / process / fetch / 定时器:它与外界只有一个宿主函数 `host(kind,
7
+ * payload)`,WASI 只给时钟、随机数与丢弃的 stdout / stderr。
8
+ *
9
+ * - 主线程 ↔ worker 的消息沿用 protocol.ts 的 `ChildMessage` 形状(`tool_call` / `output` / `store` /
10
+ * `done`),反向是 `tool_result`(值已是 JSON 字符串)与 `abort`;
11
+ * - 中断:QuickJS 的中断处理器读 `SharedArrayBuffer` 里的一个标志位;Promise 任务一件一件执行,每 64
12
+ * 件再读一次标志,所以 `while (true) await null` 这类不经过解释器轮询点的循环也能停下;
13
+ * - 内存:`qjs_set_memory_limit`;JS 递归由 `qjs_set_max_stack_size` 转成脚本里可捕获的 RangeError;不经 JS 调用的原生递归仍会以宿主陷阱的形式冒出来,此时 VM 不再可用,直接以失败结束;
14
+ * - 脚本等待一个永远不会落定的 Promise(没有未完成的工具调用)时立即失败,不拖到超时。
15
+ *
16
+ * 本文件**只能 import node: 内置模块与类型**:源码树里它被 Node 直接剥离类型运行(不经构建),打进
17
+ * ama.cjs 时由 build-bundle.mjs 单独编译成字符串内嵌;所以不依赖任何其它源文件的运行时代码。
18
+ */
19
+ import type { ChildMessage, ToolDecl } from "../protocol.js";
20
+ /** 主线程经 `workerData` 传入的启动参数。 */
21
+ export interface QuickjsWorkerData {
22
+ module: WebAssembly.Module;
23
+ /** 与 Node 引擎共用的引导脚本源码(sandbox-entry.ts 的 BOOTSTRAP)。 */
24
+ bootstrap: string;
25
+ script: string;
26
+ tools: ToolDecl[];
27
+ store: Record<string, unknown>;
28
+ /** 引导脚本的配置:并发上限与 store 上限。 */
29
+ limits: {
30
+ maxConcurrent: number;
31
+ maxValueChars: number;
32
+ maxTotalChars: number;
33
+ maxImages: number;
34
+ };
35
+ /** QuickJS 内存上限(字节);0 不设上限。 */
36
+ memoryLimitBytes: number;
37
+ /** 4 字节的中断标志:非 0 表示该停了。 */
38
+ flag: SharedArrayBuffer;
39
+ }
40
+ /** worker → 主线程的消息:ChildMessage(含 done)。 */
41
+ export type WorkerOutMessage = ChildMessage;
42
+ /** 主线程 → worker。 */
43
+ export type WorkerInMessage = {
44
+ type: "tool_result";
45
+ id: number;
46
+ ok: true;
47
+ json: string | undefined;
48
+ } | {
49
+ type: "tool_result";
50
+ id: number;
51
+ ok: false;
52
+ error: string;
53
+ } | {
54
+ type: "abort";
55
+ };