@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
@@ -0,0 +1,457 @@
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 { randomFillSync } from "node:crypto";
20
+ import { parentPort, workerData } from "node:worker_threads";
21
+ const SCRIPT_FILENAME = "codemode-script.js";
22
+ const BOOTSTRAP_FILENAME = "codemode-bootstrap.js";
23
+ const JOBS_PER_POLL = 64;
24
+ /**
25
+ * QuickJS 的 JS 调用栈上限(字节)。wasm 的 C 栈约 400 KB(超出即陷阱、整个实例作废),留出余量后取 320 KB:
26
+ * 脚本里的无界递归在这里抛出可捕获的 `RangeError: Maximum call stack size exceeded`,与 Node 引擎一致;
27
+ * 只有不经 JS 调用的原生递归(超深 JSON、超深嵌套字面量)仍可能直接陷阱,见 describeHostError。
28
+ */
29
+ const MAX_STACK_BYTES = 320 * 1024;
30
+ /** 先于引导脚本执行:冻结所有内建对象(Error 原型除外:子类里 `this.name = ...` 要能赋值)。 */
31
+ const FREEZE_SOURCE = String.raw `(function () {
32
+ "use strict";
33
+ const seen = new Set();
34
+ const keep = new Set([
35
+ Error.prototype, EvalError.prototype, RangeError.prototype, ReferenceError.prototype,
36
+ SyntaxError.prototype, TypeError.prototype, URIError.prototype, InternalError.prototype,
37
+ AggregateError.prototype, DOMException.prototype,
38
+ ]);
39
+ const root = globalThis;
40
+ function visit(value) {
41
+ if ((typeof value !== "object" && typeof value !== "function") || value === null) return;
42
+ if (seen.has(value)) return;
43
+ seen.add(value);
44
+ for (const key of Reflect.ownKeys(value)) {
45
+ const desc = Reflect.getOwnPropertyDescriptor(value, key);
46
+ if (desc === undefined) continue;
47
+ if ("value" in desc) visit(desc.value);
48
+ else { visit(desc.get); visit(desc.set); }
49
+ }
50
+ visit(Reflect.getPrototypeOf(value));
51
+ if (value !== root && !keep.has(value)) Object.freeze(value);
52
+ }
53
+ visit(root);
54
+ for (const sample of [async function () {}, function* () {}, async function* () {}, [][Symbol.iterator](),
55
+ new Map()[Symbol.iterator](), new Set()[Symbol.iterator](), ""[Symbol.iterator](), /x/[Symbol.matchAll]("x")]) {
56
+ visit(Reflect.getPrototypeOf(sample));
57
+ }
58
+ visit(Reflect.getPrototypeOf(Int8Array));
59
+ })`;
60
+ /** 跑在 VM 里的收尾层:引导脚本的 `run` 落定后经宿主函数报告,错误描述带脚本行号。 */
61
+ const DRIVER_SOURCE = String.raw `(function (factory, host, config) {
62
+ "use strict";
63
+ const bridge = factory(host, config);
64
+ const describe = (e) => {
65
+ if (typeof e !== "object" || e === null) return String(e);
66
+ const base = typeof e.message === "string"
67
+ ? (typeof e.name === "string" ? e.name : "Error") + ": " + e.message
68
+ : String(e);
69
+ const stack = typeof e.stack === "string" ? e.stack : "";
70
+ const at = /codemode-script\.js:(\d+)/.exec(stack);
71
+ return at === null ? base : base + " (line " + at[1] + ")";
72
+ };
73
+ return {
74
+ deliver: bridge.deliver,
75
+ finish: bridge.finish,
76
+ start: (main) => {
77
+ bridge.run(main).then(() => host("done", ""), (e) => host("fail", describe(e)));
78
+ },
79
+ };
80
+ })`;
81
+ /** VM 里的脚本以失败结束(语法错误、未捕获的异常、被中断)。 */
82
+ class ScriptFailure extends Error {
83
+ }
84
+ const encoder = new TextEncoder();
85
+ const decoder = new TextDecoder();
86
+ /** QuickJS 实例:句柄是 wasm 堆上的 JSValue 盒子,调用方负责 `free`。 */
87
+ class Vm {
88
+ x;
89
+ flag;
90
+ undef;
91
+ yes;
92
+ no;
93
+ hostHandler = () => undefined;
94
+ constructor(module, flag, memoryLimitBytes) {
95
+ this.flag = flag;
96
+ let memory;
97
+ const mem = () => memory;
98
+ const instance = new WebAssembly.Instance(module, {
99
+ env: {
100
+ host_call: (namePtr, nameLen, _this, argc, argv) => this.onHostCall(namePtr, nameLen, argc, argv),
101
+ host_interrupt: () => (Atomics.load(this.flag, 0) !== 0 ? 1 : 0),
102
+ host_promise_rejection: () => { },
103
+ host_module_normalize: () => 0,
104
+ host_module_load: () => 0,
105
+ host_get_timezone_offset: (hi, lo) => -new Date(Number((BigInt(hi) << 32n) | BigInt(lo >>> 0)) * 1000).getTimezoneOffset() * 60,
106
+ },
107
+ wasi_snapshot_preview1: {
108
+ clock_time_get: (_id, _precision, out) => {
109
+ new DataView(mem().buffer).setBigUint64(out, BigInt(Date.now()) * 1000000n, true);
110
+ return 0;
111
+ },
112
+ // stdout / stderr 丢弃:引擎的内部日志不该出现在宿主终端里
113
+ fd_write: (_fd, iovs, iovsLen, written) => {
114
+ const view = new DataView(mem().buffer);
115
+ let total = 0;
116
+ for (let i = 0; i < iovsLen; i++)
117
+ total += view.getUint32(iovs + i * 8 + 4, true);
118
+ view.setUint32(written, total, true);
119
+ return 0;
120
+ },
121
+ fd_close: () => 0,
122
+ fd_fdstat_get: (fd, out) => {
123
+ if (fd > 2)
124
+ return 8;
125
+ new Uint8Array(mem().buffer, out, 24).fill(0);
126
+ new Uint8Array(mem().buffer)[out] = 2;
127
+ return 0;
128
+ },
129
+ fd_seek: () => 70,
130
+ random_get: (ptr, len) => {
131
+ randomFillSync(new Uint8Array(mem().buffer, ptr, len));
132
+ return 0;
133
+ },
134
+ },
135
+ });
136
+ const x = instance.exports;
137
+ memory = x.memory;
138
+ this.x = x;
139
+ x._initialize();
140
+ if (x.qjs_init() !== 0)
141
+ throw new Error("Failed to initialize QuickJS");
142
+ if (memoryLimitBytes > 0)
143
+ x.qjs_set_memory_limit(memoryLimitBytes);
144
+ x.qjs_set_max_stack_size(MAX_STACK_BYTES);
145
+ x.qjs_set_interrupt_handler(1);
146
+ this.undef = x.qjs_get_undefined();
147
+ this.yes = x.qjs_get_true();
148
+ this.no = x.qjs_get_false();
149
+ }
150
+ onHostCall(_namePtr, _nameLen, argc, argv) {
151
+ const args = [];
152
+ const view = new DataView(this.x.memory.buffer);
153
+ for (let i = 0; i < Math.min(argc, 2); i++)
154
+ args.push(this.text(view.getUint32(argv + i * 4, true)));
155
+ const reply = this.hostHandler(args[0] ?? "", args[1] ?? "");
156
+ return reply === undefined ? this.x.qjs_dup_value(this.undef) : this.str(reply);
157
+ }
158
+ /** 把字符串写进 wasm 堆(NUL 结尾)。 */
159
+ put(text) {
160
+ const bytes = encoder.encode(text);
161
+ const ptr = this.x.wasm_malloc(bytes.length + 1);
162
+ if (ptr === 0)
163
+ throw new Error("wasm_malloc failed");
164
+ const heap = new Uint8Array(this.x.memory.buffer);
165
+ heap.set(bytes, ptr);
166
+ heap[ptr + bytes.length] = 0;
167
+ return { ptr, len: bytes.length };
168
+ }
169
+ /** 任意值转字符串(对象会触发 toString)。 */
170
+ text(box) {
171
+ const lenPtr = this.x.wasm_malloc(4);
172
+ try {
173
+ const cstr = this.x.qjs_get_string_len(box, lenPtr);
174
+ if (cstr === 0)
175
+ return "";
176
+ const len = new DataView(this.x.memory.buffer).getUint32(lenPtr, true);
177
+ const out = decoder.decode(new Uint8Array(this.x.memory.buffer, cstr, len));
178
+ this.x.qjs_free_cstring(cstr);
179
+ return out;
180
+ }
181
+ finally {
182
+ this.x.wasm_free(lenPtr);
183
+ }
184
+ }
185
+ str(text) {
186
+ const { ptr, len } = this.put(text);
187
+ try {
188
+ return this.x.qjs_new_string(ptr, len);
189
+ }
190
+ finally {
191
+ this.x.wasm_free(ptr);
192
+ }
193
+ }
194
+ prop(obj, name) {
195
+ const { ptr } = this.put(name);
196
+ try {
197
+ return this.x.qjs_get_prop_string(obj, ptr);
198
+ }
199
+ finally {
200
+ this.x.wasm_free(ptr);
201
+ }
202
+ }
203
+ free(...boxes) {
204
+ for (const box of boxes)
205
+ this.x.qjs_free_value(box);
206
+ }
207
+ /** 取出当前异常并描述成 `Name: message (line N)`;被中断 → 固定文案。 */
208
+ takeFailure() {
209
+ const box = this.x.qjs_get_exception();
210
+ try {
211
+ if (this.x.qjs_is_uncatchable_error(box) !== 0) {
212
+ // 中断标志没拉而引擎抛出不可捕获的错误:内存上限
213
+ return new ScriptFailure(Atomics.load(this.flag, 0) !== 0 ? "Script interrupted" : "InternalError: out of memory");
214
+ }
215
+ if (this.x.qjs_is_object(box) === 0)
216
+ return new ScriptFailure(this.text(box));
217
+ const field = (name) => {
218
+ const value = this.prop(box, name);
219
+ try {
220
+ return this.x.qjs_is_undefined(value) !== 0 ? undefined : this.text(value);
221
+ }
222
+ finally {
223
+ this.free(value);
224
+ }
225
+ };
226
+ const message = field("message");
227
+ const base = message === undefined ? this.text(box) : `${field("name") ?? "Error"}: ${message}`;
228
+ const at = /codemode-script\.js:(\d+)/.exec(field("stack") ?? "");
229
+ return new ScriptFailure(at === null ? base : `${base} (line ${at[1]})`);
230
+ }
231
+ finally {
232
+ this.free(box);
233
+ }
234
+ }
235
+ /** 求值;抛出的异常变成 ScriptFailure。 */
236
+ evalCode(code, filename) {
237
+ const source = this.put(code);
238
+ const name = this.put(filename);
239
+ try {
240
+ const result = this.x.qjs_eval(source.ptr, source.len, name.ptr, 0);
241
+ if (this.x.qjs_is_exception(result) === 0)
242
+ return result;
243
+ this.free(result);
244
+ throw this.takeFailure();
245
+ }
246
+ finally {
247
+ this.x.wasm_free(source.ptr);
248
+ this.x.wasm_free(name.ptr);
249
+ }
250
+ }
251
+ /** 调用函数;`args` 里的盒子由调用方释放。 */
252
+ call(fn, thisArg, args) {
253
+ const argv = args.length === 0 ? 0 : this.x.wasm_malloc(args.length * 4);
254
+ if (args.length > 0) {
255
+ const view = new DataView(this.x.memory.buffer);
256
+ args.forEach((box, i) => view.setUint32(argv + i * 4, box, true));
257
+ }
258
+ try {
259
+ const result = this.x.qjs_call(fn, thisArg, args.length, argv);
260
+ if (this.x.qjs_is_exception(result) === 0)
261
+ return result;
262
+ this.free(result);
263
+ throw this.takeFailure();
264
+ }
265
+ finally {
266
+ if (argv !== 0)
267
+ this.x.wasm_free(argv);
268
+ }
269
+ }
270
+ /** 把全局属性 `name` 设为宿主函数(注册名 `host`)。 */
271
+ newHostFunction(name) {
272
+ const { ptr, len } = this.put(name);
273
+ try {
274
+ return this.x.qjs_new_host_function(ptr, len, 0);
275
+ }
276
+ finally {
277
+ this.x.wasm_free(ptr);
278
+ }
279
+ }
280
+ /** 逐个执行待处理的 Promise 任务;周期性读中断标志。返回前 `stop()` 为真则提前结束。 */
281
+ drain(stop) {
282
+ let jobs = 0;
283
+ while (!stop() && this.x.qjs_is_job_pending() !== 0) {
284
+ if (this.x.qjs_execute_pending_job() < 0)
285
+ throw this.takeFailure();
286
+ if (++jobs % JOBS_PER_POLL === 0 && Atomics.load(this.flag, 0) !== 0) {
287
+ throw new ScriptFailure("Script interrupted");
288
+ }
289
+ }
290
+ }
291
+ }
292
+ function post(message) {
293
+ parentPort.postMessage(message);
294
+ }
295
+ function run(data) {
296
+ const started = Date.now();
297
+ let finished = false;
298
+ let outstanding = 0;
299
+ let failure;
300
+ let vm;
301
+ let driver;
302
+ const conclude = (ok, error) => {
303
+ if (finished && driver === undefined)
304
+ return;
305
+ finished = true;
306
+ if (vm !== undefined && driver !== undefined) {
307
+ const current = driver;
308
+ driver = undefined;
309
+ try {
310
+ const snapshot = vm.call(current.finish, vm.undef, []);
311
+ try {
312
+ if (ok && vm.x.qjs_is_undefined(snapshot) === 0) {
313
+ post({
314
+ type: "store",
315
+ entries: JSON.parse(vm.text(snapshot)),
316
+ });
317
+ }
318
+ }
319
+ finally {
320
+ vm.free(snapshot);
321
+ }
322
+ }
323
+ catch {
324
+ // VM 已不可用(栈溢出、被中断):没有 store 可交
325
+ }
326
+ }
327
+ const message = { type: "done", ok, elapsedMs: Date.now() - started };
328
+ if (error !== undefined)
329
+ message.error = error;
330
+ post(message);
331
+ };
332
+ /** 排空 Promise 任务;脚本没结束又没有未完成的工具调用 → 它不可能再前进。 */
333
+ const pump = () => {
334
+ const machine = vm;
335
+ machine.drain(() => finished);
336
+ if (failure !== undefined)
337
+ conclude(false, failure);
338
+ else if (finished)
339
+ conclude(true);
340
+ else if (outstanding === 0) {
341
+ conclude(false, "Script awaited a promise that can never settle (no tool call is pending)");
342
+ }
343
+ };
344
+ const guard = (fn) => {
345
+ try {
346
+ fn();
347
+ }
348
+ catch (error) {
349
+ conclude(false, describeHostError(error));
350
+ }
351
+ };
352
+ guard(() => {
353
+ vm = new Vm(data.module, new Int32Array(data.flag), data.memoryLimitBytes);
354
+ const machine = vm;
355
+ machine.hostHandler = (kind, payload) => {
356
+ if (finished)
357
+ return undefined;
358
+ if (kind === "image") {
359
+ // 引导脚本已校验并计数
360
+ const normalized = JSON.parse(payload);
361
+ post({ type: "image", data: normalized.data, mimeType: normalized.mimeType });
362
+ }
363
+ else if (kind === "output") {
364
+ post({ type: "output", text: payload });
365
+ }
366
+ else if (kind === "tool_call") {
367
+ const newline = payload.indexOf("\n");
368
+ const call = JSON.parse(payload.slice(newline + 1));
369
+ outstanding++;
370
+ post({
371
+ type: "tool_call",
372
+ id: Number(payload.slice(0, newline)),
373
+ name: call.name,
374
+ input: call.input,
375
+ });
376
+ }
377
+ else if (kind === "done") {
378
+ finished = true;
379
+ }
380
+ else if (kind === "fail") {
381
+ finished = true;
382
+ failure = payload;
383
+ }
384
+ return undefined;
385
+ };
386
+ machine.free(machine.call(machine.evalCode(FREEZE_SOURCE, "codemode-freeze.js"), machine.undef, []));
387
+ const factory = machine.evalCode(data.bootstrap, BOOTSTRAP_FILENAME);
388
+ const host = machine.newHostFunction("host");
389
+ const config = machine.evalCode(`(${JSON.stringify({
390
+ maxConcurrent: data.limits.maxConcurrent,
391
+ maxValueChars: data.limits.maxValueChars,
392
+ maxTotalChars: data.limits.maxTotalChars,
393
+ maxImages: data.limits.maxImages,
394
+ tools: JSON.stringify(data.tools),
395
+ store: JSON.stringify(data.store),
396
+ })})`, BOOTSTRAP_FILENAME);
397
+ const make = machine.evalCode(DRIVER_SOURCE, "codemode-driver.js");
398
+ const made = machine.call(make, machine.undef, [factory, host, config]);
399
+ driver = {
400
+ deliver: machine.prop(made, "deliver"),
401
+ finish: machine.prop(made, "finish"),
402
+ start: machine.prop(made, "start"),
403
+ };
404
+ machine.free(made, make, config, host, factory);
405
+ // 前缀与脚本首行同一行,报告的行号与脚本一致
406
+ const main = machine.evalCode(`(async () => {${data.script}\n})()`, SCRIPT_FILENAME);
407
+ machine.free(machine.call(driver.start, machine.undef, [main]));
408
+ machine.free(main);
409
+ pump();
410
+ });
411
+ parentPort.on("message", (message) => {
412
+ if (finished)
413
+ return;
414
+ if (message.type === "abort") {
415
+ conclude(false, "Script aborted");
416
+ return;
417
+ }
418
+ guard(() => {
419
+ const machine = vm;
420
+ const current = driver;
421
+ if (current === undefined)
422
+ return;
423
+ outstanding--;
424
+ const id = machine.x.qjs_new_number(message.id);
425
+ const ok = message.ok ? machine.yes : machine.no;
426
+ const payload = message.ok ? message.json : message.error;
427
+ const arg = payload === undefined ? machine.undef : machine.str(payload);
428
+ try {
429
+ machine.free(machine.call(current.deliver, machine.undef, [id, ok, arg]));
430
+ }
431
+ finally {
432
+ machine.free(id);
433
+ if (payload !== undefined)
434
+ machine.free(arg);
435
+ }
436
+ pump();
437
+ });
438
+ });
439
+ }
440
+ /** 宿主侧异常(栈溢出、wasm 陷阱、内存增长失败)的说明。 */
441
+ function describeHostError(error) {
442
+ if (error instanceof ScriptFailure)
443
+ return error.message;
444
+ const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
445
+ if (error instanceof RangeError && /call stack/i.test(error.message)) {
446
+ return "RangeError: Maximum call stack size exceeded";
447
+ }
448
+ if (error instanceof WebAssembly.RuntimeError) {
449
+ // 不经 JS 调用的原生递归越过了 JS 栈上限检查,把 wasm 栈写穿:实例作废、无法在脚本里捕获,
450
+ // 报与 Node 引擎同一句开头的错误(此前已产生的输出由主线程照常保留)
451
+ return `RangeError: Maximum call stack size exceeded (QuickJS engine trap: ${text})`;
452
+ }
453
+ return `codemode QuickJS engine failed: ${text}`;
454
+ }
455
+ if (parentPort !== null && workerData !== null && typeof workerData === "object") {
456
+ run(workerData);
457
+ }
@@ -21,5 +21,9 @@
21
21
  export declare const MAX_CONCURRENT = 8;
22
22
  export declare const MAX_STORE_VALUE_CHARS = 262144;
23
23
  export declare const MAX_STORE_TOTAL_CHARS = 1048576;
24
+ /** 在 vm 上下文里执行的引导脚本:返回 `{ deliver, finish, run }`,全部是上下文 realm 的函数。 */
25
+ export declare const BOOTSTRAP: string;
24
26
  /** 错误 → 一行说明;带上脚本里的行号(若能从栈里找到)。 */
25
27
  export declare function describeError(error: unknown): string;
28
+ /** 单个脚本最多附几张图;校验在引导脚本里(两个引擎共用),超限由它抛错。 */
29
+ export declare const MAX_SCRIPT_IMAGES = 8;
@@ -24,7 +24,7 @@ export const MAX_STORE_VALUE_CHARS = 262_144;
24
24
  export const MAX_STORE_TOTAL_CHARS = 1_048_576;
25
25
  const SCRIPT_FILENAME = "codemode-script.js";
26
26
  /** 在 vm 上下文里执行的引导脚本:返回 `{ deliver, finish, run }`,全部是上下文 realm 的函数。 */
27
- const BOOTSTRAP = String.raw `(function (host, config) {
27
+ export const BOOTSTRAP = String.raw `(function (host, config) {
28
28
  "use strict";
29
29
  const MAX = config.maxConcurrent;
30
30
  const stringify = JSON.stringify;
@@ -153,6 +153,86 @@ const BOOTSTRAP = String.raw `(function (host, config) {
153
153
  const json = storeMap.get(key);
154
154
  return json === undefined ? undefined : parse(json);
155
155
  }
156
+ // image(): one implementation for both engines (the QuickJS worker cannot import source files)
157
+ const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
158
+ const IMAGE_FORMS = "image(value): pass a base64 data: URL, { image_url }, or { type: 'image', data, mimeType }";
159
+ let imageCount = 0;
160
+ // the first 12 bytes of a base64 string, enough for every signature below
161
+ function headBytes(b64) {
162
+ const bytes = [];
163
+ let acc = 0;
164
+ let bits = 0;
165
+ for (let i = 0; i < b64.length && bytes.length < 12; i++) {
166
+ const v = BASE64_ALPHABET.indexOf(b64[i]);
167
+ if (v < 0) break;
168
+ acc = (acc << 6) | v;
169
+ bits += 6;
170
+ if (bits >= 8) {
171
+ bits -= 8;
172
+ bytes.push((acc >> bits) & 255);
173
+ acc &= (1 << bits) - 1;
174
+ }
175
+ }
176
+ return bytes;
177
+ }
178
+ function ascii(bytes, from, to) {
179
+ let out = "";
180
+ for (let i = from; i < to; i++) out += String.fromCharCode(bytes[i]);
181
+ return out;
182
+ }
183
+ // PNG / JPEG / GIF / WebP by magic bytes only; the declared MIME type is never trusted
184
+ function sniffImage(b) {
185
+ if (b.length >= 8 && b[0] === 0x89 && ascii(b, 1, 4) === "PNG" && b[4] === 0x0d && b[5] === 0x0a && b[6] === 0x1a && b[7] === 0x0a) return "image/png";
186
+ if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return "image/jpeg";
187
+ if (b.length >= 6 && /^GIF8[79]a$/.test(ascii(b, 0, 6))) return "image/gif";
188
+ if (b.length >= 12 && ascii(b, 0, 4) === "RIFF" && ascii(b, 8, 12) === "WEBP") return "image/webp";
189
+ return undefined;
190
+ }
191
+ function normalizeImage(value) {
192
+ let raw = value;
193
+ if (typeof raw === "object" && raw !== null) {
194
+ if (raw.type === "image" && typeof raw.data === "string") raw = raw.data;
195
+ else if (typeof raw.image_url === "string") raw = raw.image_url;
196
+ else if (typeof raw.image_url === "object" && raw.image_url !== null && typeof raw.image_url.url === "string") raw = raw.image_url.url;
197
+ }
198
+ if (typeof raw !== "string") return IMAGE_FORMS;
199
+ let base64 = raw.trim();
200
+ const schemeMatch = /^([a-z][a-z0-9+.-]*):/i.exec(base64);
201
+ const scheme = schemeMatch === null ? undefined : schemeMatch[1].toLowerCase();
202
+ if (scheme !== undefined && scheme !== "data") {
203
+ return "image(value): remote URLs are not supported; pass a base64 data: URL";
204
+ }
205
+ if (scheme === "data") {
206
+ const match = /^data:[^,]*;base64,([\s\S]*)$/i.exec(base64);
207
+ if (match === null) return "image(value): the data: URL must be base64-encoded";
208
+ base64 = match[1].trim();
209
+ }
210
+ base64 = base64.replace(/\s+/g, "");
211
+ if (base64 === "" || !/^[A-Za-z0-9+/]*={0,2}$/.test(base64)) {
212
+ return "image(value): the image data is not valid base64";
213
+ }
214
+ const mimeType = sniffImage(headBytes(base64));
215
+ if (mimeType === undefined) return "image(value): not a PNG, JPEG, GIF or WebP image";
216
+ return { data: base64, mimeType: mimeType };
217
+ }
218
+ function image(value) {
219
+ let normalized;
220
+ try {
221
+ normalized = normalizeImage(value);
222
+ } catch (error) {
223
+ throw new TypeError("image(value): value must be JSON-serializable");
224
+ }
225
+ if (typeof normalized === "string") throw new TypeError(normalized);
226
+ if (imageCount >= config.maxImages) {
227
+ throw new TypeError("image(value): at most " + config.maxImages + " images per script");
228
+ }
229
+ imageCount++;
230
+ host("image", stringify(normalized));
231
+ }
232
+ // reserved call name, same as SEARCH_TOOLS_CALL in protocol.ts; the parent ranks tools with BM25
233
+ function searchTools(query, options) {
234
+ return callTool("@searchTools", { query: query, options: options });
235
+ }
156
236
  function describeTool(name) {
157
237
  return declByName.get(callName.get(name) ?? name);
158
238
  }
@@ -168,6 +248,8 @@ const BOOTSTRAP = String.raw `(function (host, config) {
168
248
  load: load,
169
249
  ALL_TOOLS: names,
170
250
  describeTool: describeTool,
251
+ searchTools: searchTools,
252
+ image: image,
171
253
  };
172
254
  for (const [key, value] of Object.entries(globals)) {
173
255
  Object.defineProperty(globalThis, key, { value: value, writable: false, enumerable: false, configurable: false });
@@ -229,12 +311,20 @@ function done(ok, error) {
229
311
  // 等 stdout 冲完再退出(macOS 上管道写是异步的)。
230
312
  process.stdout.write("", () => process.exit(0));
231
313
  }
314
+ /** 单个脚本最多附几张图;校验在引导脚本里(两个引擎共用),超限由它抛错。 */
315
+ export const MAX_SCRIPT_IMAGES = 8;
232
316
  function host(kind, payload) {
233
317
  if (finished)
234
- return;
318
+ return undefined;
319
+ if (kind === "image") {
320
+ // 已由引导脚本校验并计数
321
+ const normalized = JSON.parse(payload);
322
+ send({ type: "image", data: normalized.data, mimeType: normalized.mimeType });
323
+ return undefined;
324
+ }
235
325
  if (kind === "output") {
236
326
  send({ type: "output", text: payload });
237
- return;
327
+ return undefined;
238
328
  }
239
329
  if (kind === "tool_call") {
240
330
  const newline = payload.indexOf("\n");
@@ -242,6 +332,7 @@ function host(kind, payload) {
242
332
  const call = JSON.parse(payload.slice(newline + 1));
243
333
  send({ type: "tool_call", id, name: call.name, input: call.input });
244
334
  }
335
+ return undefined;
245
336
  }
246
337
  function start(run) {
247
338
  started = true;
@@ -255,6 +346,7 @@ function start(run) {
255
346
  maxConcurrent: MAX_CONCURRENT,
256
347
  maxValueChars: MAX_STORE_VALUE_CHARS,
257
348
  maxTotalChars: MAX_STORE_TOTAL_CHARS,
349
+ maxImages: MAX_SCRIPT_IMAGES,
258
350
  tools: JSON.stringify(run.tools),
259
351
  store: JSON.stringify(run.store ?? {}),
260
352
  };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * 脚本里 `image(v)` 产出的图片 → 工具结果里的图片块(父进程侧)。
3
+ *
4
+ * 子进程已按文件头校验过,但父进程不信任它:再按文件头认一遍 MIME(只认 PNG / JPEG / GIF / WebP,
5
+ * 声明的 MIME 一律忽略),再按端点的单图上限检查;每张通过的图既作为图片块附在结果后面,也存成
6
+ * `<outputDir>/<toolCallId>-image-<n>.<ext>`(与超长文本同目录),路径写进结果文本。
7
+ */
8
+ import type { ImageBlock } from "../ai/types.js";
9
+ export interface PreparedImages {
10
+ blocks: ImageBlock[];
11
+ /** 追加到结果文本的说明行(保存路径、被跳过的原因)。 */
12
+ notes: string[];
13
+ paths: string[];
14
+ }
15
+ export declare function prepareScriptImages(images: readonly {
16
+ data: string;
17
+ mimeType: string;
18
+ }[], save: (bytes: Buffer, extension: string, index: number) => string | undefined): Promise<PreparedImages>;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * 脚本里 `image(v)` 产出的图片 → 工具结果里的图片块(父进程侧)。
3
+ *
4
+ * 子进程已按文件头校验过,但父进程不信任它:再按文件头认一遍 MIME(只认 PNG / JPEG / GIF / WebP,
5
+ * 声明的 MIME 一律忽略),再按端点的单图上限检查;每张通过的图既作为图片块附在结果后面,也存成
6
+ * `<outputDir>/<toolCallId>-image-<n>.<ext>`(与超长文本同目录),路径写进结果文本。
7
+ */
8
+ import { internImage } from "../ai/image-intern.js";
9
+ import { fitImage, sniffImageMime } from "../tools/image-file.js";
10
+ const EXTENSIONS = {
11
+ "image/png": "png",
12
+ "image/jpeg": "jpg",
13
+ "image/gif": "gif",
14
+ "image/webp": "webp",
15
+ };
16
+ export async function prepareScriptImages(images, save) {
17
+ const out = { blocks: [], notes: [], paths: [] };
18
+ for (const [i, image] of images.entries()) {
19
+ const n = i + 1;
20
+ const bytes = Buffer.from(image.data, "base64");
21
+ const mimeType = sniffImageMime(bytes);
22
+ if (mimeType === undefined) {
23
+ out.notes.push(`[Image ${n} skipped: not a PNG, JPEG, GIF or WebP image]`);
24
+ continue;
25
+ }
26
+ const fit = await fitImage(bytes, mimeType);
27
+ if (!fit.ok) {
28
+ out.notes.push(`[Image ${n} skipped: ${fit.note}]`);
29
+ continue;
30
+ }
31
+ out.blocks.push(internImage({ type: "image", data: fit.buf.toString("base64"), mimeType: fit.mimeType }));
32
+ const path = save(fit.buf, EXTENSIONS[fit.mimeType] ?? "bin", n);
33
+ if (path !== undefined)
34
+ out.paths.push(path);
35
+ out.notes.push(path === undefined ? `[Image ${n} attached]` : `[Image ${n} attached; saved to ${path}]`);
36
+ }
37
+ return out;
38
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * 脚本内 `tools.bash` 的输出放宽(codemode 指南「返回值」)。
3
+ *
4
+ * 直接调用时 bash 的结果按会话上限尾截断(2000 行 / 50 KB),全文落在 `fullOutputPath`。脚本里要
5
+ * 自己过滤、统计输出,这个上限太紧:`output` 放宽到 1 MiB;更长时保留首尾各 512 KiB,中间换成说明,
6
+ * `truncated` 为真,全文仍在 `fullOutputPath`。只改脚本拿到的值,模型直接调用 bash 的结果不变。
7
+ */
8
+ export declare const SCRIPT_OUTPUT_LIMIT_BYTES: number;
9
+ export declare const SCRIPT_OUTPUT_HALF_BYTES: number;
10
+ export interface LimitableBashValue {
11
+ output: string;
12
+ truncated: boolean;
13
+ fullOutputPath?: string;
14
+ }
15
+ /**
16
+ * bash 结果被直接调用的上限截过(`truncated` 且有全文文件)时,按脚本的上限重新取 `output`;读不到
17
+ * 文件就原样返回。全文 ≤ 1 MiB 时 `output` 是全文、`truncated` 为假。
18
+ */
19
+ export declare function widenScriptBashOutput<T extends LimitableBashValue>(value: T): Promise<T>;