@armadra/agent 0.17.2 → 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 +36 -0
  2. package/CHANGELOG.zh-CN.md +36 -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,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
+ };