@armadra/agent 0.17.3 → 0.18.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 (88) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/CHANGELOG.zh-CN.md +30 -0
  3. package/THIRD_PARTY_NOTICES.md +6 -0
  4. package/assets/quickjs/LICENSE +57 -0
  5. package/assets/quickjs/README.md +14 -0
  6. package/assets/quickjs/quickjs.wasm +0 -0
  7. package/dist/agent/recovery-reminder.js +6 -1
  8. package/dist/agent/schema-coerce.d.ts +24 -0
  9. package/dist/agent/schema-coerce.js +157 -0
  10. package/dist/agent/schema.d.ts +1 -1
  11. package/dist/agent/schema.js +1 -1
  12. package/dist/agent/session-cache.js +12 -0
  13. package/dist/agent/tool-runner.js +57 -28
  14. package/dist/agent/types.d.ts +4 -0
  15. package/dist/ai/apis/anthropic-compat.d.ts +3 -1
  16. package/dist/ai/apis/anthropic-compat.js +8 -1
  17. package/dist/ai/apis/anthropic-messages.js +54 -2
  18. package/dist/ai/apis/anthropic-request.d.ts +3 -0
  19. package/dist/ai/apis/anthropic-request.js +7 -1
  20. package/dist/ai/apis/anthropic-threads.d.ts +64 -0
  21. package/dist/ai/apis/anthropic-threads.js +192 -0
  22. package/dist/ai/providers/catalog-data.js +5 -5
  23. package/dist/ai/providers/models-dev-data.js +22 -22
  24. package/dist/ai/types.d.ts +16 -0
  25. package/dist/bundle/ama-sandbox.cjs +96 -2
  26. package/dist/bundle/ama.cjs +2386 -890
  27. package/dist/cli/subcommands/config.d.ts +3 -0
  28. package/dist/cli/subcommands/config.js +22 -7
  29. package/dist/cli/subcommands/doctor.js +1 -0
  30. package/dist/cli/subcommands/models-discover.js +6 -2
  31. package/dist/codemode/capability.d.ts +14 -2
  32. package/dist/codemode/capability.js +19 -2
  33. package/dist/codemode/host-side.d.ts +14 -0
  34. package/dist/codemode/host-side.js +81 -10
  35. package/dist/codemode/inner-calls.d.ts +19 -0
  36. package/dist/codemode/inner-calls.js +24 -0
  37. package/dist/codemode/protocol.d.ts +14 -0
  38. package/dist/codemode/protocol.js +9 -1
  39. package/dist/codemode/quickjs/host.d.ts +15 -0
  40. package/dist/codemode/quickjs/host.js +243 -0
  41. package/dist/codemode/quickjs/wasm.d.ts +21 -0
  42. package/dist/codemode/quickjs/wasm.js +39 -0
  43. package/dist/codemode/quickjs/worker.d.ts +55 -0
  44. package/dist/codemode/quickjs/worker.js +457 -0
  45. package/dist/codemode/sandbox-entry.d.ts +4 -0
  46. package/dist/codemode/sandbox-entry.js +95 -3
  47. package/dist/codemode/script-images.d.ts +18 -0
  48. package/dist/codemode/script-images.js +38 -0
  49. package/dist/codemode/script-output.d.ts +19 -0
  50. package/dist/codemode/script-output.js +67 -0
  51. package/dist/codemode/search-tools.d.ts +27 -0
  52. package/dist/codemode/search-tools.js +83 -0
  53. package/dist/codemode/tool.d.ts +4 -0
  54. package/dist/codemode/tool.js +60 -9
  55. package/dist/codemode/worker-pool.d.ts +65 -0
  56. package/dist/codemode/worker-pool.js +131 -0
  57. package/dist/config/json-schema.js +3 -1
  58. package/dist/config/key-docs.js +7 -1
  59. package/dist/config/schema.js +4 -2
  60. package/dist/config/settings-registry.js +2 -0
  61. package/dist/config/types.d.ts +10 -0
  62. package/dist/config/types.js +1 -0
  63. package/dist/i18n/catalog.d.ts +8 -0
  64. package/dist/i18n/messages/config-keys.d.ts +4 -0
  65. package/dist/i18n/messages/config-keys.js +6 -2
  66. package/dist/i18n/messages/config.d.ts +4 -0
  67. package/dist/i18n/messages/interactive-view.d.ts +2 -0
  68. package/dist/i18n/messages/interactive-view.js +2 -0
  69. package/dist/i18n/messages/interactive.d.ts +2 -0
  70. package/dist/i18n/messages/report.d.ts +2 -0
  71. package/dist/i18n/messages/report.js +2 -0
  72. package/dist/i18n/messages/subcommands-config.d.ts +8 -0
  73. package/dist/i18n/messages/subcommands-config.js +8 -0
  74. package/dist/i18n/messages/subcommands.d.ts +8 -0
  75. package/dist/modes/interactive/tool-view.d.ts +8 -2
  76. package/dist/modes/interactive/tool-view.js +12 -5
  77. package/dist/session/unclean-end.d.ts +8 -0
  78. package/dist/session/unclean-end.js +39 -7
  79. package/docs/en/guides/providers.md +27 -7
  80. package/docs/en/guides/tui.md +1 -1
  81. package/docs/en/reference/rpc.md +3 -1
  82. package/docs/guides/codemode.md +52 -12
  83. package/docs/guides/providers.md +21 -1
  84. package/docs/guides/sandbox.md +2 -0
  85. package/docs/guides/tui.md +1 -1
  86. package/docs/reference/rpc.md +3 -1
  87. package/docs/reference/session-format.md +10 -9
  88. package/package.json +2 -1
@@ -0,0 +1,67 @@
1
+ /**
2
+ * 脚本内 `tools.bash` 的输出放宽(codemode 指南「返回值」)。
3
+ *
4
+ * 直接调用时 bash 的结果按会话上限尾截断(2000 行 / 50 KB),全文落在 `fullOutputPath`。脚本里要
5
+ * 自己过滤、统计输出,这个上限太紧:`output` 放宽到 1 MiB;更长时保留首尾各 512 KiB,中间换成说明,
6
+ * `truncated` 为真,全文仍在 `fullOutputPath`。只改脚本拿到的值,模型直接调用 bash 的结果不变。
7
+ */
8
+ import { open } from "node:fs/promises";
9
+ import { sanitizeOutput } from "../tools/output-accumulator.js";
10
+ export const SCRIPT_OUTPUT_LIMIT_BYTES = 1024 * 1024;
11
+ export const SCRIPT_OUTPUT_HALF_BYTES = SCRIPT_OUTPUT_LIMIT_BYTES / 2;
12
+ /** 从缓冲区头部取 UTF-8 文本,丢掉末尾被截断的半个字符。 */
13
+ function decodeHead(buffer) {
14
+ let end = buffer.length;
15
+ // 回退到最后一个完整字符之前:末尾若有不完整的多字节序列就整体丢掉
16
+ let back = 0;
17
+ while (back < 3 && end - back > 0 && ((buffer[end - back - 1] ?? 0) & 0xc0) === 0x80)
18
+ back++;
19
+ const lead = buffer[end - back - 1] ?? 0;
20
+ const need = lead >= 0xf0 ? 4 : lead >= 0xe0 ? 3 : lead >= 0xc0 ? 2 : 1;
21
+ if (need > back + 1)
22
+ end = end - back - 1;
23
+ return buffer.subarray(0, end).toString("utf8");
24
+ }
25
+ /** 从缓冲区尾部取 UTF-8 文本,丢掉开头的续字节。 */
26
+ function decodeTail(buffer) {
27
+ let start = 0;
28
+ while (start < buffer.length && ((buffer[start] ?? 0) & 0xc0) === 0x80)
29
+ start++;
30
+ return buffer.subarray(start).toString("utf8");
31
+ }
32
+ /**
33
+ * bash 结果被直接调用的上限截过(`truncated` 且有全文文件)时,按脚本的上限重新取 `output`;读不到
34
+ * 文件就原样返回。全文 ≤ 1 MiB 时 `output` 是全文、`truncated` 为假。
35
+ */
36
+ export async function widenScriptBashOutput(value) {
37
+ const path = value.fullOutputPath;
38
+ if (!value.truncated || path === undefined)
39
+ return value;
40
+ let handle;
41
+ try {
42
+ handle = await open(path, "r");
43
+ const { size } = await handle.stat();
44
+ if (size <= SCRIPT_OUTPUT_LIMIT_BYTES) {
45
+ const whole = Buffer.alloc(size);
46
+ await handle.read(whole, 0, size, 0);
47
+ return { ...value, output: sanitizeOutput(whole.toString("utf8")), truncated: false };
48
+ }
49
+ const head = Buffer.alloc(SCRIPT_OUTPUT_HALF_BYTES);
50
+ const tail = Buffer.alloc(SCRIPT_OUTPUT_HALF_BYTES);
51
+ await handle.read(head, 0, head.length, 0);
52
+ await handle.read(tail, 0, tail.length, size - tail.length);
53
+ const omitted = size - SCRIPT_OUTPUT_LIMIT_BYTES;
54
+ const marker = `\n[... ${omitted} bytes omitted; full output: ${path} ...]\n`;
55
+ return {
56
+ ...value,
57
+ output: `${sanitizeOutput(decodeHead(head))}${marker}${sanitizeOutput(decodeTail(tail))}`,
58
+ truncated: true,
59
+ };
60
+ }
61
+ catch {
62
+ return value;
63
+ }
64
+ finally {
65
+ await handle?.close().catch(() => { });
66
+ }
67
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * 脚本里的 `searchTools(query, { limit?, namespace? })`:在可调用工具里按 BM25(名字 + 描述)排序。
3
+ *
4
+ * 工具很多时(宿主注册了一批 `canvas_*` 之类),描述里放不下全部声明,脚本先搜再用
5
+ * `describeTool(name)` 取签名。纯函数,每次调用现建索引(工具几十个,微秒级)。
6
+ */
7
+ export declare const DEFAULT_SEARCH_LIMIT = 8;
8
+ export declare const MAX_SEARCH_LIMIT = 50;
9
+ /** 结果里描述的字符上限。 */
10
+ export declare const SEARCH_DESCRIPTION_CHARS = 240;
11
+ export interface SearchableTool {
12
+ name: string;
13
+ description: string;
14
+ }
15
+ export interface SearchToolsOptions {
16
+ limit?: number;
17
+ /** 工具名的前缀(`_` `.` `:` `-` 之前的部分),例如 `canvas` 匹配 `canvas_add`。 */
18
+ namespace?: string;
19
+ }
20
+ export interface SearchHit {
21
+ name: string;
22
+ description: string;
23
+ }
24
+ /** 小写,按非字母数字切词,驼峰也切开;`read_file` → read / file。 */
25
+ export declare function tokenize(text: string): string[];
26
+ /** 参数检查失败抛 TypeError(消息给脚本);没有命中返回空数组。 */
27
+ export declare function searchTools(tools: readonly SearchableTool[], query: unknown, options?: unknown): SearchHit[];
@@ -0,0 +1,83 @@
1
+ /**
2
+ * 脚本里的 `searchTools(query, { limit?, namespace? })`:在可调用工具里按 BM25(名字 + 描述)排序。
3
+ *
4
+ * 工具很多时(宿主注册了一批 `canvas_*` 之类),描述里放不下全部声明,脚本先搜再用
5
+ * `describeTool(name)` 取签名。纯函数,每次调用现建索引(工具几十个,微秒级)。
6
+ */
7
+ export const DEFAULT_SEARCH_LIMIT = 8;
8
+ export const MAX_SEARCH_LIMIT = 50;
9
+ /** 结果里描述的字符上限。 */
10
+ export const SEARCH_DESCRIPTION_CHARS = 240;
11
+ const K1 = 1.2;
12
+ const B = 0.75;
13
+ /** 小写,按非字母数字切词,驼峰也切开;`read_file` → read / file。 */
14
+ export function tokenize(text) {
15
+ return text
16
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
17
+ .toLowerCase()
18
+ .split(/[^\p{L}\p{N}]+/u)
19
+ .filter((token) => token !== "");
20
+ }
21
+ function inNamespace(name, namespace) {
22
+ const prefix = namespace.toLowerCase();
23
+ const lower = name.toLowerCase();
24
+ if (!lower.startsWith(prefix))
25
+ return false;
26
+ const next = lower[prefix.length];
27
+ return next === undefined || /[_.:-]/.test(next);
28
+ }
29
+ function shorten(description) {
30
+ const firstParagraph = description.trim().split(/\n\s*\n/, 1)[0] ?? "";
31
+ const oneLine = firstParagraph.replace(/\s+/g, " ");
32
+ return oneLine.length > SEARCH_DESCRIPTION_CHARS
33
+ ? `${oneLine.slice(0, SEARCH_DESCRIPTION_CHARS - 1)}…`
34
+ : oneLine;
35
+ }
36
+ /** 参数检查失败抛 TypeError(消息给脚本);没有命中返回空数组。 */
37
+ export function searchTools(tools, query, options = {}) {
38
+ if (typeof query !== "string")
39
+ throw new TypeError("searchTools(query): query must be a string");
40
+ if (typeof options !== "object" || options === null || Array.isArray(options)) {
41
+ throw new TypeError("searchTools(query, options): options must be an object");
42
+ }
43
+ const { limit: rawLimit, namespace } = options;
44
+ if (rawLimit !== undefined &&
45
+ (typeof rawLimit !== "number" || !Number.isInteger(rawLimit) || rawLimit < 1)) {
46
+ throw new TypeError("searchTools: limit must be a positive integer");
47
+ }
48
+ if (namespace !== undefined && typeof namespace !== "string") {
49
+ throw new TypeError("searchTools: namespace must be a string");
50
+ }
51
+ const limit = Math.min(rawLimit ?? DEFAULT_SEARCH_LIMIT, MAX_SEARCH_LIMIT);
52
+ const pool = tools.filter((tool) => namespace === undefined || namespace === "" || inNamespace(tool.name, namespace));
53
+ const queryTerms = [...new Set(tokenize(query))];
54
+ if (queryTerms.length === 0 || pool.length === 0)
55
+ return [];
56
+ const docs = pool.map((tool) => ({ tool, terms: tokenize(`${tool.name} ${tool.description}`) }));
57
+ const avgLength = docs.reduce((sum, doc) => sum + doc.terms.length, 0) / docs.length || 1;
58
+ const docFreq = new Map();
59
+ for (const doc of docs) {
60
+ for (const term of new Set(doc.terms))
61
+ docFreq.set(term, (docFreq.get(term) ?? 0) + 1);
62
+ }
63
+ const scored = docs.map((doc, index) => {
64
+ const counts = new Map();
65
+ for (const term of doc.terms)
66
+ counts.set(term, (counts.get(term) ?? 0) + 1);
67
+ let score = 0;
68
+ for (const term of queryTerms) {
69
+ const tf = counts.get(term) ?? 0;
70
+ if (tf === 0)
71
+ continue;
72
+ const df = docFreq.get(term) ?? 0;
73
+ const idf = Math.log(1 + (docs.length - df + 0.5) / (df + 0.5));
74
+ score += (idf * tf * (K1 + 1)) / (tf + K1 * (1 - B + (B * doc.terms.length) / avgLength));
75
+ }
76
+ return { tool: doc.tool, score, index };
77
+ });
78
+ return scored
79
+ .filter((entry) => entry.score > 0)
80
+ .sort((a, b) => b.score - a.score || a.tool.name.localeCompare(b.tool.name) || a.index - b.index)
81
+ .slice(0, limit)
82
+ .map(({ tool }) => ({ name: tool.name, description: shorten(tool.description) }));
83
+ }
@@ -50,6 +50,8 @@ export interface CodemodeToolOptions {
50
50
  nodePath?: string;
51
51
  /** 子进程堆上限(MB,`codemode.maxHeapMb`);缺省 256,0 不设上限。 */
52
52
  maxHeapMb?: number;
53
+ /** `codemode.maxWorkers`;环境变量 `AMA_CODEMODE_MAX_WORKERS` 优先,每次执行时读取。 */
54
+ maxWorkers?: number;
53
55
  }
54
56
  export interface CodemodeDetails {
55
57
  ok: boolean;
@@ -59,6 +61,8 @@ export interface CodemodeDetails {
59
61
  aborted: boolean;
60
62
  strict: boolean;
61
63
  fullOutputPath?: string;
64
+ /** `image()` 的图落盘的路径。 */
65
+ imagePaths?: string[];
62
66
  error?: string;
63
67
  }
64
68
  /** 脚本里拿到的 bash 结果。 */
@@ -23,7 +23,13 @@ import { codemodeCallableFilter, resolveCodemodeMode } from "../tools/presets.js
23
23
  import { codemodeAvailability, detectSandboxCapability, sandboxCapabilityFor, strictNeedsOsSandbox, } from "./capability.js";
24
24
  import { BASH_RESULT_DECLARATION, DEFAULT_INLINE_BUDGET, buildDeclarationBlock, toolDeclaration, } from "./declarations.js";
25
25
  import { runSandbox } from "./host-side.js";
26
+ import { runQuickjs } from "./quickjs/host.js";
26
27
  import { parseOptionsLine } from "./protocol.js";
28
+ import { recordInnerCall } from "./inner-calls.js";
29
+ import { prepareScriptImages } from "./script-images.js";
30
+ import { searchTools } from "./search-tools.js";
31
+ import { widenScriptBashOutput } from "./script-output.js";
32
+ import { resolveMaxWorkers } from "./worker-pool.js";
27
33
  import { commitStore, readStore } from "./store.js";
28
34
  export const CODEMODE_TOOL_NAME = "codemode";
29
35
  /** 与 agent/tool-runner.ts 的 DEFAULT_MAX_TOOL_RESULT_CHARS 一致(codemode 与 tools 同层,不 import agent)。 */
@@ -33,6 +39,12 @@ function textOf(content) {
33
39
  return content;
34
40
  return content.map((block) => (block.type === "text" ? block.text : "")).join("");
35
41
  }
42
+ function isScriptBashResult(value) {
43
+ return (typeof value === "object" &&
44
+ value !== null &&
45
+ typeof value.output === "string" &&
46
+ typeof value.exitCode === "number");
47
+ }
36
48
  function isBashStructured(value) {
37
49
  return (typeof value === "object" &&
38
50
  value !== null &&
@@ -55,6 +67,13 @@ export function toScriptValue(name, result) {
55
67
  }
56
68
  if (result.isError === true)
57
69
  throw new Error(textOf(result.content) || `Tool ${name} failed`);
70
+ // 图片结果(read 一张图)给脚本一个 image() 直接收的图片块
71
+ if (result.structured === undefined && Array.isArray(result.content)) {
72
+ const image = result.content.find((block) => block.type === "image");
73
+ if (image !== undefined && image.type === "image") {
74
+ return { type: "image", data: image.data, mimeType: image.mimeType };
75
+ }
76
+ }
58
77
  return result.structured !== undefined ? result.structured : textOf(result.content);
59
78
  }
60
79
  /** 描述里的示例脚本(6 行):并发两个 read、过滤、return。 */
@@ -72,7 +91,7 @@ const SCRIPT_ONLY_GLOBALS = /\b(require|process|fetch|setTimeout|setInterval|set
72
91
  * (实测模型常见的两种错误)。其它错误原样返回。
73
92
  */
74
93
  export function scriptErrorHint(error, toolNames) {
75
- if (/Cannot use import statement|dynamic import callback/.test(error) ||
94
+ if (/Cannot use import statement|dynamic import callback|could not load module/.test(error) ||
76
95
  SCRIPT_ONLY_GLOBALS.test(error)) {
77
96
  return `${error}\nOnly tools.<name>(args) is available in codemode scripts (no require, import, process, fetch or timers).`;
78
97
  }
@@ -98,7 +117,7 @@ function buildOnDescription(tools, capability) {
98
117
  "Input: raw JavaScript (not JSON, no code fence), the body of an async function (top-level await and return work). Only tools.<name>(args) exists: no require, import, process, fetch or timers.",
99
118
  "Example:",
100
119
  ...CODEMODE_EXAMPLE,
101
- "tools.<name>(args) returns a Promise that rejects when the call fails or is denied (Promise.allSettled keeps the rest); text(v) / console.log(...) append output; return v is text(v); store(key, v) / load(key) keep small JSON values across scripts; describeTool(name) returns a signature. At most 8 calls run at once, each through the normal permissions.",
120
+ "tools.<name>(args) returns a Promise that rejects when the call fails or is denied (Promise.allSettled keeps the rest); text(v) / console.log(...) append output; return v is text(v); store(key, v) / load(key) keep small JSON values across scripts; describeTool(name) returns a signature; searchTools(query, {limit?, namespace?}) ranks tools; image(v) attaches a data: URL or tools.read image. At most 8 calls run at once, each through the normal permissions.",
102
121
  ];
103
122
  if (!capability.strict)
104
123
  lines.push(`Sandbox: ${capability.reason}.`);
@@ -121,7 +140,7 @@ export function buildCodemodeDescription(tools, inlineBudget, capability, layout
121
140
  'The input is raw JavaScript (not JSON, no code fence), run as the body of an async function: top-level await and return work. Optional first line: // @options: {"max_output_tokens": 10000, "timeout_ms": 300000}',
122
141
  "Example:",
123
142
  ...CODEMODE_EXAMPLE,
124
- "Globals: tools.<name>(args) returns a Promise and rejects with an Error when the call fails or is denied (use Promise.allSettled to keep the rest); text(v) and console.log(...) append output (non-strings as JSON); return v is text(v); store(key, v) / load(key) keep small JSON values across scripts (saved only when the script succeeds); ALL_TOOLS lists callable tools; describeTool(name) returns a declaration. At most 8 tool calls run at once; codemode cannot call itself. Every call goes through the normal hooks, permissions and approvals.",
143
+ "Globals: tools.<name>(args) returns a Promise and rejects with an Error when the call fails or is denied (use Promise.allSettled to keep the rest); text(v) and console.log(...) append output (non-strings as JSON); return v is text(v); store(key, v) / load(key) keep small JSON values across scripts (saved only when the script succeeds); ALL_TOOLS lists callable tools; describeTool(name) returns a declaration; searchTools(query, {limit?, namespace?}) ranks callable tools by name and description; image(v) attaches a PNG/JPEG/GIF/WebP data: URL or a tools.read image result to your result. At most 8 tool calls run at once; codemode cannot call itself. Every call goes through the normal hooks, permissions and approvals.",
125
144
  ];
126
145
  if (!capability.strict) {
127
146
  lines.push(`Sandbox: ${capability.reason}.`);
@@ -155,18 +174,22 @@ export function formatCodemodeResult(run, limitChars, saveFull) {
155
174
  result.fullOutputPath = fullOutputPath;
156
175
  return result;
157
176
  }
158
- function saveFullOutput(ctx, text) {
177
+ /** 超长文本与 `image()` 的图共用的落盘位置:`<会话目录>/outputs`(内存会话为系统临时目录)。 */
178
+ function saveOutputFile(ctx, suffix, data) {
159
179
  try {
160
180
  const dir = ctx.outputDir ?? join(tmpdir(), "ama-codemode");
161
181
  mkdirSync(dir, { recursive: true });
162
- const file = join(dir, `${ctx.toolCallId.replace(/[^A-Za-z0-9_-]/g, "_")}.txt`);
163
- writeFileSync(file, text, "utf8");
182
+ const file = join(dir, `${ctx.toolCallId.replace(/[^A-Za-z0-9_-]/g, "_")}${suffix}`);
183
+ writeFileSync(file, data);
164
184
  return file;
165
185
  }
166
186
  catch {
167
187
  return undefined;
168
188
  }
169
189
  }
190
+ function saveFullOutput(ctx, text) {
191
+ return saveOutputFile(ctx, ".txt", text);
192
+ }
170
193
  const TAIL_CHARS = 4000;
171
194
  /** `only` 模式的系统提示规则(实测模型仍会先直接调用 read / edit / bash)。 */
172
195
  export const CODEMODE_ONLY_GUIDELINE = "read, edit, write, bash and the other tools are not callable directly here: every tool call goes inside a codemode script as tools.<name>(args); batch related calls in one script.";
@@ -212,7 +235,9 @@ export function createCodemodeTool(options) {
212
235
  // 只有清单里的工具可调(coordinator 预设的清单只含活动集);脚本拼出别的名字也不放行。
213
236
  const callable = new Set(tools.map((t) => t.name));
214
237
  let tail = "";
215
- const run = await runSandbox({
238
+ // 引擎二选一:QuickJS(WebAssembly worker)或 Node 子进程;请求与结果同一形状
239
+ const execute = capability.engine === "quickjs" ? runQuickjs : runSandbox;
240
+ const run = await execute({
216
241
  script: input.script,
217
242
  options: scriptOptions,
218
243
  tools,
@@ -223,10 +248,21 @@ export function createCodemodeTool(options) {
223
248
  ...(options.entry !== undefined ? { entry: options.entry } : {}),
224
249
  ...(options.nodePath !== undefined ? { nodePath: options.nodePath } : {}),
225
250
  ...(options.maxHeapMb !== undefined ? { maxHeapMb: options.maxHeapMb } : {}),
251
+ maxWorkers: resolveMaxWorkers(options.maxWorkers),
252
+ searchTools: (query, searchOptions) => searchTools(options
253
+ .listTools()
254
+ .map(({ tool: t }) => ({ name: t.name, description: t.description })), query, searchOptions),
226
255
  callTool: async (name, args, signal) => {
227
256
  if (!callable.has(name))
228
257
  throw new Error(`Tool ${name} is not available in codemode`);
229
- return toScriptValue(name, await ctx.tools.executeTool(name, args, { signal }));
258
+ const result = await ctx.tools.executeTool(name, args, { signal });
259
+ if (!signal.aborted) {
260
+ recordInnerCall(ctx.session, ctx.toolCallId, name, args, result.isError !== true);
261
+ }
262
+ const value = toScriptValue(name, result);
263
+ return name === "bash" && isScriptBashResult(value)
264
+ ? widenScriptBashOutput(value)
265
+ : value;
230
266
  },
231
267
  onOutput: (text) => {
232
268
  tail = `${tail}${tail === "" ? "" : "\n"}${text}`.slice(-TAIL_CHARS);
@@ -245,6 +281,7 @@ export function createCodemodeTool(options) {
245
281
  }
246
282
  const limitChars = Math.max(1000, Math.min(scriptOptions.maxOutputTokens * 4, maxResultChars - 500));
247
283
  const formatted = formatCodemodeResult(run, limitChars, (text) => saveFullOutput(ctx, text));
284
+ const images = await prepareScriptImages(run.images, (bytes, extension, n) => saveOutputFile(ctx, `-image-${n}.${extension}`, bytes));
248
285
  const details = {
249
286
  ok: run.ok,
250
287
  elapsedMs: run.elapsedMs,
@@ -257,7 +294,18 @@ export function createCodemodeTool(options) {
257
294
  details.fullOutputPath = formatted.fullOutputPath;
258
295
  if (run.error !== undefined)
259
296
  details.error = run.error;
260
- return { content: formatted.text, isError: !run.ok, details };
297
+ if (images.paths.length > 0)
298
+ details.imagePaths = images.paths;
299
+ if (images.notes.length === 0)
300
+ return { content: formatted.text, isError: !run.ok, details };
301
+ return {
302
+ content: [
303
+ { type: "text", text: `${formatted.text}\n\n${images.notes.join("\n")}` },
304
+ ...images.blocks,
305
+ ],
306
+ isError: !run.ok,
307
+ details,
308
+ };
261
309
  },
262
310
  renderCall(input, width) {
263
311
  const lines = input.script.split("\n");
@@ -320,6 +368,9 @@ export function codemodeToolFactory(overrides = {}) {
320
368
  const heapMb = ctx.config.codemode?.maxHeapMb;
321
369
  if (heapMb !== undefined)
322
370
  options.maxHeapMb = heapMb;
371
+ const workers = ctx.config.codemode?.maxWorkers;
372
+ if (workers !== undefined)
373
+ options.maxWorkers = workers;
323
374
  const maxChars = ctx.config.tools?.maxToolResultChars;
324
375
  if (maxChars !== undefined)
325
376
  options.maxResultChars = maxChars;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * codemode 脚本子进程的进程级并发闸门(设计 §5.5 沙箱)。
3
+ *
4
+ * 整个 ama 进程(所有会话、所有子 Agent)共享一个池:同时存活的沙箱子进程不超过上限(缺省 2),
5
+ * 多出的脚本按先来先到排队。等待不超过 60 s,也不超过脚本自己的 `timeout_ms`(等待计入超时);
6
+ * 等待期间外层 abort 立即结束。名额在子进程**真正退出**(`close`)时才归还,而不是脚本结果落定时:
7
+ * 结果已经给了模型,但被杀的进程树还没死透时,新脚本不该顶上去。
8
+ *
9
+ * 上限每次获取时重新读取:环境变量 `AMA_CODEMODE_MAX_WORKERS`(正整数)优先于配置
10
+ * `codemode.maxWorkers`,都没有或不合法用缺省。时钟可注入,测试不用真实等待。
11
+ */
12
+ export declare const DEFAULT_MAX_WORKERS = 2;
13
+ /** 排队等名额的上限(毫秒)。 */
14
+ export declare const MAX_WORKER_WAIT_MS = 60000;
15
+ export declare const MAX_WORKERS_ENV = "AMA_CODEMODE_MAX_WORKERS";
16
+ /** 环境变量 > 配置 > 缺省 2;不是正整数的值被忽略。 */
17
+ export declare function resolveMaxWorkers(configValue: number | undefined, env?: NodeJS.ProcessEnv): number;
18
+ export interface PoolClock {
19
+ now(): number;
20
+ setTimeout(fn: () => void, ms: number): unknown;
21
+ clearTimeout(handle: unknown): void;
22
+ }
23
+ export interface WorkerLease {
24
+ /** 归还名额;重复调用无害。 */
25
+ release(): void;
26
+ }
27
+ export type AcquireResult = {
28
+ status: "granted";
29
+ lease: WorkerLease;
30
+ waitedMs: number;
31
+ } | {
32
+ status: "timeout";
33
+ waitedMs: number;
34
+ active: number;
35
+ } | {
36
+ status: "aborted";
37
+ waitedMs: number;
38
+ };
39
+ export interface AcquireRequest {
40
+ /** 同时存活的上限(调用方每次读取环境变量 / 配置后传入)。 */
41
+ limit: number;
42
+ /** 最多等多久(毫秒)。 */
43
+ waitMs: number;
44
+ signal?: AbortSignal;
45
+ }
46
+ export declare class WorkerPool {
47
+ private readonly clock;
48
+ private live;
49
+ private readonly queue;
50
+ private idleResolvers;
51
+ constructor(clock?: PoolClock);
52
+ /** 当前占用的名额。 */
53
+ get active(): number;
54
+ get waiting(): number;
55
+ /** 所有名额归还、队列为空时 resolve(测试与收尾用)。 */
56
+ whenIdle(): Promise<void>;
57
+ acquire(request: AcquireRequest): Promise<AcquireResult>;
58
+ private take;
59
+ private remove;
60
+ /** 先来先到:队首放不进就整队等,不越过它。 */
61
+ private drain;
62
+ private notifyIdle;
63
+ }
64
+ /** 整个进程共享的池。 */
65
+ export declare const codemodeWorkerPool: WorkerPool;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * codemode 脚本子进程的进程级并发闸门(设计 §5.5 沙箱)。
3
+ *
4
+ * 整个 ama 进程(所有会话、所有子 Agent)共享一个池:同时存活的沙箱子进程不超过上限(缺省 2),
5
+ * 多出的脚本按先来先到排队。等待不超过 60 s,也不超过脚本自己的 `timeout_ms`(等待计入超时);
6
+ * 等待期间外层 abort 立即结束。名额在子进程**真正退出**(`close`)时才归还,而不是脚本结果落定时:
7
+ * 结果已经给了模型,但被杀的进程树还没死透时,新脚本不该顶上去。
8
+ *
9
+ * 上限每次获取时重新读取:环境变量 `AMA_CODEMODE_MAX_WORKERS`(正整数)优先于配置
10
+ * `codemode.maxWorkers`,都没有或不合法用缺省。时钟可注入,测试不用真实等待。
11
+ */
12
+ export const DEFAULT_MAX_WORKERS = 2;
13
+ /** 排队等名额的上限(毫秒)。 */
14
+ export const MAX_WORKER_WAIT_MS = 60_000;
15
+ export const MAX_WORKERS_ENV = "AMA_CODEMODE_MAX_WORKERS";
16
+ function positiveInt(value) {
17
+ const n = typeof value === "string" && /^\s*\d+\s*$/.test(value) ? Number(value) : value;
18
+ return typeof n === "number" && Number.isInteger(n) && n >= 1 ? n : undefined;
19
+ }
20
+ /** 环境变量 > 配置 > 缺省 2;不是正整数的值被忽略。 */
21
+ export function resolveMaxWorkers(configValue, env = process.env) {
22
+ return positiveInt(env[MAX_WORKERS_ENV]) ?? positiveInt(configValue) ?? DEFAULT_MAX_WORKERS;
23
+ }
24
+ const realClock = {
25
+ now: () => Date.now(),
26
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
27
+ clearTimeout: (handle) => clearTimeout(handle),
28
+ };
29
+ export class WorkerPool {
30
+ clock;
31
+ live = 0;
32
+ queue = [];
33
+ idleResolvers = [];
34
+ constructor(clock = realClock) {
35
+ this.clock = clock;
36
+ }
37
+ /** 当前占用的名额。 */
38
+ get active() {
39
+ return this.live;
40
+ }
41
+ get waiting() {
42
+ return this.queue.length;
43
+ }
44
+ /** 所有名额归还、队列为空时 resolve(测试与收尾用)。 */
45
+ whenIdle() {
46
+ if (this.live === 0 && this.queue.length === 0)
47
+ return Promise.resolve();
48
+ return new Promise((resolve) => this.idleResolvers.push(resolve));
49
+ }
50
+ acquire(request) {
51
+ const started = this.clock.now();
52
+ const waited = () => this.clock.now() - started;
53
+ if (request.signal?.aborted === true) {
54
+ return Promise.resolve({ status: "aborted", waitedMs: 0 });
55
+ }
56
+ if (this.queue.length === 0 && this.live < request.limit) {
57
+ return Promise.resolve({ status: "granted", lease: this.take(), waitedMs: 0 });
58
+ }
59
+ return new Promise((resolve) => {
60
+ let timer;
61
+ const onAbort = () => {
62
+ this.remove(waiter);
63
+ waiter.settle({ status: "aborted", waitedMs: waited() });
64
+ this.drain();
65
+ };
66
+ const waiter = {
67
+ limit: request.limit,
68
+ started,
69
+ settle: (result) => {
70
+ waiter.cancel();
71
+ resolve(result);
72
+ },
73
+ cancel: () => {
74
+ this.clock.clearTimeout(timer);
75
+ request.signal?.removeEventListener("abort", onAbort);
76
+ },
77
+ };
78
+ timer = this.clock.setTimeout(() => {
79
+ this.remove(waiter);
80
+ waiter.settle({ status: "timeout", waitedMs: waited(), active: this.live });
81
+ this.drain();
82
+ }, Math.max(0, request.waitMs));
83
+ request.signal?.addEventListener("abort", onAbort, { once: true });
84
+ this.queue.push(waiter);
85
+ });
86
+ }
87
+ take() {
88
+ this.live++;
89
+ let released = false;
90
+ return {
91
+ release: () => {
92
+ if (released)
93
+ return;
94
+ released = true;
95
+ this.live--;
96
+ this.drain();
97
+ this.notifyIdle();
98
+ },
99
+ };
100
+ }
101
+ remove(waiter) {
102
+ const index = this.queue.indexOf(waiter);
103
+ if (index >= 0)
104
+ this.queue.splice(index, 1);
105
+ }
106
+ /** 先来先到:队首放不进就整队等,不越过它。 */
107
+ drain() {
108
+ for (;;) {
109
+ const head = this.queue[0];
110
+ if (head === undefined || this.live >= head.limit)
111
+ break;
112
+ this.queue.shift();
113
+ head.settle({
114
+ status: "granted",
115
+ lease: this.take(),
116
+ waitedMs: this.clock.now() - head.started,
117
+ });
118
+ }
119
+ this.notifyIdle();
120
+ }
121
+ notifyIdle() {
122
+ if (this.live !== 0 || this.queue.length !== 0)
123
+ return;
124
+ const resolvers = this.idleResolvers;
125
+ this.idleResolvers = [];
126
+ for (const resolve of resolvers)
127
+ resolve();
128
+ }
129
+ }
130
+ /** 整个进程共享的池。 */
131
+ export const codemodeWorkerPool = new WorkerPool();
@@ -12,7 +12,7 @@ import { msg } from "../i18n/index.js";
12
12
  import { MAX_TIMER_MS } from "../tools/timers.js";
13
13
  import { defaultFor, isDynamicDefault, keyDoc } from "./key-docs.js";
14
14
  import { HOOK_TIMEOUT_MAX_MS, THINKING_LEVELS } from "./schema.js";
15
- import { CACHE_RETENTIONS, CHANNEL_NAME_PATTERN, CHECKPOINT_MODES, SANDBOX_ENABLED_MODES, SANDBOX_NETWORK_MODES, CODEMODE_MODES, IMAGE_RESIZE_MODES, PLAN_BASH_MODES_STRICT_FIRST, PLAN_UNATTENDED_MODES, STATUS_LINE_MODES, TOOLS_PRESET_INPUTS, LANGUAGE_SETTINGS, AGENT_BAR_MODES, CHATGPT_FLAVORS, MEMORY_SCOPES, MEMORY_SUBAGENT_MODES, MIN_CONTEXT_BUDGET, } from "./types.js";
15
+ import { CACHE_RETENTIONS, CHANNEL_NAME_PATTERN, CHECKPOINT_MODES, SANDBOX_ENABLED_MODES, SANDBOX_NETWORK_MODES, CODEMODE_ENGINES, CODEMODE_MODES, IMAGE_RESIZE_MODES, PLAN_BASH_MODES_STRICT_FIRST, PLAN_UNATTENDED_MODES, STATUS_LINE_MODES, TOOLS_PRESET_INPUTS, LANGUAGE_SETTINGS, AGENT_BAR_MODES, CHATGPT_FLAVORS, MEMORY_SCOPES, MEMORY_SUBAGENT_MODES, MIN_CONTEXT_BUDGET, } from "./types.js";
16
16
  import { AGENT_ID_PATTERN } from "./schema-w5.js";
17
17
  import { AGENTS_RESERVED_KEYS, SUBAGENT_BACKGROUND_MODES } from "./types-w5.js";
18
18
  export const CONFIG_SCHEMA_FILE = "config.schema.json";
@@ -279,6 +279,8 @@ function buildBaseSchema() {
279
279
  inlineBudget: num(0),
280
280
  requireStrict: bool(),
281
281
  maxHeapMb: num(0),
282
+ maxWorkers: num(1),
283
+ engine: oneOf(CODEMODE_ENGINES),
282
284
  }),
283
285
  hooks: object({ timeoutMs: num(1, HOOK_TIMEOUT_MAX_MS) }),
284
286
  ui: object({
@@ -21,7 +21,13 @@ const IMPLICIT_DEFAULTS = {
21
21
  permission: { builtinDeny: true, autoSafeCommands: [] },
22
22
  // [#267] 寿命上限;[#266] bashAutoBackgroundAfterMs 的缺省由运行方式决定(dynamicDefaults)
23
23
  tools: { default: [], bashBackgroundMaxMs: 7_200_000 },
24
- codemode: { inlineBudget: DEFAULT_INLINE_BUDGET, requireStrict: false, maxHeapMb: 256 },
24
+ codemode: {
25
+ inlineBudget: DEFAULT_INLINE_BUDGET,
26
+ requireStrict: false,
27
+ maxHeapMb: 256,
28
+ maxWorkers: 2,
29
+ engine: "auto",
30
+ },
25
31
  cache: { ...DEFAULT_CACHE_CONFIG },
26
32
  request: {
27
33
  idleTimeoutMs: DEFAULT_IDLE_TIMEOUT_MS,
@@ -16,7 +16,7 @@ import { HOOK_EVENTS } from "../hooks/types.js";
16
16
  import { PERMISSION_MODES_STRICT_FIRST } from "../permissions/types.js";
17
17
  import { WARMING_MODES } from "../ai/cache/types.js";
18
18
  import { BUILTIN_PROVIDERS } from "../ai/providers/builtin.js";
19
- import { CACHE_RETENTIONS, CHANNEL_NAME_PATTERN, CHECKPOINT_MODES, SANDBOX_ENABLED_MODES, SANDBOX_NETWORK_MODES, CODEMODE_MODES, TOOLS_PRESET_INPUTS, } from "./types.js";
19
+ import { CACHE_RETENTIONS, CHANNEL_NAME_PATTERN, CHECKPOINT_MODES, SANDBOX_ENABLED_MODES, SANDBOX_NETWORK_MODES, CODEMODE_ENGINES, CODEMODE_MODES, TOOLS_PRESET_INPUTS, } from "./types.js";
20
20
  export { CONFIG_FILE_VERSION } from "./types.js";
21
21
  export { THINKING_LEVELS } from "./checker.js";
22
22
  export const HOOK_TIMEOUT_MAX_MS = 600_000;
@@ -266,11 +266,13 @@ export function validateConfig(value) {
266
266
  c.number(s, "bashBackgroundMaxMs", p, 0, MAX_TIMER_MS);
267
267
  c.stringArray(s, "disabled", p);
268
268
  });
269
- checkSection(c, value, "codemode", ["mode", "inlineBudget", "requireStrict", "maxHeapMb"], (s, p) => {
269
+ checkSection(c, value, "codemode", ["mode", "inlineBudget", "requireStrict", "maxHeapMb", "maxWorkers", "engine"], (s, p) => {
270
270
  c.oneOf(s, "mode", p, CODEMODE_MODES);
271
271
  c.number(s, "inlineBudget", p, 0);
272
272
  c.boolean(s, "requireStrict", p);
273
273
  c.number(s, "maxHeapMb", p, 0);
274
+ c.number(s, "maxWorkers", p, 1);
275
+ c.oneOf(s, "engine", p, CODEMODE_ENGINES);
274
276
  });
275
277
  checkSection(c, value, "hooks", ["timeoutMs"], (s, p) => {
276
278
  c.number(s, "timeoutMs", p, 1, HOOK_TIMEOUT_MAX_MS);
@@ -58,6 +58,8 @@ const ROWS = [
58
58
  row("codemode.inlineBudget", "tools", "restart", "deny", { prefix: true }),
59
59
  row("codemode.requireStrict", "tools", "restart", "deny"),
60
60
  row("codemode.maxHeapMb", "tools", "restart", "deny"),
61
+ row("codemode.maxWorkers", "tools", "restart", "deny"),
62
+ row("codemode.engine", "tools", "restart", "deny"),
61
63
  row("tools.maxToolResultChars", "tools", "nextSession", "deny"),
62
64
  row("tools.bashTimeoutMs", "tools", "restart", "deny"),
63
65
  // [#266 / #267] 长命令转后台与后台寿命;缺省由运行方式决定的键也是面板行(显示规则)
@@ -136,6 +136,9 @@ export interface ToolsConfig {
136
136
  /** codemode 调用方式(设计 §5.5):off 不注册;on 全部工具 + codemode;only 只有 codemode。 */
137
137
  export type CodemodeMode = "off" | "on" | "only";
138
138
  export declare const CODEMODE_MODES: readonly CodemodeMode[];
139
+ /** codemode 脚本引擎:node = Node 子进程;quickjs = WebAssembly 里的 QuickJS;auto 按网络隔离能力选。 */
140
+ export type CodemodeEngineSetting = "auto" | "node" | "quickjs";
141
+ export declare const CODEMODE_ENGINES: readonly CodemodeEngineSetting[];
139
142
  export interface CodemodeConfig {
140
143
  /** 命令行 `--codemode`;项目级只接受 "off"。 */
141
144
  mode?: CodemodeMode;
@@ -145,6 +148,13 @@ export interface CodemodeConfig {
145
148
  requireStrict?: boolean;
146
149
  /** [M-F] 脚本子进程的 V8 堆上限(MB,`--max-old-space-size`),缺省 256,0 不加;只认用户级。 */
147
150
  maxHeapMb?: number;
151
+ /**
152
+ * 整个 ama 进程里同时存活的脚本子进程数上限(所有会话共享),缺省 2;正整数。环境变量
153
+ * `AMA_CODEMODE_MAX_WORKERS` 优先于它;只认用户级。
154
+ */
155
+ maxWorkers?: number;
156
+ /** 脚本引擎,缺省 auto:网络已隔离(Node ≥ 25 或 OS 沙箱)用 node,否则用 quickjs;只认用户级。 */
157
+ engine?: CodemodeEngineSetting;
148
158
  }
149
159
  export interface HooksSettings {
150
160
  timeoutMs?: number;