@qwen-code/qwen-harness 0.1.4 → 0.1.6
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 +13 -4
- package/dist/child-runtime.js +89 -7
- package/dist/child-runtime.js.map +3 -3
- package/dist/entrypoint.js +120 -20
- package/dist/entrypoint.js.map +4 -4
- package/package.json +6 -5
package/README.md
CHANGED
|
@@ -15,6 +15,9 @@ qwen-harness --help
|
|
|
15
15
|
|
|
16
16
|
For repository development, install dependencies with `npm install --ignore-scripts`.
|
|
17
17
|
|
|
18
|
+
Pi dependencies are pinned to 0.85.0. The explicit `@earendil-works/pi-server`
|
|
19
|
+
dependency supplies a runtime import omitted from Pi 0.85.0's package dependencies.
|
|
20
|
+
|
|
18
21
|
## Development
|
|
19
22
|
|
|
20
23
|
Use one development command for every harness. Omitting `--harness` runs the `pi` profile:
|
|
@@ -219,10 +222,16 @@ run_code(code, timeout_ms?, max_output_chars?)
|
|
|
219
222
|
|
|
220
223
|
The `pi-ptc` profile disables direct built-in-tool exposure and nests Pi's default `read`,
|
|
221
224
|
`bash`, `edit`, and `write` definitions under the JavaScript `tools` object.
|
|
222
|
-
Scripts emit selected results with `text()` or forward an image block
|
|
223
|
-
call runs in a fresh child Node process with an empty
|
|
224
|
-
limit, and Node's permission model denying direct filesystem,
|
|
225
|
-
access.
|
|
225
|
+
Scripts emit selected results with `text()` or forward either an image block or a nested
|
|
226
|
+
tool result with `image()`. Each call runs in a fresh child Node process with an empty
|
|
227
|
+
environment, a memory limit, and Node's permission model denying direct filesystem,
|
|
228
|
+
child-process, and worker access. The runtime stops synchronous JavaScript loops and scripts
|
|
229
|
+
that make no progress, but it does not impose a default wall-clock deadline while a nested
|
|
230
|
+
tool or a bounded `setTimeout()` is active. Configure duration on the nested tool doing the
|
|
231
|
+
work (for example, `tools.bash({ command, timeout: 300 })`). Use top-level `timeout_ms` only
|
|
232
|
+
when the entire orchestration needs an additional independent hard deadline. When embedding
|
|
233
|
+
shell parameter expansion in a JavaScript template literal, escape its dollar sign (for
|
|
234
|
+
example, `\${name}`). No runtime dependency or copied Codex source is added.
|
|
226
235
|
|
|
227
236
|
Pi's public extension API can enumerate another extension's tool metadata, but it does not
|
|
228
237
|
provide an execution handle for those tools. Consequently, this capability cannot safely
|
package/dist/child-runtime.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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
|
-
|
|
105
|
-
|
|
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
|
-
|
|
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}\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;
|
|
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,KA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AAC;AACjE,QAAM,OAAO,aAAa,SAAS,EAAE,SAAS,QAAQ,cAAc,CAAC;AAErE,MAAI,SAAU;AACd,aAAW;AACX,kBAAgB;AAChB,MAAI,OAAO,eAAe,YAAY;AACrC,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACxD;AACA,QAAM,SAAS,WAAW;AAC1B,OAAK,EAAE,MAAM,QAAQ,SAAS,KAAK,MAAM,MAAM,EAAE,CAAC;AAClD,QAAM,MAAM;AACZ,UAAQ,MAAM,MAAM;AACrB;AAEA,MAAM,GAAG,QAAQ,CAAC,SAAS;AAE1B,MAAI;AACJ,MAAI;AACH,cAAU,KAAK,MAAM,IAAI;AAAA,EAC1B,SAAS,OAAO;AACf,SAAK,IAAI,MAAM,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE,CAAC;AACnG;AAAA,EACD;AACA,MAAI,QAAQ,SAAS,QAAQ;AAC5B,SAAK,MAAM,OAAO,EAAE,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": ["request", "id"]
|
|
7
7
|
}
|
package/dist/entrypoint.js
CHANGED
|
@@ -1976,14 +1976,51 @@ function isolateHarnessArgs(args, systemPrompt, options = {}) {
|
|
|
1976
1976
|
];
|
|
1977
1977
|
}
|
|
1978
1978
|
|
|
1979
|
+
// src/runtime/headless-outcome.ts
|
|
1980
|
+
function createHeadlessOutcomeTracker() {
|
|
1981
|
+
let failure2;
|
|
1982
|
+
return {
|
|
1983
|
+
getFailure: () => failure2,
|
|
1984
|
+
extension: {
|
|
1985
|
+
name: "headless-outcome",
|
|
1986
|
+
hidden: true,
|
|
1987
|
+
factory(pi) {
|
|
1988
|
+
pi.on("session_start", () => {
|
|
1989
|
+
failure2 = void 0;
|
|
1990
|
+
});
|
|
1991
|
+
pi.on("message_end", (event, context) => {
|
|
1992
|
+
if (context.mode !== "json" && context.mode !== "print") return;
|
|
1993
|
+
const message = event.message;
|
|
1994
|
+
if (message.role !== "assistant") return;
|
|
1995
|
+
failure2 = void 0;
|
|
1996
|
+
if (message.stopReason === "error") {
|
|
1997
|
+
failure2 = /\b429\b|rate[\s_-]?limit|too many requests/iu.test(message.errorMessage ?? "") ? "ApiRateLimitError: API rate limit exhausted (HTTP 429)." : "ApiError: final model request failed; inspect the recorded session.";
|
|
1998
|
+
} else if (message.stopReason === "aborted") {
|
|
1999
|
+
failure2 = "AgentAbortedError: final model request was aborted.";
|
|
2000
|
+
} else if (message.stopReason === "length") {
|
|
2001
|
+
failure2 = "AgentOutputLimitError: final response reached the output token limit.";
|
|
2002
|
+
}
|
|
2003
|
+
});
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
};
|
|
2007
|
+
}
|
|
2008
|
+
|
|
1979
2009
|
// src/runtime/harness-main.ts
|
|
1980
2010
|
function createHarnessExtensionFactories(extensionFactories = []) {
|
|
1981
2011
|
return [createSessionAffinityCapability(), ...extensionFactories];
|
|
1982
2012
|
}
|
|
1983
2013
|
async function runHarnessMain(args, extensionFactories = []) {
|
|
2014
|
+
const outcome = createHeadlessOutcomeTracker();
|
|
1984
2015
|
await piMain([...args], {
|
|
1985
|
-
extensionFactories: createHarnessExtensionFactories(extensionFactories)
|
|
2016
|
+
extensionFactories: createHarnessExtensionFactories([outcome.extension, ...extensionFactories])
|
|
1986
2017
|
});
|
|
2018
|
+
const failure2 = outcome.getFailure();
|
|
2019
|
+
if (failure2) {
|
|
2020
|
+
process.stderr.write(`${failure2}
|
|
2021
|
+
`);
|
|
2022
|
+
process.exitCode = 1;
|
|
2023
|
+
}
|
|
1987
2024
|
}
|
|
1988
2025
|
async function runComposedHarness(args, options = {}) {
|
|
1989
2026
|
const capabilities = composeHarnessCapabilities(options.capabilities ?? []);
|
|
@@ -3597,7 +3634,8 @@ import {
|
|
|
3597
3634
|
import { Type as Type21 } from "typebox";
|
|
3598
3635
|
import { Value } from "typebox/value";
|
|
3599
3636
|
var RUN_CODE_TOOL_NAME = "run_code";
|
|
3600
|
-
var
|
|
3637
|
+
var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
|
|
3638
|
+
var DEFAULT_SYNC_TIMEOUT_MS = 5e3;
|
|
3601
3639
|
var MAX_TIMEOUT_MS = 6e5;
|
|
3602
3640
|
var DEFAULT_MAX_OUTPUT_CHARS = 5e4;
|
|
3603
3641
|
var MAX_OUTPUT_CHARS = 2e5;
|
|
@@ -3679,7 +3717,10 @@ function runCodeDescription(tools) {
|
|
|
3679
3717
|
"The code runs in a fresh, short-lived child process. Node globals, filesystem APIs, network APIs, and console are not exposed to the script; use nested tools for side effects.",
|
|
3680
3718
|
"All nested tools are async functions on the global `tools` object. Always await calls whose result or completion matters.",
|
|
3681
3719
|
"Use `text(value)` to emit model-visible text. Non-string values are JSON-encoded when possible.",
|
|
3682
|
-
"Use `image(value)` to forward an image content block
|
|
3720
|
+
"Use `image(value)` to forward either an image content block or a nested tool result containing images.",
|
|
3721
|
+
"Use `setTimeout` and `clearTimeout` for bounded waits; timer delays are limited to 10 minutes.",
|
|
3722
|
+
"Set timeouts on the nested tool that performs the work. The top-level `timeout_ms` is only an optional hard deadline for the entire orchestration and normally should be omitted.",
|
|
3723
|
+
"When a JavaScript template literal contains shell parameter expansion such as `${name}`, escape the dollar sign as `\\${name}` so JavaScript does not treat it as interpolation.",
|
|
3683
3724
|
"`ALL_TOOLS` contains `{ name, description }` metadata. Unawaited work is discarded when the script completes.",
|
|
3684
3725
|
"The `code` argument must be raw JavaScript source without Markdown fences.",
|
|
3685
3726
|
"",
|
|
@@ -3688,8 +3729,11 @@ function runCodeDescription(tools) {
|
|
|
3688
3729
|
"declare const tools: Record<string, (args: unknown) => Promise<string | NestedToolResult>>;",
|
|
3689
3730
|
"declare const ALL_TOOLS: ReadonlyArray<{ name: string; description: string }>;",
|
|
3690
3731
|
"declare function text(value: unknown): void;",
|
|
3691
|
-
'
|
|
3692
|
-
|
|
3732
|
+
'type ImageContent = { type?: "image"; data: string; mimeType: string };',
|
|
3733
|
+
"declare function image(value: ImageContent | NestedToolResult): void;",
|
|
3734
|
+
"declare function setTimeout(callback: (...args: unknown[]) => void, delayMs?: number, ...args: unknown[]): string;",
|
|
3735
|
+
"declare function clearTimeout(handle: string): void;",
|
|
3736
|
+
'type NestedToolResult = { content: Array<{ type: "text"; text: string } | ImageContent> };',
|
|
3693
3737
|
"```",
|
|
3694
3738
|
"",
|
|
3695
3739
|
...tools.map(nestedToolDescription)
|
|
@@ -3704,8 +3748,7 @@ var runCodeSchema = Type21.Object({
|
|
|
3704
3748
|
timeout_ms: Type21.Optional(Type21.Integer({
|
|
3705
3749
|
minimum: 100,
|
|
3706
3750
|
maximum: MAX_TIMEOUT_MS,
|
|
3707
|
-
|
|
3708
|
-
description: "Wall-clock limit for the complete script, including nested tool calls."
|
|
3751
|
+
description: "Optional hard wall-clock deadline for the complete orchestration. This is independent of nested tool timeouts; normally omit it and set timeout on the nested tool instead."
|
|
3709
3752
|
})),
|
|
3710
3753
|
max_output_chars: Type21.Optional(Type21.Integer({
|
|
3711
3754
|
minimum: 100,
|
|
@@ -3787,15 +3830,17 @@ function emittedContent(value, maxOutputChars) {
|
|
|
3787
3830
|
}
|
|
3788
3831
|
return content.length ? content : [{ type: "text", text: "Code completed without emitted output." }];
|
|
3789
3832
|
}
|
|
3790
|
-
async function executeRunCode(toolCallId, params, signal, context, tools) {
|
|
3833
|
+
async function executeRunCode(toolCallId, params, signal, context, tools, limits) {
|
|
3791
3834
|
assertNestedTools(tools);
|
|
3792
3835
|
const toolsByName = new Map(tools.map((tool) => [normalizedToolName(tool.name), tool]));
|
|
3793
|
-
const
|
|
3836
|
+
const explicitTimeoutMs = params.timeout_ms;
|
|
3794
3837
|
const maxOutputChars = params.max_output_chars ?? DEFAULT_MAX_OUTPUT_CHARS;
|
|
3795
3838
|
const controller = new AbortController();
|
|
3796
3839
|
const calls = [];
|
|
3797
3840
|
let settled = false;
|
|
3798
3841
|
let stderr = "";
|
|
3842
|
+
let activeTimerCount = 0;
|
|
3843
|
+
const activeCalls = /* @__PURE__ */ new Map();
|
|
3799
3844
|
const child = spawn2(process.execPath, [
|
|
3800
3845
|
"--permission",
|
|
3801
3846
|
"--no-warnings",
|
|
@@ -3817,9 +3862,18 @@ async function executeRunCode(toolCallId, params, signal, context, tools) {
|
|
|
3817
3862
|
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
3818
3863
|
try {
|
|
3819
3864
|
return await new Promise((resolve, reject) => {
|
|
3865
|
+
let idleTimer;
|
|
3866
|
+
let wallTimer;
|
|
3867
|
+
const clearWatchdogs = () => {
|
|
3868
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
3869
|
+
if (wallTimer) clearTimeout(wallTimer);
|
|
3870
|
+
idleTimer = void 0;
|
|
3871
|
+
wallTimer = void 0;
|
|
3872
|
+
};
|
|
3820
3873
|
const finish = (outcome) => {
|
|
3821
3874
|
if (settled) return;
|
|
3822
3875
|
settled = true;
|
|
3876
|
+
clearWatchdogs();
|
|
3823
3877
|
if (outcome.error) {
|
|
3824
3878
|
reject(new Error(outcome.error));
|
|
3825
3879
|
return;
|
|
@@ -3833,12 +3887,40 @@ async function executeRunCode(toolCallId, params, signal, context, tools) {
|
|
|
3833
3887
|
reject(error);
|
|
3834
3888
|
}
|
|
3835
3889
|
};
|
|
3836
|
-
const
|
|
3837
|
-
|
|
3838
|
-
|
|
3839
|
-
|
|
3840
|
-
|
|
3841
|
-
|
|
3890
|
+
const activeCallSummary = () => {
|
|
3891
|
+
if (!activeCalls.size) return "none";
|
|
3892
|
+
return [...activeCalls.values()].map((call) => `${call.name} (${Date.now() - call.startedAt} ms)`).join(", ");
|
|
3893
|
+
};
|
|
3894
|
+
const armIdleWatchdog = () => {
|
|
3895
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
3896
|
+
idleTimer = void 0;
|
|
3897
|
+
if (settled || activeCalls.size || activeTimerCount) return;
|
|
3898
|
+
idleTimer = setTimeout(() => {
|
|
3899
|
+
const message = [
|
|
3900
|
+
`run_code made no progress for ${limits.idleTimeoutMs} ms with no active nested tools or timers.`,
|
|
3901
|
+
"This usually means the script is waiting on an unresolved promise or running JavaScript outside a nested tool."
|
|
3902
|
+
].join(" ");
|
|
3903
|
+
finish({ error: message });
|
|
3904
|
+
controller.abort(new Error(message));
|
|
3905
|
+
child.kill();
|
|
3906
|
+
}, limits.idleTimeoutMs);
|
|
3907
|
+
idleTimer.unref();
|
|
3908
|
+
};
|
|
3909
|
+
if (explicitTimeoutMs !== void 0) {
|
|
3910
|
+
wallTimer = setTimeout(() => {
|
|
3911
|
+
const message = [
|
|
3912
|
+
`run_code explicit outer wall-clock timeout expired after ${explicitTimeoutMs} ms.`,
|
|
3913
|
+
"This deadline is independent of nested tool timeouts.",
|
|
3914
|
+
`Active nested calls: ${activeCallSummary()}.`,
|
|
3915
|
+
"Increase top-level timeout_ms, or omit it and set timeout on the nested tool instead."
|
|
3916
|
+
].join(" ");
|
|
3917
|
+
finish({ error: message });
|
|
3918
|
+
controller.abort(new Error(message));
|
|
3919
|
+
child.kill();
|
|
3920
|
+
}, explicitTimeoutMs);
|
|
3921
|
+
wallTimer.unref();
|
|
3922
|
+
}
|
|
3923
|
+
armIdleWatchdog();
|
|
3842
3924
|
const rejectAborted = () => {
|
|
3843
3925
|
child.kill();
|
|
3844
3926
|
finish({ error: "Operation aborted" });
|
|
@@ -3851,7 +3933,6 @@ async function executeRunCode(toolCallId, params, signal, context, tools) {
|
|
|
3851
3933
|
});
|
|
3852
3934
|
child.on("error", (error) => finish({ error: `Failed to start run_code: ${error.message}` }));
|
|
3853
3935
|
child.on("exit", (code, exitSignal) => {
|
|
3854
|
-
clearTimeout(timer);
|
|
3855
3936
|
if (settled) return;
|
|
3856
3937
|
const detail = stderr.trim() ? `: ${stderr.trim()}` : "";
|
|
3857
3938
|
finish({
|
|
@@ -3867,18 +3948,29 @@ async function executeRunCode(toolCallId, params, signal, context, tools) {
|
|
|
3867
3948
|
return;
|
|
3868
3949
|
}
|
|
3869
3950
|
if (message.type === "done") {
|
|
3870
|
-
clearTimeout(timer);
|
|
3871
3951
|
finish(message);
|
|
3872
3952
|
return;
|
|
3873
3953
|
}
|
|
3954
|
+
if (message.type === "timer_state") {
|
|
3955
|
+
if (!Number.isSafeInteger(message.active) || message.active < 0) {
|
|
3956
|
+
finish({ error: "run_code child emitted an invalid timer state" });
|
|
3957
|
+
return;
|
|
3958
|
+
}
|
|
3959
|
+
activeTimerCount = message.active;
|
|
3960
|
+
armIdleWatchdog();
|
|
3961
|
+
return;
|
|
3962
|
+
}
|
|
3874
3963
|
if (message.type !== "tool_call") return;
|
|
3875
3964
|
const startedAt = Date.now();
|
|
3876
3965
|
const tool = toolsByName.get(message.name);
|
|
3877
3966
|
if (!tool) {
|
|
3878
3967
|
calls.push({ name: message.name, durationMs: 0, status: "error" });
|
|
3879
3968
|
post({ type: "tool_error", id: message.id, error: `Unknown nested tool: ${message.name}` });
|
|
3969
|
+
armIdleWatchdog();
|
|
3880
3970
|
return;
|
|
3881
3971
|
}
|
|
3972
|
+
activeCalls.set(message.id, { name: tool.name, startedAt });
|
|
3973
|
+
armIdleWatchdog();
|
|
3882
3974
|
void (async () => {
|
|
3883
3975
|
try {
|
|
3884
3976
|
const args = validatedArguments(tool, message.args);
|
|
@@ -3898,13 +3990,16 @@ async function executeRunCode(toolCallId, params, signal, context, tools) {
|
|
|
3898
3990
|
id: message.id,
|
|
3899
3991
|
error: error instanceof Error ? error.message : String(error)
|
|
3900
3992
|
});
|
|
3993
|
+
} finally {
|
|
3994
|
+
activeCalls.delete(message.id);
|
|
3995
|
+
armIdleWatchdog();
|
|
3901
3996
|
}
|
|
3902
3997
|
})();
|
|
3903
3998
|
});
|
|
3904
3999
|
post({
|
|
3905
4000
|
type: "init",
|
|
3906
4001
|
code: params.code,
|
|
3907
|
-
syncTimeoutMs:
|
|
4002
|
+
syncTimeoutMs: limits.syncTimeoutMs,
|
|
3908
4003
|
tools: tools.map((tool) => ({
|
|
3909
4004
|
name: normalizedToolName(tool.name),
|
|
3910
4005
|
description: tool.description
|
|
@@ -3928,13 +4023,18 @@ function createRunCodeTool(options) {
|
|
|
3928
4023
|
promptSnippet: "Orchestrate all Pi tools through JavaScript",
|
|
3929
4024
|
promptGuidelines: [
|
|
3930
4025
|
"Use run_code for every tool operation; direct nested tools are intentionally unavailable.",
|
|
3931
|
-
"Compose and filter nested tool results in JavaScript, then emit only the information needed with text() or image()."
|
|
4026
|
+
"Compose and filter nested tool results in JavaScript, then emit only the information needed with text() or image().",
|
|
4027
|
+
"Set timeout on the nested tool that performs the work; normally omit run_code timeout_ms because it is only an independent hard deadline for the whole orchestration.",
|
|
4028
|
+
"Escape shell parameter expansion inside JavaScript template literals, for example write \\${name} instead of ${name}."
|
|
3932
4029
|
],
|
|
3933
4030
|
parameters: runCodeSchema,
|
|
3934
4031
|
executionMode: "sequential",
|
|
3935
4032
|
async execute(toolCallId, params, signal, _onUpdate, context) {
|
|
3936
4033
|
const tools = options.resolveNestedTools?.(context) ?? options.nestedTools;
|
|
3937
|
-
return executeRunCode(toolCallId, params, signal, context, tools
|
|
4034
|
+
return executeRunCode(toolCallId, params, signal, context, tools, {
|
|
4035
|
+
idleTimeoutMs: options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,
|
|
4036
|
+
syncTimeoutMs: options.syncTimeoutMs ?? DEFAULT_SYNC_TIMEOUT_MS
|
|
4037
|
+
});
|
|
3938
4038
|
}
|
|
3939
4039
|
});
|
|
3940
4040
|
}
|