@qwen-code/qwen-harness 0.1.0 → 0.1.1

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,15 +1,8 @@
1
1
  # Pi Training Harness
2
2
 
3
- This repository provides native Pi plus five harness profiles without replacing Pi's runtime:
3
+ This repository provides native Pi plus focused harness profiles without replacing Pi's runtime. See [Profiles](#profiles) for the complete list.
4
4
 
5
- - `pi` (native Pi with its default prompt and tools)
6
- - `agent-arena`
7
- - `code-arena-html`
8
- - `code-arena-react`
9
- - `code-arena-full-stack`
10
- - `long-horizon`
11
-
12
- The five 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 native Pi.
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.
13
6
 
14
7
  ## Install
15
8
 
@@ -28,41 +21,33 @@ Use one development command for every harness. Omitting `--harness` runs native
28
21
 
29
22
  ```bash
30
23
  npm run dev
31
- npm run dev -- --harness agent-arena
32
- npm run dev -- --harness code-arena-react --mode json "Build a product page"
33
- npm run dev -- --harness long-horizon -p "Complete this long-horizon task"
24
+ npm run dev -- --harness bash-apply-patch -p "Fix the failing tests"
34
25
  ```
35
26
 
36
27
  ## Run
37
28
 
38
29
  ```bash
39
30
  qwen-harness
40
- qwen-harness --harness pi
41
- qwen-harness --harness agent-arena
42
- qwen-harness --harness code-arena-html
43
- qwen-harness --harness code-arena-react
44
- qwen-harness --harness code-arena-full-stack
45
- qwen-harness --harness long-horizon
31
+ qwen-harness --harness bash-apply-patch -p "Fix the failing tests"
46
32
  ```
47
33
 
48
- The wrapper consumes only the optional `--harness`; every other argument is passed to Pi unchanged:
49
-
50
- ```bash
51
- qwen-harness --harness pi -p "Analyze this repository"
52
- qwen-harness --harness code-arena-html --resume
53
- qwen-harness --harness code-arena-react --mode json "Build a product page"
54
- qwen-harness --harness code-arena-full-stack --mode rpc
55
- qwen-harness --harness long-horizon -p "Complete this long-horizon task"
56
- ```
34
+ Pass any name from the [Profiles](#profiles) table to `--harness`. The wrapper consumes only this optional argument; every other argument is passed to Pi unchanged.
57
35
 
58
36
  To use the same command from a checkout, run `npm run build && npm link` once. Re-run
59
37
  `npm run build` after source changes; `qwen-harness` will continue to point at this checkout.
60
38
 
61
39
  The compiled entrypoint calls Pi's public `main()` function. The `pi` harness adds no
62
- system prompt or tools, so it behaves like native Pi. The Arena profiles load only their explicit tool extensions. Long Horizon
40
+ system prompt or tools, so it behaves like native Pi. `pi-ptc` preserves Pi's normal prompt
41
+ but activates the packaged programmatic-tool-calling capability: the model sees only
42
+ `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.
45
+ The Arena profiles load only their explicit tool extensions. Long Horizon
63
46
  loads only its declared `pi-subagents` dependency by its resolved package path and restricts
64
47
  the Supervisor to its three orchestration tools. Extension discovery, built-in tools, and
65
48
  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
50
+ model-visible tool allowlist, and load only the selected custom editor when one is required.
66
51
 
67
52
  ## Pi settings
68
53
 
@@ -178,20 +163,107 @@ chmod 600 ~/.pi/agent/settings.json
178
163
  - `harnesses.tools.webSearch`, `generateImage`, and `generateSpeech` configure the corresponding external tool calls.
179
164
  - `harnesses.tools.imageCaption` is optional. When the active Pi model cannot read images, `read_file` sends the image to this Pi-registered side model and returns its caption. The side model uses Pi's model registry and credentials; `provider` and `model` must resolve through the same Pi installation.
180
165
 
181
- ## Profile isolation
166
+ ## Profiles
182
167
 
183
168
  | Profile | Distinct behavior |
184
169
  | --- | --- |
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 |
185
173
  | `agent-arena` | General workspace agent tools, multimodal file reading, search, image and speech generation, and interactive `ask_user` |
186
174
  | `code-arena-html` | Single-file HTML tools with a smaller edit/search/media tool set |
187
175
  | `code-arena-react` | React/Vite file tools, package installation, build validation, research, media search, and image generation |
188
176
  | `code-arena-full-stack` | Next.js/PostgreSQL tools, bash, managed build/start validation, research, media search, and image generation |
189
- | `long-horizon` | A supervisor session coordinating fresh Manager, Executor, and Auditor child Pi sessions through `pi-subagents` |
177
+ | `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 |
179
+ | `bash-apply-patch` | `bash` plus the Codex-style `apply_patch` capability |
180
+ | `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 |
182
+
183
+ ### Tool-interface comparison
184
+
185
+ The profiles under `src/harnesses/tool-comparison/` form a controlled tool-interface matrix.
186
+ They all retain Pi's native prompt, model runtime, settings, sessions, and workspace behavior while
187
+ disabling external resource discovery. Their model-visible tool sets are:
188
+
189
+ | Experiment | Run with `--harness` | Active tools |
190
+ | --- | --- | --- |
191
+ | Bash only | `bash-only` | `bash` |
192
+ | Codex editing | `bash-apply-patch` | `bash`, `apply_patch` |
193
+ | Pi editing baseline | `pi` | `read`, `bash`, `edit`, `write` |
194
+ | Programmatic tool calling | `pi-ptc` | `run_code` (nests Pi's four default tools) |
195
+ | DSH editing | `bash-str-replace-editor` | `bash`, `str_replace_editor` |
196
+ | File search and editing | `bash-file-search` | `read`, `bash`, `edit`, `write`, `grep`, `glob` |
197
+
198
+ Pi calls its native glob-based search tool `find`; the final experiment exposes that same
199
+ implementation under the conventional `glob` name without changing its execution or result format.
200
+
201
+ ### Programmatic tool calling / code mode
202
+
203
+ `createProgrammaticToolCallingCapability(cwd, options?)` (also exported as
204
+ `createCodeModeCapability`) registers one model-visible function tool:
205
+
206
+ ```text
207
+ run_code(code, timeout_ms?, max_output_chars?)
208
+ ```
209
+
210
+ The `pi-ptc` profile disables direct built-in-tool exposure and nests Pi's default `read`,
211
+ `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.
216
+
217
+ Pi's public extension API can enumerate another extension's tool metadata, but it does not
218
+ provide an execution handle for those tools. Consequently, this capability cannot safely
219
+ auto-capture arbitrary peer-extension tools. A future profile that needs custom nested tools
220
+ must pass their `ToolDefinition` objects explicitly through `options.nestedTools` (and,
221
+ when cwd-bound, `options.resolveNestedTools`). The current `pi-ptc` profile needs no such bridge
222
+ because its nested set consists of Pi's four public default tool definitions.
223
+
224
+ ### Reusable editing capabilities
225
+
226
+ Two standalone editing capabilities are available for profile composition. The comparison profiles
227
+ activate them independently so their effects can be evaluated without changing another profile:
228
+
229
+ - `createApplyPatchCapability(cwd)` registers `apply_patch`, which accepts a Codex patch envelope
230
+ in `{ "patch": "*** Begin Patch\n...\n*** End Patch" }` and supports add, update, delete,
231
+ and move hunks.
232
+ - `createStrReplaceEditorCapability(cwd, options?)` registers DSH-style
233
+ `str_replace_editor` with `view`, `create`, `str_replace`, and `insert` commands. Its public
234
+ paths are absolute and confined to `cwd`.
235
+
236
+ Both factories return the normal `HarnessCapability` contract, so another profile can pass them to
237
+ `runComposedHarness` or merge them with `composeHarnessCapabilities` without copying their tools.
238
+
239
+ ### SelfCompact context compaction
240
+
241
+ The `self-compact` harness loads the reusable capability implemented under
242
+ `context-management/self-compact`, inspired by
243
+ [Self-Compacting Language Model Agents](https://arxiv.org/abs/2606.23525).
244
+ Before every model call, the capability injects an ephemeral `<context_status>` block with
245
+ estimated tokens, context-window size, used percentage, and remaining tokens. It registers
246
+ one model tool:
247
+
248
+ ```text
249
+ compact_context(reason, preserve?)
250
+ ```
251
+
252
+ Before calling the tool, the model applies the paper-inspired rubric: the current work unit
253
+ must be closed, the continuation state must be safely summarizable, concrete progress must
254
+ exist since the last compaction, and the agent must not be stuck. Token pressure alone is
255
+ not enough. The tool finishes its own tool turn,
256
+ runs Pi's native compactor, and automatically starts a continuation turn from the compacted
257
+ state. The capability cancels only threshold-triggered automatic compaction. Pi's overflow
258
+ recovery and user-initiated `/compact` remain enabled. Keep Pi's native
259
+ `compaction.enabled` setting set to `true`; the capability suppresses the threshold through
260
+ the compaction lifecycle hook rather than disabling Pi's safety path.
190
261
 
191
262
  ### Long-horizon orchestration
192
263
 
193
- The `long-horizon` profile gives the parent session only `ask_user` and the explicitly
194
- loaded `pi-subagents` tools. It runs three namespaced harness-owned agents in order:
264
+ The `long-horizon-mea` profile activates a reusable orchestration capability. The capability
265
+ gives the parent session `ask_user` and the explicitly loaded `pi-subagents` tools, then
266
+ runs three namespaced package-owned agents in order:
195
267
 
196
268
  ```text
197
269
  long-horizon.manager → long-horizon.executor → long-horizon.auditor
@@ -203,7 +275,7 @@ receives the native `read`, `bash`, `grep`, `find`, and `ls` tools. No custom ch
203
275
  extension is loaded. The parent repeats the cycle until an Auditor independently reports
204
276
  complete, clean, contract-aligned evidence.
205
277
 
206
- Role definitions ship under `.pi/agents/long-horizon/`. At startup, the profile resolves
278
+ Role definitions ship under `.pi/agents/long-horizon/`. At startup, the capability resolves
207
279
  that catalog relative to the installed `@qwen-code/qwen-harness` package, independently of the
208
280
  task workspace. Future harnesses can add their own subdirectory and unique `package`
209
281
  namespace under `.pi/agents/`. The Long Horizon Supervisor also registers an
@@ -221,35 +293,63 @@ grouped by how it participates in the harness:
221
293
  long-horizon/ namespaced Manager, Executor, and Auditor definitions
222
294
  src/
223
295
  capabilities/
296
+ types.ts common contract for composable harness capabilities
224
297
  settings.ts loads Pi-owned settings and composes capability-owned settings
298
+ global/
299
+ session_affinity.ts capability enabled for every harness
300
+ orchestration/
301
+ mea/ prompt, Supervisor lifecycle, round tracking, and role contract
302
+ context-management/
303
+ self-compact/ model-visible status, compaction rubric, and continuation lifecycle
225
304
  tools/
226
305
  settings.ts composes tool-owned settings
227
306
  ask-user/ Pi tool adapter for the question workflow
307
+ context-management/ model-visible context management tools
228
308
  execution/ tools and their local settings parser
229
309
  filesystem/ model-visible workspace file tools
230
310
  media/ media tools and their local settings parser
311
+ programmatic-tool-calling/ run_code adapter and isolated JavaScript child runtime
231
312
  web/ web tools and their local settings parser
232
- infrastructure/
233
- settings.ts composes infrastructure-owned settings
313
+ utils/
314
+ capability_settings.ts composes settings consumed by reusable utilities
315
+ ask-user/ interactive question workflow, independent of tool schemas
316
+ filesystem/ document extraction and its settings parser
317
+ image-caption/ side-model perception and its settings parser
318
+ settings.ts shared parsing primitives
319
+ workspace.ts workspace confinement and common result formatting
320
+ clients/
321
+ settings.ts composes external-client settings
234
322
  media/ DashScope and Pexels clients plus their settings parser
235
- retry.ts provider-style HTTP retry shared by infrastructure clients
323
+ retry.ts provider-style HTTP retry shared by external clients
236
324
  web/ Routify clients and settings parser
237
- shared/
238
- capability_settings.ts composes shared capability settings
239
- ask-user/ interactive question workflow, independent of tool schemas
240
- filesystem/ document extraction and its settings parser
241
- image-caption/ side-model perception and its settings parser
242
- settings.ts shared parsing primitives
243
- workspace.ts workspace confinement and common result formatting
244
- harnesses/ each harness system prompt, tool selection, and Pi startup
325
+ runtime/
326
+ harness-capabilities.ts merges peer capability contributions
327
+ harness-main.ts starts isolated and composed harnesses
328
+ harnesses/ thin profile composition and Pi startup
245
329
  entrypoint.ts selects and starts one harness
246
330
  ```
247
331
 
332
+ Capability directories follow seven harness dimensions by primary responsibility:
333
+
334
+ - **E — Execution environment:** runtimes, sandboxes, microVMs, browser or computer-use environments, and OS permission boundaries.
335
+ - **T — Tool interface and protocol:** tool description, discovery, selection, invocation protocols, tool-augmented training, and session interfaces. The current `tools/` directory belongs here.
336
+ - **C — Context and memory management:** short-term context, session state, persistent memory, long-horizon context, and context-drift mitigation.
337
+ - **L — Lifecycle and orchestration:** agent loops, multi-agent control flow, state transitions, and end-to-end task pipelines. The current `orchestration/` directory belongs here.
338
+ - **O — Observability and operations:** traces, costs, failures, reliability signals, and operational control planes.
339
+ - **V — Verification and evaluation:** benchmarks, controlled execution, judgement, failure attribution, regression feedback, and deployment-time evaluation.
340
+ - **G — Governance and security:** permissions, lifecycle hooks, component hardening, constitutions, audit, and organizational policy.
341
+
342
+ New capabilities should live under the dimension that owns their primary behavior.
343
+ Reusable implementation belongs under `utils/`, and provider-specific network access
344
+ belongs under `utils/clients/`, instead of being presented as independently activatable
345
+ capabilities. Dimension directories are added when they gain a concrete capability rather
346
+ than being created empty in advance.
347
+
248
348
  `capabilities/tools/` contains the Pi-specific exposure layer: tool names, TypeBox
249
- parameter schemas, descriptions, and result contracts. `capabilities/infrastructure/`
250
- owns vendor-specific transport and retry behavior. `capabilities/shared/` contains
251
- reusable implementations that are not independently exposed to the model. For example,
252
- the `ask_user` tool delegates to the shared interactive-question workflow, while
349
+ parameter schemas, descriptions, and result contracts. `utils/clients/` owns
350
+ vendor-specific transport and retry behavior. The rest of `utils/` contains reusable
351
+ implementations that are not independently exposed to the model. For example, the
352
+ `ask_user` tool delegates to the reusable interactive-question workflow, while
253
353
  `read_file` composes document extraction, image captioning, and workspace confinement.
254
354
  Plain-text reads and filesystem search delegate their result limits, truncation, and
255
355
  continuation notices to Pi instead of defining harness-specific caps.
@@ -259,11 +359,19 @@ settings objects. Adding a capability changes its local parser and category comp
259
359
  not the root loader.
260
360
 
261
361
  Dependencies point inward: harnesses select `capabilities/tools`, tools may compose
262
- `shared` and `infrastructure`, and those lower layers do not import tool adapters. Both
362
+ `utils` and `utils/clients`, and those lower layers do not import tool adapters. Both
263
363
  `fetch_page` and `web_fetch` use Routify; `fetch_page` adds its own 8,000-character
264
364
  chunking and cache.
265
- Each file under `src/harnesses/` still owns a complete runnable profile: its system prompt,
266
- selected tool factories, inline-extension registration, and Pi startup.
365
+
366
+ Harness capabilities are peer contributions. They may append system-prompt sections,
367
+ declare tools and extension paths, register inline extensions, and prepare packaged
368
+ resources. A harness may still provide one base system prompt; normal capability prompts
369
+ append after it, and orchestration prompts append last. Long Horizon uses this final phase
370
+ so an existing harness prompt remains available as task and domain requirements while the
371
+ Supervisor protocol controls how those requirements are delegated. The standalone
372
+ `long-horizon-mea` harness is only a thin preset around `createLongHorizonCapability()`; another
373
+ harness can compose that capability with its own peer capabilities without copying the
374
+ Manager, Executor, Auditor, prompt, or runtime setup.
267
375
 
268
376
  ## Sessions and resume
269
377
 
@@ -273,7 +381,7 @@ Sessions use Pi's native storage under `~/.pi/agent/sessions/`, organized by wor
273
381
  npm run agent-arena -- --resume
274
382
  npm run code-arena-react -- --continue
275
383
  npm run code-arena-html -- --session /absolute/path/to/session.jsonl
276
- npm run long-horizon -- --resume
384
+ npm run long-horizon-mea -- --resume
277
385
  ```
278
386
 
279
387
  Headless modes use the same session behavior:
@@ -0,0 +1,182 @@
1
+ // src/capabilities/tools/programmatic-tool-calling/child-runtime.js
2
+ import readline from "node:readline";
3
+ import vm from "node:vm";
4
+ var input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
5
+ var initialized = false;
6
+ var finished = false;
7
+ var nextCallId = 1;
8
+ var settleToolCall;
9
+ var takeOutput;
10
+ function send(message) {
11
+ process.stdout.write(`${JSON.stringify(message)}
12
+ `);
13
+ }
14
+ function fail(error) {
15
+ if (finished) return;
16
+ finished = true;
17
+ const message = error instanceof Error ? error.message : String(error);
18
+ send({ type: "done", error: message });
19
+ input.close();
20
+ process.stdin.unref();
21
+ }
22
+ function createBridge() {
23
+ const bridge = (operation, first, second) => {
24
+ if (operation === "register") {
25
+ if (settleToolCall || takeOutput || typeof first !== "function" || typeof second !== "function") {
26
+ throw new Error("run_code bridge registration failed");
27
+ }
28
+ settleToolCall = first;
29
+ takeOutput = second;
30
+ return void 0;
31
+ }
32
+ if (typeof first !== "string") {
33
+ throw new TypeError("run_code bridge expects serialized input");
34
+ }
35
+ const request = JSON.parse(first);
36
+ const id = String(nextCallId++);
37
+ send({ type: "tool_call", id, name: request.name, args: request.args });
38
+ return id;
39
+ };
40
+ Object.setPrototypeOf(bridge, null);
41
+ return bridge;
42
+ }
43
+ function bootstrapGlobals() {
44
+ const runtimeGlobal = (
45
+ /** @type {any} */
46
+ globalThis
47
+ );
48
+ const bridge = runtimeGlobal.__runCodeBridge;
49
+ const parse = JSON.parse.bind(JSON);
50
+ const stringify = JSON.stringify.bind(JSON);
51
+ const metadata = parse(runtimeGlobal.__runCodeMetadata);
52
+ const emitted = [];
53
+ const pending = /* @__PURE__ */ new Map();
54
+ const settle = (id, value, error) => {
55
+ const entry = pending.get(id);
56
+ if (!entry) return;
57
+ pending.delete(id);
58
+ if (error !== void 0) entry.reject(new Error(error));
59
+ else entry.resolve(value === void 0 ? void 0 : parse(value));
60
+ };
61
+ const output = () => stringify(emitted);
62
+ bridge("register", settle, output);
63
+ const tools = /* @__PURE__ */ Object.create(null);
64
+ for (const item of metadata) {
65
+ Object.defineProperty(tools, item.name, {
66
+ enumerable: true,
67
+ value: (args) => new Promise((resolve, reject) => {
68
+ let request;
69
+ try {
70
+ request = stringify({ name: item.name, args });
71
+ } catch (error) {
72
+ reject(error);
73
+ return;
74
+ }
75
+ const id = bridge("call", request);
76
+ if (typeof id !== "string") {
77
+ reject(new Error("run_code bridge did not return a tool call id"));
78
+ return;
79
+ }
80
+ pending.set(id, { resolve, reject });
81
+ })
82
+ });
83
+ }
84
+ Object.freeze(tools);
85
+ const printable = (value) => {
86
+ if (typeof value === "string") return value;
87
+ if (value === void 0) return "undefined";
88
+ try {
89
+ const encoded = stringify(value);
90
+ return encoded === void 0 ? String(value) : encoded;
91
+ } catch {
92
+ return String(value);
93
+ }
94
+ };
95
+ const text = (value) => emitted.push({ type: "text", text: printable(value) });
96
+ const image = (value) => {
97
+ if (!value || typeof value !== "object") {
98
+ throw new TypeError("image() expects an image content object");
99
+ }
100
+ const item = (
101
+ /** @type {Record<string, unknown>} */
102
+ value
103
+ );
104
+ if (typeof item.data !== "string" || typeof item.mimeType !== "string") {
105
+ throw new TypeError("image() expects string data and mimeType fields");
106
+ }
107
+ emitted.push({ type: "image", data: item.data, mimeType: item.mimeType });
108
+ };
109
+ Object.defineProperties(runtimeGlobal, {
110
+ tools: { value: tools, enumerable: true },
111
+ ALL_TOOLS: {
112
+ value: Object.freeze(metadata.map((item) => Object.freeze({ ...item }))),
113
+ enumerable: true
114
+ },
115
+ text: { value: text, enumerable: true },
116
+ image: { value: image, enumerable: true },
117
+ console: { value: void 0 }
118
+ });
119
+ delete runtimeGlobal.__runCodeBridge;
120
+ delete runtimeGlobal.__runCodeMetadata;
121
+ }
122
+ function installGlobals(context, metadata) {
123
+ context.__runCodeBridge = createBridge();
124
+ context.__runCodeMetadata = JSON.stringify(metadata);
125
+ const bootstrap = new vm.Script(`(${bootstrapGlobals.toString()})()`);
126
+ bootstrap.runInContext(context);
127
+ if (typeof settleToolCall !== "function" || typeof takeOutput !== "function") {
128
+ throw new Error("run_code failed to initialize its tool bridge");
129
+ }
130
+ }
131
+ function handleToolResponse(message) {
132
+ if (typeof settleToolCall !== "function") return;
133
+ if (message.type === "tool_result") {
134
+ const value = message.value === void 0 ? void 0 : JSON.stringify(message.value);
135
+ settleToolCall(message.id, value, void 0);
136
+ } else {
137
+ settleToolCall(message.id, void 0, message.error || "Nested tool call failed");
138
+ }
139
+ }
140
+ async function start(message) {
141
+ if (initialized) throw new Error("run_code child received more than one init message");
142
+ initialized = true;
143
+ const context = vm.createContext(/* @__PURE__ */ Object.create(null), {
144
+ name: "pi-run-code",
145
+ codeGeneration: { strings: false, wasm: false }
146
+ });
147
+ installGlobals(context, message.tools);
148
+ const wrapped = `"use strict"; (async () => {
149
+ ${message.code}
150
+ })()`;
151
+ const script = new vm.Script(wrapped, { filename: "run_code.js" });
152
+ await script.runInContext(context, { timeout: message.syncTimeoutMs });
153
+ if (finished) return;
154
+ finished = true;
155
+ if (typeof takeOutput !== "function") {
156
+ throw new Error("run_code output bridge is unavailable");
157
+ }
158
+ const output = takeOutput();
159
+ send({ type: "done", content: JSON.parse(output) });
160
+ input.close();
161
+ process.stdin.unref();
162
+ }
163
+ input.on("line", (line) => {
164
+ let message;
165
+ try {
166
+ message = JSON.parse(line);
167
+ } catch (error) {
168
+ fail(new Error(`Invalid parent message: ${error instanceof Error ? error.message : String(error)}`));
169
+ return;
170
+ }
171
+ if (message.type === "init") {
172
+ void start(message).catch(fail);
173
+ return;
174
+ }
175
+ if (message.type === "tool_result" || message.type === "tool_error") {
176
+ handleToolResponse(message);
177
+ }
178
+ });
179
+ input.on("close", () => {
180
+ if (!finished) fail(new Error("run_code parent disconnected"));
181
+ });
182
+ //# sourceMappingURL=child-runtime.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 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}\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;AAEjB,IAAI;AAEJ,IAAI;AAGJ,SAAS,KAAK,SAAS;AACtB,UAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,OAAO,CAAC;AAAA,CAAI;AACpD;AAGA,SAAS,KAAK,OAAO;AACpB,MAAI,SAAU;AACd,aAAW;AACX,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,OAAK,EAAE,MAAM,QAAQ,OAAO,QAAQ,CAAC;AAC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