@qwen-code/qwen-harness 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Pi Training Harness
2
2
 
3
- This repository provides native Pi plus focused harness profiles without replacing Pi's runtime. See [Profiles](#profiles) for the complete list.
3
+ This repository provides Pi-based focused harness profiles without replacing Pi's runtime. See [Profiles](#profiles) for the complete list.
4
4
 
5
5
  The custom profiles share Pi's model runtime, TUI, headless modes, compaction, resume, and native JSONL sessions. Their system prompts and tool contracts remain isolated from the `pi` harness.
6
6
 
@@ -17,7 +17,7 @@ For repository development, install dependencies with `npm install --ignore-scri
17
17
 
18
18
  ## Development
19
19
 
20
- Use one development command for every harness. Omitting `--harness` runs native Pi:
20
+ Use one development command for every harness. Omitting `--harness` runs the `pi` profile:
21
21
 
22
22
  ```bash
23
23
  npm run dev
@@ -37,16 +37,19 @@ To use the same command from a checkout, run `npm run build && npm link` once. R
37
37
  `npm run build` after source changes; `qwen-harness` will continue to point at this checkout.
38
38
 
39
39
  The compiled entrypoint calls Pi's public `main()` function. The `pi` harness adds no
40
- system prompt or tools, so it behaves like native Pi. `pi-ptc` preserves Pi's normal prompt
40
+ system prompt or new tool names; it keeps Pi's four built-in tools and applies the bounded
41
+ `bash` capability. `pi-ptc` preserves Pi's normal prompt
41
42
  but activates the packaged programmatic-tool-calling capability: the model sees only
42
43
  `run_code`, while Pi's four default tools are callable from its JavaScript runtime.
43
- `self-compact` preserves Pi's normal prompt and built-in tools while adding one packaged
44
- capability; external extension and skill discovery are disabled for these harnesses.
44
+ `self-compact` preserves Pi's normal prompt and built-in tool names while adding context
45
+ compaction and applying the same bounded `bash` capability; external extension and
46
+ skill discovery are disabled for these harnesses.
45
47
  The Arena profiles load only their explicit tool extensions. Long Horizon
46
48
  loads only its declared `pi-subagents` dependency by its resolved package path and restricts
47
49
  the Supervisor to its three orchestration tools. Extension discovery, built-in tools, and
48
50
  unrelated resource catalogs remain disabled by each profile's own contract.
49
- The tool-comparison profiles keep Pi's native built-in implementations, apply an explicit
51
+ The tool-comparison profiles keep Pi's built-in implementations except for the bounded
52
+ `bash` capability, apply an explicit
50
53
  model-visible tool allowlist, and load only the selected custom editor when one is required.
51
54
 
52
55
  ## Pi settings
@@ -148,6 +151,13 @@ DashScope, and Pexels HTTP requests use `retry.provider.maxRetries` and
148
151
  policy. The `harnesses` namespace contains only capability-specific settings that Pi
149
152
  does not own.
150
153
 
154
+ The optional `bash` capability wraps Pi's built-in `bash` definition and
155
+ changes only its omitted timeout to 120 seconds; explicit timeouts are preserved. Profiles
156
+ must compose the capability to install it. Every profile that already exposed `bash` now
157
+ uses it: `pi`, `self-compact`, Agent Arena, Code Arena Full Stack, and all four tool-
158
+ comparison profiles. `pi-ptc` reuses the same `bash` definition for its nested tool.
159
+ Profiles that did not expose `bash` do not gain it.
160
+
151
161
  Tool service and model configuration does not read the legacy `ARENA_*`, `CODE_HARNESS_*`, `DASHSCOPE_*`, `ROUTIFY_*`, or `PEXELS_*` variables. Subprocess tools still inherit the normal process environment so builds and user programs can access their own environment variables; the runtime also injects workspace-path variables for command compatibility.
152
162
 
153
163
  The settings file can contain plaintext service credentials. Restrict it to the current user:
@@ -167,18 +177,18 @@ chmod 600 ~/.pi/agent/settings.json
167
177
 
168
178
  | Profile | Distinct behavior |
169
179
  | --- | --- |
170
- | `pi` | Native Pi prompt with the default active `read`, `bash`, `edit`, and `write` tools |
171
- | `pi-ptc` | Native Pi prompt with only `run_code` model-visible; JavaScript can call nested `read`, `bash`, `edit`, and `write` |
172
- | `self-compact` | Isolated native Pi plus SelfCompact-style context status, rubric, and the `compact_context` tool |
180
+ | `pi` | Pi's default prompt and tool names, with the bounded `bash` capability |
181
+ | `pi-ptc` | Pi's default prompt with only `run_code` model-visible; JavaScript can call nested `read`, `bash`, `edit`, and `write` |
182
+ | `self-compact` | Isolated Pi plus the bounded `bash`, SelfCompact-style context status, rubric, and the `compact_context` tool |
173
183
  | `agent-arena` | General workspace agent tools, multimodal file reading, search, image and speech generation, and interactive `ask_user` |
174
184
  | `code-arena-html` | Single-file HTML tools with a smaller edit/search/media tool set |
175
185
  | `code-arena-react` | React/Vite file tools, package installation, build validation, research, media search, and image generation |
176
186
  | `code-arena-full-stack` | Next.js/PostgreSQL tools, bash, managed build/start validation, research, media search, and image generation |
177
187
  | `long-horizon-mea` | A supervisor session coordinating fresh Manager, Executor, and Auditor child Pi sessions through `pi-subagents` |
178
- | `bash-only` | Native Pi prompt and runtime with only `bash` active |
188
+ | `bash-only` | Pi's default prompt and runtime with only the bounded `bash` active |
179
189
  | `bash-apply-patch` | `bash` plus the Codex-style `apply_patch` capability |
180
190
  | `bash-str-replace-editor` | `bash` plus the DSH-style `str_replace_editor` capability |
181
- | `bash-file-search` | Native `read`, `bash`, `edit`, `write`, and `grep`, plus `glob` backed by Pi's native file finder |
191
+ | `bash-file-search` | Pi's built-in `read`, `edit`, `write`, and `grep`, the bounded `bash`, plus `glob` backed by Pi's native file finder |
182
192
 
183
193
  ### Tool-interface comparison
184
194
 
@@ -209,10 +219,16 @@ run_code(code, timeout_ms?, max_output_chars?)
209
219
 
210
220
  The `pi-ptc` profile disables direct built-in-tool exposure and nests Pi's default `read`,
211
221
  `bash`, `edit`, and `write` definitions under the JavaScript `tools` object.
212
- Scripts emit selected results with `text()` or forward an image block with `image()`. Each
213
- call runs in a fresh child Node process with an empty environment, a memory and wall-clock
214
- limit, and Node's permission model denying direct filesystem, child-process, and worker
215
- access. No runtime dependency or copied Codex source is added.
222
+ Scripts emit selected results with `text()` or forward either an image block or a nested
223
+ tool result with `image()`. Each call runs in a fresh child Node process with an empty
224
+ environment, a memory limit, and Node's permission model denying direct filesystem,
225
+ child-process, and worker access. The runtime stops synchronous JavaScript loops and scripts
226
+ that make no progress, but it does not impose a default wall-clock deadline while a nested
227
+ tool or a bounded `setTimeout()` is active. Configure duration on the nested tool doing the
228
+ work (for example, `tools.bash({ command, timeout: 300 })`). Use top-level `timeout_ms` only
229
+ when the entire orchestration needs an additional independent hard deadline. When embedding
230
+ shell parameter expansion in a JavaScript template literal, escape its dollar sign (for
231
+ example, `\${name}`). No runtime dependency or copied Codex source is added.
216
232
 
217
233
  Pi's public extension API can enumerate another extension's tool metadata, but it does not
218
234
  provide an execution handle for those tools. Consequently, this capability cannot safely
@@ -270,9 +286,10 @@ long-horizon.manager → long-horizon.executor → long-horizon.auditor
270
286
  ```
271
287
 
272
288
  Each role starts with fresh context. Manager has no workspace tools. Executor receives
273
- Pi's native `read`, `bash`, `edit`, `write`, `grep`, `find`, and `ls` tools; Auditor
274
- receives the native `read`, `bash`, `grep`, `find`, and `ls` tools. No custom child tool
275
- extension is loaded. The parent repeats the cycle until an Auditor independently reports
289
+ Pi's built-in `read`, `edit`, `write`, `grep`, `find`, and `ls` plus the bounded `bash`;
290
+ Auditor receives the built-in read-only tools plus the same `bash`. Their packaged child
291
+ runtime applies the shared capability; no role-specific child
292
+ tool extension is loaded. The parent repeats the cycle until an Auditor independently reports
276
293
  complete, clean, contract-aligned evidence.
277
294
 
278
295
  Role definitions ship under `.pi/agents/long-horizon/`. At startup, the capability resolves
@@ -305,7 +322,7 @@ src/
305
322
  settings.ts composes tool-owned settings
306
323
  ask-user/ Pi tool adapter for the question workflow
307
324
  context-management/ model-visible context management tools
308
- execution/ tools and their local settings parser
325
+ execution/ tools, the bash capability, and their local settings parser
309
326
  filesystem/ model-visible workspace file tools
310
327
  media/ media tools and their local settings parser
311
328
  programmatic-tool-calling/ run_code adapter and isolated JavaScript child runtime
@@ -5,33 +5,79 @@ var input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity
5
5
  var initialized = false;
6
6
  var finished = false;
7
7
  var nextCallId = 1;
8
+ var nextTimerId = 1;
9
+ var hostTimers = /* @__PURE__ */ new Map();
8
10
  var settleToolCall;
9
11
  var takeOutput;
12
+ var fireTimer;
10
13
  function send(message) {
11
14
  process.stdout.write(`${JSON.stringify(message)}
12
15
  `);
13
16
  }
17
+ function sendTimerState() {
18
+ if (!finished) send({ type: "timer_state", active: hostTimers.size });
19
+ }
20
+ function clearHostTimers() {
21
+ for (const timer of hostTimers.values()) clearTimeout(timer);
22
+ hostTimers.clear();
23
+ }
14
24
  function fail(error) {
15
25
  if (finished) return;
16
26
  finished = true;
27
+ clearHostTimers();
17
28
  const message = error instanceof Error ? error.message : String(error);
18
29
  send({ type: "done", error: message });
19
30
  input.close();
20
31
  process.stdin.unref();
21
32
  }
22
33
  function createBridge() {
23
- const bridge = (operation, first, second) => {
34
+ const bridge = (operation, first, second, third) => {
24
35
  if (operation === "register") {
25
- if (settleToolCall || takeOutput || typeof first !== "function" || typeof second !== "function") {
36
+ if (settleToolCall || takeOutput || fireTimer || typeof first !== "function" || typeof second !== "function" || typeof third !== "function") {
26
37
  throw new Error("run_code bridge registration failed");
27
38
  }
28
39
  settleToolCall = first;
29
40
  takeOutput = second;
41
+ fireTimer = third;
30
42
  return void 0;
31
43
  }
32
44
  if (typeof first !== "string") {
33
45
  throw new TypeError("run_code bridge expects serialized input");
34
46
  }
47
+ if (operation === "set_timer") {
48
+ const request2 = JSON.parse(first);
49
+ const delay = Number(request2.delay ?? 0);
50
+ if (!Number.isFinite(delay) || delay < 0 || delay > 6e5) {
51
+ throw new RangeError("setTimeout delay must be between 0 and 600000 ms");
52
+ }
53
+ const id2 = `timer-${String(nextTimerId++)}`;
54
+ const timer = setTimeout(() => {
55
+ hostTimers.delete(id2);
56
+ sendTimerState();
57
+ if (finished || typeof fireTimer !== "function") return;
58
+ try {
59
+ const result = fireTimer(id2);
60
+ if (result && typeof /** @type {any} */
61
+ result.then === "function") {
62
+ void Promise.resolve(result).catch(fail);
63
+ }
64
+ } catch (error) {
65
+ fail(error);
66
+ }
67
+ }, Math.floor(delay));
68
+ timer.unref();
69
+ hostTimers.set(id2, timer);
70
+ sendTimerState();
71
+ return id2;
72
+ }
73
+ if (operation === "clear_timer") {
74
+ const timer = hostTimers.get(first);
75
+ if (timer) clearTimeout(timer);
76
+ hostTimers.delete(first);
77
+ sendTimerState();
78
+ return void 0;
79
+ }
80
+ if (operation !== "call") throw new Error(`Unknown run_code bridge operation: ${operation}`);
35
81
  const request = JSON.parse(first);
36
82
  const id = String(nextCallId++);
37
83
  send({ type: "tool_call", id, name: request.name, args: request.args });
@@ -51,6 +97,7 @@ function bootstrapGlobals() {
51
97
  const metadata = parse(runtimeGlobal.__runCodeMetadata);
52
98
  const emitted = [];
53
99
  const pending = /* @__PURE__ */ new Map();
100
+ const timerCallbacks = /* @__PURE__ */ new Map();
54
101
  const settle = (id, value, error) => {
55
102
  const entry = pending.get(id);
56
103
  if (!entry) return;
@@ -59,7 +106,13 @@ function bootstrapGlobals() {
59
106
  else entry.resolve(value === void 0 ? void 0 : parse(value));
60
107
  };
61
108
  const output = () => stringify(emitted);
62
- bridge("register", settle, output);
109
+ const fireTimerCallback = (id) => {
110
+ const entry = timerCallbacks.get(id);
111
+ if (!entry) return void 0;
112
+ timerCallbacks.delete(id);
113
+ return entry.callback(...entry.args);
114
+ };
115
+ bridge("register", settle, output, fireTimerCallback);
63
116
  const tools = /* @__PURE__ */ Object.create(null);
64
117
  for (const item of metadata) {
65
118
  Object.defineProperty(tools, item.name, {
@@ -95,16 +148,42 @@ function bootstrapGlobals() {
95
148
  const text = (value) => emitted.push({ type: "text", text: printable(value) });
96
149
  const image = (value) => {
97
150
  if (!value || typeof value !== "object") {
98
- throw new TypeError("image() expects an image content object");
151
+ throw new TypeError("image() expects an image content block or nested tool result");
99
152
  }
100
153
  const item = (
101
154
  /** @type {Record<string, unknown>} */
102
155
  value
103
156
  );
104
- if (typeof item.data !== "string" || typeof item.mimeType !== "string") {
105
- throw new TypeError("image() expects string data and mimeType fields");
157
+ const candidates = Array.isArray(item.content) ? item.content : [item];
158
+ let count = 0;
159
+ for (const candidate of candidates) {
160
+ if (!candidate || typeof candidate !== "object") continue;
161
+ const content = (
162
+ /** @type {Record<string, unknown>} */
163
+ candidate
164
+ );
165
+ if ((content.type === void 0 || content.type === "image") && typeof content.data === "string" && typeof content.mimeType === "string") {
166
+ emitted.push({ type: "image", data: content.data, mimeType: content.mimeType });
167
+ count += 1;
168
+ }
106
169
  }
107
- emitted.push({ type: "image", data: item.data, mimeType: item.mimeType });
170
+ if (!count) throw new TypeError("image() input does not contain an image block");
171
+ };
172
+ const scheduleTimeout = (callback, delay = 0, ...args) => {
173
+ if (typeof callback !== "function") throw new TypeError("setTimeout callback must be a function");
174
+ const numericDelay = Number(delay);
175
+ if (!Number.isFinite(numericDelay) || numericDelay < 0 || numericDelay > 6e5) {
176
+ throw new RangeError("setTimeout delay must be between 0 and 600000 ms");
177
+ }
178
+ const id = bridge("set_timer", stringify({ delay: Math.floor(numericDelay) }));
179
+ if (typeof id !== "string") throw new Error("run_code bridge did not return a timer id");
180
+ timerCallbacks.set(id, { callback, args });
181
+ return id;
182
+ };
183
+ const cancelTimeout = (handle) => {
184
+ if (typeof handle !== "string") return;
185
+ timerCallbacks.delete(handle);
186
+ bridge("clear_timer", handle);
108
187
  };
109
188
  Object.defineProperties(runtimeGlobal, {
110
189
  tools: { value: tools, enumerable: true },
@@ -114,6 +193,8 @@ function bootstrapGlobals() {
114
193
  },
115
194
  text: { value: text, enumerable: true },
116
195
  image: { value: image, enumerable: true },
196
+ setTimeout: { value: scheduleTimeout, enumerable: true },
197
+ clearTimeout: { value: cancelTimeout, enumerable: true },
117
198
  console: { value: void 0 }
118
199
  });
119
200
  delete runtimeGlobal.__runCodeBridge;
@@ -152,6 +233,7 @@ ${message.code}
152
233
  await script.runInContext(context, { timeout: message.syncTimeoutMs });
153
234
  if (finished) return;
154
235
  finished = true;
236
+ clearHostTimers();
155
237
  if (typeof takeOutput !== "function") {
156
238
  throw new Error("run_code output bridge is unavailable");
157
239
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/capabilities/tools/programmatic-tool-calling/child-runtime.js"],
4
- "sourcesContent": ["// @ts-check\n\n/**\n * Short-lived JavaScript runtime used by run_code.\n *\n * This file is both directly executable from the source tree and compiled as a\n * separate package entrypoint. Model-authored code runs in a vm context without\n * Node globals. Nested tool calls are forwarded to the parent over JSON lines.\n */\n\nimport readline from \"node:readline\";\nimport vm from \"node:vm\";\n\n/** @typedef {import(\"./protocol.js\").ChildDoneMessage} ChildDoneMessage */\n/** @typedef {import(\"./protocol.js\").ChildMessage} ChildMessage */\n/** @typedef {import(\"./protocol.js\").ChildToolCallMessage} ChildToolCallMessage */\n/** @typedef {import(\"./protocol.js\").NestedToolMetadata} NestedToolMetadata */\n/** @typedef {import(\"./protocol.js\").ParentMessage} ParentMessage */\n\nconst input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });\nlet initialized = false;\nlet finished = false;\nlet nextCallId = 1;\n/** @type {((id: string, value: string | undefined, error: string | undefined) => void) | undefined} */\nlet settleToolCall;\n/** @type {(() => string) | undefined} */\nlet takeOutput;\n\n/** @param {ChildMessage} message */\nfunction send(message) {\n\tprocess.stdout.write(`${JSON.stringify(message)}\\n`);\n}\n\n/** @param {unknown} error */\nfunction fail(error) {\n\tif (finished) return;\n\tfinished = true;\n\tconst message = error instanceof Error ? error.message : String(error);\n\tsend({ type: \"done\", error: message });\n\tinput.close();\n\tprocess.stdin.unref();\n}\n\nfunction createBridge() {\n\t/**\n\t * @param {\"register\" | \"call\"} operation\n\t * @param {string | ((id: string, value: string | undefined, error: string | undefined) => void)} first\n\t * @param {(() => string) | undefined} [second]\n\t */\n\tconst bridge = (operation, first, second) => {\n\t\tif (operation === \"register\") {\n\t\t\tif (\n\t\t\t\tsettleToolCall\n\t\t\t\t|| takeOutput\n\t\t\t\t|| typeof first !== \"function\"\n\t\t\t\t|| typeof second !== \"function\"\n\t\t\t) {\n\t\t\t\tthrow new Error(\"run_code bridge registration failed\");\n\t\t\t}\n\t\t\tsettleToolCall = first;\n\t\t\ttakeOutput = second;\n\t\t\treturn undefined;\n\t\t}\n\t\tif (typeof first !== \"string\") {\n\t\t\tthrow new TypeError(\"run_code bridge expects serialized input\");\n\t\t}\n\t\t/** @type {{ name: string; args?: unknown }} */\n\t\tconst request = JSON.parse(first);\n\t\tconst id = String(nextCallId++);\n\t\tsend({ type: \"tool_call\", id, name: request.name, args: request.args });\n\t\treturn id;\n\t};\n\tObject.setPrototypeOf(bridge, null);\n\treturn bridge;\n}\n\n/**\n * This function is stringified and evaluated inside the model's vm context so\n * all user-facing functions belong to that realm, not the Node host realm.\n */\nfunction bootstrapGlobals() {\n\tconst runtimeGlobal = /** @type {any} */ (globalThis);\n\t/** @type {(operation: \"register\" | \"call\", first: string | ((id: string, value: string | undefined, error: string | undefined) => void), second?: () => string) => string | undefined} */\n\tconst bridge = runtimeGlobal.__runCodeBridge;\n\tconst parse = JSON.parse.bind(JSON);\n\tconst stringify = JSON.stringify.bind(JSON);\n\t/** @type {NestedToolMetadata[]} */\n\tconst metadata = parse(runtimeGlobal.__runCodeMetadata);\n\t/** @type {Array<{ type: \"text\"; text: string } | { type: \"image\"; data: string; mimeType: string }>} */\n\tconst emitted = [];\n\t/** @type {Map<string, { resolve: (value: unknown) => void; reject: (reason?: unknown) => void }>} */\n\tconst pending = new Map();\n\n\t/**\n\t * @param {string} id\n\t * @param {string | undefined} value\n\t * @param {string | undefined} error\n\t */\n\tconst settle = (id, value, error) => {\n\t\tconst entry = pending.get(id);\n\t\tif (!entry) return;\n\t\tpending.delete(id);\n\t\tif (error !== undefined) entry.reject(new Error(error));\n\t\telse entry.resolve(value === undefined ? undefined : parse(value));\n\t};\n\tconst output = () => stringify(emitted);\n\tbridge(\"register\", settle, output);\n\n\tconst tools = Object.create(null);\n\tfor (const item of metadata) {\n\t\tObject.defineProperty(tools, item.name, {\n\t\t\tenumerable: true,\n\t\t\tvalue: (/** @type {unknown} */ args) => new Promise((resolve, reject) => {\n\t\t\t\tlet request;\n\t\t\t\ttry {\n\t\t\t\t\trequest = stringify({ name: item.name, args });\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst id = bridge(\"call\", request);\n\t\t\t\tif (typeof id !== \"string\") {\n\t\t\t\t\treject(new Error(\"run_code bridge did not return a tool call id\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tpending.set(id, { resolve, reject });\n\t\t\t}),\n\t\t});\n\t}\n\tObject.freeze(tools);\n\n\t/** @param {unknown} value */\n\tconst printable = (value) => {\n\t\tif (typeof value === \"string\") return value;\n\t\tif (value === undefined) return \"undefined\";\n\t\ttry {\n\t\t\tconst encoded = stringify(value);\n\t\t\treturn encoded === undefined ? String(value) : encoded;\n\t\t} catch {\n\t\t\treturn String(value);\n\t\t}\n\t};\n\t/** @param {unknown} value */\n\tconst text = (value) => emitted.push({ type: \"text\", text: printable(value) });\n\t/** @param {unknown} value */\n\tconst image = (value) => {\n\t\tif (!value || typeof value !== \"object\") {\n\t\t\tthrow new TypeError(\"image() expects an image content object\");\n\t\t}\n\t\tconst item = /** @type {Record<string, unknown>} */ (value);\n\t\tif (typeof item.data !== \"string\" || typeof item.mimeType !== \"string\") {\n\t\t\tthrow new TypeError(\"image() expects string data and mimeType fields\");\n\t\t}\n\t\temitted.push({ type: \"image\", data: item.data, mimeType: item.mimeType });\n\t};\n\n\tObject.defineProperties(runtimeGlobal, {\n\t\ttools: { value: tools, enumerable: true },\n\t\tALL_TOOLS: {\n\t\t\tvalue: Object.freeze(metadata.map((item) => Object.freeze({ ...item }))),\n\t\t\tenumerable: true,\n\t\t},\n\t\ttext: { value: text, enumerable: true },\n\t\timage: { value: image, enumerable: true },\n\t\tconsole: { value: undefined },\n\t});\n\tdelete runtimeGlobal.__runCodeBridge;\n\tdelete runtimeGlobal.__runCodeMetadata;\n}\n\n/**\n * @param {vm.Context} context\n * @param {NestedToolMetadata[]} metadata\n */\nfunction installGlobals(context, metadata) {\n\tcontext.__runCodeBridge = createBridge();\n\tcontext.__runCodeMetadata = JSON.stringify(metadata);\n\tconst bootstrap = new vm.Script(`(${bootstrapGlobals.toString()})()`);\n\tbootstrap.runInContext(context);\n\tif (typeof settleToolCall !== \"function\" || typeof takeOutput !== \"function\") {\n\t\tthrow new Error(\"run_code failed to initialize its tool bridge\");\n\t}\n}\n\n/** @param {import(\"./protocol.js\").ChildToolResultMessage | import(\"./protocol.js\").ChildToolErrorMessage} message */\nfunction handleToolResponse(message) {\n\tif (typeof settleToolCall !== \"function\") return;\n\tif (message.type === \"tool_result\") {\n\t\tconst value = message.value === undefined ? undefined : JSON.stringify(message.value);\n\t\tsettleToolCall(message.id, value, undefined);\n\t} else {\n\t\tsettleToolCall(message.id, undefined, message.error || \"Nested tool call failed\");\n\t}\n}\n\n/** @param {import(\"./protocol.js\").ChildInitMessage} message */\nasync function start(message) {\n\tif (initialized) throw new Error(\"run_code child received more than one init message\");\n\tinitialized = true;\n\tconst context = vm.createContext(Object.create(null), {\n\t\tname: \"pi-run-code\",\n\t\tcodeGeneration: { strings: false, wasm: false },\n\t});\n\tinstallGlobals(context, message.tools);\n\tconst wrapped = `\"use strict\"; (async () => {\\n${message.code}\\n})()`;\n\tconst script = new vm.Script(wrapped, { filename: \"run_code.js\" });\n\tawait script.runInContext(context, { timeout: message.syncTimeoutMs });\n\n\tif (finished) return;\n\tfinished = true;\n\tif (typeof takeOutput !== \"function\") {\n\t\tthrow new Error(\"run_code output bridge is unavailable\");\n\t}\n\tconst output = takeOutput();\n\tsend({ type: \"done\", content: JSON.parse(output) });\n\tinput.close();\n\tprocess.stdin.unref();\n}\n\ninput.on(\"line\", (line) => {\n\t/** @type {ParentMessage} */\n\tlet message;\n\ttry {\n\t\tmessage = JSON.parse(line);\n\t} catch (error) {\n\t\tfail(new Error(`Invalid parent message: ${error instanceof Error ? error.message : String(error)}`));\n\t\treturn;\n\t}\n\tif (message.type === \"init\") {\n\t\tvoid start(message).catch(fail);\n\t\treturn;\n\t}\n\tif (message.type === \"tool_result\" || message.type === \"tool_error\") {\n\t\thandleToolResponse(message);\n\t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AE,MAAM,IAAI;AAC9B;AAAA,EACD;AACA,MAAI,QAAQ,SAAS,iBAAiB,QAAQ,SAAS,cAAc;AACpE,uBAAmB,OAAO;AAAA,EAC3B;AACD,CAAC;AAED,MAAM,GAAG,SAAS,MAAM;AACvB,MAAI,CAAC,SAAU,MAAK,IAAI,MAAM,8BAA8B,CAAC;AAC9D,CAAC;",
6
- "names": []
4
+ "sourcesContent": ["// @ts-check\n\n/**\n * Short-lived JavaScript runtime used by run_code.\n *\n * This file is both directly executable from the source tree and compiled as a\n * separate package entrypoint. Model-authored code runs in a vm context without\n * Node globals. Nested tool calls are forwarded to the parent over JSON lines.\n */\n\nimport readline from \"node:readline\";\nimport vm from \"node:vm\";\n\n/** @typedef {import(\"./protocol.js\").ChildDoneMessage} ChildDoneMessage */\n/** @typedef {import(\"./protocol.js\").ChildMessage} ChildMessage */\n/** @typedef {import(\"./protocol.js\").ChildToolCallMessage} ChildToolCallMessage */\n/** @typedef {import(\"./protocol.js\").NestedToolMetadata} NestedToolMetadata */\n/** @typedef {import(\"./protocol.js\").ParentMessage} ParentMessage */\n\nconst input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });\nlet initialized = false;\nlet finished = false;\nlet nextCallId = 1;\nlet nextTimerId = 1;\n/** @type {Map<string, ReturnType<typeof setTimeout>>} */\nconst hostTimers = new Map();\n/** @type {((id: string, value: string | undefined, error: string | undefined) => void) | undefined} */\nlet settleToolCall;\n/** @type {(() => string) | undefined} */\nlet takeOutput;\n/** @type {((id: string) => unknown) | undefined} */\nlet fireTimer;\n\n/** @param {ChildMessage} message */\nfunction send(message) {\n\tprocess.stdout.write(`${JSON.stringify(message)}\\n`);\n}\n\nfunction sendTimerState() {\n\tif (!finished) send({ type: \"timer_state\", active: hostTimers.size });\n}\n\nfunction clearHostTimers() {\n\tfor (const timer of hostTimers.values()) clearTimeout(timer);\n\thostTimers.clear();\n}\n\n/** @param {unknown} error */\nfunction fail(error) {\n\tif (finished) return;\n\tfinished = true;\n\tclearHostTimers();\n\tconst message = error instanceof Error ? error.message : String(error);\n\tsend({ type: \"done\", error: message });\n\tinput.close();\n\tprocess.stdin.unref();\n}\n\nfunction createBridge() {\n\t/**\n\t * @param {\"register\" | \"call\" | \"set_timer\" | \"clear_timer\"} operation\n\t * @param {string | ((id: string, value: string | undefined, error: string | undefined) => void)} first\n\t * @param {(() => string) | undefined} [second]\n\t * @param {((id: string) => unknown) | undefined} [third]\n\t */\n\tconst bridge = (operation, first, second, third) => {\n\t\tif (operation === \"register\") {\n\t\t\tif (\n\t\t\t\tsettleToolCall\n\t\t\t\t\t|| takeOutput\n\t\t\t\t\t|| fireTimer\n\t\t\t\t\t|| typeof first !== \"function\"\n\t\t\t\t\t|| typeof second !== \"function\"\n\t\t\t\t\t|| typeof third !== \"function\"\n\t\t\t) {\n\t\t\t\tthrow new Error(\"run_code bridge registration failed\");\n\t\t\t}\n\t\t\tsettleToolCall = first;\n\t\t\ttakeOutput = second;\n\t\t\tfireTimer = third;\n\t\t\treturn undefined;\n\t\t}\n\t\tif (typeof first !== \"string\") {\n\t\t\tthrow new TypeError(\"run_code bridge expects serialized input\");\n\t\t}\n\t\tif (operation === \"set_timer\") {\n\t\t\t/** @type {{ delay?: unknown }} */\n\t\t\tconst request = JSON.parse(first);\n\t\t\tconst delay = Number(request.delay ?? 0);\n\t\t\tif (!Number.isFinite(delay) || delay < 0 || delay > 600_000) {\n\t\t\t\tthrow new RangeError(\"setTimeout delay must be between 0 and 600000 ms\");\n\t\t\t}\n\t\t\tconst id = `timer-${String(nextTimerId++)}`;\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\thostTimers.delete(id);\n\t\t\t\tsendTimerState();\n\t\t\t\tif (finished || typeof fireTimer !== \"function\") return;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = fireTimer(id);\n\t\t\t\t\tif (result && typeof /** @type {any} */ (result).then === \"function\") {\n\t\t\t\t\t\tvoid Promise.resolve(result).catch(fail);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfail(error);\n\t\t\t\t}\n\t\t\t}, Math.floor(delay));\n\t\t\ttimer.unref();\n\t\t\thostTimers.set(id, timer);\n\t\t\tsendTimerState();\n\t\t\treturn id;\n\t\t}\n\t\tif (operation === \"clear_timer\") {\n\t\t\tconst timer = hostTimers.get(first);\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\thostTimers.delete(first);\n\t\t\tsendTimerState();\n\t\t\treturn undefined;\n\t\t}\n\t\tif (operation !== \"call\") throw new Error(`Unknown run_code bridge operation: ${operation}`);\n\t\t/** @type {{ name: string; args?: unknown }} */\n\t\tconst request = JSON.parse(first);\n\t\tconst id = String(nextCallId++);\n\t\tsend({ type: \"tool_call\", id, name: request.name, args: request.args });\n\t\treturn id;\n\t};\n\tObject.setPrototypeOf(bridge, null);\n\treturn bridge;\n}\n\n/**\n * This function is stringified and evaluated inside the model's vm context so\n * all user-facing functions belong to that realm, not the Node host realm.\n */\nfunction bootstrapGlobals() {\n\tconst runtimeGlobal = /** @type {any} */ (globalThis);\n\t/** @type {(operation: \"register\" | \"call\" | \"set_timer\" | \"clear_timer\", first: string | ((id: string, value: string | undefined, error: string | undefined) => void), second?: () => string, third?: (id: string) => unknown) => string | undefined} */\n\tconst bridge = runtimeGlobal.__runCodeBridge;\n\tconst parse = JSON.parse.bind(JSON);\n\tconst stringify = JSON.stringify.bind(JSON);\n\t/** @type {NestedToolMetadata[]} */\n\tconst metadata = parse(runtimeGlobal.__runCodeMetadata);\n\t/** @type {Array<{ type: \"text\"; text: string } | { type: \"image\"; data: string; mimeType: string }>} */\n\tconst emitted = [];\n\t/** @type {Map<string, { resolve: (value: unknown) => void; reject: (reason?: unknown) => void }>} */\n\tconst pending = new Map();\n\t/** @type {Map<string, { callback: (...args: unknown[]) => unknown; args: unknown[] }>} */\n\tconst timerCallbacks = new Map();\n\n\t/**\n\t * @param {string} id\n\t * @param {string | undefined} value\n\t * @param {string | undefined} error\n\t */\n\tconst settle = (id, value, error) => {\n\t\tconst entry = pending.get(id);\n\t\tif (!entry) return;\n\t\tpending.delete(id);\n\t\tif (error !== undefined) entry.reject(new Error(error));\n\t\telse entry.resolve(value === undefined ? undefined : parse(value));\n\t};\n\tconst output = () => stringify(emitted);\n\t/** @param {string} id */\n\tconst fireTimerCallback = (id) => {\n\t\tconst entry = timerCallbacks.get(id);\n\t\tif (!entry) return undefined;\n\t\ttimerCallbacks.delete(id);\n\t\treturn entry.callback(...entry.args);\n\t};\n\tbridge(\"register\", settle, output, fireTimerCallback);\n\n\tconst tools = Object.create(null);\n\tfor (const item of metadata) {\n\t\tObject.defineProperty(tools, item.name, {\n\t\t\tenumerable: true,\n\t\t\tvalue: (/** @type {unknown} */ args) => new Promise((resolve, reject) => {\n\t\t\t\tlet request;\n\t\t\t\ttry {\n\t\t\t\t\trequest = stringify({ name: item.name, args });\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst id = bridge(\"call\", request);\n\t\t\t\tif (typeof id !== \"string\") {\n\t\t\t\t\treject(new Error(\"run_code bridge did not return a tool call id\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tpending.set(id, { resolve, reject });\n\t\t\t}),\n\t\t});\n\t}\n\tObject.freeze(tools);\n\n\t/** @param {unknown} value */\n\tconst printable = (value) => {\n\t\tif (typeof value === \"string\") return value;\n\t\tif (value === undefined) return \"undefined\";\n\t\ttry {\n\t\t\tconst encoded = stringify(value);\n\t\t\treturn encoded === undefined ? String(value) : encoded;\n\t\t} catch {\n\t\t\treturn String(value);\n\t\t}\n\t};\n\t/** @param {unknown} value */\n\tconst text = (value) => emitted.push({ type: \"text\", text: printable(value) });\n\t/** @param {unknown} value */\n\tconst image = (value) => {\n\t\tif (!value || typeof value !== \"object\") {\n\t\t\tthrow new TypeError(\"image() expects an image content block or nested tool result\");\n\t\t}\n\t\tconst item = /** @type {Record<string, unknown>} */ (value);\n\t\tconst candidates = Array.isArray(item.content) ? item.content : [item];\n\t\tlet count = 0;\n\t\tfor (const candidate of candidates) {\n\t\t\tif (!candidate || typeof candidate !== \"object\") continue;\n\t\t\tconst content = /** @type {Record<string, unknown>} */ (candidate);\n\t\t\tif (\n\t\t\t\t(content.type === undefined || content.type === \"image\")\n\t\t\t\t\t&& typeof content.data === \"string\"\n\t\t\t\t\t&& typeof content.mimeType === \"string\"\n\t\t\t) {\n\t\t\t\temitted.push({ type: \"image\", data: content.data, mimeType: content.mimeType });\n\t\t\t\tcount += 1;\n\t\t\t}\n\t\t}\n\t\tif (!count) throw new TypeError(\"image() input does not contain an image block\");\n\t};\n\t/**\n\t * @param {(...args: unknown[]) => unknown} callback\n\t * @param {unknown} [delay]\n\t * @param {...unknown} args\n\t */\n\tconst scheduleTimeout = (callback, delay = 0, ...args) => {\n\t\tif (typeof callback !== \"function\") throw new TypeError(\"setTimeout callback must be a function\");\n\t\tconst numericDelay = Number(delay);\n\t\tif (!Number.isFinite(numericDelay) || numericDelay < 0 || numericDelay > 600_000) {\n\t\t\tthrow new RangeError(\"setTimeout delay must be between 0 and 600000 ms\");\n\t\t}\n\t\tconst id = bridge(\"set_timer\", stringify({ delay: Math.floor(numericDelay) }));\n\t\tif (typeof id !== \"string\") throw new Error(\"run_code bridge did not return a timer id\");\n\t\ttimerCallbacks.set(id, { callback, args });\n\t\treturn id;\n\t};\n\t/** @param {unknown} handle */\n\tconst cancelTimeout = (handle) => {\n\t\tif (typeof handle !== \"string\") return;\n\t\ttimerCallbacks.delete(handle);\n\t\tbridge(\"clear_timer\", handle);\n\t};\n\n\tObject.defineProperties(runtimeGlobal, {\n\t\ttools: { value: tools, enumerable: true },\n\t\tALL_TOOLS: {\n\t\t\tvalue: Object.freeze(metadata.map((item) => Object.freeze({ ...item }))),\n\t\t\tenumerable: true,\n\t\t},\n\t\ttext: { value: text, enumerable: true },\n\t\timage: { value: image, enumerable: true },\n\t\tsetTimeout: { value: scheduleTimeout, enumerable: true },\n\t\tclearTimeout: { value: cancelTimeout, enumerable: true },\n\t\tconsole: { value: undefined },\n\t});\n\tdelete runtimeGlobal.__runCodeBridge;\n\tdelete runtimeGlobal.__runCodeMetadata;\n}\n\n/**\n * @param {vm.Context} context\n * @param {NestedToolMetadata[]} metadata\n */\nfunction installGlobals(context, metadata) {\n\tcontext.__runCodeBridge = createBridge();\n\tcontext.__runCodeMetadata = JSON.stringify(metadata);\n\tconst bootstrap = new vm.Script(`(${bootstrapGlobals.toString()})()`);\n\tbootstrap.runInContext(context);\n\tif (typeof settleToolCall !== \"function\" || typeof takeOutput !== \"function\") {\n\t\tthrow new Error(\"run_code failed to initialize its tool bridge\");\n\t}\n}\n\n/** @param {import(\"./protocol.js\").ChildToolResultMessage | import(\"./protocol.js\").ChildToolErrorMessage} message */\nfunction handleToolResponse(message) {\n\tif (typeof settleToolCall !== \"function\") return;\n\tif (message.type === \"tool_result\") {\n\t\tconst value = message.value === undefined ? undefined : JSON.stringify(message.value);\n\t\tsettleToolCall(message.id, value, undefined);\n\t} else {\n\t\tsettleToolCall(message.id, undefined, message.error || \"Nested tool call failed\");\n\t}\n}\n\n/** @param {import(\"./protocol.js\").ChildInitMessage} message */\nasync function start(message) {\n\tif (initialized) throw new Error(\"run_code child received more than one init message\");\n\tinitialized = true;\n\tconst context = vm.createContext(Object.create(null), {\n\t\tname: \"pi-run-code\",\n\t\tcodeGeneration: { strings: false, wasm: false },\n\t});\n\tinstallGlobals(context, message.tools);\n\tconst wrapped = `\"use strict\"; (async () => {\\n${message.code}\\n})()`;\n\tconst script = new vm.Script(wrapped, { filename: \"run_code.js\" });\n\tawait script.runInContext(context, { timeout: message.syncTimeoutMs });\n\n\tif (finished) return;\n\tfinished = true;\n\tclearHostTimers();\n\tif (typeof takeOutput !== \"function\") {\n\t\tthrow new Error(\"run_code output bridge is unavailable\");\n\t}\n\tconst output = takeOutput();\n\tsend({ type: \"done\", content: JSON.parse(output) });\n\tinput.close();\n\tprocess.stdin.unref();\n}\n\ninput.on(\"line\", (line) => {\n\t/** @type {ParentMessage} */\n\tlet message;\n\ttry {\n\t\tmessage = JSON.parse(line);\n\t} catch (error) {\n\t\tfail(new Error(`Invalid parent message: ${error instanceof Error ? error.message : String(error)}`));\n\t\treturn;\n\t}\n\tif (message.type === \"init\") {\n\t\tvoid start(message).catch(fail);\n\t\treturn;\n\t}\n\tif (message.type === \"tool_result\" || message.type === \"tool_error\") {\n\t\thandleToolResponse(message);\n\t}\n});\n\ninput.on(\"close\", () => {\n\tif (!finished) fail(new Error(\"run_code parent disconnected\"));\n});\n"],
5
+ "mappings": ";AAUA,OAAO,cAAc;AACrB,OAAO,QAAQ;AAQf,IAAM,QAAQ,SAAS,gBAAgB,EAAE,OAAO,QAAQ,OAAO,WAAW,SAAS,CAAC;AACpF,IAAI,cAAc;AAClB,IAAI,WAAW;AACf,IAAI,aAAa;AACjB,IAAI,cAAc;AAElB,IAAM,aAAa,oBAAI,IAAI;AAE3B,IAAI;AAEJ,IAAI;AAEJ,IAAI;AAGJ,SAAS,KAAK,SAAS;AACtB,UAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,OAAO,CAAC;AAAA,CAAI;AACpD;AAEA,SAAS,iBAAiB;AACzB,MAAI,CAAC,SAAU,MAAK,EAAE,MAAM,eAAe,QAAQ,WAAW,KAAK,CAAC;AACrE;AAEA,SAAS,kBAAkB;AAC1B,aAAW,SAAS,WAAW,OAAO,EAAG,cAAa,KAAK;AAC3D,aAAW,MAAM;AAClB;AAGA,SAAS,KAAK,OAAO;AACpB,MAAI,SAAU;AACd,aAAW;AACX,kBAAgB;AAChB,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,OAAK,EAAE,MAAM,QAAQ,OAAO,QAAQ,CAAC;AACrC,QAAM,MAAM;AACZ,UAAQ,MAAM,MAAM;AACrB;AAEA,SAAS,eAAe;AAOvB,QAAM,SAAS,CAAC,WAAW,OAAO,QAAQ,UAAU;AACnD,QAAI,cAAc,YAAY;AA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