@howaboua/pi-durable-code 0.9.1 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/activation.js +4766 -0
- package/dist/code/src/activation.d.ts +5 -0
- package/dist/code/src/history.d.ts +1 -1
- package/dist/execution/src/custom-commands.d.ts +1 -1
- package/dist/execution/src/tool-contract.d.ts +2 -2
- package/dist/index.js +17 -10
- package/package.json +30 -6
|
@@ -0,0 +1,4766 @@
|
|
|
1
|
+
// packages/code/src/activation.ts
|
|
2
|
+
import {
|
|
3
|
+
defineCapability,
|
|
4
|
+
isCapabilityObject,
|
|
5
|
+
nodeExecutionCapability,
|
|
6
|
+
stateCapability
|
|
7
|
+
} from "@howaboua/pi-durable-components";
|
|
8
|
+
import { Type as Type4 } from "typebox";
|
|
9
|
+
import { Check } from "typebox/value";
|
|
10
|
+
|
|
11
|
+
// packages/code/src/index.ts
|
|
12
|
+
import {
|
|
13
|
+
defineTool as defineTool3,
|
|
14
|
+
section
|
|
15
|
+
} from "@earendil-works/pi-durable";
|
|
16
|
+
import { Type as Type3 } from "typebox";
|
|
17
|
+
|
|
18
|
+
// packages/execution/src/exec-source.ts
|
|
19
|
+
var MAX_CODE_MODE_OUTPUT_TOKENS = 1e5;
|
|
20
|
+
var TRUNCATED_OUTPUT_NOTICE = "[Output truncated; later results may be omitted. Narrow reads or fetch missing help separately. Do not rerun side effects for output.]";
|
|
21
|
+
function adaptiveWaitMs(requestedMs, previousIncompleteWaits) {
|
|
22
|
+
const multiplier = 2 ** previousIncompleteWaits;
|
|
23
|
+
const adaptive = Math.min(1800000, Math.max(5000 * multiplier, requestedMs * multiplier * 2));
|
|
24
|
+
return Math.max(requestedMs, adaptive);
|
|
25
|
+
}
|
|
26
|
+
var CODE_MODE_EXEC_GRAMMAR = String.raw`
|
|
27
|
+
start: pragma_source | plain_source
|
|
28
|
+
pragma_source: PRAGMA_LINE NEWLINE SOURCE
|
|
29
|
+
plain_source: SOURCE
|
|
30
|
+
|
|
31
|
+
PRAGMA_LINE: /[ \t]*\/\/ @exec:[^\r\n]*/
|
|
32
|
+
NEWLINE: /\r?\n/
|
|
33
|
+
SOURCE: /[\s\S]+/
|
|
34
|
+
`;
|
|
35
|
+
var CODE_MODE_EXEC_CONSTRAINED_SAMPLING = {
|
|
36
|
+
type: "grammar",
|
|
37
|
+
variants: { openai_lark: CODE_MODE_EXEC_GRAMMAR }
|
|
38
|
+
};
|
|
39
|
+
function parseExecSource(source, capabilities = {}) {
|
|
40
|
+
if (!source.trim())
|
|
41
|
+
throw new Error("exec requires non-empty JavaScript source");
|
|
42
|
+
const [first, ...rest] = source.split(`
|
|
43
|
+
`);
|
|
44
|
+
const trimmed = first?.trimStart() ?? "";
|
|
45
|
+
if (!trimmed.startsWith("// @exec:"))
|
|
46
|
+
return {
|
|
47
|
+
code: source,
|
|
48
|
+
yieldTimeMs: null,
|
|
49
|
+
maxOutputTokens: null,
|
|
50
|
+
isolated: false
|
|
51
|
+
};
|
|
52
|
+
if (rest.join(`
|
|
53
|
+
`).trim() === "")
|
|
54
|
+
throw new Error("exec pragma must be followed by JavaScript source");
|
|
55
|
+
const options = JSON.parse(trimmed.slice("// @exec:".length).trim());
|
|
56
|
+
if (options === null || typeof options !== "object" || Array.isArray(options))
|
|
57
|
+
throw new Error("exec pragma must be a JSON object");
|
|
58
|
+
for (const key of Object.keys(options))
|
|
59
|
+
if (key !== "yield_time_ms" && key !== "max_output_tokens" && !(key === "isolated" && capabilities.allowIsolated))
|
|
60
|
+
throw new Error(`Unsupported exec pragma field: ${key}`);
|
|
61
|
+
if ("isolated" in options && typeof options.isolated !== "boolean")
|
|
62
|
+
throw new Error("isolated must be a boolean");
|
|
63
|
+
return {
|
|
64
|
+
isolated: "isolated" in options && options.isolated === true,
|
|
65
|
+
code: rest.join(`
|
|
66
|
+
`),
|
|
67
|
+
yieldTimeMs: parseInteger("yield_time_ms" in options ? options.yield_time_ms : undefined, "yield_time_ms"),
|
|
68
|
+
maxOutputTokens: parseInteger("max_output_tokens" in options ? options.max_output_tokens : undefined, "max_output_tokens", 1, MAX_CODE_MODE_OUTPUT_TOKENS)
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
function parseInteger(value, name, minimum = 0, maximum = Number.MAX_SAFE_INTEGER) {
|
|
72
|
+
if (value === undefined)
|
|
73
|
+
return null;
|
|
74
|
+
if (!Number.isSafeInteger(value) || Number(value) < minimum || Number(value) > maximum)
|
|
75
|
+
throw new Error(`${name} must be a safe integer from ${minimum} to ${maximum}`);
|
|
76
|
+
return Number(value);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// packages/execution/src/cells.ts
|
|
80
|
+
import { copyJson as copyJson10 } from "@earendil-works/chord";
|
|
81
|
+
import { withCancel } from "@earendil-works/chord/context";
|
|
82
|
+
import {
|
|
83
|
+
defineExtension
|
|
84
|
+
} from "@earendil-works/pi-durable";
|
|
85
|
+
|
|
86
|
+
// packages/execution/src/cell-observation.ts
|
|
87
|
+
import {
|
|
88
|
+
defineDocFamily
|
|
89
|
+
} from "@earendil-works/pi-durable";
|
|
90
|
+
|
|
91
|
+
// packages/execution/src/forwarding.ts
|
|
92
|
+
import { copyJson as copyJson2 } from "@earendil-works/chord";
|
|
93
|
+
import {
|
|
94
|
+
LiveDoc,
|
|
95
|
+
NestedCallDoc,
|
|
96
|
+
ToolTask
|
|
97
|
+
} from "@earendil-works/pi-durable";
|
|
98
|
+
|
|
99
|
+
// packages/execution/src/invocation-state.ts
|
|
100
|
+
import {
|
|
101
|
+
copyJson
|
|
102
|
+
} from "@earendil-works/chord";
|
|
103
|
+
import {
|
|
104
|
+
defineDoc
|
|
105
|
+
} from "@earendil-works/pi-durable";
|
|
106
|
+
var InvocationDoc = defineDoc({
|
|
107
|
+
kind: "howaboua.execution.invocation",
|
|
108
|
+
version: 2,
|
|
109
|
+
scope: "task",
|
|
110
|
+
checkpointWhen: () => false,
|
|
111
|
+
initial: () => ({ result: {} }),
|
|
112
|
+
migrate: (value) => ({
|
|
113
|
+
...value,
|
|
114
|
+
result: storeResult(readStoredResult(value["result"]))
|
|
115
|
+
})
|
|
116
|
+
});
|
|
117
|
+
function readStoredResult(result) {
|
|
118
|
+
if (result.output !== undefined || !("content" in result))
|
|
119
|
+
return result;
|
|
120
|
+
const { content, ...rest } = result;
|
|
121
|
+
return {
|
|
122
|
+
...rest,
|
|
123
|
+
output: content
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
function storeResult(result) {
|
|
127
|
+
return copyJson(result, { omitUndefinedProperties: true });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// packages/execution/src/output.ts
|
|
131
|
+
function utf8ByteLength(text) {
|
|
132
|
+
return new TextEncoder().encode(text).length;
|
|
133
|
+
}
|
|
134
|
+
var NEWLINE = 10;
|
|
135
|
+
var INVALID_OUTPUT = /[\x00-\x08\x0b-\x1f\ufff9-\ufffb]/g;
|
|
136
|
+
var encoder = new TextEncoder;
|
|
137
|
+
var decoder = new TextDecoder("utf-8", { ignoreBOM: true });
|
|
138
|
+
function sanitizeOutput(text) {
|
|
139
|
+
return text.replace(INVALID_OUTPUT, "");
|
|
140
|
+
}
|
|
141
|
+
function boundOutput(text, limits) {
|
|
142
|
+
const bytes = encoder.encode(text);
|
|
143
|
+
const [from, to] = limits.retain === "head" ? headRange(bytes, limits) : tailRange(bytes, limits);
|
|
144
|
+
const kept = bytes.subarray(from, to);
|
|
145
|
+
return {
|
|
146
|
+
text: kept.length === bytes.length ? text : decoder.decode(kept),
|
|
147
|
+
bytes: kept.length,
|
|
148
|
+
droppedBytes: bytes.length - kept.length,
|
|
149
|
+
droppedLines: lineCount(bytes) - lineCount(kept)
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function headRange(bytes, limits) {
|
|
153
|
+
if (limits.maxLines === 0 || limits.maxBytes === 0)
|
|
154
|
+
return [0, 0];
|
|
155
|
+
let end = bytes.length;
|
|
156
|
+
let lines = 0;
|
|
157
|
+
for (let index = bytes.indexOf(NEWLINE);index !== -1; index = bytes.indexOf(NEWLINE, index + 1)) {
|
|
158
|
+
if (++lines === limits.maxLines) {
|
|
159
|
+
end = index + 1;
|
|
160
|
+
break;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (end > limits.maxBytes) {
|
|
164
|
+
const newline = bytes.lastIndexOf(NEWLINE, limits.maxBytes - 1);
|
|
165
|
+
end = newline === -1 ? characterEnd(bytes, limits.maxBytes) : newline + 1;
|
|
166
|
+
}
|
|
167
|
+
return [0, end];
|
|
168
|
+
}
|
|
169
|
+
function tailRange(bytes, limits) {
|
|
170
|
+
if (limits.maxLines === 0 || limits.maxBytes === 0)
|
|
171
|
+
return [bytes.length, bytes.length];
|
|
172
|
+
const last = bytes[bytes.length - 1] === NEWLINE ? bytes.length - 2 : bytes.length - 1;
|
|
173
|
+
let start = 0;
|
|
174
|
+
let lines = 1;
|
|
175
|
+
for (let index = last < 0 ? -1 : bytes.lastIndexOf(NEWLINE, last);index !== -1; ) {
|
|
176
|
+
if (lines === limits.maxLines) {
|
|
177
|
+
start = index + 1;
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
lines++;
|
|
181
|
+
index = index === 0 ? -1 : bytes.lastIndexOf(NEWLINE, index - 1);
|
|
182
|
+
}
|
|
183
|
+
if (bytes.length - start > limits.maxBytes) {
|
|
184
|
+
const from = bytes.length - limits.maxBytes;
|
|
185
|
+
const newline = bytes.indexOf(NEWLINE, from - 1);
|
|
186
|
+
start = newline !== -1 && newline + 1 < bytes.length ? newline + 1 : characterStart(bytes, from);
|
|
187
|
+
}
|
|
188
|
+
return [start, bytes.length];
|
|
189
|
+
}
|
|
190
|
+
function characterEnd(bytes, index) {
|
|
191
|
+
let end = index;
|
|
192
|
+
while (end > 0 && ((bytes[end] ?? 0) & 192) === 128)
|
|
193
|
+
end--;
|
|
194
|
+
return end;
|
|
195
|
+
}
|
|
196
|
+
function characterStart(bytes, index) {
|
|
197
|
+
let start = index;
|
|
198
|
+
while (start < bytes.length && ((bytes[start] ?? 0) & 192) === 128)
|
|
199
|
+
start++;
|
|
200
|
+
return start;
|
|
201
|
+
}
|
|
202
|
+
function lineCount(bytes) {
|
|
203
|
+
if (bytes.length === 0)
|
|
204
|
+
return 0;
|
|
205
|
+
let newlines = 0;
|
|
206
|
+
for (let index = bytes.indexOf(NEWLINE);index !== -1; index = bytes.indexOf(NEWLINE, index + 1))
|
|
207
|
+
newlines++;
|
|
208
|
+
return newlines + (bytes[bytes.length - 1] === NEWLINE ? 0 : 1);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
class OutputBuffer {
|
|
212
|
+
#limits;
|
|
213
|
+
#decoder = new TextDecoder("utf-8", { ignoreBOM: true });
|
|
214
|
+
#started = false;
|
|
215
|
+
#chunks = [];
|
|
216
|
+
#storedBytes = 0;
|
|
217
|
+
#storedNewlines = 0;
|
|
218
|
+
#full = false;
|
|
219
|
+
#totalBytes = 0;
|
|
220
|
+
#totalNewlines = 0;
|
|
221
|
+
#endsWithNewline = true;
|
|
222
|
+
constructor(limits) {
|
|
223
|
+
this.#limits = limits;
|
|
224
|
+
}
|
|
225
|
+
get storedBytes() {
|
|
226
|
+
return this.#storedBytes;
|
|
227
|
+
}
|
|
228
|
+
push(chunk, skipped) {
|
|
229
|
+
const pending = typeof chunk === "string" || skipped !== undefined ? this.#decoder.decode() : "";
|
|
230
|
+
let text = typeof chunk === "string" ? chunk : this.#decoder.decode(chunk, { stream: true });
|
|
231
|
+
const first = !this.#started && pending === "" && skipped === undefined;
|
|
232
|
+
if (pending !== "" || text !== "" || skipped !== undefined)
|
|
233
|
+
this.#started = true;
|
|
234
|
+
if (first && typeof chunk !== "string" && text.startsWith("\uFEFF"))
|
|
235
|
+
text = text.slice(1);
|
|
236
|
+
if (skipped === undefined)
|
|
237
|
+
return this.#accept(pending + text);
|
|
238
|
+
if (this.#limits.retain !== "tail")
|
|
239
|
+
throw new Error("Skipped output requires tail retention");
|
|
240
|
+
this.#accept(pending);
|
|
241
|
+
this.#skip(skipped);
|
|
242
|
+
this.#accept(text);
|
|
243
|
+
return true;
|
|
244
|
+
}
|
|
245
|
+
#skip(skipped) {
|
|
246
|
+
if (skipped.bytes === 0)
|
|
247
|
+
return;
|
|
248
|
+
this.#totalBytes += skipped.bytes;
|
|
249
|
+
this.#totalNewlines += skipped.newlines;
|
|
250
|
+
this.#endsWithNewline = skipped.endsWithNewline;
|
|
251
|
+
this.#chunks = [];
|
|
252
|
+
this.#storedBytes = 0;
|
|
253
|
+
this.#storedNewlines = 0;
|
|
254
|
+
}
|
|
255
|
+
end() {
|
|
256
|
+
this.#accept(this.#decoder.decode());
|
|
257
|
+
}
|
|
258
|
+
#accept(text) {
|
|
259
|
+
if (text.length === 0)
|
|
260
|
+
return false;
|
|
261
|
+
const bytes = utf8ByteLength(text);
|
|
262
|
+
const newlines = countNewlines(text);
|
|
263
|
+
this.#totalBytes += bytes;
|
|
264
|
+
this.#totalNewlines += newlines;
|
|
265
|
+
this.#endsWithNewline = text.endsWith(`
|
|
266
|
+
`);
|
|
267
|
+
if (this.#full)
|
|
268
|
+
return true;
|
|
269
|
+
this.#chunks.push({ text, bytes, newlines });
|
|
270
|
+
this.#storedBytes += bytes;
|
|
271
|
+
this.#storedNewlines += newlines;
|
|
272
|
+
if (this.#limits.retain === "head") {
|
|
273
|
+
this.#full = this.#storedBytes > this.#limits.maxBytes || this.#storedNewlines >= this.#limits.maxLines;
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
while (this.#chunks.length > 1) {
|
|
277
|
+
const first = this.#chunks[0];
|
|
278
|
+
const bytesAfter = this.#storedBytes - first.bytes;
|
|
279
|
+
const newlinesAfter = this.#storedNewlines - first.newlines;
|
|
280
|
+
if (bytesAfter <= this.#limits.maxBytes + 1 && newlinesAfter <= this.#limits.maxLines + 1)
|
|
281
|
+
break;
|
|
282
|
+
this.#chunks.shift();
|
|
283
|
+
this.#storedBytes = bytesAfter;
|
|
284
|
+
this.#storedNewlines = newlinesAfter;
|
|
285
|
+
}
|
|
286
|
+
return true;
|
|
287
|
+
}
|
|
288
|
+
snapshot() {
|
|
289
|
+
const stored = this.#chunks.length === 1 ? this.#chunks[0].text : this.#chunks.map((chunk) => chunk.text).join("");
|
|
290
|
+
const kept = boundOutput(stored, this.#limits);
|
|
291
|
+
const storedLines = lines(this.#storedNewlines, stored === "" || stored.endsWith(`
|
|
292
|
+
`));
|
|
293
|
+
const keptLines = storedLines - kept.droppedLines;
|
|
294
|
+
if (this.#limits.retain === "tail" || this.#chunks.length > 1) {
|
|
295
|
+
const text = this.#limits.retain === "tail" ? tailMargin(stored, this.#limits) : stored;
|
|
296
|
+
const bytes = this.#limits.retain === "tail" ? utf8ByteLength(text) : this.#storedBytes;
|
|
297
|
+
this.#chunks = text === "" ? [] : [{ text, bytes, newlines: countNewlines(text) }];
|
|
298
|
+
this.#storedBytes = bytes;
|
|
299
|
+
this.#storedNewlines = this.#chunks[0]?.newlines ?? 0;
|
|
300
|
+
}
|
|
301
|
+
return {
|
|
302
|
+
text: sanitizeOutput(kept.text),
|
|
303
|
+
droppedBytes: this.#totalBytes - kept.bytes,
|
|
304
|
+
droppedLines: lines(this.#totalNewlines, this.#endsWithNewline) - keptLines
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
function tailMargin(text, limits) {
|
|
309
|
+
const bytes = encoder.encode(text);
|
|
310
|
+
const byteStart = bytes.length > limits.maxBytes ? characterEnd(bytes, bytes.length - limits.maxBytes - 1) : 0;
|
|
311
|
+
let lineStart = 0;
|
|
312
|
+
let newlines = 0;
|
|
313
|
+
for (let index = bytes.lastIndexOf(NEWLINE);index !== -1; index = bytes.lastIndexOf(NEWLINE, index - 1)) {
|
|
314
|
+
if (++newlines > limits.maxLines) {
|
|
315
|
+
lineStart = index;
|
|
316
|
+
break;
|
|
317
|
+
}
|
|
318
|
+
if (index === 0)
|
|
319
|
+
break;
|
|
320
|
+
}
|
|
321
|
+
const start = Math.max(byteStart, lineStart);
|
|
322
|
+
return start === 0 ? text : decoder.decode(bytes.subarray(start));
|
|
323
|
+
}
|
|
324
|
+
function lines(newlines, terminated) {
|
|
325
|
+
return newlines + (terminated ? 0 : 1);
|
|
326
|
+
}
|
|
327
|
+
function countNewlines(text) {
|
|
328
|
+
let count = 0;
|
|
329
|
+
for (let index = text.indexOf(`
|
|
330
|
+
`);index !== -1; index = text.indexOf(`
|
|
331
|
+
`, index + 1))
|
|
332
|
+
count++;
|
|
333
|
+
return count;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// packages/execution/src/forwarding.ts
|
|
337
|
+
var bytes = (value) => new TextEncoder().encode(JSON.stringify(value)).length;
|
|
338
|
+
function boundForwardedToolCalls(value, budget) {
|
|
339
|
+
const calls = [];
|
|
340
|
+
let remaining = budget;
|
|
341
|
+
let omittedCalls = value.omittedCalls;
|
|
342
|
+
for (const source of value.calls) {
|
|
343
|
+
let call = source;
|
|
344
|
+
if (bytes(call) > remaining && call.result !== null) {
|
|
345
|
+
call = {
|
|
346
|
+
...call,
|
|
347
|
+
result: null,
|
|
348
|
+
omittedFields: [...call.omittedFields, "result"]
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
if (bytes(call) > remaining && call.arguments !== undefined) {
|
|
352
|
+
const { arguments: _arguments, ...rest } = call;
|
|
353
|
+
call = { ...rest, omittedFields: [...call.omittedFields, "arguments"] };
|
|
354
|
+
}
|
|
355
|
+
const cost = bytes(call);
|
|
356
|
+
if (cost > remaining)
|
|
357
|
+
omittedCalls++;
|
|
358
|
+
else {
|
|
359
|
+
calls.push(call);
|
|
360
|
+
remaining -= cost;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return { ...value, calls, omittedCalls };
|
|
364
|
+
}
|
|
365
|
+
function displayResult(result, budget) {
|
|
366
|
+
let remaining = budget;
|
|
367
|
+
let omitted = false;
|
|
368
|
+
const content = [];
|
|
369
|
+
for (const item of result.output ?? []) {
|
|
370
|
+
if (item.type === "image") {
|
|
371
|
+
const cost = bytes(item);
|
|
372
|
+
if (cost <= remaining) {
|
|
373
|
+
content.push(item);
|
|
374
|
+
remaining -= cost;
|
|
375
|
+
} else
|
|
376
|
+
omitted = true;
|
|
377
|
+
} else {
|
|
378
|
+
const bounded = boundOutput(item.text, {
|
|
379
|
+
maxBytes: remaining,
|
|
380
|
+
maxLines: Number.MAX_SAFE_INTEGER,
|
|
381
|
+
retain: "head"
|
|
382
|
+
});
|
|
383
|
+
if (bounded.text)
|
|
384
|
+
content.push({ type: "text", text: bounded.text });
|
|
385
|
+
remaining -= bounded.bytes;
|
|
386
|
+
omitted ||= bounded.droppedBytes > 0;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return {
|
|
390
|
+
content,
|
|
391
|
+
isError: result.isError ?? false,
|
|
392
|
+
details: result.details ?? null,
|
|
393
|
+
diagnostics: [
|
|
394
|
+
...result.diagnostics ?? [],
|
|
395
|
+
...omitted ? [
|
|
396
|
+
{
|
|
397
|
+
severity: "warn",
|
|
398
|
+
code: "forwarded_display_truncated",
|
|
399
|
+
message: "Forwarded display output was truncated; the original tool result is unchanged"
|
|
400
|
+
}
|
|
401
|
+
] : []
|
|
402
|
+
]
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
function forwardedStatus(result, fallback) {
|
|
406
|
+
if (result.diagnostics?.some((item) => item.code === "interrupted"))
|
|
407
|
+
return "interrupted";
|
|
408
|
+
if (result.diagnostics?.some((item) => item.code === "aborted" || item.code === "abandoned"))
|
|
409
|
+
return "aborted";
|
|
410
|
+
return fallback;
|
|
411
|
+
}
|
|
412
|
+
async function forwardCall(tx, cellId, call, admission = false, nativeTask) {
|
|
413
|
+
if (cellId === undefined)
|
|
414
|
+
return;
|
|
415
|
+
const doc = await tx.doc(InvocationDoc, cellId);
|
|
416
|
+
const snapshot = doc.forwardedToolCalls;
|
|
417
|
+
if (snapshot === undefined)
|
|
418
|
+
return;
|
|
419
|
+
const position = snapshot.calls.findIndex((item) => item.callId === call.callId);
|
|
420
|
+
if (position === -1 && !admission)
|
|
421
|
+
return;
|
|
422
|
+
const calls = [...snapshot.calls];
|
|
423
|
+
if (position === -1)
|
|
424
|
+
calls.push(call);
|
|
425
|
+
else
|
|
426
|
+
calls[position] = call;
|
|
427
|
+
doc.forwardedToolCalls = copyJson2(boundForwardedToolCalls({ ...snapshot, calls }, doc.forwardingBudget ?? 40000), { omitUndefinedProperties: true });
|
|
428
|
+
const retained = new Set(doc.forwardedToolCalls.calls.map((item) => item.callId));
|
|
429
|
+
if (doc.forwardedNativeTasks !== undefined)
|
|
430
|
+
doc.forwardedNativeTasks = doc.forwardedNativeTasks.filter((item) => retained.has(item.callId));
|
|
431
|
+
if (nativeTask !== undefined && retained.has(call.callId) && !doc.forwardedNativeTasks?.some((item) => item.callId === call.callId)) {
|
|
432
|
+
doc.forwardedNativeTasks ??= [];
|
|
433
|
+
doc.forwardedNativeTasks.push({ callId: call.callId, ...nativeTask });
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
async function forwardInvocationResult(tx, taskId, result, status) {
|
|
437
|
+
const cellId = (await tx.doc(InvocationDoc, taskId)).forwardingCellId;
|
|
438
|
+
if (cellId === undefined || cellId === taskId)
|
|
439
|
+
return;
|
|
440
|
+
const doc = await tx.doc(InvocationDoc, cellId);
|
|
441
|
+
const previous = doc.forwardedToolCalls?.calls.find((call) => call.callId === `nested-${taskId}`);
|
|
442
|
+
if (previous === undefined)
|
|
443
|
+
return;
|
|
444
|
+
await forwardCall(tx, cellId, {
|
|
445
|
+
...previous,
|
|
446
|
+
status: forwardedStatus(result, status),
|
|
447
|
+
result: displayResult(result, doc.forwardingBudget ?? 40000),
|
|
448
|
+
omittedFields: previous.omittedFields.filter((field) => field !== "result")
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
async function captureNativeCalls(tx, conversationId, owner, cellId) {
|
|
452
|
+
if (cellId === undefined)
|
|
453
|
+
return;
|
|
454
|
+
const live = await tx.doc(LiveDoc, conversationId);
|
|
455
|
+
const owners = new Set([owner]);
|
|
456
|
+
const cell = await tx.doc(InvocationDoc, cellId);
|
|
457
|
+
const budget = cell.forwardingBudget ?? 40000;
|
|
458
|
+
const admitted = new Set(cell.forwardedToolCalls?.calls.map((call) => call.callId));
|
|
459
|
+
for (const slot of live.nestedTools ?? []) {
|
|
460
|
+
if (!owners.has(slot.parentTaskId) && !admitted.has(slot.callId))
|
|
461
|
+
continue;
|
|
462
|
+
owners.add(slot.taskId);
|
|
463
|
+
const key = slot.callId.slice(slot.parentCallId.length + 1);
|
|
464
|
+
const stored = (await tx.doc(NestedCallDoc, slot.parentTaskId, key, null)).result;
|
|
465
|
+
const record = await tx.task(slot.taskId);
|
|
466
|
+
const outcome = record?.state.status === "terminal" ? record.state.outcome : undefined;
|
|
467
|
+
const previous = cell.forwardedToolCalls?.calls.find((call) => call.callId === slot.callId);
|
|
468
|
+
if (stored === undefined && previous !== undefined && previous.status !== "pending" && previous.status !== "running")
|
|
469
|
+
continue;
|
|
470
|
+
const captured = previous !== undefined && previous.status !== "pending" && previous.status !== "running" && !previous.result?.diagnostics.some((item) => item.code === "forwarded_output_unavailable");
|
|
471
|
+
const terminal = stored !== undefined || outcome !== undefined || slot.status === "done";
|
|
472
|
+
const result = stored ?? {
|
|
473
|
+
...slot.output === undefined ? {} : { output: [{ type: "text", text: slot.output }] },
|
|
474
|
+
...slot.details === undefined ? {} : { details: slot.details },
|
|
475
|
+
...slot.diagnostics === undefined ? {} : { diagnostics: slot.diagnostics }
|
|
476
|
+
};
|
|
477
|
+
const receipt = stored === undefined ? displayResult(result, budget) : {
|
|
478
|
+
content: previous?.result?.content ?? [],
|
|
479
|
+
isError: stored.isError,
|
|
480
|
+
details: stored.details ?? null,
|
|
481
|
+
diagnostics: [
|
|
482
|
+
...stored.diagnostics,
|
|
483
|
+
...!captured ? [
|
|
484
|
+
{
|
|
485
|
+
severity: "warn",
|
|
486
|
+
code: "forwarded_output_unavailable",
|
|
487
|
+
message: "Native display output was not retained. Bind this execution component to its owning Harness before running native nested calls"
|
|
488
|
+
}
|
|
489
|
+
] : []
|
|
490
|
+
]
|
|
491
|
+
};
|
|
492
|
+
await forwardCall(tx, cellId, {
|
|
493
|
+
callId: slot.callId,
|
|
494
|
+
parentCallId: slot.parentCallId,
|
|
495
|
+
name: slot.name,
|
|
496
|
+
arguments: slot.arguments,
|
|
497
|
+
status: terminal ? forwardedStatus(result, outcome?.status === "aborted" ? "aborted" : outcome?.status === "completed" ? "completed" : "failed") : slot.status === "pending" ? "pending" : "running",
|
|
498
|
+
result: terminal && previous?.omittedFields.includes("result") ? null : receipt,
|
|
499
|
+
omittedFields: terminal && previous?.omittedFields.includes("result") ? ["result"] : []
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
const visible = new Set(live.nestedTools?.map((slot) => slot.callId));
|
|
503
|
+
for (const admitted of [...cell.forwardedNativeTasks ?? []]) {
|
|
504
|
+
if (visible.has(admitted.callId))
|
|
505
|
+
continue;
|
|
506
|
+
const record = await tx.task(admitted.taskId);
|
|
507
|
+
if (record === undefined || record.kind !== ToolTask.definition.name || record.owner !== admitted.ownerTaskId || record.conversationId !== conversationId)
|
|
508
|
+
throw new Error(`Native forwarded task ${admitted.taskId} does not match its admission`);
|
|
509
|
+
if (record.state.status !== "terminal")
|
|
510
|
+
continue;
|
|
511
|
+
const call = cell.forwardedToolCalls?.calls.find((item) => item.callId === admitted.callId);
|
|
512
|
+
if (call !== undefined) {
|
|
513
|
+
const outcome = record.state.outcome;
|
|
514
|
+
const unfinished = call.status === "pending" || call.status === "running";
|
|
515
|
+
const completedStatus = unfinished ? forwardedStatus({ diagnostics: call.result?.diagnostics ?? [] }, call.result?.isError ? "failed" : "completed") : call.status;
|
|
516
|
+
const status = record.abortReason === "restart" ? "interrupted" : outcome.status === "completed" ? completedStatus : outcome.status === "aborted" ? "aborted" : "failed";
|
|
517
|
+
if (unfinished || call.status !== status) {
|
|
518
|
+
const diagnostic = status === "completed" ? {
|
|
519
|
+
severity: "warn",
|
|
520
|
+
code: "forwarded_result_unavailable",
|
|
521
|
+
message: "Native task completed, but its final display result was not retained; the retained output may be partial"
|
|
522
|
+
} : {
|
|
523
|
+
severity: "error",
|
|
524
|
+
code: status,
|
|
525
|
+
message: `Native tool ${call.name} ${status}; external side effects may have partially run`
|
|
526
|
+
};
|
|
527
|
+
await forwardCall(tx, cellId, {
|
|
528
|
+
...call,
|
|
529
|
+
status,
|
|
530
|
+
result: call.omittedFields.includes("result") ? null : {
|
|
531
|
+
content: call.result?.content ?? [],
|
|
532
|
+
isError: status === "completed" ? call.result?.isError ?? false : true,
|
|
533
|
+
details: call.result?.details ?? null,
|
|
534
|
+
diagnostics: [...call.result?.diagnostics ?? [], diagnostic]
|
|
535
|
+
}
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
cell.forwardedNativeTasks = cell.forwardedNativeTasks?.filter((item) => item.callId !== admitted.callId) ?? [];
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// packages/execution/src/cell-observation.ts
|
|
544
|
+
var CellStateDoc = defineDocFamily({
|
|
545
|
+
kind: "howaboua.execution.cells",
|
|
546
|
+
family: true,
|
|
547
|
+
version: 2,
|
|
548
|
+
scope: "conversation",
|
|
549
|
+
history: "latest",
|
|
550
|
+
fork: "initial",
|
|
551
|
+
checkpointWhen: () => true,
|
|
552
|
+
initial: () => ({ result: {} }),
|
|
553
|
+
migrate: (value) => ({
|
|
554
|
+
...value,
|
|
555
|
+
result: storeResult(readStoredResult(value["result"]))
|
|
556
|
+
})
|
|
557
|
+
});
|
|
558
|
+
async function observeCell(kind, id, api, context, budget) {
|
|
559
|
+
const record = await api.getTask(id, context);
|
|
560
|
+
if (record === undefined || record.kind !== kind || record.conversationId !== api.conversationId)
|
|
561
|
+
throw new Error(`Unknown cell ${id}`);
|
|
562
|
+
const doc = await api.snapshot(InvocationDoc, id, context) ?? await api.snapshot(CellStateDoc, api.conversationId, String(id), context);
|
|
563
|
+
const outcome = record.state.status === "terminal" ? record.state.outcome : undefined;
|
|
564
|
+
const result = readStoredResult(outcome?.result ?? doc?.result ?? {});
|
|
565
|
+
const interrupted = result.diagnostics?.some((each) => each.code === "interrupted") ?? false;
|
|
566
|
+
const status = interrupted ? "interrupted" : outcome?.status === "completed" ? "completed" : outcome?.status === "aborted" ? "aborted" : outcome !== undefined ? "failed" : "running";
|
|
567
|
+
return {
|
|
568
|
+
cellId: id,
|
|
569
|
+
status,
|
|
570
|
+
result,
|
|
571
|
+
...doc?.forwardedToolCalls === undefined ? {} : {
|
|
572
|
+
forwardedToolCalls: budget === undefined ? doc.forwardedToolCalls : boundForwardedToolCalls(doc.forwardedToolCalls, budget)
|
|
573
|
+
},
|
|
574
|
+
...doc?.checkpoint === undefined ? {} : { checkpoint: doc.checkpoint }
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// packages/execution/src/cell-progress.ts
|
|
579
|
+
import { copyJson as copyJson3 } from "@earendil-works/chord";
|
|
580
|
+
import {
|
|
581
|
+
LiveDoc as LiveDoc2
|
|
582
|
+
} from "@earendil-works/pi-durable";
|
|
583
|
+
async function observeCellProgress(id, api, context, budget) {
|
|
584
|
+
const pending = new Set;
|
|
585
|
+
const publish = async (value) => {
|
|
586
|
+
if (value?.forwardedToolCalls === undefined)
|
|
587
|
+
return;
|
|
588
|
+
await api.details({
|
|
589
|
+
cell_id: String(id),
|
|
590
|
+
status: "running",
|
|
591
|
+
forwardedToolCalls: copyJson3(boundForwardedToolCalls(value.forwardedToolCalls, budget), { omitUndefinedProperties: true })
|
|
592
|
+
}, context);
|
|
593
|
+
};
|
|
594
|
+
const cell = await api.watchDoc(InvocationDoc, id, context);
|
|
595
|
+
if (cell === undefined) {
|
|
596
|
+
await publish(await api.snapshot(CellStateDoc, api.conversationId, String(id), context));
|
|
597
|
+
return async () => {};
|
|
598
|
+
}
|
|
599
|
+
const own = (action) => {
|
|
600
|
+
const work = action();
|
|
601
|
+
pending.add(work);
|
|
602
|
+
work.then(() => pending.delete(work), () => pending.delete(work));
|
|
603
|
+
return work;
|
|
604
|
+
};
|
|
605
|
+
const live = await api.watchDoc(LiveDoc2, api.conversationId, context);
|
|
606
|
+
cell.start((call) => own(async () => {
|
|
607
|
+
if (call.kind === "failed")
|
|
608
|
+
throw call.error;
|
|
609
|
+
await publish(call.value);
|
|
610
|
+
}));
|
|
611
|
+
live?.start((call) => own(async () => {
|
|
612
|
+
if (call.kind === "failed")
|
|
613
|
+
throw call.error;
|
|
614
|
+
await api.commit(async (tx) => {
|
|
615
|
+
const record = await tx.task(id);
|
|
616
|
+
if (record === undefined || record.state.status === "terminal")
|
|
617
|
+
return;
|
|
618
|
+
await captureNativeCalls(tx, api.conversationId, id, id);
|
|
619
|
+
}, context);
|
|
620
|
+
}));
|
|
621
|
+
try {
|
|
622
|
+
await publish(cell.value);
|
|
623
|
+
} catch (error) {
|
|
624
|
+
await cell.stop();
|
|
625
|
+
await live?.stop();
|
|
626
|
+
await Promise.allSettled([...pending]);
|
|
627
|
+
throw error;
|
|
628
|
+
}
|
|
629
|
+
return async () => {
|
|
630
|
+
const endings = await Promise.all([cell.stop(), live?.stop()]);
|
|
631
|
+
await Promise.all([...pending]);
|
|
632
|
+
for (const ending of endings)
|
|
633
|
+
if (ending?.kind === "listener_error" || ending?.kind === "failed")
|
|
634
|
+
throw ending.error;
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// packages/execution/src/cell-task.ts
|
|
639
|
+
import { copyJson as copyJson8 } from "@earendil-works/chord";
|
|
640
|
+
import { withAbortSignal } from "@earendil-works/chord/context";
|
|
641
|
+
import {
|
|
642
|
+
defineTask
|
|
643
|
+
} from "@earendil-works/pi-durable";
|
|
644
|
+
|
|
645
|
+
// packages/execution/src/cell-tools.ts
|
|
646
|
+
import { copyJson as copyJson6 } from "@earendil-works/chord";
|
|
647
|
+
import { withoutAbortSignal as withoutAbortSignal2 } from "@earendil-works/chord/context";
|
|
648
|
+
|
|
649
|
+
// packages/execution/src/invocation.ts
|
|
650
|
+
import { copyJson as copyJson5 } from "@earendil-works/chord";
|
|
651
|
+
import { awaitWithContext } from "@earendil-works/chord/context";
|
|
652
|
+
|
|
653
|
+
// packages/execution/src/native-tools.ts
|
|
654
|
+
import { copyJson as copyJson4 } from "@earendil-works/chord";
|
|
655
|
+
import { withoutAbortSignal } from "@earendil-works/chord/context";
|
|
656
|
+
import {
|
|
657
|
+
LiveDoc as LiveDoc3,
|
|
658
|
+
NestedCallDoc as NestedCallDoc2,
|
|
659
|
+
ToolTask as ToolTask2
|
|
660
|
+
} from "@earendil-works/pi-durable";
|
|
661
|
+
import { Equal } from "typebox/value";
|
|
662
|
+
function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
663
|
+
let sequence = 0;
|
|
664
|
+
const admissions = [];
|
|
665
|
+
const execute = async (name, args, callContext, options = {}) => {
|
|
666
|
+
assertLive();
|
|
667
|
+
const key = options.key ?? String(++sequence);
|
|
668
|
+
if (options.key !== undefined && (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)))
|
|
669
|
+
throw new Error("Invalid nested call key");
|
|
670
|
+
const call = {
|
|
671
|
+
type: "toolCall",
|
|
672
|
+
id: `${callId}/${key}`,
|
|
673
|
+
name,
|
|
674
|
+
arguments: copyJson4(args, {
|
|
675
|
+
omitUndefinedProperties: true
|
|
676
|
+
})
|
|
677
|
+
};
|
|
678
|
+
const admission = runtime.commit(async (tx) => {
|
|
679
|
+
const slot = await tx.doc(NestedCallDoc2, runtime.taskId, key, null);
|
|
680
|
+
if (slot.taskId !== undefined) {
|
|
681
|
+
const input = (await tx.task(slot.taskId))?.input;
|
|
682
|
+
if (input?.kind !== "nested" || input.call.name !== name || !Equal(input.call.arguments, call.arguments))
|
|
683
|
+
throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
|
|
684
|
+
} else {
|
|
685
|
+
slot.taskId = await tx.createTask(ToolTask2, {
|
|
686
|
+
kind: "nested",
|
|
687
|
+
parent: runtime.taskId,
|
|
688
|
+
parentCallId: callId,
|
|
689
|
+
key,
|
|
690
|
+
call,
|
|
691
|
+
...options.progress === false ? { progress: false } : {}
|
|
692
|
+
}, {
|
|
693
|
+
ownership: { kind: "task", taskId: runtime.taskId },
|
|
694
|
+
abandonOnRestart: replay !== "safe"
|
|
695
|
+
});
|
|
696
|
+
const live = await tx.doc(LiveDoc3, runtime.conversationId);
|
|
697
|
+
live.nestedTools ??= [];
|
|
698
|
+
live.nestedTools.push({
|
|
699
|
+
callId: call.id,
|
|
700
|
+
parentCallId: callId,
|
|
701
|
+
parentTaskId: runtime.taskId,
|
|
702
|
+
name,
|
|
703
|
+
taskId: slot.taskId,
|
|
704
|
+
arguments: call.arguments,
|
|
705
|
+
status: "pending"
|
|
706
|
+
});
|
|
707
|
+
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
708
|
+
if (owner.forwardingCellId !== undefined) {
|
|
709
|
+
(await tx.doc(InvocationDoc, slot.taskId)).forwardingCellId = owner.forwardingCellId;
|
|
710
|
+
await forwardCall(tx, owner.forwardingCellId, {
|
|
711
|
+
callId: call.id,
|
|
712
|
+
parentCallId: callId,
|
|
713
|
+
name,
|
|
714
|
+
arguments: call.arguments,
|
|
715
|
+
status: "pending",
|
|
716
|
+
result: null,
|
|
717
|
+
omittedFields: []
|
|
718
|
+
}, true, { taskId: slot.taskId, ownerTaskId: runtime.taskId });
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
return;
|
|
722
|
+
}, callContext);
|
|
723
|
+
admissions.push(admission);
|
|
724
|
+
await admission;
|
|
725
|
+
const slot = await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext);
|
|
726
|
+
if (slot?.taskId === undefined)
|
|
727
|
+
throw new Error("Nested task creation did not commit");
|
|
728
|
+
const settled = await runtime.waitForTask(slot.taskId, callContext);
|
|
729
|
+
const result = (await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext))?.result;
|
|
730
|
+
await runtime.commit(async (tx) => {
|
|
731
|
+
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
732
|
+
await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
|
|
733
|
+
return;
|
|
734
|
+
}, callContext);
|
|
735
|
+
return result === undefined ? {
|
|
736
|
+
taskId: slot.taskId,
|
|
737
|
+
isError: true,
|
|
738
|
+
diagnostics: [
|
|
739
|
+
{
|
|
740
|
+
severity: "error",
|
|
741
|
+
code: settled.state.outcome.status,
|
|
742
|
+
message: `Tool ${name} did not return a result`
|
|
743
|
+
}
|
|
744
|
+
]
|
|
745
|
+
} : copyJson4(result);
|
|
746
|
+
};
|
|
747
|
+
return {
|
|
748
|
+
execute,
|
|
749
|
+
async finish() {
|
|
750
|
+
await Promise.allSettled(admissions);
|
|
751
|
+
await cleanupNativeCalls(runtime, withoutAbortSignal(context));
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
async function cleanupNativeCalls(runtime, context) {
|
|
756
|
+
await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask2.definition.name).map((child) => runtime.abortOwned(child.id, context)));
|
|
757
|
+
await runtime.commit(async (tx) => {
|
|
758
|
+
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
759
|
+
await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
|
|
760
|
+
const live = await tx.doc(LiveDoc3, runtime.conversationId);
|
|
761
|
+
const removed = new Set([runtime.taskId]);
|
|
762
|
+
for (const slot of live.nestedTools ?? [])
|
|
763
|
+
if (removed.has(slot.parentTaskId))
|
|
764
|
+
removed.add(slot.taskId);
|
|
765
|
+
if (live.nestedTools !== undefined) {
|
|
766
|
+
live.nestedTools = live.nestedTools.filter((slot) => !removed.has(slot.parentTaskId));
|
|
767
|
+
if (!live.nestedTools.length)
|
|
768
|
+
delete live.nestedTools;
|
|
769
|
+
}
|
|
770
|
+
return;
|
|
771
|
+
}, context);
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// packages/execution/src/progress.ts
|
|
775
|
+
var PROGRESS_BYTES_PER_SECOND = 100 * 1024;
|
|
776
|
+
|
|
777
|
+
class Progress {
|
|
778
|
+
#write;
|
|
779
|
+
#onError;
|
|
780
|
+
#minIntervalMs;
|
|
781
|
+
#waiters = [];
|
|
782
|
+
#timer;
|
|
783
|
+
#inFlight;
|
|
784
|
+
#nextAt = 0;
|
|
785
|
+
#dirty = false;
|
|
786
|
+
#stopped = false;
|
|
787
|
+
constructor(write, onError, minIntervalMs) {
|
|
788
|
+
this.#write = write;
|
|
789
|
+
this.#onError = onError;
|
|
790
|
+
this.#minIntervalMs = minIntervalMs;
|
|
791
|
+
}
|
|
792
|
+
mark() {
|
|
793
|
+
this.#dirty = true;
|
|
794
|
+
this.#schedule();
|
|
795
|
+
}
|
|
796
|
+
markAndWait() {
|
|
797
|
+
let resolve;
|
|
798
|
+
let reject;
|
|
799
|
+
const promise = new Promise((yes, no) => {
|
|
800
|
+
resolve = yes;
|
|
801
|
+
reject = no;
|
|
802
|
+
});
|
|
803
|
+
const waiter = { promise, resolve, reject };
|
|
804
|
+
this.#waiters.push(waiter);
|
|
805
|
+
this.mark();
|
|
806
|
+
return waiter.promise;
|
|
807
|
+
}
|
|
808
|
+
async stop() {
|
|
809
|
+
this.#stopped = true;
|
|
810
|
+
clearTimeout(this.#timer);
|
|
811
|
+
this.#timer = undefined;
|
|
812
|
+
await this.#inFlight;
|
|
813
|
+
return this.#waiters.splice(0);
|
|
814
|
+
}
|
|
815
|
+
#schedule() {
|
|
816
|
+
if (this.#stopped || this.#timer !== undefined || this.#inFlight !== undefined)
|
|
817
|
+
return;
|
|
818
|
+
const wait = this.#nextAt - Date.now();
|
|
819
|
+
if (wait <= 0)
|
|
820
|
+
this.#flush();
|
|
821
|
+
else
|
|
822
|
+
this.#timer = setTimeout(() => {
|
|
823
|
+
this.#timer = undefined;
|
|
824
|
+
this.#flush();
|
|
825
|
+
}, wait);
|
|
826
|
+
}
|
|
827
|
+
#flush() {
|
|
828
|
+
if (this.#stopped || !this.#dirty)
|
|
829
|
+
return;
|
|
830
|
+
this.#dirty = false;
|
|
831
|
+
const waiters = this.#waiters.splice(0);
|
|
832
|
+
const started = Date.now();
|
|
833
|
+
this.#inFlight = this.#write().then((bytes) => {
|
|
834
|
+
this.#nextAt = started + Math.max(this.#minIntervalMs, bytes * 1000 / PROGRESS_BYTES_PER_SECOND);
|
|
835
|
+
for (const waiter of waiters)
|
|
836
|
+
waiter.resolve();
|
|
837
|
+
}, (error) => {
|
|
838
|
+
this.#nextAt = started + this.#minIntervalMs;
|
|
839
|
+
for (const waiter of waiters)
|
|
840
|
+
waiter.reject(error);
|
|
841
|
+
this.#onError(error);
|
|
842
|
+
}).finally(() => {
|
|
843
|
+
this.#inFlight = undefined;
|
|
844
|
+
if (this.#dirty)
|
|
845
|
+
this.#schedule();
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
// packages/execution/src/tool-origin.ts
|
|
851
|
+
import {
|
|
852
|
+
defineDoc as defineDoc2
|
|
853
|
+
} from "@earendil-works/pi-durable";
|
|
854
|
+
var ToolOriginDoc = defineDoc2({
|
|
855
|
+
kind: "howaboua.tool-origin",
|
|
856
|
+
version: 1,
|
|
857
|
+
scope: "task",
|
|
858
|
+
checkpointWhen: () => false,
|
|
859
|
+
initial: () => ({})
|
|
860
|
+
});
|
|
861
|
+
|
|
862
|
+
// packages/execution/src/invocation.ts
|
|
863
|
+
function executionError(code, message) {
|
|
864
|
+
return {
|
|
865
|
+
output: [],
|
|
866
|
+
isError: true,
|
|
867
|
+
diagnostics: [{ severity: "error", code, message }]
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
function errorText(error) {
|
|
871
|
+
return error instanceof Error ? error.message : String(error);
|
|
872
|
+
}
|
|
873
|
+
function createInvocation(runtime, tool, context) {
|
|
874
|
+
const limits = {
|
|
875
|
+
maxBytes: tool.outputLimits?.maxBytes ?? 50 * 1024,
|
|
876
|
+
maxLines: tool.outputLimits?.maxLines ?? 2000,
|
|
877
|
+
retain: tool.outputLimits?.retain ?? "head"
|
|
878
|
+
};
|
|
879
|
+
const output = new OutputBuffer(limits);
|
|
880
|
+
const diagnostics = [];
|
|
881
|
+
let details;
|
|
882
|
+
let ended = false;
|
|
883
|
+
const assertLive = () => {
|
|
884
|
+
if (ended)
|
|
885
|
+
throw new Error(`Invocation ${runtime.taskId} has settled`);
|
|
886
|
+
};
|
|
887
|
+
const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, assertLive, context);
|
|
888
|
+
const snapshot = () => {
|
|
889
|
+
const retained = output.snapshot();
|
|
890
|
+
return {
|
|
891
|
+
output: retained.text === "" ? [] : [{ type: "text", text: retained.text }],
|
|
892
|
+
...details === undefined ? {} : { details },
|
|
893
|
+
diagnostics: [...diagnostics]
|
|
894
|
+
};
|
|
895
|
+
};
|
|
896
|
+
const progress = new Progress(async () => {
|
|
897
|
+
const result = storeResult(snapshot());
|
|
898
|
+
const retained = output.snapshot();
|
|
899
|
+
await runtime.commit(async (tx) => {
|
|
900
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
901
|
+
doc.result = result;
|
|
902
|
+
doc.droppedBytes = retained.droppedBytes;
|
|
903
|
+
doc.droppedLines = retained.droppedLines;
|
|
904
|
+
await forwardInvocationResult(tx, runtime.taskId, result, "running");
|
|
905
|
+
return;
|
|
906
|
+
}, context);
|
|
907
|
+
return JSON.stringify(result).length;
|
|
908
|
+
}, (error) => {
|
|
909
|
+
if (!runtime.signal.aborted)
|
|
910
|
+
runtime.report(error);
|
|
911
|
+
}, runtime.settings.progress.outputIntervalMs);
|
|
912
|
+
const api = {
|
|
913
|
+
taskId: runtime.taskId,
|
|
914
|
+
conversationId: runtime.conversationId,
|
|
915
|
+
callId: `nested-${runtime.taskId}`,
|
|
916
|
+
registry: runtime.registry,
|
|
917
|
+
agent: runtime.agent,
|
|
918
|
+
env: undefined,
|
|
919
|
+
now: () => runtime.now(),
|
|
920
|
+
outputWindow: limits.retain === "tail" ? {
|
|
921
|
+
maxBytes: limits.maxBytes,
|
|
922
|
+
maxLines: limits.maxLines,
|
|
923
|
+
minIntervalMs: runtime.settings.progress.outputIntervalMs,
|
|
924
|
+
bytesPerSecond: PROGRESS_BYTES_PER_SECOND
|
|
925
|
+
} : undefined,
|
|
926
|
+
output: (chunk, skipped) => {
|
|
927
|
+
assertLive();
|
|
928
|
+
if (output.push(chunk, skipped))
|
|
929
|
+
progress.mark();
|
|
930
|
+
},
|
|
931
|
+
retainedOutput: () => {
|
|
932
|
+
assertLive();
|
|
933
|
+
const retained = output.snapshot();
|
|
934
|
+
return { text: retained.text, truncated: retained.droppedBytes > 0 };
|
|
935
|
+
},
|
|
936
|
+
executeTool: (...args) => native.execute(...args),
|
|
937
|
+
diagnostic: (value) => {
|
|
938
|
+
assertLive();
|
|
939
|
+
diagnostics.push(copyJson5(value, { omitUndefinedProperties: true }));
|
|
940
|
+
progress.mark();
|
|
941
|
+
},
|
|
942
|
+
details: async (value, detailContext) => {
|
|
943
|
+
assertLive();
|
|
944
|
+
detailContext.abortSignal?.throwIfAborted();
|
|
945
|
+
details = copyJson5(value, { omitUndefinedProperties: true });
|
|
946
|
+
const committed = progress.markAndWait();
|
|
947
|
+
committed.catch(() => {});
|
|
948
|
+
await awaitWithContext(committed, detailContext);
|
|
949
|
+
},
|
|
950
|
+
commit: async (change, commitContext) => {
|
|
951
|
+
assertLive();
|
|
952
|
+
let result;
|
|
953
|
+
await runtime.commit(async (tx) => {
|
|
954
|
+
result = await change(tx);
|
|
955
|
+
return;
|
|
956
|
+
}, commitContext);
|
|
957
|
+
return result;
|
|
958
|
+
},
|
|
959
|
+
memo: runtime.memo,
|
|
960
|
+
createTask: async (task, input, options, taskContext) => {
|
|
961
|
+
assertLive();
|
|
962
|
+
let id;
|
|
963
|
+
await runtime.commit(async (tx) => {
|
|
964
|
+
id = await tx.createTask(task, input, {
|
|
965
|
+
...options,
|
|
966
|
+
...options.abandonOnRestart === undefined && tool.replay !== "safe" && options.ownership.kind === "task" && options.ownership.taskId === runtime.taskId ? { abandonOnRestart: true } : {}
|
|
967
|
+
});
|
|
968
|
+
const source = await tx.doc(ToolOriginDoc, runtime.taskId);
|
|
969
|
+
if (source.origin !== undefined)
|
|
970
|
+
(await tx.doc(ToolOriginDoc, id)).origin = { ...source.origin };
|
|
971
|
+
return;
|
|
972
|
+
}, taskContext);
|
|
973
|
+
if (id === undefined)
|
|
974
|
+
throw new Error("Task creation did not commit");
|
|
975
|
+
return id;
|
|
976
|
+
},
|
|
977
|
+
getTask: runtime.getTask,
|
|
978
|
+
waitForTask: runtime.waitForTask,
|
|
979
|
+
conversation: runtime.conversation,
|
|
980
|
+
snapshot: runtime.snapshot,
|
|
981
|
+
snapshotAsOf: runtime.snapshotAsOf,
|
|
982
|
+
watchDoc: runtime.watchDoc
|
|
983
|
+
};
|
|
984
|
+
return {
|
|
985
|
+
async executionApi() {
|
|
986
|
+
return {
|
|
987
|
+
...api,
|
|
988
|
+
get models() {
|
|
989
|
+
return runtime.models;
|
|
990
|
+
},
|
|
991
|
+
env: await runtime.env(context)
|
|
992
|
+
};
|
|
993
|
+
},
|
|
994
|
+
async finish(result) {
|
|
995
|
+
ended = true;
|
|
996
|
+
await native.finish();
|
|
997
|
+
output.end();
|
|
998
|
+
const pending = await progress.stop();
|
|
999
|
+
const retained = output.snapshot();
|
|
1000
|
+
const content = result.output ?? (retained.text === "" ? [] : [{ type: "text", text: retained.text }]);
|
|
1001
|
+
const final = {
|
|
1002
|
+
...result,
|
|
1003
|
+
output: content,
|
|
1004
|
+
...result.details === undefined && details !== undefined ? { details } : {},
|
|
1005
|
+
diagnostics: [...diagnostics, ...result.diagnostics ?? []]
|
|
1006
|
+
};
|
|
1007
|
+
return { result: final, pending, retained, content };
|
|
1008
|
+
},
|
|
1009
|
+
async stop(error) {
|
|
1010
|
+
ended = true;
|
|
1011
|
+
for (const waiter of await progress.stop())
|
|
1012
|
+
waiter.reject(error);
|
|
1013
|
+
},
|
|
1014
|
+
limits,
|
|
1015
|
+
output,
|
|
1016
|
+
progress
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
function boundResult(result, limits) {
|
|
1020
|
+
const content = result.output ?? [];
|
|
1021
|
+
const texts = content.filter((item) => item.type === "text");
|
|
1022
|
+
const bounded = boundOutput(texts.map((item) => item.text).join(""), limits);
|
|
1023
|
+
if (bounded.droppedBytes === 0)
|
|
1024
|
+
return result;
|
|
1025
|
+
const keep = limits.retain === "head" ? texts[0] : texts.at(-1);
|
|
1026
|
+
return {
|
|
1027
|
+
...result,
|
|
1028
|
+
output: content.flatMap((item) => item.type !== "text" ? [item] : item === keep ? [{ ...item, text: bounded.text }] : []),
|
|
1029
|
+
diagnostics: [
|
|
1030
|
+
...result.diagnostics ?? [],
|
|
1031
|
+
truncation(bounded, limits.retain)
|
|
1032
|
+
]
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
function truncation(dropped, retain) {
|
|
1036
|
+
const kept = retain === undefined ? "" : ` to its ${retain === "head" ? "beginning" : "end"}`;
|
|
1037
|
+
return {
|
|
1038
|
+
severity: "warn",
|
|
1039
|
+
code: "truncated",
|
|
1040
|
+
message: `Output truncated${kept}: ${dropped.droppedLines} lines, ${dropped.droppedBytes} bytes dropped`
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
// packages/execution/src/cell-tools.ts
|
|
1045
|
+
function cellTools(runtime, toolApi, registrations, nestedTask, controls, cancelTask, cellContext) {
|
|
1046
|
+
const tools = Object.create(null);
|
|
1047
|
+
for (const registration of registrations)
|
|
1048
|
+
tools[registration.name] = async (args, signal) => {
|
|
1049
|
+
signal?.throwIfAborted();
|
|
1050
|
+
const owner = await toolApi.snapshot(InvocationDoc, runtime.taskId, cellContext);
|
|
1051
|
+
const cellId = owner?.forwardingCellId;
|
|
1052
|
+
const position = controls.length;
|
|
1053
|
+
controls.push(undefined);
|
|
1054
|
+
const id = await toolApi.createTask(nestedTask, {
|
|
1055
|
+
name: registration.name,
|
|
1056
|
+
arguments: copyJson6(args),
|
|
1057
|
+
parent: { taskId: runtime.taskId, callId: toolApi.callId },
|
|
1058
|
+
...cellId === undefined ? {} : { cellId }
|
|
1059
|
+
}, {
|
|
1060
|
+
ownership: { kind: "task", taskId: runtime.taskId },
|
|
1061
|
+
abandonOnRestart: false
|
|
1062
|
+
}, cellContext);
|
|
1063
|
+
let cancelling;
|
|
1064
|
+
const cancel = () => {
|
|
1065
|
+
cancelling ??= cancelTask(id, withoutAbortSignal2(cellContext));
|
|
1066
|
+
cancelling.catch((error) => {
|
|
1067
|
+
if (!runtime.signal.aborted)
|
|
1068
|
+
runtime.report(error);
|
|
1069
|
+
});
|
|
1070
|
+
};
|
|
1071
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
1072
|
+
if (signal?.aborted)
|
|
1073
|
+
cancel();
|
|
1074
|
+
try {
|
|
1075
|
+
const settled = await runtime.waitForTask(id, cellContext);
|
|
1076
|
+
const result = readStoredResult(settled.state.outcome.result ?? executionError(settled.state.outcome.status, "Nested tool did not return a result"));
|
|
1077
|
+
controls[position] = result.control;
|
|
1078
|
+
await toolApi.commit(async (tx) => {
|
|
1079
|
+
const current = cellId === undefined ? undefined : (await tx.doc(InvocationDoc, cellId)).forwardedToolCalls?.calls.find((call) => call.callId === `nested-${id}`);
|
|
1080
|
+
if (current !== undefined)
|
|
1081
|
+
await forwardCall(tx, cellId, {
|
|
1082
|
+
...current,
|
|
1083
|
+
status: forwardedStatus(result, settled.state.outcome.status === "completed" ? "completed" : settled.state.outcome.status === "aborted" ? "aborted" : "failed"),
|
|
1084
|
+
result: displayResult(result, owner?.forwardingBudget ?? 40000),
|
|
1085
|
+
omittedFields: current.omittedFields.filter((field) => field !== "result")
|
|
1086
|
+
});
|
|
1087
|
+
}, cellContext);
|
|
1088
|
+
return { ...result, callId: `nested-${id}` };
|
|
1089
|
+
} finally {
|
|
1090
|
+
signal?.removeEventListener("abort", cancel);
|
|
1091
|
+
if (cancelling !== undefined)
|
|
1092
|
+
await cancelling;
|
|
1093
|
+
}
|
|
1094
|
+
};
|
|
1095
|
+
return tools;
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
// packages/execution/src/controls.ts
|
|
1099
|
+
function combineControls(controls, allowTermination = true) {
|
|
1100
|
+
const addTools = [
|
|
1101
|
+
...new Set(controls.flatMap((control) => control?.addTools ?? []))
|
|
1102
|
+
];
|
|
1103
|
+
const terminate = allowTermination && controls.some((control) => control?.terminate === true);
|
|
1104
|
+
const handoff = controls.find((control) => control?.handoff !== undefined)?.handoff;
|
|
1105
|
+
if (addTools.length === 0 && !terminate && handoff === undefined)
|
|
1106
|
+
return;
|
|
1107
|
+
return {
|
|
1108
|
+
...addTools.length === 0 ? {} : { addTools },
|
|
1109
|
+
...terminate ? { terminate: true } : {},
|
|
1110
|
+
...handoff === undefined ? {} : { handoff }
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
// packages/execution/src/tool-contract.ts
|
|
1115
|
+
import { copyJson as copyJson7 } from "@earendil-works/chord";
|
|
1116
|
+
var nestedToolDiscoveryGuidance = "Tools without a shown call signature: help is required only while their current arguments are unknown. Call with no arguments and read the result before composing an operation. Reuse known arguments without repeating help. Structured discovery uses {}";
|
|
1117
|
+
function readToolContract(tool) {
|
|
1118
|
+
const candidate = "executionHints" in tool ? tool.executionHints : undefined;
|
|
1119
|
+
if (candidate !== undefined && (candidate === null || typeof candidate !== "object" || Array.isArray(candidate))) {
|
|
1120
|
+
throw new Error(`Tool ${tool.name} executionHints must be an object`);
|
|
1121
|
+
}
|
|
1122
|
+
const hints = candidate ?? {};
|
|
1123
|
+
const supported = new Set([
|
|
1124
|
+
"usage",
|
|
1125
|
+
"output",
|
|
1126
|
+
"deferLoading",
|
|
1127
|
+
"yieldTimeMs",
|
|
1128
|
+
"inputSchema",
|
|
1129
|
+
"nativeOnly",
|
|
1130
|
+
"discovery"
|
|
1131
|
+
]);
|
|
1132
|
+
for (const key of Object.keys(hints))
|
|
1133
|
+
if (!supported.has(key))
|
|
1134
|
+
throw new Error(`Tool ${tool.name} executionHints has unsupported field ${key}`);
|
|
1135
|
+
const usageHint = "usage" in hints ? hints.usage : undefined;
|
|
1136
|
+
const discovery = "discovery" in hints ? hints.discovery : undefined;
|
|
1137
|
+
if (discovery !== undefined && discovery !== "help")
|
|
1138
|
+
throw new Error(`Tool ${tool.name} executionHints.discovery must be help`);
|
|
1139
|
+
const output = "output" in hints ? hints.output : undefined;
|
|
1140
|
+
for (const [field, value] of [
|
|
1141
|
+
["usage", usageHint],
|
|
1142
|
+
["output", output]
|
|
1143
|
+
]) {
|
|
1144
|
+
if (value !== undefined && (typeof value !== "string" || !value.trim()))
|
|
1145
|
+
throw new Error(`Tool ${tool.name} executionHints.${field} must be a non-empty string`);
|
|
1146
|
+
}
|
|
1147
|
+
const deferred = "deferLoading" in hints ? hints.deferLoading : undefined;
|
|
1148
|
+
if (deferred !== undefined && typeof deferred !== "boolean")
|
|
1149
|
+
throw new Error(`Tool ${tool.name} executionHints.deferLoading must be a boolean`);
|
|
1150
|
+
const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
|
|
1151
|
+
if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
|
|
1152
|
+
throw new Error(`Tool ${tool.name} executionHints.nativeOnly must be a boolean`);
|
|
1153
|
+
const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
|
|
1154
|
+
if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
|
|
1155
|
+
throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
|
|
1156
|
+
const inputSchema = "inputSchema" in hints && hints.inputSchema !== undefined ? copyJson7(hints.inputSchema) : copyJson7(JSON.parse(JSON.stringify(tool.parameters)));
|
|
1157
|
+
const reference = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(tool.name) ? `tools.${tool.name}` : `tools[${JSON.stringify(tool.name)}]`;
|
|
1158
|
+
const usage = typeof usageHint === "string" ? usageHint : `await ${reference}(${discovery === "help" ? "" : "args"})`;
|
|
1159
|
+
const outputHint = typeof output === "string" ? output : undefined;
|
|
1160
|
+
return {
|
|
1161
|
+
name: tool.name,
|
|
1162
|
+
...discovery === "help" ? { discovery } : {},
|
|
1163
|
+
description: tool.description,
|
|
1164
|
+
usage,
|
|
1165
|
+
prompt: discovery === "help" ? `${reference}: ${tool.description}` : usage,
|
|
1166
|
+
inputSchema,
|
|
1167
|
+
deferLoading: typeof deferred === "boolean" ? deferred : true,
|
|
1168
|
+
nativeOnly: nativeOnly === true,
|
|
1169
|
+
...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
|
|
1170
|
+
...outputHint === undefined ? {} : { output: outputHint },
|
|
1171
|
+
help: [
|
|
1172
|
+
`Usage: ${usage}`,
|
|
1173
|
+
tool.description,
|
|
1174
|
+
`Schema: ${JSON.stringify(inputSchema)}`,
|
|
1175
|
+
...outputHint === undefined ? [] : [`Output: ${outputHint}`]
|
|
1176
|
+
].filter(Boolean).join(`
|
|
1177
|
+
`)
|
|
1178
|
+
};
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
// packages/execution/src/cell-task.ts
|
|
1182
|
+
function yieldSignal() {
|
|
1183
|
+
let resolve;
|
|
1184
|
+
const promise = new Promise((yes) => {
|
|
1185
|
+
resolve = yes;
|
|
1186
|
+
});
|
|
1187
|
+
return { promise, resolve };
|
|
1188
|
+
}
|
|
1189
|
+
function createCellTask(options, nestedTask) {
|
|
1190
|
+
let closed = false;
|
|
1191
|
+
let closing;
|
|
1192
|
+
const active = new Map;
|
|
1193
|
+
const yields = new Map;
|
|
1194
|
+
const yieldState = (id) => {
|
|
1195
|
+
let state = yields.get(id);
|
|
1196
|
+
if (state === undefined) {
|
|
1197
|
+
state = { yielded: false, wake: yieldSignal() };
|
|
1198
|
+
yields.set(id, state);
|
|
1199
|
+
}
|
|
1200
|
+
return state;
|
|
1201
|
+
};
|
|
1202
|
+
const excluded = new Set(options.surfaceTools.filter((name) => !options.callableSurfaceTools?.includes(name)));
|
|
1203
|
+
const task = defineTask({
|
|
1204
|
+
name: `howaboua.execution.cell.${options.name}`,
|
|
1205
|
+
version: 1,
|
|
1206
|
+
initial: () => ({ phase: "start" }),
|
|
1207
|
+
phases: {
|
|
1208
|
+
start: async (record, runtime, context) => {
|
|
1209
|
+
await runtime.commit(async (tx) => {
|
|
1210
|
+
await tx.doc(InvocationDoc, runtime.taskId);
|
|
1211
|
+
return { status: "running", checkpoint: { phase: "execute" } };
|
|
1212
|
+
}, context);
|
|
1213
|
+
const controller = new AbortController;
|
|
1214
|
+
const running = { controller, done: yieldSignal() };
|
|
1215
|
+
const yielding = yieldState(runtime.taskId);
|
|
1216
|
+
active.set(runtime.taskId, running);
|
|
1217
|
+
const signal = AbortSignal.any([runtime.signal, controller.signal]);
|
|
1218
|
+
const cellContext = withAbortSignal(signal, context);
|
|
1219
|
+
let invocation;
|
|
1220
|
+
let ending = "completed";
|
|
1221
|
+
let result;
|
|
1222
|
+
const controls = [];
|
|
1223
|
+
try {
|
|
1224
|
+
if (closed)
|
|
1225
|
+
throw new Error("Execution host is closed");
|
|
1226
|
+
invocation = createInvocation(runtime, {}, cellContext);
|
|
1227
|
+
const registrations = (await runtime.agent(cellContext)).callable.filter((tool) => !excluded.has(tool.name) && !readToolContract(tool).nativeOnly);
|
|
1228
|
+
const toolApi = await invocation.executionApi();
|
|
1229
|
+
const tools = cellTools(runtime, toolApi, registrations, nestedTask, controls, options.cancelTask, cellContext);
|
|
1230
|
+
const api = {
|
|
1231
|
+
taskId: runtime.taskId,
|
|
1232
|
+
conversationId: runtime.conversationId,
|
|
1233
|
+
signal,
|
|
1234
|
+
toolApi,
|
|
1235
|
+
registrations,
|
|
1236
|
+
tools,
|
|
1237
|
+
publish: async (value, publishContext) => {
|
|
1238
|
+
const result = storeResult(value);
|
|
1239
|
+
await runtime.commit(async (tx) => {
|
|
1240
|
+
(await tx.doc(InvocationDoc, runtime.taskId)).result = result;
|
|
1241
|
+
return;
|
|
1242
|
+
}, publishContext);
|
|
1243
|
+
},
|
|
1244
|
+
requestYield: async (yieldContext) => {
|
|
1245
|
+
await runtime.commit(async (tx) => {
|
|
1246
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1247
|
+
doc.yieldCount = (doc.yieldCount ?? 0) + 1;
|
|
1248
|
+
return;
|
|
1249
|
+
}, yieldContext);
|
|
1250
|
+
yielding.yielded = true;
|
|
1251
|
+
yielding.wake.resolve();
|
|
1252
|
+
yielding.wake = yieldSignal();
|
|
1253
|
+
},
|
|
1254
|
+
checkpoint: async (value, checkpointContext) => {
|
|
1255
|
+
const checkpoint = copyJson8(value);
|
|
1256
|
+
await runtime.commit(async (tx) => {
|
|
1257
|
+
(await tx.doc(InvocationDoc, runtime.taskId)).checkpoint = checkpoint;
|
|
1258
|
+
return;
|
|
1259
|
+
}, checkpointContext);
|
|
1260
|
+
}
|
|
1261
|
+
};
|
|
1262
|
+
result = await options.engine.run(record.input, api, cellContext);
|
|
1263
|
+
signal.throwIfAborted();
|
|
1264
|
+
} catch (error) {
|
|
1265
|
+
if (runtime.signal.aborted) {
|
|
1266
|
+
await invocation?.stop(error);
|
|
1267
|
+
throw error;
|
|
1268
|
+
}
|
|
1269
|
+
const partial = await runtime.snapshot(InvocationDoc, runtime.taskId, context);
|
|
1270
|
+
result = {
|
|
1271
|
+
...partial?.result ?? {},
|
|
1272
|
+
isError: true,
|
|
1273
|
+
diagnostics: [
|
|
1274
|
+
...partial?.result.diagnostics ?? [],
|
|
1275
|
+
{
|
|
1276
|
+
severity: "error",
|
|
1277
|
+
code: "cell_error",
|
|
1278
|
+
message: errorText(error)
|
|
1279
|
+
}
|
|
1280
|
+
]
|
|
1281
|
+
};
|
|
1282
|
+
ending = "failed";
|
|
1283
|
+
} finally {
|
|
1284
|
+
if (runtime.signal.aborted) {
|
|
1285
|
+
active.delete(runtime.taskId);
|
|
1286
|
+
yields.delete(runtime.taskId);
|
|
1287
|
+
running.done.resolve();
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
let finished;
|
|
1291
|
+
try {
|
|
1292
|
+
finished = await invocation?.finish(result);
|
|
1293
|
+
const finalResult = finished?.result ?? result;
|
|
1294
|
+
const control = combineControls([...controls, finalResult.control], ending === "completed" && !finalResult.isError);
|
|
1295
|
+
const { control: _driverControl, ...withoutControl } = finalResult;
|
|
1296
|
+
const final = control === undefined ? withoutControl : { ...withoutControl, control };
|
|
1297
|
+
await runtime.commit(async (tx) => {
|
|
1298
|
+
(await tx.doc(InvocationDoc, runtime.taskId)).result = storeResult(final);
|
|
1299
|
+
Object.assign(await tx.doc(CellStateDoc, runtime.conversationId, String(runtime.taskId), null), await tx.doc(InvocationDoc, runtime.taskId));
|
|
1300
|
+
return {
|
|
1301
|
+
status: "terminal",
|
|
1302
|
+
outcome: ending === "completed" ? { status: "completed", result: final } : {
|
|
1303
|
+
status: "failed",
|
|
1304
|
+
error: { message: "Cell execution failed" },
|
|
1305
|
+
result: final
|
|
1306
|
+
}
|
|
1307
|
+
};
|
|
1308
|
+
}, context);
|
|
1309
|
+
for (const waiter of finished?.pending ?? [])
|
|
1310
|
+
waiter.resolve();
|
|
1311
|
+
} catch (error) {
|
|
1312
|
+
for (const waiter of finished?.pending ?? [])
|
|
1313
|
+
waiter.reject(error);
|
|
1314
|
+
throw error;
|
|
1315
|
+
} finally {
|
|
1316
|
+
active.delete(runtime.taskId);
|
|
1317
|
+
yields.delete(runtime.taskId);
|
|
1318
|
+
running.done.resolve();
|
|
1319
|
+
}
|
|
1320
|
+
},
|
|
1321
|
+
execute: async (_record, runtime, context) => {
|
|
1322
|
+
await cleanupNativeCalls(runtime, context);
|
|
1323
|
+
await runtime.commit(async (tx) => {
|
|
1324
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1325
|
+
const error = executionError("interrupted", "Cell was interrupted and may have partially run. Code was not replayed");
|
|
1326
|
+
const result = {
|
|
1327
|
+
...doc.result,
|
|
1328
|
+
isError: true,
|
|
1329
|
+
diagnostics: [
|
|
1330
|
+
...doc.result.diagnostics ?? [],
|
|
1331
|
+
...error.diagnostics ?? []
|
|
1332
|
+
]
|
|
1333
|
+
};
|
|
1334
|
+
doc.result = storeResult(result);
|
|
1335
|
+
Object.assign(await tx.doc(CellStateDoc, runtime.conversationId, String(runtime.taskId), null), doc);
|
|
1336
|
+
return {
|
|
1337
|
+
status: "terminal",
|
|
1338
|
+
outcome: {
|
|
1339
|
+
status: "failed",
|
|
1340
|
+
error: { message: "Cell was interrupted" },
|
|
1341
|
+
result
|
|
1342
|
+
}
|
|
1343
|
+
};
|
|
1344
|
+
}, context);
|
|
1345
|
+
}
|
|
1346
|
+
},
|
|
1347
|
+
abort: async (_record, runtime, context) => {
|
|
1348
|
+
await cleanupNativeCalls(runtime, context);
|
|
1349
|
+
await runtime.commit(async (tx) => {
|
|
1350
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1351
|
+
const error = executionError("aborted", "Cell was aborted");
|
|
1352
|
+
const result = {
|
|
1353
|
+
...doc.result,
|
|
1354
|
+
isError: true,
|
|
1355
|
+
diagnostics: [
|
|
1356
|
+
...doc.result.diagnostics ?? [],
|
|
1357
|
+
...error.diagnostics ?? []
|
|
1358
|
+
]
|
|
1359
|
+
};
|
|
1360
|
+
doc.result = storeResult(result);
|
|
1361
|
+
Object.assign(await tx.doc(CellStateDoc, runtime.conversationId, String(runtime.taskId), null), doc);
|
|
1362
|
+
return { status: "terminal", outcome: { status: "aborted", result } };
|
|
1363
|
+
}, context);
|
|
1364
|
+
}
|
|
1365
|
+
});
|
|
1366
|
+
return {
|
|
1367
|
+
task,
|
|
1368
|
+
get closed() {
|
|
1369
|
+
return closed;
|
|
1370
|
+
},
|
|
1371
|
+
observeYield(id) {
|
|
1372
|
+
const yielding = yieldState(id);
|
|
1373
|
+
return {
|
|
1374
|
+
wake: yielding.wake.promise,
|
|
1375
|
+
consume() {
|
|
1376
|
+
const yielded = yielding.yielded;
|
|
1377
|
+
yielding.yielded = false;
|
|
1378
|
+
return yielded;
|
|
1379
|
+
}
|
|
1380
|
+
};
|
|
1381
|
+
},
|
|
1382
|
+
close() {
|
|
1383
|
+
if (closing !== undefined)
|
|
1384
|
+
return closing;
|
|
1385
|
+
closed = true;
|
|
1386
|
+
const invocations = [...active.values()];
|
|
1387
|
+
for (const running of invocations)
|
|
1388
|
+
running.controller.abort(new Error("Execution host closed"));
|
|
1389
|
+
closing = Promise.all([
|
|
1390
|
+
options.engine.close(),
|
|
1391
|
+
...invocations.map((running) => running.done.promise)
|
|
1392
|
+
]).then(() => {
|
|
1393
|
+
return;
|
|
1394
|
+
});
|
|
1395
|
+
return closing;
|
|
1396
|
+
}
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
// packages/execution/src/forwarding-hook.ts
|
|
1401
|
+
import {
|
|
1402
|
+
hook,
|
|
1403
|
+
LiveDoc as LiveDoc4,
|
|
1404
|
+
ToolTask as ToolTask3
|
|
1405
|
+
} from "@earendil-works/pi-durable";
|
|
1406
|
+
function forwardingHook() {
|
|
1407
|
+
let host;
|
|
1408
|
+
return {
|
|
1409
|
+
bind(harness) {
|
|
1410
|
+
if (host !== undefined && host !== harness)
|
|
1411
|
+
throw new Error("Create a separate execution component for each Harness");
|
|
1412
|
+
host = harness;
|
|
1413
|
+
},
|
|
1414
|
+
hook: hook(ToolTask3, {
|
|
1415
|
+
async beforeTool(call, api, context) {
|
|
1416
|
+
const parent = call.parent;
|
|
1417
|
+
if (parent === undefined || host === undefined)
|
|
1418
|
+
return;
|
|
1419
|
+
const source = await api.snapshot(InvocationDoc, parent.taskId, context);
|
|
1420
|
+
const cellId = source?.forwardingCellId;
|
|
1421
|
+
if (cellId === undefined)
|
|
1422
|
+
return;
|
|
1423
|
+
const conversation = await host.conversation(api.conversationId, context);
|
|
1424
|
+
if (conversation === undefined)
|
|
1425
|
+
throw new Error("Forwarded call conversation is unavailable");
|
|
1426
|
+
await conversation.commit(async (tx) => {
|
|
1427
|
+
if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
|
|
1428
|
+
return;
|
|
1429
|
+
const owner = await tx.doc(InvocationDoc, api.taskId);
|
|
1430
|
+
const admission = owner.forwardingCellId === undefined;
|
|
1431
|
+
owner.forwardingCellId = cellId;
|
|
1432
|
+
await forwardCall(tx, cellId, {
|
|
1433
|
+
callId: call.id,
|
|
1434
|
+
parentCallId: parent.callId,
|
|
1435
|
+
name: call.name,
|
|
1436
|
+
arguments: call.arguments,
|
|
1437
|
+
status: "pending",
|
|
1438
|
+
result: null,
|
|
1439
|
+
omittedFields: []
|
|
1440
|
+
}, admission, { taskId: api.taskId, ownerTaskId: parent.taskId });
|
|
1441
|
+
}, context);
|
|
1442
|
+
},
|
|
1443
|
+
async afterTool(call, result, api, context) {
|
|
1444
|
+
const parent = call.parent;
|
|
1445
|
+
if (parent === undefined || host === undefined)
|
|
1446
|
+
return;
|
|
1447
|
+
const source = await api.snapshot(InvocationDoc, api.taskId, context);
|
|
1448
|
+
if (source?.forwardingCellId === undefined)
|
|
1449
|
+
return;
|
|
1450
|
+
const conversation = await host.conversation(api.conversationId, context);
|
|
1451
|
+
if (conversation === undefined)
|
|
1452
|
+
throw new Error("Forwarded call conversation is unavailable");
|
|
1453
|
+
await conversation.commit(async (tx) => {
|
|
1454
|
+
if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
|
|
1455
|
+
return;
|
|
1456
|
+
const owner = await tx.doc(InvocationDoc, api.taskId);
|
|
1457
|
+
const cellId = owner.forwardingCellId;
|
|
1458
|
+
if (cellId === undefined)
|
|
1459
|
+
return;
|
|
1460
|
+
await captureNativeCalls(tx, api.conversationId, api.taskId, cellId);
|
|
1461
|
+
const slot = (await tx.doc(LiveDoc4, api.conversationId)).nestedTools?.find((slot) => slot.callId === call.id);
|
|
1462
|
+
const cell = await tx.doc(InvocationDoc, cellId);
|
|
1463
|
+
await forwardCall(tx, cellId, {
|
|
1464
|
+
callId: call.id,
|
|
1465
|
+
parentCallId: parent.callId,
|
|
1466
|
+
name: call.name,
|
|
1467
|
+
arguments: slot?.arguments ?? call.arguments,
|
|
1468
|
+
status: "completed",
|
|
1469
|
+
result: displayResult(result, cell.forwardingBudget ?? 40000),
|
|
1470
|
+
omittedFields: []
|
|
1471
|
+
});
|
|
1472
|
+
}, context);
|
|
1473
|
+
}
|
|
1474
|
+
})
|
|
1475
|
+
};
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
// packages/execution/src/nested.ts
|
|
1479
|
+
import {
|
|
1480
|
+
defineTask as defineTask2
|
|
1481
|
+
} from "@earendil-works/pi-durable";
|
|
1482
|
+
import { compile as compile2 } from "@earendil-works/pi-schema";
|
|
1483
|
+
|
|
1484
|
+
// packages/execution/src/nested-call.ts
|
|
1485
|
+
import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
|
|
1486
|
+
import {
|
|
1487
|
+
ToolTask as ToolTask4
|
|
1488
|
+
} from "@earendil-works/pi-durable";
|
|
1489
|
+
import { compile } from "@earendil-works/pi-schema";
|
|
1490
|
+
function nestedCall(runtime, input) {
|
|
1491
|
+
const args = input.arguments;
|
|
1492
|
+
return {
|
|
1493
|
+
type: "toolCall",
|
|
1494
|
+
id: `nested-${runtime.taskId}`,
|
|
1495
|
+
name: input.name,
|
|
1496
|
+
...input.parent === undefined ? {} : { parent: input.parent },
|
|
1497
|
+
arguments: args !== null && typeof args === "object" && !Array.isArray(args) ? args : {}
|
|
1498
|
+
};
|
|
1499
|
+
}
|
|
1500
|
+
function checked(tool, call, args) {
|
|
1501
|
+
return validateToolArguments(tool, {
|
|
1502
|
+
...call,
|
|
1503
|
+
arguments: args
|
|
1504
|
+
});
|
|
1505
|
+
}
|
|
1506
|
+
function prepareNestedInput(tool, input) {
|
|
1507
|
+
if (typeof input !== "string")
|
|
1508
|
+
return input;
|
|
1509
|
+
const contract = readToolContract(tool);
|
|
1510
|
+
if (Boolean(compile(tool.parameters).check(input)) || (typeof contract.inputSchema === "boolean" || typeof contract.inputSchema === "object" && contract.inputSchema !== null && !Array.isArray(contract.inputSchema)) && Boolean(compile(contract.inputSchema).check(input)))
|
|
1511
|
+
return input;
|
|
1512
|
+
const text = input.trim();
|
|
1513
|
+
if (contract.discovery === "help" && text === "help")
|
|
1514
|
+
return {};
|
|
1515
|
+
let parsed;
|
|
1516
|
+
try {
|
|
1517
|
+
parsed = JSON.parse(text);
|
|
1518
|
+
} catch {
|
|
1519
|
+
if (tool.prepareArguments !== undefined)
|
|
1520
|
+
return input;
|
|
1521
|
+
throw new Error(`Invalid ${tool.name} arguments; use a structured request or valid JSON`);
|
|
1522
|
+
}
|
|
1523
|
+
if (parsed === null || typeof parsed !== "object") {
|
|
1524
|
+
if (tool.prepareArguments !== undefined)
|
|
1525
|
+
return input;
|
|
1526
|
+
throw new Error(`Invalid ${tool.name} arguments; use a structured request or JSON object or array`);
|
|
1527
|
+
}
|
|
1528
|
+
return parsed;
|
|
1529
|
+
}
|
|
1530
|
+
async function eachHook(agent, name, api, invoke) {
|
|
1531
|
+
for (const extension of agent.extensions)
|
|
1532
|
+
for (const registration of extension.hooks ?? []) {
|
|
1533
|
+
if (registration.task !== ToolTask4.definition.name)
|
|
1534
|
+
continue;
|
|
1535
|
+
const handler = registration.handlers[name];
|
|
1536
|
+
if (handler === undefined)
|
|
1537
|
+
continue;
|
|
1538
|
+
try {
|
|
1539
|
+
await invoke(handler);
|
|
1540
|
+
} catch (error) {
|
|
1541
|
+
if (api.signal.aborted)
|
|
1542
|
+
throw error;
|
|
1543
|
+
api.report(error);
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
// packages/execution/src/nested-result.ts
|
|
1549
|
+
import { copyJson as copyJson9 } from "@earendil-works/chord";
|
|
1550
|
+
import {
|
|
1551
|
+
defineEntry,
|
|
1552
|
+
UsageDoc
|
|
1553
|
+
} from "@earendil-works/pi-durable";
|
|
1554
|
+
var NestedResultEntry = defineEntry("howaboua.execution.nested-result");
|
|
1555
|
+
async function interrupted(runtime, call, code, message, context) {
|
|
1556
|
+
await cleanupNativeCalls(runtime, context);
|
|
1557
|
+
const state = await runtime.snapshot(InvocationDoc, runtime.taskId, context);
|
|
1558
|
+
const partial = state?.result ?? {};
|
|
1559
|
+
const diagnostics = [...partial.diagnostics ?? []];
|
|
1560
|
+
if ((state?.droppedBytes ?? 0) > 0)
|
|
1561
|
+
diagnostics.push(truncation({
|
|
1562
|
+
droppedBytes: state?.droppedBytes ?? 0,
|
|
1563
|
+
droppedLines: state?.droppedLines ?? 0
|
|
1564
|
+
}));
|
|
1565
|
+
await settle(runtime, call, {
|
|
1566
|
+
...partial,
|
|
1567
|
+
isError: true,
|
|
1568
|
+
diagnostics: [
|
|
1569
|
+
...diagnostics,
|
|
1570
|
+
...executionError(code, message).diagnostics ?? []
|
|
1571
|
+
]
|
|
1572
|
+
}, code === "aborted" ? "aborted" : "failed", context);
|
|
1573
|
+
}
|
|
1574
|
+
async function settle(runtime, call, result, ending, context) {
|
|
1575
|
+
const stored = storeResult(result);
|
|
1576
|
+
await runtime.commit(async (tx, current) => {
|
|
1577
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1578
|
+
if (doc.forwardingCellId === undefined && current.input.cellId !== undefined) {
|
|
1579
|
+
doc.forwardingCellId = current.input.cellId;
|
|
1580
|
+
await forwardCall(tx, current.input.cellId, {
|
|
1581
|
+
callId: call.id,
|
|
1582
|
+
parentCallId: current.input.parent?.callId ?? `nested-${current.input.cellId}`,
|
|
1583
|
+
name: call.name,
|
|
1584
|
+
arguments: current.input.arguments,
|
|
1585
|
+
status: "pending",
|
|
1586
|
+
result: null,
|
|
1587
|
+
omittedFields: []
|
|
1588
|
+
}, true);
|
|
1589
|
+
}
|
|
1590
|
+
doc.result = stored;
|
|
1591
|
+
await forwardInvocationResult(tx, runtime.taskId, result, ending);
|
|
1592
|
+
await tx.appendEntry(NestedResultEntry, runtime.conversationId, {
|
|
1593
|
+
data: {
|
|
1594
|
+
taskId: runtime.taskId,
|
|
1595
|
+
callId: call.id,
|
|
1596
|
+
name: call.name,
|
|
1597
|
+
arguments: copyJson9(call.arguments),
|
|
1598
|
+
result: stored,
|
|
1599
|
+
...current.state.checkpoint.phase === "execute" ? {
|
|
1600
|
+
intent: {
|
|
1601
|
+
arguments: copyJson9(current.state.checkpoint.arguments),
|
|
1602
|
+
replay: current.state.checkpoint.replay
|
|
1603
|
+
}
|
|
1604
|
+
} : {}
|
|
1605
|
+
}
|
|
1606
|
+
});
|
|
1607
|
+
if (result.usage !== undefined) {
|
|
1608
|
+
const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
|
|
1609
|
+
const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
|
|
1610
|
+
totals[call.name] = copyJson9(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
|
|
1611
|
+
}
|
|
1612
|
+
const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
|
|
1613
|
+
status: ending,
|
|
1614
|
+
error: {
|
|
1615
|
+
message: `Tool ${call.name} ${result.diagnostics?.at(-1)?.code === "interrupted" ? "was interrupted" : "threw"}`
|
|
1616
|
+
},
|
|
1617
|
+
result: stored
|
|
1618
|
+
};
|
|
1619
|
+
return { status: "terminal", outcome };
|
|
1620
|
+
}, context);
|
|
1621
|
+
}
|
|
1622
|
+
function sumUsage(previous, added) {
|
|
1623
|
+
return {
|
|
1624
|
+
input: previous.input + added.input,
|
|
1625
|
+
output: previous.output + added.output,
|
|
1626
|
+
cacheRead: previous.cacheRead + added.cacheRead,
|
|
1627
|
+
cacheWrite: previous.cacheWrite + added.cacheWrite,
|
|
1628
|
+
totalTokens: previous.totalTokens + added.totalTokens,
|
|
1629
|
+
...previous.cacheWrite1h === undefined && added.cacheWrite1h === undefined ? {} : {
|
|
1630
|
+
cacheWrite1h: (previous.cacheWrite1h ?? 0) + (added.cacheWrite1h ?? 0)
|
|
1631
|
+
},
|
|
1632
|
+
...previous.reasoning === undefined && added.reasoning === undefined ? {} : { reasoning: (previous.reasoning ?? 0) + (added.reasoning ?? 0) },
|
|
1633
|
+
cost: {
|
|
1634
|
+
input: previous.cost.input + added.cost.input,
|
|
1635
|
+
output: previous.cost.output + added.cost.output,
|
|
1636
|
+
cacheRead: previous.cost.cacheRead + added.cost.cacheRead,
|
|
1637
|
+
cacheWrite: previous.cost.cacheWrite + added.cost.cacheWrite,
|
|
1638
|
+
total: previous.cost.total + added.cost.total
|
|
1639
|
+
}
|
|
1640
|
+
};
|
|
1641
|
+
}
|
|
1642
|
+
|
|
1643
|
+
// packages/execution/src/nested.ts
|
|
1644
|
+
function createNestedToolTask(name) {
|
|
1645
|
+
return defineTask2({
|
|
1646
|
+
name,
|
|
1647
|
+
version: 1,
|
|
1648
|
+
initial: () => ({ phase: "call" }),
|
|
1649
|
+
phases: {
|
|
1650
|
+
call: async (task, runtime, context) => {
|
|
1651
|
+
const call = nestedCall(runtime, task.input);
|
|
1652
|
+
await runtime.commit(async (tx) => {
|
|
1653
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1654
|
+
if (task.input.cellId !== undefined)
|
|
1655
|
+
doc.forwardingCellId = task.input.cellId;
|
|
1656
|
+
await forwardCall(tx, task.input.cellId, {
|
|
1657
|
+
callId: call.id,
|
|
1658
|
+
parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
|
|
1659
|
+
name: call.name,
|
|
1660
|
+
arguments: task.input.arguments,
|
|
1661
|
+
status: "pending",
|
|
1662
|
+
result: null,
|
|
1663
|
+
omittedFields: []
|
|
1664
|
+
}, true);
|
|
1665
|
+
return;
|
|
1666
|
+
}, context);
|
|
1667
|
+
const agent = await runtime.agent(context);
|
|
1668
|
+
const tool = agent.callable.find((each) => each.name === call.name);
|
|
1669
|
+
if (tool === undefined || readToolContract(tool).nativeOnly)
|
|
1670
|
+
return reject(runtime, call, executionError("tool_unavailable", `Tool ${call.name} is not available`), agent, tool, context);
|
|
1671
|
+
let args;
|
|
1672
|
+
try {
|
|
1673
|
+
const supplied = task.input.arguments === null && !compile2(tool.parameters).check(null) && compile2(tool.parameters).check({}) ? undefined : task.input.arguments;
|
|
1674
|
+
const prepared = tool.prepareArguments === undefined ? prepareNestedInput(tool, supplied) : tool.prepareArguments(prepareNestedInput(tool, supplied));
|
|
1675
|
+
args = checked(tool, call, prepared === undefined && compile2(tool.parameters).check({}) ? {} : prepared);
|
|
1676
|
+
if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
|
|
1677
|
+
call.arguments = args;
|
|
1678
|
+
} catch (error) {
|
|
1679
|
+
return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
|
|
1680
|
+
}
|
|
1681
|
+
let block;
|
|
1682
|
+
await eachHook(agent, "beforeTool", runtime, async (handler) => {
|
|
1683
|
+
if (block !== undefined)
|
|
1684
|
+
return;
|
|
1685
|
+
try {
|
|
1686
|
+
const decision = await handler({ ...call, arguments: args }, runtime, context);
|
|
1687
|
+
if (decision?.block !== undefined)
|
|
1688
|
+
block = decision.block;
|
|
1689
|
+
else if (decision?.arguments !== undefined)
|
|
1690
|
+
args = decision.arguments;
|
|
1691
|
+
} catch (error) {
|
|
1692
|
+
if (runtime.signal.aborted)
|
|
1693
|
+
throw error;
|
|
1694
|
+
block = errorText(error);
|
|
1695
|
+
}
|
|
1696
|
+
});
|
|
1697
|
+
if (block !== undefined)
|
|
1698
|
+
return reject(runtime, call, executionError("blocked", `Tool call blocked: ${block}`), agent, tool, context);
|
|
1699
|
+
try {
|
|
1700
|
+
args = checked(tool, call, args);
|
|
1701
|
+
} catch (error) {
|
|
1702
|
+
return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
|
|
1703
|
+
}
|
|
1704
|
+
await runtime.commit(async (tx) => {
|
|
1705
|
+
await tx.doc(InvocationDoc, runtime.taskId);
|
|
1706
|
+
await forwardCall(tx, task.input.cellId, {
|
|
1707
|
+
callId: call.id,
|
|
1708
|
+
parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
|
|
1709
|
+
name: call.name,
|
|
1710
|
+
arguments: args,
|
|
1711
|
+
status: "running",
|
|
1712
|
+
result: null,
|
|
1713
|
+
omittedFields: []
|
|
1714
|
+
});
|
|
1715
|
+
return {
|
|
1716
|
+
status: "running",
|
|
1717
|
+
checkpoint: {
|
|
1718
|
+
phase: "execute",
|
|
1719
|
+
arguments: args,
|
|
1720
|
+
replay: tool.replay ?? "unsafe"
|
|
1721
|
+
}
|
|
1722
|
+
};
|
|
1723
|
+
}, context);
|
|
1724
|
+
await run(runtime, call, tool, args, agent, context);
|
|
1725
|
+
},
|
|
1726
|
+
execute: async (task, runtime, context) => {
|
|
1727
|
+
const call = nestedCall(runtime, task.input);
|
|
1728
|
+
if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
|
|
1729
|
+
call.arguments = task.state.checkpoint.arguments;
|
|
1730
|
+
const agent = await runtime.agent(context);
|
|
1731
|
+
const tool = agent.callable.find((each) => each.name === call.name);
|
|
1732
|
+
if (task.state.checkpoint.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
|
|
1733
|
+
await runtime.commit(async (tx) => {
|
|
1734
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1735
|
+
doc.result = {};
|
|
1736
|
+
doc.droppedBytes = 0;
|
|
1737
|
+
doc.droppedLines = 0;
|
|
1738
|
+
return;
|
|
1739
|
+
}, context);
|
|
1740
|
+
return run(runtime, call, tool, task.state.checkpoint.arguments, agent, context);
|
|
1741
|
+
}
|
|
1742
|
+
await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
|
|
1743
|
+
}
|
|
1744
|
+
},
|
|
1745
|
+
abort: async (task, runtime, context) => {
|
|
1746
|
+
const call = nestedCall(runtime, task.input);
|
|
1747
|
+
await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
|
|
1748
|
+
}
|
|
1749
|
+
});
|
|
1750
|
+
}
|
|
1751
|
+
async function reject(runtime, call, result, agent, tool, context) {
|
|
1752
|
+
await eachHook(agent, "afterTool", runtime, async (handler) => {
|
|
1753
|
+
result = await handler(call, result, runtime, context) ?? result;
|
|
1754
|
+
});
|
|
1755
|
+
await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
|
|
1756
|
+
}
|
|
1757
|
+
async function run(runtime, call, tool, args, agent, context) {
|
|
1758
|
+
let invocation;
|
|
1759
|
+
let result;
|
|
1760
|
+
let ending = "completed";
|
|
1761
|
+
try {
|
|
1762
|
+
invocation = createInvocation(runtime, tool, context);
|
|
1763
|
+
result = await tool.execute(args, await invocation.executionApi(), context);
|
|
1764
|
+
} catch (error) {
|
|
1765
|
+
if (runtime.signal.aborted) {
|
|
1766
|
+
await invocation?.stop(error);
|
|
1767
|
+
throw error;
|
|
1768
|
+
}
|
|
1769
|
+
result = {
|
|
1770
|
+
isError: true,
|
|
1771
|
+
diagnostics: [
|
|
1772
|
+
{ severity: "error", code: "tool_error", message: errorText(error) }
|
|
1773
|
+
]
|
|
1774
|
+
};
|
|
1775
|
+
ending = "failed";
|
|
1776
|
+
}
|
|
1777
|
+
const finished = await invocation?.finish(result);
|
|
1778
|
+
let final = finished?.result ?? result;
|
|
1779
|
+
await eachHook(agent, "afterTool", runtime, async (handler) => {
|
|
1780
|
+
final = await handler(call, final, runtime, context) ?? final;
|
|
1781
|
+
});
|
|
1782
|
+
if (finished !== undefined && result.output === undefined && finished.retained.droppedBytes > 0 && final.output === finished.content) {
|
|
1783
|
+
final = {
|
|
1784
|
+
...final,
|
|
1785
|
+
diagnostics: [
|
|
1786
|
+
...final.diagnostics ?? [],
|
|
1787
|
+
truncation(finished.retained, invocation?.limits.retain)
|
|
1788
|
+
]
|
|
1789
|
+
};
|
|
1790
|
+
}
|
|
1791
|
+
final = finishResult(tool, call.name, final);
|
|
1792
|
+
try {
|
|
1793
|
+
await settle(runtime, call, final, ending, context);
|
|
1794
|
+
for (const waiter of finished?.pending ?? [])
|
|
1795
|
+
waiter.resolve();
|
|
1796
|
+
} catch (error) {
|
|
1797
|
+
for (const waiter of finished?.pending ?? [])
|
|
1798
|
+
waiter.reject(error);
|
|
1799
|
+
throw error;
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
function finishResult(tool, name, result) {
|
|
1803
|
+
let final = boundResult(result, {
|
|
1804
|
+
maxBytes: tool?.outputLimits?.maxBytes ?? 50 * 1024,
|
|
1805
|
+
maxLines: tool?.outputLimits?.maxLines ?? 2000,
|
|
1806
|
+
retain: tool?.outputLimits?.retain ?? "head"
|
|
1807
|
+
});
|
|
1808
|
+
try {
|
|
1809
|
+
if (tool?.structuredOutputSchema === undefined) {
|
|
1810
|
+
if (final.structuredOutput !== undefined)
|
|
1811
|
+
throw new Error(`Tool ${name} returned structuredOutput but declares no structuredOutputSchema`);
|
|
1812
|
+
} else if (final.structuredOutput === undefined) {
|
|
1813
|
+
if (!final.isError)
|
|
1814
|
+
throw new Error(`Tool ${name} returned no structuredOutput`);
|
|
1815
|
+
} else if (!compile2(tool.structuredOutputSchema).check(final.structuredOutput)) {
|
|
1816
|
+
throw new Error(`Tool ${name} returned structuredOutput that does not match its schema`);
|
|
1817
|
+
}
|
|
1818
|
+
} catch (error) {
|
|
1819
|
+
const { structuredOutput: _invalid, ...rest } = final;
|
|
1820
|
+
final = {
|
|
1821
|
+
...rest,
|
|
1822
|
+
isError: true,
|
|
1823
|
+
diagnostics: [
|
|
1824
|
+
...rest.diagnostics ?? [],
|
|
1825
|
+
{
|
|
1826
|
+
severity: "error",
|
|
1827
|
+
code: "invalid_structured_output",
|
|
1828
|
+
message: errorText(error)
|
|
1829
|
+
}
|
|
1830
|
+
]
|
|
1831
|
+
};
|
|
1832
|
+
}
|
|
1833
|
+
return final;
|
|
1834
|
+
}
|
|
1835
|
+
|
|
1836
|
+
// packages/execution/src/projection.ts
|
|
1837
|
+
import { GenerationTask, hook as hook2 } from "@earendil-works/pi-durable";
|
|
1838
|
+
function projectToolSchemas(messages, visible) {
|
|
1839
|
+
return messages.map((message) => message.role !== "system" ? message : {
|
|
1840
|
+
...message,
|
|
1841
|
+
...message.toolsAdded === undefined ? {} : {
|
|
1842
|
+
toolsAdded: message.toolsAdded.filter((tool) => visible.has(tool.name))
|
|
1843
|
+
},
|
|
1844
|
+
...message.toolsRemoved === undefined ? {} : {
|
|
1845
|
+
toolsRemoved: message.toolsRemoved.filter((tool) => visible.has(tool.name))
|
|
1846
|
+
}
|
|
1847
|
+
});
|
|
1848
|
+
}
|
|
1849
|
+
function providerProjection(surfaceTools) {
|
|
1850
|
+
let host;
|
|
1851
|
+
return {
|
|
1852
|
+
bind(harness) {
|
|
1853
|
+
if (host !== undefined && host !== harness)
|
|
1854
|
+
throw new Error("Create a separate execution component for each Harness");
|
|
1855
|
+
host = harness;
|
|
1856
|
+
},
|
|
1857
|
+
hook: hook2(GenerationTask, {
|
|
1858
|
+
beforeRequest: async (request, api, context) => {
|
|
1859
|
+
const visible = new Set(surfaceTools);
|
|
1860
|
+
if (host !== undefined) {
|
|
1861
|
+
const conversation = await host.conversation(api.conversationId, context);
|
|
1862
|
+
if (conversation === undefined)
|
|
1863
|
+
throw new Error(`Conversation ${api.conversationId} is unavailable`);
|
|
1864
|
+
for (const tool of (await conversation.agent(context)).tools)
|
|
1865
|
+
if (readToolContract(tool).nativeOnly)
|
|
1866
|
+
visible.add(tool.name);
|
|
1867
|
+
}
|
|
1868
|
+
return { messages: projectToolSchemas(request.messages, visible) };
|
|
1869
|
+
}
|
|
1870
|
+
})
|
|
1871
|
+
};
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
// packages/execution/src/wait-session.ts
|
|
1875
|
+
import { withoutAbortSignal as withoutAbortSignal3 } from "@earendil-works/chord/context";
|
|
1876
|
+
|
|
1877
|
+
// packages/execution/src/tool-value.ts
|
|
1878
|
+
class NestedToolError extends Error {
|
|
1879
|
+
result;
|
|
1880
|
+
constructor(result, text) {
|
|
1881
|
+
super(result.diagnostics?.filter((item) => item.severity === "error").map((item) => item.message).join(`
|
|
1882
|
+
`) || text || "Tool failed");
|
|
1883
|
+
this.name = "NestedToolError";
|
|
1884
|
+
this.result = result;
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
function toolValue(result) {
|
|
1888
|
+
if (result.structuredOutput !== undefined)
|
|
1889
|
+
return result.structuredOutput;
|
|
1890
|
+
const texts = (result.output ?? []).filter((item) => item.type === "text").map((item) => item.text);
|
|
1891
|
+
if (result.isError)
|
|
1892
|
+
throw new NestedToolError(result, texts.join(`
|
|
1893
|
+
`));
|
|
1894
|
+
const images = (result.output ?? []).filter((item) => item.type === "image").map((item) => ({
|
|
1895
|
+
image_url: `data:${item.mimeType};base64,${item.data}`
|
|
1896
|
+
}));
|
|
1897
|
+
let value = result.details;
|
|
1898
|
+
const objectDetails = value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
|
|
1899
|
+
if (value === undefined || objectDetails !== undefined && Object.keys(objectDetails).length === 0) {
|
|
1900
|
+
const text = texts.join(`
|
|
1901
|
+
`);
|
|
1902
|
+
try {
|
|
1903
|
+
value = JSON.parse(text);
|
|
1904
|
+
} catch {
|
|
1905
|
+
value = text;
|
|
1906
|
+
}
|
|
1907
|
+
} else if (objectDetails !== undefined && (result.output?.length ?? 0) > 0) {
|
|
1908
|
+
value = {
|
|
1909
|
+
...objectDetails,
|
|
1910
|
+
[Object.hasOwn(objectDetails, "content") ? "toolResultContent" : "content"]: result.output
|
|
1911
|
+
};
|
|
1912
|
+
} else if ((result.output?.length ?? 0) > 0 && !(typeof value === "string" && images.length === 0 && texts.join(`
|
|
1913
|
+
`) === value)) {
|
|
1914
|
+
value = { value, content: result.output };
|
|
1915
|
+
}
|
|
1916
|
+
if (images.length)
|
|
1917
|
+
return {
|
|
1918
|
+
...value !== null && typeof value === "object" && !Array.isArray(value) ? value : { value },
|
|
1919
|
+
...images[0],
|
|
1920
|
+
...images.length > 1 ? { images } : {}
|
|
1921
|
+
};
|
|
1922
|
+
return value;
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
// packages/execution/src/wait-session.ts
|
|
1926
|
+
async function recoverWaitSession(cellId, yieldTimeMs, maxTokens, api, context, nestedTask, cancelTask) {
|
|
1927
|
+
if (!Number.isSafeInteger(cellId) || cellId < 0)
|
|
1928
|
+
return;
|
|
1929
|
+
const registration = (await api.agent(context)).callable.find((tool) => tool.name === "write_stdin" && !readToolContract(tool).nativeOnly);
|
|
1930
|
+
if (!registration)
|
|
1931
|
+
return;
|
|
1932
|
+
const id = await api.createTask(nestedTask, {
|
|
1933
|
+
name: registration.name,
|
|
1934
|
+
arguments: {
|
|
1935
|
+
session_id: cellId,
|
|
1936
|
+
yield_time_ms: yieldTimeMs,
|
|
1937
|
+
max_output_tokens: maxTokens
|
|
1938
|
+
},
|
|
1939
|
+
parent: { taskId: api.taskId, callId: api.callId }
|
|
1940
|
+
}, {
|
|
1941
|
+
ownership: { kind: "task", taskId: api.taskId },
|
|
1942
|
+
abandonOnRestart: false
|
|
1943
|
+
}, context);
|
|
1944
|
+
let cancelling;
|
|
1945
|
+
const abort = () => {
|
|
1946
|
+
cancelling ??= cancelTask(id, withoutAbortSignal3(context));
|
|
1947
|
+
cancelling.catch(() => {});
|
|
1948
|
+
};
|
|
1949
|
+
context.abortSignal?.addEventListener("abort", abort, { once: true });
|
|
1950
|
+
if (context.abortSignal?.aborted)
|
|
1951
|
+
abort();
|
|
1952
|
+
try {
|
|
1953
|
+
const settled = await api.waitForTask(id, context);
|
|
1954
|
+
const result = readStoredResult(settled.state.outcome.result ?? executionError(settled.state.outcome.status, "Shell continuation did not return a result"));
|
|
1955
|
+
let value;
|
|
1956
|
+
try {
|
|
1957
|
+
value = toolValue(result);
|
|
1958
|
+
} catch (error) {
|
|
1959
|
+
if (error instanceof Error && /unknown(?: or expired)? process id/i.test(error.message))
|
|
1960
|
+
return;
|
|
1961
|
+
throw error;
|
|
1962
|
+
}
|
|
1963
|
+
if (!value || typeof value !== "object" || !("output" in value))
|
|
1964
|
+
return;
|
|
1965
|
+
const output = typeof value.output === "string" ? value.output : "";
|
|
1966
|
+
const running = "session_id" in value && typeof value.session_id === "number";
|
|
1967
|
+
const exitCode = "exit_code" in value && typeof value.exit_code === "number" ? value.exit_code : undefined;
|
|
1968
|
+
return {
|
|
1969
|
+
cellId,
|
|
1970
|
+
status: "completed",
|
|
1971
|
+
recoveredSession: true,
|
|
1972
|
+
result: {
|
|
1973
|
+
...result,
|
|
1974
|
+
output: [
|
|
1975
|
+
{
|
|
1976
|
+
type: "text",
|
|
1977
|
+
text: `Recovered wait cell_id ${cellId} as exec_command session_id ${cellId} and continued it with write_stdin`
|
|
1978
|
+
},
|
|
1979
|
+
...output ? [{ type: "text", text: output }] : [],
|
|
1980
|
+
...exitCode === undefined ? [] : [
|
|
1981
|
+
{
|
|
1982
|
+
type: "text",
|
|
1983
|
+
text: `Process exited with code ${exitCode}`
|
|
1984
|
+
}
|
|
1985
|
+
],
|
|
1986
|
+
...running ? [
|
|
1987
|
+
{
|
|
1988
|
+
type: "text",
|
|
1989
|
+
text: `Session ${cellId} still running. Resume with write_stdin; set yield_time_ms near expected completion and lengthen later waits`
|
|
1990
|
+
}
|
|
1991
|
+
] : []
|
|
1992
|
+
]
|
|
1993
|
+
}
|
|
1994
|
+
};
|
|
1995
|
+
} finally {
|
|
1996
|
+
context.abortSignal?.removeEventListener("abort", abort);
|
|
1997
|
+
if (cancelling)
|
|
1998
|
+
await cancelling;
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
|
|
2002
|
+
// packages/execution/src/cells.ts
|
|
2003
|
+
function assertSingleExecutionMode(agent) {
|
|
2004
|
+
const modes = agent.extensions.filter((extension) => extension.tasks?.some((task) => task.definition.name.startsWith("howaboua.execution.cell.")));
|
|
2005
|
+
if (modes.length > 1)
|
|
2006
|
+
throw new Error(`Select exactly one execution mode with conversation.configure({ extensions: [...] }). Selected: ${modes.map((mode) => mode.name).join(", ")}`);
|
|
2007
|
+
}
|
|
2008
|
+
function createCellCoordinator(options) {
|
|
2009
|
+
const nestedTask = createNestedToolTask(`howaboua.execution.nested-tool.${options.name}`);
|
|
2010
|
+
const driver = createCellTask(options, nestedTask);
|
|
2011
|
+
const task = driver.task;
|
|
2012
|
+
const projection = providerProjection(options.surfaceTools);
|
|
2013
|
+
const forwarding = forwardingHook();
|
|
2014
|
+
const extension = defineExtension({
|
|
2015
|
+
name: options.name,
|
|
2016
|
+
tasks: [task, nestedTask],
|
|
2017
|
+
hooks: [projection.hook, forwarding.hook]
|
|
2018
|
+
});
|
|
2019
|
+
return {
|
|
2020
|
+
extension,
|
|
2021
|
+
nestedTask,
|
|
2022
|
+
bind(harness) {
|
|
2023
|
+
projection.bind(harness);
|
|
2024
|
+
forwarding.bind(harness);
|
|
2025
|
+
},
|
|
2026
|
+
async start(input, api, context) {
|
|
2027
|
+
if (driver.closed)
|
|
2028
|
+
throw new Error("Execution host is closed");
|
|
2029
|
+
assertSingleExecutionMode(await api.agent(context));
|
|
2030
|
+
const copied = copyJson10(input);
|
|
2031
|
+
return api.commit(async (tx) => {
|
|
2032
|
+
const isolatedLimit = options.isolatedConcurrency ?? 0;
|
|
2033
|
+
const isolated = isolatedLimit > 0 && input["isolated"] === true;
|
|
2034
|
+
let isolatedCount = 0;
|
|
2035
|
+
let normalCount = 0;
|
|
2036
|
+
let activeCount = 0;
|
|
2037
|
+
for (const status of [
|
|
2038
|
+
"pending",
|
|
2039
|
+
"running",
|
|
2040
|
+
"waiting",
|
|
2041
|
+
"sleeping",
|
|
2042
|
+
"completing"
|
|
2043
|
+
]) {
|
|
2044
|
+
const live = await tx.scanTasks({
|
|
2045
|
+
conversationId: api.conversationId,
|
|
2046
|
+
kind: task.definition.name,
|
|
2047
|
+
status
|
|
2048
|
+
}, Math.max(isolatedLimit + (options.normalQueueLimit ?? 1), options.activeCellLimit ?? 1));
|
|
2049
|
+
for (const cell of live.items) {
|
|
2050
|
+
activeCount++;
|
|
2051
|
+
if ((await tx.doc(InvocationDoc, cell.id)).isolated)
|
|
2052
|
+
isolatedCount++;
|
|
2053
|
+
else if (!isolated && ++normalCount >= (options.normalQueueLimit ?? 1))
|
|
2054
|
+
throw new Error(`Cell ${cell.id} is still running. Wait or terminate it before starting another cell`);
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
if (options.activeCellLimit !== undefined && activeCount >= options.activeCellLimit)
|
|
2058
|
+
throw new Error(`Execution allows ${options.activeCellLimit} active cells at a time; wait for or terminate an earlier cell`);
|
|
2059
|
+
if (isolated && isolatedCount >= isolatedLimit)
|
|
2060
|
+
throw new Error(`Notebook allows ${options.isolatedConcurrency} isolated cells at a time; wait for or terminate an isolated cell first`);
|
|
2061
|
+
const id = await tx.createTask(task, copied, {
|
|
2062
|
+
ownership: { kind: "conversation" }
|
|
2063
|
+
});
|
|
2064
|
+
const doc = await tx.doc(InvocationDoc, id);
|
|
2065
|
+
if (isolated)
|
|
2066
|
+
doc.isolated = true;
|
|
2067
|
+
doc.forwardingCellId = id;
|
|
2068
|
+
doc.forwardingBudget = typeof input["max_output_tokens"] === "number" ? input["max_output_tokens"] * 4 : 40000;
|
|
2069
|
+
doc.forwardedToolCalls = {
|
|
2070
|
+
version: 1,
|
|
2071
|
+
cellId: String(id),
|
|
2072
|
+
calls: [],
|
|
2073
|
+
omittedCalls: 0
|
|
2074
|
+
};
|
|
2075
|
+
const inherited = await tx.doc(ToolOriginDoc, api.taskId);
|
|
2076
|
+
(await tx.doc(ToolOriginDoc, id)).origin = inherited.origin ?? {
|
|
2077
|
+
conversationId: api.conversationId,
|
|
2078
|
+
taskId: api.taskId,
|
|
2079
|
+
callId: api.callId
|
|
2080
|
+
};
|
|
2081
|
+
return id;
|
|
2082
|
+
}, context);
|
|
2083
|
+
},
|
|
2084
|
+
async wait(id, api, context, yieldTimeMs = 1e4, maxTokens = 1e4, sessionYieldTimeMs = yieldTimeMs) {
|
|
2085
|
+
if (!Number.isFinite(yieldTimeMs) || yieldTimeMs < 0)
|
|
2086
|
+
throw new Error("yieldTimeMs must be non-negative and finite");
|
|
2087
|
+
const record = await api.getTask(id, context);
|
|
2088
|
+
if (record === undefined || record.kind !== task.definition.name || record.conversationId !== api.conversationId) {
|
|
2089
|
+
const recovered = await recoverWaitSession(id, sessionYieldTimeMs, maxTokens, api, context, nestedTask, options.cancelTask);
|
|
2090
|
+
if (recovered)
|
|
2091
|
+
return recovered;
|
|
2092
|
+
}
|
|
2093
|
+
const initial = await observeCell(task.definition.name, id, api, context, maxTokens * 4);
|
|
2094
|
+
const stopProgress = await observeCellProgress(id, api, context, maxTokens * 4);
|
|
2095
|
+
try {
|
|
2096
|
+
if (initial.status !== "running" || yieldTimeMs === 0)
|
|
2097
|
+
return initial;
|
|
2098
|
+
await api.commit(async (tx) => {
|
|
2099
|
+
const inherited = (await tx.doc(ToolOriginDoc, api.taskId)).origin;
|
|
2100
|
+
(await tx.doc(ToolOriginDoc, id)).origin = inherited ?? {
|
|
2101
|
+
conversationId: api.conversationId,
|
|
2102
|
+
taskId: api.taskId,
|
|
2103
|
+
callId: api.callId
|
|
2104
|
+
};
|
|
2105
|
+
}, context);
|
|
2106
|
+
const yielding = driver.observeYield(id);
|
|
2107
|
+
if (yielding.consume()) {
|
|
2108
|
+
return initial;
|
|
2109
|
+
}
|
|
2110
|
+
const wait = withCancel(context);
|
|
2111
|
+
const timeout = new Error("Cell observation yielded");
|
|
2112
|
+
const timer = setTimeout(() => wait.cancel(timeout), Math.min(yieldTimeMs, 2147483647));
|
|
2113
|
+
try {
|
|
2114
|
+
await Promise.race([
|
|
2115
|
+
api.waitForTask(id, wait.context),
|
|
2116
|
+
yielding.wake
|
|
2117
|
+
]);
|
|
2118
|
+
yielding.consume();
|
|
2119
|
+
} catch (error) {
|
|
2120
|
+
if (wait.context.abortSignal?.reason !== timeout)
|
|
2121
|
+
throw error;
|
|
2122
|
+
} finally {
|
|
2123
|
+
clearTimeout(timer);
|
|
2124
|
+
wait.cancel();
|
|
2125
|
+
}
|
|
2126
|
+
return observeCell(task.definition.name, id, api, context, maxTokens * 4);
|
|
2127
|
+
} finally {
|
|
2128
|
+
await stopProgress();
|
|
2129
|
+
}
|
|
2130
|
+
},
|
|
2131
|
+
async cancel(id, api, context, maxTokens = 1e4) {
|
|
2132
|
+
await observeCell(task.definition.name, id, api, context);
|
|
2133
|
+
const stopProgress = await observeCellProgress(id, api, context, maxTokens * 4);
|
|
2134
|
+
try {
|
|
2135
|
+
await options.cancelTask(id, context);
|
|
2136
|
+
await api.waitForTask(id, context);
|
|
2137
|
+
return observeCell(task.definition.name, id, api, context, maxTokens * 4);
|
|
2138
|
+
} finally {
|
|
2139
|
+
await stopProgress();
|
|
2140
|
+
}
|
|
2141
|
+
},
|
|
2142
|
+
close: driver.close
|
|
2143
|
+
};
|
|
2144
|
+
}
|
|
2145
|
+
// packages/execution/src/tool-source.ts
|
|
2146
|
+
function directToolYieldTime(code, tools) {
|
|
2147
|
+
const executableCode = maskJavaScriptCommentsAndStrings(code);
|
|
2148
|
+
let forced;
|
|
2149
|
+
for (const tool of tools) {
|
|
2150
|
+
if (tool.yieldTimeMs === undefined)
|
|
2151
|
+
continue;
|
|
2152
|
+
const name = escapeRegExp(tool.name);
|
|
2153
|
+
const directReference = new RegExp(`\\btools\\s*\\.\\s*${name}(?![a-zA-Z0-9_$])\\s*\\(`);
|
|
2154
|
+
const doubleQuoted = escapeRegExp(JSON.stringify(tool.name));
|
|
2155
|
+
const singleQuoted = escapeRegExp(`'${tool.name.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`);
|
|
2156
|
+
const bracketReference = new RegExp(`\\btools\\s*\\[\\s*(?:${doubleQuoted}|${singleQuoted})\\s*\\]\\s*\\(`, "g");
|
|
2157
|
+
if (!(/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(tool.name) && directReference.test(executableCode)) && !hasExecutableBracketReference(code, executableCode, bracketReference))
|
|
2158
|
+
continue;
|
|
2159
|
+
forced = forced === undefined ? tool.yieldTimeMs : Math.max(forced, tool.yieldTimeMs);
|
|
2160
|
+
}
|
|
2161
|
+
return forced ?? null;
|
|
2162
|
+
}
|
|
2163
|
+
function hasExecutableBracketReference(code, executableCode, pattern) {
|
|
2164
|
+
for (const match of code.matchAll(pattern)) {
|
|
2165
|
+
if (match.index !== undefined && executableCode.slice(match.index, match.index + 5) === "tools")
|
|
2166
|
+
return true;
|
|
2167
|
+
}
|
|
2168
|
+
return false;
|
|
2169
|
+
}
|
|
2170
|
+
function maskJavaScriptCommentsAndStrings(code) {
|
|
2171
|
+
const output = code.split("");
|
|
2172
|
+
let state = "code";
|
|
2173
|
+
let quote = "";
|
|
2174
|
+
let regexClass = false;
|
|
2175
|
+
let templateExpressionDepth;
|
|
2176
|
+
const templateReturnDepths = [];
|
|
2177
|
+
for (let index = 0;index < code.length; index += 1) {
|
|
2178
|
+
const current = code[index];
|
|
2179
|
+
const next = code[index + 1];
|
|
2180
|
+
if (state === "template") {
|
|
2181
|
+
output[index] = current === `
|
|
2182
|
+
` || current === "\r" ? current : " ";
|
|
2183
|
+
if (current === "\\") {
|
|
2184
|
+
if (next !== undefined)
|
|
2185
|
+
output[index + 1] = " ";
|
|
2186
|
+
index += 1;
|
|
2187
|
+
} else if (current === "$" && next === "{") {
|
|
2188
|
+
output[index + 1] = " ";
|
|
2189
|
+
templateExpressionDepth = 1;
|
|
2190
|
+
state = "code";
|
|
2191
|
+
index += 1;
|
|
2192
|
+
} else if (current === "`") {
|
|
2193
|
+
templateExpressionDepth = templateReturnDepths.pop();
|
|
2194
|
+
state = "code";
|
|
2195
|
+
}
|
|
2196
|
+
continue;
|
|
2197
|
+
}
|
|
2198
|
+
if (state === "code") {
|
|
2199
|
+
if (templateExpressionDepth !== undefined && current === "{") {
|
|
2200
|
+
templateExpressionDepth += 1;
|
|
2201
|
+
} else if (templateExpressionDepth !== undefined && current === "}") {
|
|
2202
|
+
templateExpressionDepth -= 1;
|
|
2203
|
+
if (templateExpressionDepth === 0) {
|
|
2204
|
+
output[index] = " ";
|
|
2205
|
+
templateExpressionDepth = undefined;
|
|
2206
|
+
state = "template";
|
|
2207
|
+
}
|
|
2208
|
+
} else if (current === "/" && next === "/") {
|
|
2209
|
+
output[index] = output[index + 1] = " ";
|
|
2210
|
+
state = "line-comment";
|
|
2211
|
+
index += 1;
|
|
2212
|
+
} else if (current === "/" && next === "*") {
|
|
2213
|
+
output[index] = output[index + 1] = " ";
|
|
2214
|
+
state = "block-comment";
|
|
2215
|
+
index += 1;
|
|
2216
|
+
} else if (current === "/" && isRegexLiteralStart(code, index)) {
|
|
2217
|
+
output[index] = " ";
|
|
2218
|
+
regexClass = false;
|
|
2219
|
+
state = "regex";
|
|
2220
|
+
} else if (current === '"' || current === "'") {
|
|
2221
|
+
output[index] = " ";
|
|
2222
|
+
quote = current;
|
|
2223
|
+
state = "string";
|
|
2224
|
+
} else if (current === "`") {
|
|
2225
|
+
output[index] = " ";
|
|
2226
|
+
templateReturnDepths.push(templateExpressionDepth);
|
|
2227
|
+
templateExpressionDepth = undefined;
|
|
2228
|
+
state = "template";
|
|
2229
|
+
}
|
|
2230
|
+
continue;
|
|
2231
|
+
}
|
|
2232
|
+
if (state === "line-comment") {
|
|
2233
|
+
if (current === `
|
|
2234
|
+
` || current === "\r")
|
|
2235
|
+
state = "code";
|
|
2236
|
+
else
|
|
2237
|
+
output[index] = " ";
|
|
2238
|
+
continue;
|
|
2239
|
+
}
|
|
2240
|
+
if (state === "regex") {
|
|
2241
|
+
output[index] = current === `
|
|
2242
|
+
` || current === "\r" ? current : " ";
|
|
2243
|
+
if (current === "\\") {
|
|
2244
|
+
if (next !== undefined)
|
|
2245
|
+
output[index + 1] = " ";
|
|
2246
|
+
index += 1;
|
|
2247
|
+
} else if (current === "[")
|
|
2248
|
+
regexClass = true;
|
|
2249
|
+
else if (current === "]")
|
|
2250
|
+
regexClass = false;
|
|
2251
|
+
else if (current === "/" && !regexClass)
|
|
2252
|
+
state = "code";
|
|
2253
|
+
continue;
|
|
2254
|
+
}
|
|
2255
|
+
output[index] = current === `
|
|
2256
|
+
` || current === "\r" ? current : " ";
|
|
2257
|
+
if (state === "block-comment") {
|
|
2258
|
+
if (current === "*" && next === "/") {
|
|
2259
|
+
output[index + 1] = " ";
|
|
2260
|
+
state = "code";
|
|
2261
|
+
index += 1;
|
|
2262
|
+
}
|
|
2263
|
+
continue;
|
|
2264
|
+
}
|
|
2265
|
+
if (current === "\\") {
|
|
2266
|
+
if (next !== undefined)
|
|
2267
|
+
output[index + 1] = " ";
|
|
2268
|
+
index += 1;
|
|
2269
|
+
} else if (current === quote) {
|
|
2270
|
+
state = "code";
|
|
2271
|
+
quote = "";
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
return output.join("");
|
|
2275
|
+
}
|
|
2276
|
+
function isRegexLiteralStart(code, index) {
|
|
2277
|
+
const previous = code.slice(0, index).trimEnd();
|
|
2278
|
+
if (!previous)
|
|
2279
|
+
return true;
|
|
2280
|
+
if ("([{:;,=!?&|+-*%^~<>".includes(previous.at(-1)))
|
|
2281
|
+
return true;
|
|
2282
|
+
return /(?:^|[^\w$])(return|throw|case|delete|void|typeof|instanceof|in|of|yield|await|else|do)$/.test(previous);
|
|
2283
|
+
}
|
|
2284
|
+
function escapeRegExp(value) {
|
|
2285
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2286
|
+
}
|
|
2287
|
+
// packages/execution/src/shell.ts
|
|
2288
|
+
import { defineTool } from "@earendil-works/pi-durable";
|
|
2289
|
+
import { getOrThrow } from "@earendil-works/pi-durable/env";
|
|
2290
|
+
import { Type } from "typebox";
|
|
2291
|
+
|
|
2292
|
+
// packages/execution/src/shell/format.ts
|
|
2293
|
+
function formatUnifiedExecResult(result) {
|
|
2294
|
+
const sections = [];
|
|
2295
|
+
if (result.exit_code !== undefined) {
|
|
2296
|
+
sections.push(`Exit code: ${result.exit_code}`);
|
|
2297
|
+
}
|
|
2298
|
+
if (result.session_id !== undefined) {
|
|
2299
|
+
sections.push(`Session ${result.session_id} still running. Resume with write_stdin; set yield_time_ms near expected completion and lengthen later waits`);
|
|
2300
|
+
}
|
|
2301
|
+
if (result.truncated) {
|
|
2302
|
+
sections.push(`[Output truncated${result.original_token_count === undefined ? "" : `; original token count: ${result.original_token_count}`}]`);
|
|
2303
|
+
}
|
|
2304
|
+
sections.push("Output:");
|
|
2305
|
+
sections.push(result.output);
|
|
2306
|
+
return sections.join(`
|
|
2307
|
+
`);
|
|
2308
|
+
}
|
|
2309
|
+
|
|
2310
|
+
// packages/execution/src/shell/session-manager.ts
|
|
2311
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
2312
|
+
|
|
2313
|
+
// packages/execution/src/shell/process-session.ts
|
|
2314
|
+
import { StringDecoder } from "node:string_decoder";
|
|
2315
|
+
|
|
2316
|
+
// packages/execution/src/shell/shell-args.ts
|
|
2317
|
+
var CODEX_FALLBACK_SHELL = "/bin/bash";
|
|
2318
|
+
function isFishShell(shell) {
|
|
2319
|
+
return shell?.replace(/\\/g, "/").split("/").pop()?.toLowerCase() === "fish";
|
|
2320
|
+
}
|
|
2321
|
+
function getCodexRuntimeShell(shell, platform, defaultShell = CODEX_FALLBACK_SHELL) {
|
|
2322
|
+
if (!shell)
|
|
2323
|
+
return defaultShell;
|
|
2324
|
+
if (!isFishShell(shell))
|
|
2325
|
+
return shell;
|
|
2326
|
+
return platform === "win32" ? defaultShell : CODEX_FALLBACK_SHELL;
|
|
2327
|
+
}
|
|
2328
|
+
function getShellArgs(shell, command, login) {
|
|
2329
|
+
const name = shell.replace(/\\/g, "/").split("/").pop()?.toLowerCase();
|
|
2330
|
+
if (name === "cmd" || name === "cmd.exe")
|
|
2331
|
+
return ["/d", "/s", "/c", command];
|
|
2332
|
+
if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(name ?? ""))
|
|
2333
|
+
return ["-NoLogo", "-NoProfile", "-Command", command];
|
|
2334
|
+
return login ? ["-lc", command] : ["-c", command];
|
|
2335
|
+
}
|
|
2336
|
+
|
|
2337
|
+
// packages/execution/src/shell/process-session.ts
|
|
2338
|
+
function createProcessSessionRuntime(backend) {
|
|
2339
|
+
const active = new Set;
|
|
2340
|
+
let shuttingDown = false;
|
|
2341
|
+
function create({
|
|
2342
|
+
id,
|
|
2343
|
+
input,
|
|
2344
|
+
workdir,
|
|
2345
|
+
shell,
|
|
2346
|
+
signal,
|
|
2347
|
+
hooks
|
|
2348
|
+
}) {
|
|
2349
|
+
const session = {
|
|
2350
|
+
id,
|
|
2351
|
+
startup: Promise.resolve(),
|
|
2352
|
+
started: false,
|
|
2353
|
+
tty: Boolean(input.tty),
|
|
2354
|
+
command: input.command,
|
|
2355
|
+
buffer: "",
|
|
2356
|
+
bufferStartOffset: 0,
|
|
2357
|
+
emittedOffset: 0,
|
|
2358
|
+
outputVersion: 0,
|
|
2359
|
+
exitCode: undefined,
|
|
2360
|
+
listeners: new Set,
|
|
2361
|
+
interactive: Boolean(input.tty),
|
|
2362
|
+
startedAt: Date.now(),
|
|
2363
|
+
updatedAt: Date.now(),
|
|
2364
|
+
finalized: false,
|
|
2365
|
+
exposed: false,
|
|
2366
|
+
terminating: false
|
|
2367
|
+
};
|
|
2368
|
+
const decoders = {
|
|
2369
|
+
stdout: new StringDecoder("utf8"),
|
|
2370
|
+
stderr: new StringDecoder("utf8"),
|
|
2371
|
+
pty: new StringDecoder("utf8")
|
|
2372
|
+
};
|
|
2373
|
+
const close = (code) => {
|
|
2374
|
+
if (session.exitCode !== undefined)
|
|
2375
|
+
return;
|
|
2376
|
+
for (const decoder of Object.values(decoders))
|
|
2377
|
+
hooks.onOutput(session, decoder.end());
|
|
2378
|
+
session.exitCode = session.terminating && code === 0 ? 143 : code;
|
|
2379
|
+
active.delete(session);
|
|
2380
|
+
hooks.onExit(session);
|
|
2381
|
+
};
|
|
2382
|
+
active.add(session);
|
|
2383
|
+
session.startup = Promise.resolve().then(async () => {
|
|
2384
|
+
try {
|
|
2385
|
+
if (shuttingDown || signal?.aborted) {
|
|
2386
|
+
session.terminating = true;
|
|
2387
|
+
close(143);
|
|
2388
|
+
return;
|
|
2389
|
+
}
|
|
2390
|
+
session.process = await backend.spawn({
|
|
2391
|
+
shell,
|
|
2392
|
+
args: getShellArgs(shell, input.executionCommand, input.login ?? true),
|
|
2393
|
+
cwd: workdir,
|
|
2394
|
+
env: input.executionEnv,
|
|
2395
|
+
tty: Boolean(input.tty)
|
|
2396
|
+
}, {
|
|
2397
|
+
output: (stream, chunk) => {
|
|
2398
|
+
if (session.exitCode !== undefined || !hooks.isOwned(session))
|
|
2399
|
+
return;
|
|
2400
|
+
hooks.onOutput(session, typeof chunk === "string" ? chunk : decoders[stream].write(Buffer.from(chunk)));
|
|
2401
|
+
},
|
|
2402
|
+
closed: close
|
|
2403
|
+
});
|
|
2404
|
+
session.started = true;
|
|
2405
|
+
} catch (error) {
|
|
2406
|
+
hooks.onOutput(session, `${error instanceof Error ? error.message : String(error)}
|
|
2407
|
+
`);
|
|
2408
|
+
close(1);
|
|
2409
|
+
}
|
|
2410
|
+
});
|
|
2411
|
+
return session;
|
|
2412
|
+
}
|
|
2413
|
+
async function terminate(session) {
|
|
2414
|
+
session.terminating = true;
|
|
2415
|
+
await session.startup;
|
|
2416
|
+
await session.process?.terminate();
|
|
2417
|
+
}
|
|
2418
|
+
return {
|
|
2419
|
+
create,
|
|
2420
|
+
waitForStartup: async (session, signal) => {
|
|
2421
|
+
await session.startup;
|
|
2422
|
+
signal?.throwIfAborted();
|
|
2423
|
+
},
|
|
2424
|
+
write: async (session, chars) => {
|
|
2425
|
+
await session.startup;
|
|
2426
|
+
if (!session.process || session.exitCode !== undefined)
|
|
2427
|
+
throw new Error(`Process id ${session.id} already exited; cannot write stdin`);
|
|
2428
|
+
await session.process.write(chars);
|
|
2429
|
+
},
|
|
2430
|
+
terminate,
|
|
2431
|
+
shutdown: async () => {
|
|
2432
|
+
shuttingDown = true;
|
|
2433
|
+
const results = await Promise.allSettled([...active].map(terminate));
|
|
2434
|
+
const failures = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
2435
|
+
if (failures.length)
|
|
2436
|
+
throw new AggregateError(failures, "Shell process cleanup failed; process outcomes may be uncertain");
|
|
2437
|
+
}
|
|
2438
|
+
};
|
|
2439
|
+
}
|
|
2440
|
+
|
|
2441
|
+
// packages/execution/src/shell/output.ts
|
|
2442
|
+
import { randomBytes } from "node:crypto";
|
|
2443
|
+
var DEFAULT_MAX_OUTPUT_TOKENS = 1e4;
|
|
2444
|
+
function maxCharsForTokens(maxOutputTokens = DEFAULT_MAX_OUTPUT_TOKENS) {
|
|
2445
|
+
return Math.max(256, maxOutputTokens * 4);
|
|
2446
|
+
}
|
|
2447
|
+
function stripTerminalControlSequences(text) {
|
|
2448
|
+
const withoutOscAndDcs = text.replace(/\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/g, "").replace(/\u001B[P_X^][\s\S]*?\u001B\\/g, "");
|
|
2449
|
+
return withoutOscAndDcs.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, "").replace(/\u001B[@-_]/g, "").replaceAll("\x1B", "");
|
|
2450
|
+
}
|
|
2451
|
+
function sanitizeBinaryOutput(text) {
|
|
2452
|
+
return Array.from(text).filter((char) => {
|
|
2453
|
+
const code = char.codePointAt(0);
|
|
2454
|
+
if (code === undefined)
|
|
2455
|
+
return false;
|
|
2456
|
+
if (code === 9 || code === 10 || code === 13)
|
|
2457
|
+
return true;
|
|
2458
|
+
if (code <= 31)
|
|
2459
|
+
return false;
|
|
2460
|
+
if (code >= 65529 && code <= 65531)
|
|
2461
|
+
return false;
|
|
2462
|
+
return true;
|
|
2463
|
+
}).join("");
|
|
2464
|
+
}
|
|
2465
|
+
function normalizePipeOutput(text) {
|
|
2466
|
+
return sanitizeBinaryOutput(stripTerminalControlSequences(text)).replace(/\r\n/g, `
|
|
2467
|
+
`).replace(/\r/g, `
|
|
2468
|
+
`);
|
|
2469
|
+
}
|
|
2470
|
+
function truncateToTail(text, maxChars) {
|
|
2471
|
+
let start = Math.max(0, text.length - maxChars);
|
|
2472
|
+
if (start > 0 && start < text.length && /[\uDC00-\uDFFF]/.test(text[start]))
|
|
2473
|
+
start += 1;
|
|
2474
|
+
return { output: text.slice(start), removed: start };
|
|
2475
|
+
}
|
|
2476
|
+
function generateChunkId() {
|
|
2477
|
+
return randomBytes(3).toString("hex");
|
|
2478
|
+
}
|
|
2479
|
+
function truncateOutput(text, maxOutputTokens, originalCharCount = text.length) {
|
|
2480
|
+
if (text.length === 0 && originalCharCount === 0)
|
|
2481
|
+
return { output: "" };
|
|
2482
|
+
const maxChars = maxCharsForTokens(maxOutputTokens);
|
|
2483
|
+
const originalTokenCount = Math.ceil(Math.max(text.length, originalCharCount) / 4);
|
|
2484
|
+
const output = text.length <= maxChars ? text : truncateToTail(text, maxChars).output;
|
|
2485
|
+
return {
|
|
2486
|
+
output,
|
|
2487
|
+
original_token_count: originalTokenCount,
|
|
2488
|
+
...output.length < originalCharCount ? { truncated: true } : {}
|
|
2489
|
+
};
|
|
2490
|
+
}
|
|
2491
|
+
function outputSince(session, offset) {
|
|
2492
|
+
const endOffset = session.bufferStartOffset + session.buffer.length;
|
|
2493
|
+
const startOffset = Math.max(offset, session.bufferStartOffset);
|
|
2494
|
+
return {
|
|
2495
|
+
text: session.buffer.slice(startOffset - session.bufferStartOffset),
|
|
2496
|
+
originalCharCount: Math.max(0, endOffset - offset),
|
|
2497
|
+
endOffset
|
|
2498
|
+
};
|
|
2499
|
+
}
|
|
2500
|
+
function consumeOutput(session, maxOutputTokens) {
|
|
2501
|
+
const output = outputSince(session, session.emittedOffset);
|
|
2502
|
+
session.emittedOffset = output.endOffset;
|
|
2503
|
+
return truncateOutput(output.text, maxOutputTokens, output.originalCharCount);
|
|
2504
|
+
}
|
|
2505
|
+
function peekUnconsumedOutput(session, maxOutputTokens) {
|
|
2506
|
+
const output = outputSince(session, session.emittedOffset);
|
|
2507
|
+
return truncateOutput(output.text, maxOutputTokens, output.originalCharCount);
|
|
2508
|
+
}
|
|
2509
|
+
function peekOutputSince(session, baselineOffset, maxOutputTokens) {
|
|
2510
|
+
const output = outputSince(session, baselineOffset);
|
|
2511
|
+
return truncateOutput(output.text, maxOutputTokens, output.originalCharCount);
|
|
2512
|
+
}
|
|
2513
|
+
|
|
2514
|
+
// packages/execution/src/shell/results.ts
|
|
2515
|
+
function fromSnapshot(session, waitMs, snapshot) {
|
|
2516
|
+
const result = {
|
|
2517
|
+
chunk_id: generateChunkId(),
|
|
2518
|
+
wall_time_seconds: waitMs / 1000,
|
|
2519
|
+
...snapshot
|
|
2520
|
+
};
|
|
2521
|
+
if (session.exitCode === undefined || session.exitCode === null)
|
|
2522
|
+
result.session_id = session.id;
|
|
2523
|
+
else
|
|
2524
|
+
result.exit_code = session.exitCode;
|
|
2525
|
+
return result;
|
|
2526
|
+
}
|
|
2527
|
+
function makeExecResult(session, waitMs, maxOutputTokens, exposeSession, deleteSessionIfDrained) {
|
|
2528
|
+
const consumed = consumeOutput(session, maxOutputTokens);
|
|
2529
|
+
const result = fromSnapshot(session, waitMs, consumed);
|
|
2530
|
+
if (session.exitCode === undefined || session.exitCode === null) {
|
|
2531
|
+
exposeSession(session);
|
|
2532
|
+
} else if (session.emittedOffset === session.bufferStartOffset + session.buffer.length) {
|
|
2533
|
+
deleteSessionIfDrained(session.id);
|
|
2534
|
+
}
|
|
2535
|
+
return result;
|
|
2536
|
+
}
|
|
2537
|
+
function snapshotSession(session, maxOutputChars = 8000) {
|
|
2538
|
+
return {
|
|
2539
|
+
id: session.id,
|
|
2540
|
+
command: session.command,
|
|
2541
|
+
running: session.exitCode === undefined || session.exitCode === null,
|
|
2542
|
+
exitCode: session.exitCode ?? undefined,
|
|
2543
|
+
startedAt: session.startedAt,
|
|
2544
|
+
updatedAt: session.updatedAt,
|
|
2545
|
+
outputTail: session.buffer.slice(-maxOutputChars),
|
|
2546
|
+
terminating: session.terminating
|
|
2547
|
+
};
|
|
2548
|
+
}
|
|
2549
|
+
function makeSnapshotResult(session, waitMs, maxOutputTokens, unconsumedOnly = false) {
|
|
2550
|
+
const snapshot = unconsumedOnly ? peekUnconsumedOutput(session, maxOutputTokens) : truncateOutput(session.buffer, maxOutputTokens);
|
|
2551
|
+
return fromSnapshot(session, waitMs, snapshot);
|
|
2552
|
+
}
|
|
2553
|
+
function makeSnapshotSince(session, waitMs, baselineOffset, maxOutputTokens) {
|
|
2554
|
+
return fromSnapshot(session, waitMs, peekOutputSince(session, baselineOffset, maxOutputTokens));
|
|
2555
|
+
}
|
|
2556
|
+
|
|
2557
|
+
// packages/execution/src/shell/session-store.ts
|
|
2558
|
+
var MAX_COMMAND_HISTORY = 256;
|
|
2559
|
+
var MAX_COMPLETED_SESSION_HISTORY = 32;
|
|
2560
|
+
var MAX_COMPLETED_SESSION_OUTPUT_CHARS = 64 * 1024;
|
|
2561
|
+
var MAX_COMPLETED_SESSION_OUTPUT_TOKENS = MAX_COMPLETED_SESSION_OUTPUT_CHARS / 4;
|
|
2562
|
+
var DEFAULT_MAX_TTY_SESSION_BUFFER_CHARS = 1024 * 1024;
|
|
2563
|
+
var DEFAULT_MAX_PIPE_SESSION_BUFFER_CHARS = 256 * 1024 * 1024;
|
|
2564
|
+
|
|
2565
|
+
class ExecSessionStore {
|
|
2566
|
+
sessions = new Map;
|
|
2567
|
+
commandHistory = new Map;
|
|
2568
|
+
completedResults = new Map;
|
|
2569
|
+
changeListeners = new Set;
|
|
2570
|
+
exitListeners = new Set;
|
|
2571
|
+
configuredMaxSessionBufferChars;
|
|
2572
|
+
constructor(configuredMaxSessionBufferChars) {
|
|
2573
|
+
this.configuredMaxSessionBufferChars = configuredMaxSessionBufferChars;
|
|
2574
|
+
}
|
|
2575
|
+
add(session) {
|
|
2576
|
+
this.sessions.set(session.id, session);
|
|
2577
|
+
this.rememberCommand(session.id, session.command);
|
|
2578
|
+
}
|
|
2579
|
+
get(id) {
|
|
2580
|
+
return this.sessions.get(id);
|
|
2581
|
+
}
|
|
2582
|
+
remove(id) {
|
|
2583
|
+
this.sessions.delete(id);
|
|
2584
|
+
}
|
|
2585
|
+
clear() {
|
|
2586
|
+
this.sessions.clear();
|
|
2587
|
+
this.commandHistory.clear();
|
|
2588
|
+
this.completedResults.clear();
|
|
2589
|
+
}
|
|
2590
|
+
completedPoll(sessionId, chars, maxOutputTokens) {
|
|
2591
|
+
const completed = this.completedResults.get(sessionId);
|
|
2592
|
+
if (!completed)
|
|
2593
|
+
return;
|
|
2594
|
+
if (chars.length > 0)
|
|
2595
|
+
throw new Error(`Process id ${sessionId} already exited with code ${completed.exit_code}; cannot write stdin`);
|
|
2596
|
+
return this.replayCompletedResult(completed, maxOutputTokens);
|
|
2597
|
+
}
|
|
2598
|
+
rememberCommand(sessionId, command) {
|
|
2599
|
+
this.commandHistory.set(sessionId, command);
|
|
2600
|
+
if (this.commandHistory.size <= MAX_COMMAND_HISTORY) {
|
|
2601
|
+
return;
|
|
2602
|
+
}
|
|
2603
|
+
const oldest = this.commandHistory.keys().next().value;
|
|
2604
|
+
if (oldest !== undefined) {
|
|
2605
|
+
this.commandHistory.delete(oldest);
|
|
2606
|
+
}
|
|
2607
|
+
}
|
|
2608
|
+
rememberCompletedResult(sessionId, result) {
|
|
2609
|
+
const bounded = truncateToTail(result.output, MAX_COMPLETED_SESSION_OUTPUT_CHARS);
|
|
2610
|
+
this.completedResults.set(sessionId, {
|
|
2611
|
+
...result,
|
|
2612
|
+
output: bounded.removed > 0 ? `[Earlier completed output omitted]
|
|
2613
|
+
${bounded.output}` : bounded.output,
|
|
2614
|
+
...bounded.removed > 0 ? { truncated: true } : {}
|
|
2615
|
+
});
|
|
2616
|
+
if (this.completedResults.size <= MAX_COMPLETED_SESSION_HISTORY)
|
|
2617
|
+
return;
|
|
2618
|
+
const oldest = this.completedResults.keys().next().value;
|
|
2619
|
+
if (oldest !== undefined)
|
|
2620
|
+
this.completedResults.delete(oldest);
|
|
2621
|
+
}
|
|
2622
|
+
replayCompletedResult(result, maxOutputTokens) {
|
|
2623
|
+
const originalCharCount = !result.truncated || result.original_token_count === undefined ? result.output.length : result.original_token_count * 4;
|
|
2624
|
+
return {
|
|
2625
|
+
...result,
|
|
2626
|
+
...truncateOutput(result.output, maxOutputTokens, originalCharCount)
|
|
2627
|
+
};
|
|
2628
|
+
}
|
|
2629
|
+
finishResult(session, waitMs, maxOutputTokens) {
|
|
2630
|
+
const completed = session.exitCode !== undefined && session.exitCode !== null;
|
|
2631
|
+
const replaySnapshot = completed ? makeSnapshotResult(session, waitMs, MAX_COMPLETED_SESSION_OUTPUT_TOKENS, true) : undefined;
|
|
2632
|
+
const result = makeExecResult(session, waitMs, maxOutputTokens, (session) => this.exposeSession(session), (sessionId) => this.sessions.delete(sessionId));
|
|
2633
|
+
if (!replaySnapshot || this.sessions.has(session.id))
|
|
2634
|
+
return result;
|
|
2635
|
+
this.rememberCompletedResult(session.id, {
|
|
2636
|
+
...replaySnapshot,
|
|
2637
|
+
chunk_id: result.chunk_id,
|
|
2638
|
+
wall_time_seconds: result.wall_time_seconds
|
|
2639
|
+
});
|
|
2640
|
+
return result;
|
|
2641
|
+
}
|
|
2642
|
+
notify(session, reason = "output") {
|
|
2643
|
+
session.updatedAt = Date.now();
|
|
2644
|
+
for (const listener of session.listeners) {
|
|
2645
|
+
listener();
|
|
2646
|
+
}
|
|
2647
|
+
if (session.exposed)
|
|
2648
|
+
this.notifyChanged(reason);
|
|
2649
|
+
}
|
|
2650
|
+
notifyChanged(reason) {
|
|
2651
|
+
for (const listener of this.changeListeners) {
|
|
2652
|
+
listener(reason);
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
finalizeSession(session, reason = "exit") {
|
|
2656
|
+
if (session.finalized)
|
|
2657
|
+
return;
|
|
2658
|
+
session.finalized = true;
|
|
2659
|
+
for (const listener of this.exitListeners) {
|
|
2660
|
+
listener(session.id, session.command);
|
|
2661
|
+
}
|
|
2662
|
+
this.notify(session, reason);
|
|
2663
|
+
}
|
|
2664
|
+
exposeSession(session) {
|
|
2665
|
+
if (session.exposed || session.exitCode !== undefined && session.exitCode !== null)
|
|
2666
|
+
return;
|
|
2667
|
+
session.exposed = true;
|
|
2668
|
+
this.notifyChanged("start");
|
|
2669
|
+
}
|
|
2670
|
+
appendOutput(session, text) {
|
|
2671
|
+
if (text.length === 0)
|
|
2672
|
+
return;
|
|
2673
|
+
const output = session.tty ? text : normalizePipeOutput(text);
|
|
2674
|
+
session.buffer += output;
|
|
2675
|
+
session.outputVersion += 1;
|
|
2676
|
+
const maxSessionBufferChars = this.configuredMaxSessionBufferChars ?? (session.tty ? DEFAULT_MAX_TTY_SESSION_BUFFER_CHARS : DEFAULT_MAX_PIPE_SESSION_BUFFER_CHARS);
|
|
2677
|
+
if (session.buffer.length > maxSessionBufferChars) {
|
|
2678
|
+
const bounded = truncateToTail(session.buffer, maxSessionBufferChars);
|
|
2679
|
+
session.buffer = bounded.output;
|
|
2680
|
+
session.bufferStartOffset += bounded.removed;
|
|
2681
|
+
}
|
|
2682
|
+
this.notify(session);
|
|
2683
|
+
}
|
|
2684
|
+
hasSession(sessionId) {
|
|
2685
|
+
return this.sessions.has(sessionId);
|
|
2686
|
+
}
|
|
2687
|
+
getSessionCommand(sessionId) {
|
|
2688
|
+
return this.sessions.get(sessionId)?.command ?? this.commandHistory.get(sessionId);
|
|
2689
|
+
}
|
|
2690
|
+
listSessions(maxOutputChars) {
|
|
2691
|
+
const snapshotsById = new Map;
|
|
2692
|
+
for (const session of this.sessions.values()) {
|
|
2693
|
+
if (!session.exposed)
|
|
2694
|
+
continue;
|
|
2695
|
+
if (session.exitCode !== undefined && session.exitCode !== null)
|
|
2696
|
+
continue;
|
|
2697
|
+
snapshotsById.set(session.id, snapshotSession(session, maxOutputChars));
|
|
2698
|
+
}
|
|
2699
|
+
return Array.from(snapshotsById.values()).sort((a, b) => a.id - b.id);
|
|
2700
|
+
}
|
|
2701
|
+
terminateSession(sessionId, terminate) {
|
|
2702
|
+
const session = this.sessions.get(sessionId);
|
|
2703
|
+
if (!session || session.exitCode !== undefined || session.terminating)
|
|
2704
|
+
return false;
|
|
2705
|
+
session.terminating = true;
|
|
2706
|
+
terminate(session).catch((error) => {
|
|
2707
|
+
session.terminating = false;
|
|
2708
|
+
this.appendOutput(session, `Process termination failed: ${error instanceof Error ? error.message : String(error)}; outcome uncertain
|
|
2709
|
+
`);
|
|
2710
|
+
});
|
|
2711
|
+
this.notify(session, "terminate");
|
|
2712
|
+
return true;
|
|
2713
|
+
}
|
|
2714
|
+
onSessionChange(listener) {
|
|
2715
|
+
this.changeListeners.add(listener);
|
|
2716
|
+
return () => this.changeListeners.delete(listener);
|
|
2717
|
+
}
|
|
2718
|
+
onSessionExit(listener) {
|
|
2719
|
+
this.exitListeners.add(listener);
|
|
2720
|
+
return () => this.exitListeners.delete(listener);
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
|
|
2724
|
+
// packages/execution/src/shell/shell.ts
|
|
2725
|
+
var MIN_YIELD_TIME_MS = 250;
|
|
2726
|
+
var MIN_NON_INTERACTIVE_EXEC_YIELD_TIME_MS = 5000;
|
|
2727
|
+
var MIN_EMPTY_WRITE_YIELD_TIME_MS = 30000;
|
|
2728
|
+
var MAX_YIELD_TIME_MS = 30000;
|
|
2729
|
+
var MAX_EXEC_YIELD_TIME_MS = 1800000;
|
|
2730
|
+
var DEFAULT_EXEC_YIELD_TIME_MS = 1e4;
|
|
2731
|
+
var DEFAULT_WRITE_YIELD_TIME_MS = 250;
|
|
2732
|
+
var DEFAULT_MAX_EMPTY_WRITE_YIELD_TIME_MS = 1800000;
|
|
2733
|
+
var BASH_SYNC_ENV_KEYS = [
|
|
2734
|
+
"PATH",
|
|
2735
|
+
"SHELL",
|
|
2736
|
+
"HOME",
|
|
2737
|
+
"XDG_CONFIG_HOME",
|
|
2738
|
+
"XDG_DATA_HOME",
|
|
2739
|
+
"XDG_CACHE_HOME",
|
|
2740
|
+
"BUN_INSTALL",
|
|
2741
|
+
"PNPM_HOME",
|
|
2742
|
+
"MISE_DATA_DIR",
|
|
2743
|
+
"MISE_CONFIG_DIR",
|
|
2744
|
+
"MISE_SHIMS_DIR",
|
|
2745
|
+
"CARGO_HOME",
|
|
2746
|
+
"GOPATH",
|
|
2747
|
+
"PI_WEB_RUN_STATE_PATH",
|
|
2748
|
+
"PI_CODEX_MODEL",
|
|
2749
|
+
"ANDROID_HOME",
|
|
2750
|
+
"ANDROID_NDK_HOME",
|
|
2751
|
+
"JAVA_HOME"
|
|
2752
|
+
];
|
|
2753
|
+
function resolveShell(shell, platform = process.platform, defaultShell = CODEX_FALLBACK_SHELL) {
|
|
2754
|
+
if (!shell || platform === "win32" && /^(?:bash|bash\.exe)$/i.test(shell))
|
|
2755
|
+
return getCodexRuntimeShell(defaultShell, platform);
|
|
2756
|
+
return getCodexRuntimeShell(shell, platform, defaultShell);
|
|
2757
|
+
}
|
|
2758
|
+
function shellEscape(value) {
|
|
2759
|
+
if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(value))
|
|
2760
|
+
return value;
|
|
2761
|
+
return `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
2762
|
+
}
|
|
2763
|
+
function shouldSyncBashEnv(requestedShell, effectiveShell, baseEnv) {
|
|
2764
|
+
return effectiveShell === CODEX_FALLBACK_SHELL && isFishShell(requestedShell || baseEnv["SHELL"]);
|
|
2765
|
+
}
|
|
2766
|
+
function buildSyncedBashCommand(command, env) {
|
|
2767
|
+
const assignments = [];
|
|
2768
|
+
for (const key of BASH_SYNC_ENV_KEYS) {
|
|
2769
|
+
const value = key === "SHELL" ? CODEX_FALLBACK_SHELL : env[key];
|
|
2770
|
+
if (typeof value !== "string")
|
|
2771
|
+
continue;
|
|
2772
|
+
assignments.push(`export ${key}=${shellEscape(value)}`);
|
|
2773
|
+
}
|
|
2774
|
+
return assignments.length === 0 ? command : `${assignments.join("; ")}; ${command}`;
|
|
2775
|
+
}
|
|
2776
|
+
function resolveExecution(requestedShell, command, extraEnv, baseEnv, platform, defaultShell) {
|
|
2777
|
+
const shell = resolveShell(requestedShell, platform, defaultShell);
|
|
2778
|
+
const env = { ...baseEnv, ...extraEnv };
|
|
2779
|
+
env["GIT_OPTIONAL_LOCKS"] ??= "0";
|
|
2780
|
+
if (!shouldSyncBashEnv(requestedShell, shell, baseEnv))
|
|
2781
|
+
return { shell, command, env };
|
|
2782
|
+
env["SHELL"] = CODEX_FALLBACK_SHELL;
|
|
2783
|
+
return { shell, command: buildSyncedBashCommand(command, env), env };
|
|
2784
|
+
}
|
|
2785
|
+
function clampYieldTime(yieldTimeMs, fallback) {
|
|
2786
|
+
return Math.min(MAX_YIELD_TIME_MS, Math.max(MIN_YIELD_TIME_MS, yieldTimeMs ?? fallback));
|
|
2787
|
+
}
|
|
2788
|
+
function normalizeMinNonInteractiveExecYieldTime(value) {
|
|
2789
|
+
return Math.min(MAX_EXEC_YIELD_TIME_MS, Math.max(MIN_YIELD_TIME_MS, value ?? MIN_NON_INTERACTIVE_EXEC_YIELD_TIME_MS));
|
|
2790
|
+
}
|
|
2791
|
+
function normalizeMinEmptyWriteYieldTime(value) {
|
|
2792
|
+
return Math.min(MAX_YIELD_TIME_MS, Math.max(MIN_YIELD_TIME_MS, value ?? MIN_EMPTY_WRITE_YIELD_TIME_MS));
|
|
2793
|
+
}
|
|
2794
|
+
function clampExecYieldTime(yieldTimeMs, fallback, isInteractive, minNonInteractiveExecYieldTimeMs, maxYieldTimeMs = MAX_EXEC_YIELD_TIME_MS) {
|
|
2795
|
+
const value = Math.min(maxYieldTimeMs, Math.max(MIN_YIELD_TIME_MS, yieldTimeMs ?? fallback));
|
|
2796
|
+
return isInteractive ? value : Math.min(maxYieldTimeMs, Math.max(minNonInteractiveExecYieldTimeMs, value));
|
|
2797
|
+
}
|
|
2798
|
+
function clampWriteYieldTime(yieldTimeMs, fallback, isEmptyPoll, minEmptyWriteYieldTimeMs, maxEmptyWriteYieldTimeMs) {
|
|
2799
|
+
return isEmptyPoll ? Math.min(maxEmptyWriteYieldTimeMs, Math.max(minEmptyWriteYieldTimeMs, yieldTimeMs ?? fallback)) : clampYieldTime(yieldTimeMs, fallback);
|
|
2800
|
+
}
|
|
2801
|
+
|
|
2802
|
+
// packages/execution/src/shell/wait.ts
|
|
2803
|
+
function registerAbortHandler(signal, onAbort) {
|
|
2804
|
+
if (!signal)
|
|
2805
|
+
return () => {};
|
|
2806
|
+
if (signal.aborted) {
|
|
2807
|
+
onAbort();
|
|
2808
|
+
return () => {};
|
|
2809
|
+
}
|
|
2810
|
+
const abortListener = () => onAbort();
|
|
2811
|
+
signal.addEventListener("abort", abortListener, { once: true });
|
|
2812
|
+
return () => signal.removeEventListener("abort", abortListener);
|
|
2813
|
+
}
|
|
2814
|
+
function waitForExitOrInactivity(session, idleTimeMs, maxWaitMs = idleTimeMs, signal, onUpdate) {
|
|
2815
|
+
if (session.exitCode !== undefined && session.exitCode !== null)
|
|
2816
|
+
return Promise.resolve(0);
|
|
2817
|
+
if (signal?.aborted)
|
|
2818
|
+
return Promise.resolve(0);
|
|
2819
|
+
const startedAt = Date.now();
|
|
2820
|
+
const hardLimitMs = Math.max(idleTimeMs, maxWaitMs);
|
|
2821
|
+
let updateTimer;
|
|
2822
|
+
let idleTimer;
|
|
2823
|
+
let hardTimer;
|
|
2824
|
+
let lastUpdateAt = 0;
|
|
2825
|
+
let outputVersion = session.outputVersion;
|
|
2826
|
+
return new Promise((resolvePromise) => {
|
|
2827
|
+
let abortCleanup;
|
|
2828
|
+
let done = false;
|
|
2829
|
+
const cleanup = () => {
|
|
2830
|
+
if (idleTimer)
|
|
2831
|
+
clearTimeout(idleTimer);
|
|
2832
|
+
if (hardTimer)
|
|
2833
|
+
clearTimeout(hardTimer);
|
|
2834
|
+
if (updateTimer)
|
|
2835
|
+
clearInterval(updateTimer);
|
|
2836
|
+
abortCleanup?.();
|
|
2837
|
+
session.listeners.delete(onWake);
|
|
2838
|
+
};
|
|
2839
|
+
const finish = () => {
|
|
2840
|
+
if (done)
|
|
2841
|
+
return;
|
|
2842
|
+
done = true;
|
|
2843
|
+
cleanup();
|
|
2844
|
+
resolvePromise(Date.now() - startedAt);
|
|
2845
|
+
};
|
|
2846
|
+
const emitUpdate = (force = false) => {
|
|
2847
|
+
const now = Date.now();
|
|
2848
|
+
if (!force && now - lastUpdateAt < 250)
|
|
2849
|
+
return;
|
|
2850
|
+
lastUpdateAt = now;
|
|
2851
|
+
onUpdate?.(now - startedAt);
|
|
2852
|
+
};
|
|
2853
|
+
const onWake = () => {
|
|
2854
|
+
if (session.exitCode === undefined || session.exitCode === null) {
|
|
2855
|
+
if (session.outputVersion !== outputVersion) {
|
|
2856
|
+
outputVersion = session.outputVersion;
|
|
2857
|
+
if (idleTimer)
|
|
2858
|
+
clearTimeout(idleTimer);
|
|
2859
|
+
idleTimer = setTimeout(finish, idleTimeMs);
|
|
2860
|
+
}
|
|
2861
|
+
emitUpdate();
|
|
2862
|
+
return;
|
|
2863
|
+
}
|
|
2864
|
+
emitUpdate(true);
|
|
2865
|
+
finish();
|
|
2866
|
+
};
|
|
2867
|
+
idleTimer = setTimeout(finish, idleTimeMs);
|
|
2868
|
+
hardTimer = setTimeout(finish, hardLimitMs);
|
|
2869
|
+
abortCleanup = registerAbortHandler(signal, finish);
|
|
2870
|
+
if (onUpdate)
|
|
2871
|
+
updateTimer = setInterval(emitUpdate, 250);
|
|
2872
|
+
session.listeners.add(onWake);
|
|
2873
|
+
});
|
|
2874
|
+
}
|
|
2875
|
+
|
|
2876
|
+
// packages/execution/src/shell/session-manager.ts
|
|
2877
|
+
function createExecSessionManager(options) {
|
|
2878
|
+
let nextSessionId = randomBytes2(6).readUIntBE(0, 6);
|
|
2879
|
+
const processSessions = createProcessSessionRuntime(options.backend);
|
|
2880
|
+
let shuttingDown = false;
|
|
2881
|
+
let shutdownPromise;
|
|
2882
|
+
let baseEnv = { ...options.env ?? options.backend.env };
|
|
2883
|
+
const defaultExecYieldTimeMs = options.defaultExecYieldTimeMs ?? DEFAULT_EXEC_YIELD_TIME_MS;
|
|
2884
|
+
const defaultWriteYieldTimeMs = options.defaultWriteYieldTimeMs ?? DEFAULT_WRITE_YIELD_TIME_MS;
|
|
2885
|
+
const minNonInteractiveExecYieldTimeMs = normalizeMinNonInteractiveExecYieldTime(options.minNonInteractiveExecYieldTimeMs);
|
|
2886
|
+
const minEmptyWriteYieldTimeMs = normalizeMinEmptyWriteYieldTime(options.minEmptyWriteYieldTimeMs);
|
|
2887
|
+
const maxEmptyWriteYieldTimeMs = Math.max(minEmptyWriteYieldTimeMs, options.maxEmptyWriteYieldTimeMs ?? DEFAULT_MAX_EMPTY_WRITE_YIELD_TIME_MS);
|
|
2888
|
+
const configuredMaxSessionBufferChars = options.maxSessionBufferChars === undefined ? undefined : Math.max(1024, options.maxSessionBufferChars);
|
|
2889
|
+
function setBaseEnv(env) {
|
|
2890
|
+
baseEnv = { ...env };
|
|
2891
|
+
}
|
|
2892
|
+
const store = new ExecSessionStore(configuredMaxSessionBufferChars);
|
|
2893
|
+
const processHooks = {
|
|
2894
|
+
isOwned: (session) => !shuttingDown && store.get(session.id) === session,
|
|
2895
|
+
onOutput: (session, text) => store.appendOutput(session, text),
|
|
2896
|
+
onExit: (session) => store.finalizeSession(session)
|
|
2897
|
+
};
|
|
2898
|
+
return {
|
|
2899
|
+
setBaseEnv,
|
|
2900
|
+
exec: async (input, cwd, signal, onUpdate) => {
|
|
2901
|
+
if (shuttingDown)
|
|
2902
|
+
throw new Error("exec manager is shut down");
|
|
2903
|
+
signal?.throwIfAborted();
|
|
2904
|
+
const requestedShell = input.shell ?? input.defaultShell;
|
|
2905
|
+
const shell = resolveShell(requestedShell, options.backend.platform, options.backend.defaultShell);
|
|
2906
|
+
const workdir = input.workdir ?? cwd;
|
|
2907
|
+
const execution = resolveExecution(requestedShell, input.cmd, input.env, baseEnv, options.backend.platform, options.backend.defaultShell);
|
|
2908
|
+
const session = processSessions.create({
|
|
2909
|
+
id: nextSessionId++,
|
|
2910
|
+
input: {
|
|
2911
|
+
command: input.cmd,
|
|
2912
|
+
executionCommand: execution.command,
|
|
2913
|
+
executionEnv: execution.env,
|
|
2914
|
+
...input.tty === undefined ? {} : { tty: input.tty },
|
|
2915
|
+
...input.login === undefined ? {} : { login: input.login }
|
|
2916
|
+
},
|
|
2917
|
+
workdir,
|
|
2918
|
+
shell,
|
|
2919
|
+
...signal ? { signal } : {},
|
|
2920
|
+
hooks: processHooks
|
|
2921
|
+
});
|
|
2922
|
+
store.add(session);
|
|
2923
|
+
const abortCleanup = registerAbortHandler(signal, () => {
|
|
2924
|
+
if (session.exitCode === undefined)
|
|
2925
|
+
session.terminating = true;
|
|
2926
|
+
});
|
|
2927
|
+
try {
|
|
2928
|
+
onUpdate?.(makeSnapshotResult(session, 0, input.max_output_tokens, true));
|
|
2929
|
+
const execYieldMs = clampExecYieldTime(input.yield_time_ms, defaultExecYieldTimeMs, session.interactive, minNonInteractiveExecYieldTimeMs, input.max_yield_time_ms);
|
|
2930
|
+
const maxExecWaitMs = Math.max(execYieldMs, input.max_yield_time_ms ?? execYieldMs);
|
|
2931
|
+
let waitedMs = 0;
|
|
2932
|
+
let idleTimeMs = execYieldMs;
|
|
2933
|
+
for (;; ) {
|
|
2934
|
+
const elapsedMs = await waitForExitOrInactivity(session, idleTimeMs, maxExecWaitMs, signal, onUpdate ? (elapsed) => onUpdate(makeSnapshotResult(session, waitedMs + elapsed, input.max_output_tokens)) : undefined);
|
|
2935
|
+
waitedMs += elapsedMs;
|
|
2936
|
+
if (signal?.aborted) {
|
|
2937
|
+
throw signal.reason instanceof Error ? signal.reason : new Error("exec aborted");
|
|
2938
|
+
}
|
|
2939
|
+
if (!input.wait_until_exit || session.exitCode !== undefined && session.exitCode !== null)
|
|
2940
|
+
break;
|
|
2941
|
+
idleTimeMs = Math.min(maxExecWaitMs, idleTimeMs * 2);
|
|
2942
|
+
}
|
|
2943
|
+
await processSessions.waitForStartup(session, signal);
|
|
2944
|
+
if (session.exitCode === undefined || session.exitCode === null)
|
|
2945
|
+
session.nextEmptyPollYieldMs = growEmptyPollYield(Math.max(execYieldMs, waitedMs), maxEmptyWriteYieldTimeMs);
|
|
2946
|
+
return store.finishResult(session, waitedMs, input.max_output_tokens);
|
|
2947
|
+
} catch (error) {
|
|
2948
|
+
if (signal?.aborted) {
|
|
2949
|
+
await processSessions.terminate(session);
|
|
2950
|
+
store.remove(session.id);
|
|
2951
|
+
}
|
|
2952
|
+
throw error;
|
|
2953
|
+
} finally {
|
|
2954
|
+
abortCleanup();
|
|
2955
|
+
}
|
|
2956
|
+
},
|
|
2957
|
+
write: async (input, signal, onUpdate) => {
|
|
2958
|
+
if (shuttingDown)
|
|
2959
|
+
throw new Error("exec manager is shut down");
|
|
2960
|
+
if (signal?.aborted) {
|
|
2961
|
+
throw new Error("write_stdin aborted");
|
|
2962
|
+
}
|
|
2963
|
+
const session = store.get(input.session_id);
|
|
2964
|
+
if (!session) {
|
|
2965
|
+
const completed = store.completedPoll(input.session_id, input.chars ?? "", input.max_output_tokens);
|
|
2966
|
+
if (completed)
|
|
2967
|
+
return completed;
|
|
2968
|
+
throw new Error(`Unknown or expired process id ${input.session_id}; sessions are process-local and do not survive restart`);
|
|
2969
|
+
}
|
|
2970
|
+
const updateBaseline = session.bufferStartOffset + session.buffer.length;
|
|
2971
|
+
const chars = input.chars ?? "";
|
|
2972
|
+
const isEmptyPoll = chars.length === 0;
|
|
2973
|
+
if (!isEmptyPoll) {
|
|
2974
|
+
if (!session.interactive) {
|
|
2975
|
+
throw new Error("stdin is closed for this session; rerun exec_command with tty=true to keep stdin open");
|
|
2976
|
+
}
|
|
2977
|
+
await processSessions.write(session, chars);
|
|
2978
|
+
session.nextEmptyPollYieldMs = undefined;
|
|
2979
|
+
}
|
|
2980
|
+
onUpdate?.(makeSnapshotSince(session, 0, updateBaseline, input.max_output_tokens));
|
|
2981
|
+
const requestedYieldMs = clampWriteYieldTime(input.yield_time_ms, defaultWriteYieldTimeMs, isEmptyPoll, minEmptyWriteYieldTimeMs, maxEmptyWriteYieldTimeMs);
|
|
2982
|
+
const effectiveYieldMs = isEmptyPoll ? Math.max(requestedYieldMs, session.nextEmptyPollYieldMs ?? 0) : requestedYieldMs;
|
|
2983
|
+
const abortCleanup = registerAbortHandler(signal, () => {
|
|
2984
|
+
session.terminating = true;
|
|
2985
|
+
});
|
|
2986
|
+
try {
|
|
2987
|
+
const waitedMs = session.exitCode === undefined ? await waitForExitOrInactivity(session, effectiveYieldMs, effectiveYieldMs, signal, onUpdate ? (elapsedMs) => onUpdate(makeSnapshotSince(session, elapsedMs, updateBaseline, input.max_output_tokens)) : undefined) : 0;
|
|
2988
|
+
await processSessions.waitForStartup(session, signal);
|
|
2989
|
+
if (isEmptyPoll && (session.exitCode === undefined || session.exitCode === null))
|
|
2990
|
+
session.nextEmptyPollYieldMs = growEmptyPollYield(effectiveYieldMs, maxEmptyWriteYieldTimeMs);
|
|
2991
|
+
signal?.throwIfAborted();
|
|
2992
|
+
return store.finishResult(session, waitedMs, input.max_output_tokens);
|
|
2993
|
+
} catch (error) {
|
|
2994
|
+
if (signal?.aborted)
|
|
2995
|
+
await processSessions.terminate(session);
|
|
2996
|
+
throw error;
|
|
2997
|
+
} finally {
|
|
2998
|
+
abortCleanup();
|
|
2999
|
+
}
|
|
3000
|
+
},
|
|
3001
|
+
hasSession: (id) => store.hasSession(id),
|
|
3002
|
+
getSessionCommand: (id) => store.getSessionCommand(id),
|
|
3003
|
+
listSessions: (maxOutputChars) => store.listSessions(maxOutputChars),
|
|
3004
|
+
terminateSession: (id) => store.terminateSession(id, processSessions.terminate),
|
|
3005
|
+
onSessionChange: (listener) => store.onSessionChange(listener),
|
|
3006
|
+
onSessionExit: (listener) => store.onSessionExit(listener),
|
|
3007
|
+
shutdown: () => shutdownPromise ??= (async () => {
|
|
3008
|
+
shuttingDown = true;
|
|
3009
|
+
try {
|
|
3010
|
+
await processSessions.shutdown();
|
|
3011
|
+
} finally {
|
|
3012
|
+
store.clear();
|
|
3013
|
+
}
|
|
3014
|
+
})()
|
|
3015
|
+
};
|
|
3016
|
+
}
|
|
3017
|
+
function growEmptyPollYield(currentMs, maximumMs) {
|
|
3018
|
+
return Math.min(maximumMs, currentMs * 2);
|
|
3019
|
+
}
|
|
3020
|
+
|
|
3021
|
+
// packages/execution/src/shell/node-backend.ts
|
|
3022
|
+
import { spawn } from "node:child_process";
|
|
3023
|
+
import { constants } from "node:os";
|
|
3024
|
+
function createNodeShellBackend(options) {
|
|
3025
|
+
if (!options.environmentId)
|
|
3026
|
+
throw new Error("Node shell backend requires an explicit local environmentId");
|
|
3027
|
+
const env = { ...options.env ?? process.env };
|
|
3028
|
+
const defaultShell = getCodexRuntimeShell(options.defaultShell ?? env["SHELL"], process.platform, process.platform === "win32" ? env["COMSPEC"] ?? "cmd.exe" : "/bin/bash");
|
|
3029
|
+
return {
|
|
3030
|
+
environmentId: options.environmentId,
|
|
3031
|
+
platform: process.platform,
|
|
3032
|
+
env,
|
|
3033
|
+
defaultShell,
|
|
3034
|
+
spawn: (request, events) => request.tty ? spawnPty(request, events) : spawnPipe(request, events)
|
|
3035
|
+
};
|
|
3036
|
+
}
|
|
3037
|
+
function exitCode(code, signal) {
|
|
3038
|
+
return code ?? (signal ? 128 + constants.signals[signal] : 1);
|
|
3039
|
+
}
|
|
3040
|
+
function spawnPipe(request, events) {
|
|
3041
|
+
return new Promise((resolve, reject) => {
|
|
3042
|
+
const child = spawn(request.shell, [...request.args], {
|
|
3043
|
+
cwd: request.cwd,
|
|
3044
|
+
env: request.env,
|
|
3045
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
3046
|
+
detached: process.platform !== "win32"
|
|
3047
|
+
});
|
|
3048
|
+
let closed = false;
|
|
3049
|
+
let terminating;
|
|
3050
|
+
let drainTimer;
|
|
3051
|
+
let resolveClosed;
|
|
3052
|
+
const completion = new Promise((done) => {
|
|
3053
|
+
resolveClosed = done;
|
|
3054
|
+
});
|
|
3055
|
+
const finish = (code) => {
|
|
3056
|
+
if (closed)
|
|
3057
|
+
return;
|
|
3058
|
+
if (terminating && process.platform !== "win32")
|
|
3059
|
+
kill("SIGKILL");
|
|
3060
|
+
closed = true;
|
|
3061
|
+
if (drainTimer)
|
|
3062
|
+
clearTimeout(drainTimer);
|
|
3063
|
+
child.stdout.destroy();
|
|
3064
|
+
child.stderr.destroy();
|
|
3065
|
+
events.closed(code);
|
|
3066
|
+
resolveClosed();
|
|
3067
|
+
};
|
|
3068
|
+
const kill = (signal) => {
|
|
3069
|
+
try {
|
|
3070
|
+
if (process.platform !== "win32" && child.pid)
|
|
3071
|
+
process.kill(-child.pid, signal);
|
|
3072
|
+
else
|
|
3073
|
+
child.kill(signal);
|
|
3074
|
+
} catch (error) {
|
|
3075
|
+
if (error.code !== "ESRCH")
|
|
3076
|
+
throw error;
|
|
3077
|
+
}
|
|
3078
|
+
};
|
|
3079
|
+
child.stdout.on("data", (chunk) => events.output("stdout", chunk));
|
|
3080
|
+
child.stderr.on("data", (chunk) => events.output("stderr", chunk));
|
|
3081
|
+
child.once("error", (error) => {
|
|
3082
|
+
finish(1);
|
|
3083
|
+
reject(error);
|
|
3084
|
+
});
|
|
3085
|
+
child.once("exit", (code, signal) => {
|
|
3086
|
+
if (closed)
|
|
3087
|
+
return;
|
|
3088
|
+
drainTimer = setTimeout(() => finish(exitCode(code, signal)), 1000);
|
|
3089
|
+
});
|
|
3090
|
+
child.once("close", (code, signal) => finish(exitCode(code, signal)));
|
|
3091
|
+
child.once("spawn", () => resolve({
|
|
3092
|
+
write: async () => {
|
|
3093
|
+
throw new Error("stdin is closed for this session; rerun exec_command with tty=true to keep stdin open");
|
|
3094
|
+
},
|
|
3095
|
+
terminate: () => terminating ??= (async () => {
|
|
3096
|
+
if (closed)
|
|
3097
|
+
return;
|
|
3098
|
+
kill("SIGKILL");
|
|
3099
|
+
await completion;
|
|
3100
|
+
})()
|
|
3101
|
+
}));
|
|
3102
|
+
});
|
|
3103
|
+
}
|
|
3104
|
+
async function spawnPty(request, events) {
|
|
3105
|
+
if (process.versions["bun"])
|
|
3106
|
+
throw new Error("The local PTY backend requires a Node.js host; run the host with Node.js or select a compatible process backend");
|
|
3107
|
+
let pty;
|
|
3108
|
+
try {
|
|
3109
|
+
pty = await import("node-pty");
|
|
3110
|
+
} catch (cause) {
|
|
3111
|
+
throw new Error("Local PTY capability unavailable; install or rebuild node-pty@1.1.0 for this Node.js host", { cause });
|
|
3112
|
+
}
|
|
3113
|
+
const env = Object.fromEntries(Object.entries(request.env).filter((entry) => typeof entry[1] === "string"));
|
|
3114
|
+
const terminal = pty.spawn(request.shell, [...request.args], {
|
|
3115
|
+
cwd: request.cwd,
|
|
3116
|
+
env,
|
|
3117
|
+
name: "xterm-256color",
|
|
3118
|
+
cols: 80,
|
|
3119
|
+
rows: 24,
|
|
3120
|
+
encoding: null
|
|
3121
|
+
});
|
|
3122
|
+
let closed = false;
|
|
3123
|
+
let terminating;
|
|
3124
|
+
let resolveClosed;
|
|
3125
|
+
const completion = new Promise((done) => {
|
|
3126
|
+
resolveClosed = done;
|
|
3127
|
+
});
|
|
3128
|
+
const kill = (signal) => {
|
|
3129
|
+
try {
|
|
3130
|
+
if (process.platform !== "win32")
|
|
3131
|
+
process.kill(-terminal.pid, signal);
|
|
3132
|
+
else
|
|
3133
|
+
terminal.kill(signal);
|
|
3134
|
+
} catch (error) {
|
|
3135
|
+
if (error.code !== "ESRCH")
|
|
3136
|
+
throw error;
|
|
3137
|
+
}
|
|
3138
|
+
};
|
|
3139
|
+
const data = terminal.onData((chunk) => events.output("pty", chunk));
|
|
3140
|
+
const exited = terminal.onExit((result) => {
|
|
3141
|
+
if (terminating && process.platform !== "win32")
|
|
3142
|
+
kill("SIGKILL");
|
|
3143
|
+
closed = true;
|
|
3144
|
+
data.dispose();
|
|
3145
|
+
exited.dispose();
|
|
3146
|
+
events.closed(result.signal ? 128 + result.signal : result.exitCode);
|
|
3147
|
+
resolveClosed();
|
|
3148
|
+
});
|
|
3149
|
+
return {
|
|
3150
|
+
write: async (chars) => {
|
|
3151
|
+
if (closed)
|
|
3152
|
+
throw new Error("Process already exited; cannot write stdin");
|
|
3153
|
+
terminal.write(chars);
|
|
3154
|
+
},
|
|
3155
|
+
terminate: () => terminating ??= (async () => {
|
|
3156
|
+
if (closed)
|
|
3157
|
+
return;
|
|
3158
|
+
kill("SIGKILL");
|
|
3159
|
+
await completion;
|
|
3160
|
+
})()
|
|
3161
|
+
};
|
|
3162
|
+
}
|
|
3163
|
+
|
|
3164
|
+
// packages/execution/src/shell.ts
|
|
3165
|
+
var execSchema = Type.Object({
|
|
3166
|
+
cmd: Type.String({
|
|
3167
|
+
description: "Shell command; do not quote the entire command"
|
|
3168
|
+
}),
|
|
3169
|
+
workdir: Type.Optional(Type.String({ description: "Cwd" })),
|
|
3170
|
+
shell: Type.Optional(Type.String()),
|
|
3171
|
+
tty: Type.Optional(Type.Boolean({ description: "Keep stdin open for input or interruption" })),
|
|
3172
|
+
yield_time_ms: Type.Optional(Type.Number({ description: "Wait ms" })),
|
|
3173
|
+
max_output_tokens: Type.Optional(Type.Number({ description: "Truncate" })),
|
|
3174
|
+
login: Type.Optional(Type.Boolean())
|
|
3175
|
+
});
|
|
3176
|
+
var writeSchema = Type.Object({
|
|
3177
|
+
session_id: Type.Number(),
|
|
3178
|
+
chars: Type.Optional(Type.String({
|
|
3179
|
+
description: "Input requires original exec_command tty=true; omit or empty to poll"
|
|
3180
|
+
})),
|
|
3181
|
+
yield_time_ms: Type.Optional(Type.Number({ description: "Wait ms" })),
|
|
3182
|
+
max_output_tokens: Type.Optional(Type.Number({ description: "Truncate" }))
|
|
3183
|
+
});
|
|
3184
|
+
var outputLimits = {
|
|
3185
|
+
maxBytes: Number.MAX_SAFE_INTEGER,
|
|
3186
|
+
maxLines: Number.MAX_SAFE_INTEGER,
|
|
3187
|
+
retain: "tail"
|
|
3188
|
+
};
|
|
3189
|
+
function createShellRuntime(options) {
|
|
3190
|
+
if (!options.backend?.environmentId)
|
|
3191
|
+
throw new Error("Shell runtime requires an explicitly namespace-bound process backend");
|
|
3192
|
+
const sessions = createExecSessionManager(options);
|
|
3193
|
+
const ensureEnvironment = (env) => {
|
|
3194
|
+
if (!env)
|
|
3195
|
+
throw new Error("Shell tools require an execution environment");
|
|
3196
|
+
if (env.id !== options.backend.environmentId)
|
|
3197
|
+
throw new Error(`Shell process backend is bound to environment ${options.backend.environmentId}, not ${env.id}; select a backend for this environment`);
|
|
3198
|
+
return env;
|
|
3199
|
+
};
|
|
3200
|
+
const exec = defineTool({
|
|
3201
|
+
name: "exec_command",
|
|
3202
|
+
description: "Run shell commands; may return session_id",
|
|
3203
|
+
parameters: execSchema,
|
|
3204
|
+
replay: "unsafe",
|
|
3205
|
+
prepareArguments: prepareExecArguments,
|
|
3206
|
+
outputLimits,
|
|
3207
|
+
async execute(args, api, context) {
|
|
3208
|
+
context.abortSignal?.throwIfAborted();
|
|
3209
|
+
const env = ensureEnvironment(api.env);
|
|
3210
|
+
const cwd = args.workdir ? getOrThrow(await env.absolutePath(args.workdir, context)) : env.cwd;
|
|
3211
|
+
const input = {
|
|
3212
|
+
...args,
|
|
3213
|
+
workdir: cwd,
|
|
3214
|
+
...!args.tty ? {
|
|
3215
|
+
max_yield_time_ms: MAX_EXEC_YIELD_TIME_MS,
|
|
3216
|
+
wait_until_exit: options.waitForNonInteractiveExit ?? false
|
|
3217
|
+
} : {}
|
|
3218
|
+
};
|
|
3219
|
+
const updates = createUpdates((partial) => api.details(partial, context), context);
|
|
3220
|
+
try {
|
|
3221
|
+
const result = await sessions.exec(input, cwd, context.abortSignal, updates.emit);
|
|
3222
|
+
await updates.flush();
|
|
3223
|
+
return toToolResult(result);
|
|
3224
|
+
} finally {
|
|
3225
|
+
await updates.flush();
|
|
3226
|
+
}
|
|
3227
|
+
}
|
|
3228
|
+
});
|
|
3229
|
+
const write = defineTool({
|
|
3230
|
+
name: "write_stdin",
|
|
3231
|
+
description: "Write/poll exec session",
|
|
3232
|
+
parameters: writeSchema,
|
|
3233
|
+
replay: "unsafe",
|
|
3234
|
+
outputLimits,
|
|
3235
|
+
async execute(args, api, context) {
|
|
3236
|
+
ensureEnvironment(api.env);
|
|
3237
|
+
const updates = createUpdates((partial) => api.details(partial, context), context);
|
|
3238
|
+
try {
|
|
3239
|
+
const result = await sessions.write(args, context.abortSignal, updates.emit);
|
|
3240
|
+
await updates.flush();
|
|
3241
|
+
return toToolResult(result);
|
|
3242
|
+
} catch (error) {
|
|
3243
|
+
throw new Error(`write_stdin failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
3244
|
+
} finally {
|
|
3245
|
+
await updates.flush();
|
|
3246
|
+
}
|
|
3247
|
+
}
|
|
3248
|
+
});
|
|
3249
|
+
return {
|
|
3250
|
+
tools: Object.freeze([exec, write]),
|
|
3251
|
+
close: () => sessions.shutdown()
|
|
3252
|
+
};
|
|
3253
|
+
}
|
|
3254
|
+
function toToolResult(result) {
|
|
3255
|
+
return {
|
|
3256
|
+
output: [{ type: "text", text: formatUnifiedExecResult(result) }],
|
|
3257
|
+
details: result
|
|
3258
|
+
};
|
|
3259
|
+
}
|
|
3260
|
+
function prepareExecArguments(args) {
|
|
3261
|
+
if (!args || typeof args !== "object")
|
|
3262
|
+
throw new Error("exec_command requires an object parameter");
|
|
3263
|
+
const prepared = { ...args };
|
|
3264
|
+
if (!("cmd" in prepared) && "command" in prepared)
|
|
3265
|
+
prepared["cmd"] = prepared["command"];
|
|
3266
|
+
if (!("workdir" in prepared)) {
|
|
3267
|
+
if ("cwd" in prepared)
|
|
3268
|
+
prepared["workdir"] = prepared["cwd"];
|
|
3269
|
+
else if ("working_directory" in prepared)
|
|
3270
|
+
prepared["workdir"] = prepared["working_directory"];
|
|
3271
|
+
}
|
|
3272
|
+
return prepared;
|
|
3273
|
+
}
|
|
3274
|
+
function createUpdates(write, context) {
|
|
3275
|
+
let pending = Promise.resolve();
|
|
3276
|
+
let failure;
|
|
3277
|
+
return {
|
|
3278
|
+
emit: (result) => {
|
|
3279
|
+
pending = pending.then(async () => {
|
|
3280
|
+
if (failure !== undefined || context.abortSignal?.aborted)
|
|
3281
|
+
return;
|
|
3282
|
+
try {
|
|
3283
|
+
await write(result);
|
|
3284
|
+
} catch (error) {
|
|
3285
|
+
failure = error;
|
|
3286
|
+
}
|
|
3287
|
+
});
|
|
3288
|
+
},
|
|
3289
|
+
flush: async () => {
|
|
3290
|
+
await pending;
|
|
3291
|
+
if (failure !== undefined && !context.abortSignal?.aborted)
|
|
3292
|
+
throw failure;
|
|
3293
|
+
}
|
|
3294
|
+
};
|
|
3295
|
+
}
|
|
3296
|
+
|
|
3297
|
+
// packages/code/src/cell-output.ts
|
|
3298
|
+
import { copyJson as copyJson11 } from "@earendil-works/chord";
|
|
3299
|
+
|
|
3300
|
+
// packages/code/src/result.ts
|
|
3301
|
+
function runtimeResult(response, maxTokens = 1e4) {
|
|
3302
|
+
const content = [];
|
|
3303
|
+
let chars = Math.max(1, Math.min(1e5, maxTokens)) * 4;
|
|
3304
|
+
let imageChars = 0;
|
|
3305
|
+
let images = 0;
|
|
3306
|
+
let omitted = 0;
|
|
3307
|
+
let truncated = false;
|
|
3308
|
+
for (const item of response.contentItems) {
|
|
3309
|
+
if (item.type === "input_text") {
|
|
3310
|
+
if (item.text.length > chars) {
|
|
3311
|
+
if (!truncated)
|
|
3312
|
+
content.push({
|
|
3313
|
+
type: "text",
|
|
3314
|
+
text: `${item.text.slice(0, chars)}
|
|
3315
|
+
${TRUNCATED_OUTPUT_NOTICE}`
|
|
3316
|
+
});
|
|
3317
|
+
truncated = true;
|
|
3318
|
+
chars = 0;
|
|
3319
|
+
} else {
|
|
3320
|
+
content.push({ type: "text", text: item.text });
|
|
3321
|
+
chars -= item.text.length;
|
|
3322
|
+
}
|
|
3323
|
+
} else {
|
|
3324
|
+
const match = /^data:([^;,]+);base64,(.+)$/s.exec(item.image_url);
|
|
3325
|
+
if (!match?.[1] || !match[2])
|
|
3326
|
+
throw new Error("Code host image must be a base64 data URL");
|
|
3327
|
+
if (images >= 4 || imageChars + match[2].length > 16 * 1024 * 1024) {
|
|
3328
|
+
omitted++;
|
|
3329
|
+
continue;
|
|
3330
|
+
}
|
|
3331
|
+
images++;
|
|
3332
|
+
imageChars += match[2].length;
|
|
3333
|
+
content.push({ type: "image", mimeType: match[1], data: match[2] });
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
3336
|
+
if (omitted)
|
|
3337
|
+
content.push({
|
|
3338
|
+
type: "text",
|
|
3339
|
+
text: `[${omitted} code-mode images omitted]`
|
|
3340
|
+
});
|
|
3341
|
+
if (response.errorText)
|
|
3342
|
+
content.unshift({
|
|
3343
|
+
type: "text",
|
|
3344
|
+
text: `Script error: ${response.errorText}`
|
|
3345
|
+
});
|
|
3346
|
+
if (response.kind === "terminated")
|
|
3347
|
+
content.unshift({ type: "text", text: "Script terminated" });
|
|
3348
|
+
return {
|
|
3349
|
+
output: content,
|
|
3350
|
+
...response.errorText ? { isError: true } : {},
|
|
3351
|
+
details: {
|
|
3352
|
+
codeMode: true,
|
|
3353
|
+
runtimeCellId: response.cellId,
|
|
3354
|
+
status: response.kind,
|
|
3355
|
+
...response.errorText ? { scriptError: response.errorText } : {}
|
|
3356
|
+
}
|
|
3357
|
+
};
|
|
3358
|
+
}
|
|
3359
|
+
|
|
3360
|
+
// packages/code/src/cell-output.ts
|
|
3361
|
+
class CodeCellOutput {
|
|
3362
|
+
maxTokens;
|
|
3363
|
+
delivery;
|
|
3364
|
+
output = [];
|
|
3365
|
+
remainingChars = 0;
|
|
3366
|
+
imageChars = 0;
|
|
3367
|
+
imageCount = 0;
|
|
3368
|
+
omittedImages = 0;
|
|
3369
|
+
truncated = false;
|
|
3370
|
+
revision = 0;
|
|
3371
|
+
notifications = [];
|
|
3372
|
+
append(items) {
|
|
3373
|
+
for (const item of items) {
|
|
3374
|
+
if (item.type === "input_image") {
|
|
3375
|
+
if (this.imageCount >= 4 || this.imageChars + item.image_url.length > 16 * 1024 * 1024) {
|
|
3376
|
+
this.omittedImages++;
|
|
3377
|
+
} else {
|
|
3378
|
+
this.output.push(item);
|
|
3379
|
+
this.imageCount++;
|
|
3380
|
+
this.imageChars += item.image_url.length;
|
|
3381
|
+
}
|
|
3382
|
+
} else if (item.text.length === 0) {
|
|
3383
|
+
continue;
|
|
3384
|
+
} else if (this.remainingChars > 0) {
|
|
3385
|
+
const text = item.text.slice(0, this.remainingChars);
|
|
3386
|
+
this.remainingChars -= text.length;
|
|
3387
|
+
this.output.push({ ...item, text });
|
|
3388
|
+
if (text.length < item.text.length && !this.truncated) {
|
|
3389
|
+
this.truncated = true;
|
|
3390
|
+
this.output.push({
|
|
3391
|
+
type: "input_text",
|
|
3392
|
+
text: TRUNCATED_OUTPUT_NOTICE
|
|
3393
|
+
});
|
|
3394
|
+
}
|
|
3395
|
+
} else if (!this.truncated) {
|
|
3396
|
+
this.truncated = true;
|
|
3397
|
+
this.output.push({ type: "input_text", text: TRUNCATED_OUTPUT_NOTICE });
|
|
3398
|
+
}
|
|
3399
|
+
}
|
|
3400
|
+
}
|
|
3401
|
+
traces = [];
|
|
3402
|
+
droppedTraceCount = 0;
|
|
3403
|
+
current = {
|
|
3404
|
+
kind: "yielded",
|
|
3405
|
+
cellId: "pending",
|
|
3406
|
+
contentItems: this.output
|
|
3407
|
+
};
|
|
3408
|
+
constructor(maxTokens) {
|
|
3409
|
+
this.maxTokens = maxTokens;
|
|
3410
|
+
this.remainingChars = maxTokens * 4;
|
|
3411
|
+
}
|
|
3412
|
+
result() {
|
|
3413
|
+
const result = runtimeResult({
|
|
3414
|
+
...this.current,
|
|
3415
|
+
contentItems: [
|
|
3416
|
+
...this.output,
|
|
3417
|
+
...this.omittedImages ? [
|
|
3418
|
+
{
|
|
3419
|
+
type: "input_text",
|
|
3420
|
+
text: `[${this.omittedImages} code-mode images omitted]`
|
|
3421
|
+
}
|
|
3422
|
+
] : []
|
|
3423
|
+
]
|
|
3424
|
+
}, this.maxTokens);
|
|
3425
|
+
return {
|
|
3426
|
+
...result,
|
|
3427
|
+
details: {
|
|
3428
|
+
runtimeCellId: this.current.cellId,
|
|
3429
|
+
status: this.current.kind,
|
|
3430
|
+
codeMode: true,
|
|
3431
|
+
traces: this.traces.map((trace) => ({ ...trace })),
|
|
3432
|
+
droppedTraceCount: this.droppedTraceCount,
|
|
3433
|
+
deliveryRevision: this.revision,
|
|
3434
|
+
...this.current.errorText ? { scriptError: this.current.errorText } : {}
|
|
3435
|
+
}
|
|
3436
|
+
};
|
|
3437
|
+
}
|
|
3438
|
+
notify(text) {
|
|
3439
|
+
this.notifications.push({ type: "input_text", text });
|
|
3440
|
+
if (this.notifications.length > 100)
|
|
3441
|
+
this.notifications.shift();
|
|
3442
|
+
}
|
|
3443
|
+
trace(id, name, input) {
|
|
3444
|
+
if (this.traces.length === 50) {
|
|
3445
|
+
this.traces.shift();
|
|
3446
|
+
this.droppedTraceCount++;
|
|
3447
|
+
}
|
|
3448
|
+
const trace = {
|
|
3449
|
+
id,
|
|
3450
|
+
name,
|
|
3451
|
+
input: JSON.stringify(input).slice(0, 16384),
|
|
3452
|
+
status: "running",
|
|
3453
|
+
nativeCallIds: []
|
|
3454
|
+
};
|
|
3455
|
+
this.traces.push(trace);
|
|
3456
|
+
return {
|
|
3457
|
+
done(result, callId) {
|
|
3458
|
+
trace["status"] = "done";
|
|
3459
|
+
trace["nativeCallIds"] = [callId];
|
|
3460
|
+
trace["result"] = JSON.stringify(result).slice(0, 16384);
|
|
3461
|
+
},
|
|
3462
|
+
failed(error) {
|
|
3463
|
+
trace["status"] = "error";
|
|
3464
|
+
trace["error"] = (error instanceof Error ? error.message : String(error)).slice(0, 16384);
|
|
3465
|
+
}
|
|
3466
|
+
};
|
|
3467
|
+
}
|
|
3468
|
+
replaceObservation(response) {
|
|
3469
|
+
this.current = response;
|
|
3470
|
+
this.output.length = 0;
|
|
3471
|
+
this.remainingChars = this.maxTokens * 4;
|
|
3472
|
+
this.imageChars = 0;
|
|
3473
|
+
this.imageCount = 0;
|
|
3474
|
+
this.omittedImages = 0;
|
|
3475
|
+
this.truncated = false;
|
|
3476
|
+
this.append([...this.notifications.splice(0), ...response.contentItems]);
|
|
3477
|
+
this.revision++;
|
|
3478
|
+
let release;
|
|
3479
|
+
const promise = new Promise((resolve) => {
|
|
3480
|
+
release = resolve;
|
|
3481
|
+
});
|
|
3482
|
+
this.delivery = { delivered: false, promise, release };
|
|
3483
|
+
}
|
|
3484
|
+
get hasOutput() {
|
|
3485
|
+
return this.output.length > 0;
|
|
3486
|
+
}
|
|
3487
|
+
get delivered() {
|
|
3488
|
+
if (!this.delivery)
|
|
3489
|
+
throw new Error("No Code observation to deliver");
|
|
3490
|
+
return this.delivery.promise;
|
|
3491
|
+
}
|
|
3492
|
+
acknowledge(revision) {
|
|
3493
|
+
if (!this.delivery || this.revision !== revision)
|
|
3494
|
+
return true;
|
|
3495
|
+
const fresh = !this.delivery.delivered;
|
|
3496
|
+
this.delivery.delivered = true;
|
|
3497
|
+
this.delivery.release();
|
|
3498
|
+
return fresh;
|
|
3499
|
+
}
|
|
3500
|
+
}
|
|
3501
|
+
function observeCodeCell(observation, maxTokens, acknowledge) {
|
|
3502
|
+
if (observation.recoveredSession)
|
|
3503
|
+
return observation.result;
|
|
3504
|
+
const details = observation.result.details;
|
|
3505
|
+
const revision = details !== null && typeof details === "object" && !Array.isArray(details) ? details["deliveryRevision"] : undefined;
|
|
3506
|
+
const fresh = typeof revision !== "number" || acknowledge(observation.cellId, revision);
|
|
3507
|
+
let remaining = maxTokens * 4;
|
|
3508
|
+
let truncated = false;
|
|
3509
|
+
const content = [];
|
|
3510
|
+
for (const item of fresh || observation.status !== "running" ? observation.result.output ?? [] : []) {
|
|
3511
|
+
if (item.type !== "text") {
|
|
3512
|
+
content.push(item);
|
|
3513
|
+
continue;
|
|
3514
|
+
}
|
|
3515
|
+
if (remaining <= 0) {
|
|
3516
|
+
if (!truncated)
|
|
3517
|
+
content.push({ ...item, text: TRUNCATED_OUTPUT_NOTICE });
|
|
3518
|
+
truncated = true;
|
|
3519
|
+
} else if (item.text.length > remaining) {
|
|
3520
|
+
content.push({
|
|
3521
|
+
...item,
|
|
3522
|
+
text: `${item.text.slice(0, remaining)}
|
|
3523
|
+
${TRUNCATED_OUTPUT_NOTICE}`
|
|
3524
|
+
});
|
|
3525
|
+
remaining = 0;
|
|
3526
|
+
truncated = true;
|
|
3527
|
+
} else {
|
|
3528
|
+
content.push(item);
|
|
3529
|
+
remaining -= item.text.length;
|
|
3530
|
+
}
|
|
3531
|
+
}
|
|
3532
|
+
if (observation.status === "running")
|
|
3533
|
+
content.unshift({
|
|
3534
|
+
type: "text",
|
|
3535
|
+
text: `Still running (exec cell "${observation.cellId}"). Use wait near expected completion`
|
|
3536
|
+
});
|
|
3537
|
+
if (!content.length)
|
|
3538
|
+
content.push({ type: "text", text: "OK" });
|
|
3539
|
+
return {
|
|
3540
|
+
...observation.result,
|
|
3541
|
+
output: content,
|
|
3542
|
+
details: {
|
|
3543
|
+
...details !== null && typeof details === "object" && !Array.isArray(details) ? details : {},
|
|
3544
|
+
cellId: observation.cellId,
|
|
3545
|
+
...observation.forwardedToolCalls === undefined ? {} : {
|
|
3546
|
+
forwardedToolCalls: copyJson11(observation.forwardedToolCalls, {
|
|
3547
|
+
omitUndefinedProperties: true
|
|
3548
|
+
})
|
|
3549
|
+
},
|
|
3550
|
+
status: observation.status
|
|
3551
|
+
}
|
|
3552
|
+
};
|
|
3553
|
+
}
|
|
3554
|
+
|
|
3555
|
+
// packages/code/src/engine.ts
|
|
3556
|
+
import {
|
|
3557
|
+
awaitWithContext as awaitWithContext2,
|
|
3558
|
+
withAbortSignal as withAbortSignal2
|
|
3559
|
+
} from "@earendil-works/chord/context";
|
|
3560
|
+
|
|
3561
|
+
// packages/code/src/binary.ts
|
|
3562
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
3563
|
+
import { homedir } from "node:os";
|
|
3564
|
+
import { join as join2 } from "node:path";
|
|
3565
|
+
|
|
3566
|
+
// packages/code/src/host-assets.ts
|
|
3567
|
+
var HOST_RELEASE = "rust-v0.163.0";
|
|
3568
|
+
var HOST_ASSETS = {
|
|
3569
|
+
"darwin-arm64": [
|
|
3570
|
+
"codex-code-mode-host-aarch64-apple-darwin.tar.gz",
|
|
3571
|
+
"2e28f49a4767a97586843c92692b96481be74d837199b49038f731cec88e9941"
|
|
3572
|
+
],
|
|
3573
|
+
"darwin-x64": [
|
|
3574
|
+
"codex-code-mode-host-x86_64-apple-darwin.tar.gz",
|
|
3575
|
+
"5211c6ed5062c84ba5796e555903c22a6e38fcccf6fe11ee11d7e1b5687ce1fd"
|
|
3576
|
+
],
|
|
3577
|
+
"linux-arm64": [
|
|
3578
|
+
"codex-code-mode-host-aarch64-unknown-linux-musl.tar.gz",
|
|
3579
|
+
"284356aefb197f00b76b912efdfdbae8ccf3ea1f89b976dde064b7ccb43214ef"
|
|
3580
|
+
],
|
|
3581
|
+
"linux-x64": [
|
|
3582
|
+
"codex-code-mode-host-x86_64-unknown-linux-musl.tar.gz",
|
|
3583
|
+
"314263128ba6592e7e807c265deeaf928a692b72dcbfeb5e0b20c9423b703529"
|
|
3584
|
+
],
|
|
3585
|
+
"win32-arm64": [
|
|
3586
|
+
"codex-code-mode-host-aarch64-pc-windows-msvc.exe",
|
|
3587
|
+
"8abfb32791949287a132289a6633fb4e7d79bb616f01244fe2782da226755160"
|
|
3588
|
+
],
|
|
3589
|
+
"win32-x64": [
|
|
3590
|
+
"codex-code-mode-host-x86_64-pc-windows-msvc.exe",
|
|
3591
|
+
"07f3869f0849cd54b31cec1f86ec796f004501bd3a215135c1facc883a2b9988"
|
|
3592
|
+
]
|
|
3593
|
+
};
|
|
3594
|
+
function codeModeHostBinaryName(platform) {
|
|
3595
|
+
return platform === "win32" ? "codex-code-mode-host.exe" : "codex-code-mode-host";
|
|
3596
|
+
}
|
|
3597
|
+
function resolveCodeModeHostAsset(platform, arch) {
|
|
3598
|
+
const asset = HOST_ASSETS[`${platform}-${arch}`];
|
|
3599
|
+
if (!asset)
|
|
3600
|
+
throw new Error(`Unsupported code-mode platform: ${platform}-${arch}`);
|
|
3601
|
+
return asset;
|
|
3602
|
+
}
|
|
3603
|
+
function hostAssetUrl(assetName) {
|
|
3604
|
+
return `https://github.com/openai/codex/releases/download/${HOST_RELEASE}/${assetName}`;
|
|
3605
|
+
}
|
|
3606
|
+
|
|
3607
|
+
// packages/code/src/install-host.ts
|
|
3608
|
+
import { spawnSync } from "node:child_process";
|
|
3609
|
+
import { createHash } from "node:crypto";
|
|
3610
|
+
import {
|
|
3611
|
+
chmodSync,
|
|
3612
|
+
copyFileSync,
|
|
3613
|
+
existsSync,
|
|
3614
|
+
mkdirSync,
|
|
3615
|
+
mkdtempSync,
|
|
3616
|
+
readdirSync,
|
|
3617
|
+
renameSync,
|
|
3618
|
+
rmSync,
|
|
3619
|
+
statSync,
|
|
3620
|
+
writeFileSync
|
|
3621
|
+
} from "node:fs";
|
|
3622
|
+
import { tmpdir } from "node:os";
|
|
3623
|
+
import { basename, join, resolve } from "node:path";
|
|
3624
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
3625
|
+
import { getProxyForUrl } from "proxy-from-env";
|
|
3626
|
+
import { fetch, ProxyAgent } from "undici";
|
|
3627
|
+
var DOWNLOAD_TIMEOUT_MS = 120000;
|
|
3628
|
+
var INSTALL_LOCK_POLL_MS = 200;
|
|
3629
|
+
var INSTALL_LOCK_TIMEOUT_MS = 125000;
|
|
3630
|
+
var INSTALL_LOCK_STALE_MS = 180000;
|
|
3631
|
+
async function installCodeModeHost(options) {
|
|
3632
|
+
const { destination: destinationInput, platform, arch, signal } = options;
|
|
3633
|
+
const [assetName, expectedSha256] = resolveCodeModeHostAsset(platform, arch);
|
|
3634
|
+
const binaryName = codeModeHostBinaryName(platform);
|
|
3635
|
+
const destination = resolve(destinationInput);
|
|
3636
|
+
if (basename(destination) !== binaryName) {
|
|
3637
|
+
throw new Error(`Code-mode host destination must end with ${binaryName}`);
|
|
3638
|
+
}
|
|
3639
|
+
if (existsSync(destination))
|
|
3640
|
+
return;
|
|
3641
|
+
mkdirSync(resolve(destination, ".."), { recursive: true });
|
|
3642
|
+
const lockPath = `${destination}.lock`;
|
|
3643
|
+
if (!await acquireInstallLock(lockPath, destination, signal))
|
|
3644
|
+
return;
|
|
3645
|
+
const temporary = mkdtempSync(join(tmpdir(), "pi-codex-code-mode-"));
|
|
3646
|
+
const staged = `${destination}.${process.pid}.tmp`;
|
|
3647
|
+
try {
|
|
3648
|
+
const assetUrl = hostAssetUrl(assetName);
|
|
3649
|
+
let bytes;
|
|
3650
|
+
const proxy = getProxyForUrl(assetUrl);
|
|
3651
|
+
const dispatcher = proxy ? new ProxyAgent(proxy) : undefined;
|
|
3652
|
+
try {
|
|
3653
|
+
const timeoutSignal = AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS);
|
|
3654
|
+
const response = await fetch(assetUrl, {
|
|
3655
|
+
redirect: "follow",
|
|
3656
|
+
signal: signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal,
|
|
3657
|
+
...dispatcher ? { dispatcher } : {}
|
|
3658
|
+
});
|
|
3659
|
+
if (!response.ok)
|
|
3660
|
+
throw new Error(`download failed: ${response.status} ${response.statusText}`);
|
|
3661
|
+
bytes = Buffer.from(await response.arrayBuffer());
|
|
3662
|
+
} catch (error) {
|
|
3663
|
+
throw new Error(`failed to download ${assetUrl}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
3664
|
+
} finally {
|
|
3665
|
+
await dispatcher?.close();
|
|
3666
|
+
}
|
|
3667
|
+
if (createHash("sha256").update(bytes).digest("hex") !== expectedSha256) {
|
|
3668
|
+
throw new Error(`checksum mismatch for ${assetName}`);
|
|
3669
|
+
}
|
|
3670
|
+
if (platform === "win32") {
|
|
3671
|
+
writeFileSync(staged, bytes);
|
|
3672
|
+
} else {
|
|
3673
|
+
const archive = join(temporary, basename(assetName));
|
|
3674
|
+
writeFileSync(archive, bytes);
|
|
3675
|
+
const extracted = join(temporary, "extracted");
|
|
3676
|
+
mkdirSync(extracted);
|
|
3677
|
+
const result = spawnSync("tar", ["-xzf", archive, "-C", extracted], {
|
|
3678
|
+
stdio: "inherit"
|
|
3679
|
+
});
|
|
3680
|
+
signal?.throwIfAborted();
|
|
3681
|
+
if (result.status !== 0)
|
|
3682
|
+
throw new Error("failed to extract code-mode host archive");
|
|
3683
|
+
const candidates = walk(extracted).filter((path) => basename(path).startsWith("codex-code-mode-host"));
|
|
3684
|
+
if (candidates.length !== 1)
|
|
3685
|
+
throw new Error(`expected one code-mode host binary, found ${candidates.length}`);
|
|
3686
|
+
copyFileSync(candidates[0], staged);
|
|
3687
|
+
chmodSync(staged, 493);
|
|
3688
|
+
}
|
|
3689
|
+
signal?.throwIfAborted();
|
|
3690
|
+
renameSync(staged, destination);
|
|
3691
|
+
} finally {
|
|
3692
|
+
rmSync(staged, { force: true });
|
|
3693
|
+
rmSync(temporary, { recursive: true, force: true });
|
|
3694
|
+
rmSync(lockPath, { recursive: true, force: true });
|
|
3695
|
+
}
|
|
3696
|
+
}
|
|
3697
|
+
async function acquireInstallLock(lockPath, destination, signal) {
|
|
3698
|
+
const deadline = Date.now() + INSTALL_LOCK_TIMEOUT_MS;
|
|
3699
|
+
while (Date.now() < deadline) {
|
|
3700
|
+
signal?.throwIfAborted();
|
|
3701
|
+
if (existsSync(destination))
|
|
3702
|
+
return false;
|
|
3703
|
+
try {
|
|
3704
|
+
mkdirSync(lockPath);
|
|
3705
|
+
return true;
|
|
3706
|
+
} catch (error) {
|
|
3707
|
+
if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST")
|
|
3708
|
+
throw error;
|
|
3709
|
+
try {
|
|
3710
|
+
if (Date.now() - statSync(lockPath).mtimeMs > INSTALL_LOCK_STALE_MS) {
|
|
3711
|
+
rmSync(lockPath, { recursive: true, force: true });
|
|
3712
|
+
continue;
|
|
3713
|
+
}
|
|
3714
|
+
} catch (statError) {
|
|
3715
|
+
if (!statError || typeof statError !== "object" || !("code" in statError) || statError.code !== "ENOENT")
|
|
3716
|
+
throw statError;
|
|
3717
|
+
}
|
|
3718
|
+
await delay(INSTALL_LOCK_POLL_MS, undefined, signal ? { signal } : undefined);
|
|
3719
|
+
}
|
|
3720
|
+
}
|
|
3721
|
+
if (existsSync(destination))
|
|
3722
|
+
return false;
|
|
3723
|
+
throw new Error(`timed out waiting for code-mode host install lock: ${lockPath}`);
|
|
3724
|
+
}
|
|
3725
|
+
function walk(dir) {
|
|
3726
|
+
const paths = [];
|
|
3727
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
3728
|
+
const path = join(dir, entry.name);
|
|
3729
|
+
if (entry.isDirectory())
|
|
3730
|
+
paths.push(...walk(path));
|
|
3731
|
+
else
|
|
3732
|
+
paths.push(path);
|
|
3733
|
+
}
|
|
3734
|
+
return paths;
|
|
3735
|
+
}
|
|
3736
|
+
|
|
3737
|
+
// packages/code/src/binary.ts
|
|
3738
|
+
async function ensureHost(options, signal) {
|
|
3739
|
+
signal?.throwIfAborted();
|
|
3740
|
+
if (options.hostPath !== undefined) {
|
|
3741
|
+
if (!existsSync2(options.hostPath))
|
|
3742
|
+
throw new Error(`Code host does not exist: ${options.hostPath}`);
|
|
3743
|
+
return options.hostPath;
|
|
3744
|
+
}
|
|
3745
|
+
const destination = join2(options.cacheDirectory ?? join2(homedir(), ".cache", "pi-durable-code"), HOST_RELEASE, `${process.platform}-${process.arch}`, codeModeHostBinaryName(process.platform));
|
|
3746
|
+
await installCodeModeHost({
|
|
3747
|
+
destination,
|
|
3748
|
+
platform: process.platform,
|
|
3749
|
+
arch: process.arch,
|
|
3750
|
+
...signal ? { signal } : {}
|
|
3751
|
+
});
|
|
3752
|
+
signal?.throwIfAborted();
|
|
3753
|
+
return destination;
|
|
3754
|
+
}
|
|
3755
|
+
|
|
3756
|
+
// packages/code/src/host-runtime.ts
|
|
3757
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
3758
|
+
|
|
3759
|
+
// packages/code/src/host-protocol.ts
|
|
3760
|
+
function isRecord(value) {
|
|
3761
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
3762
|
+
}
|
|
3763
|
+
function parseHostMessage(value) {
|
|
3764
|
+
if (!isRecord(value) || typeof value["type"] !== "string")
|
|
3765
|
+
throw new Error("Code-mode host returned an invalid message");
|
|
3766
|
+
const type = value["type"];
|
|
3767
|
+
if (type === "connection/ready") {
|
|
3768
|
+
if (value["selectedVersion"] !== 1 || !isStringArray(value["capabilities"]))
|
|
3769
|
+
throw new Error("Code-mode host negotiated an invalid protocol");
|
|
3770
|
+
return { type, selectedVersion: 1, capabilities: value["capabilities"] };
|
|
3771
|
+
}
|
|
3772
|
+
if (type === "connection/rejected")
|
|
3773
|
+
return { type, reason: value["reason"] };
|
|
3774
|
+
if (type === "operation/response" || type === "execute/initialResponse")
|
|
3775
|
+
return {
|
|
3776
|
+
type,
|
|
3777
|
+
id: parseMessageId(value["id"]),
|
|
3778
|
+
result: parseHostResult(value["result"])
|
|
3779
|
+
};
|
|
3780
|
+
if (type === "delegate/cancel")
|
|
3781
|
+
return { type, id: parseMessageId(value["id"]) };
|
|
3782
|
+
if (type === "cell/closed") {
|
|
3783
|
+
if (typeof value["cellId"] !== "string")
|
|
3784
|
+
throw new Error("Code-mode host returned an invalid cell closure");
|
|
3785
|
+
return { type, cellId: value["cellId"] };
|
|
3786
|
+
}
|
|
3787
|
+
if (type === "delegate/request")
|
|
3788
|
+
return { type, ...parseDelegateRequest(value) };
|
|
3789
|
+
throw new Error(`Code-mode host returned an unsupported message: ${type}`);
|
|
3790
|
+
}
|
|
3791
|
+
function executionCellId(value) {
|
|
3792
|
+
return isRecord(value) && value["type"] === "execution/started" && typeof value["cellId"] === "string" ? value["cellId"] : undefined;
|
|
3793
|
+
}
|
|
3794
|
+
function runtimeOutcome(value) {
|
|
3795
|
+
if (!isRecord(value) || !isRecord(value["outcome"]))
|
|
3796
|
+
return;
|
|
3797
|
+
return value["outcome"]["LiveCell"] ?? value["outcome"]["MissingCell"];
|
|
3798
|
+
}
|
|
3799
|
+
function parseDelegateRequest(value) {
|
|
3800
|
+
const id = parseMessageId(value["id"]);
|
|
3801
|
+
const request = value["request"];
|
|
3802
|
+
if (!isRecord(request) || typeof request["type"] !== "string")
|
|
3803
|
+
throw new Error("Code-mode host returned an invalid delegate request");
|
|
3804
|
+
if (request["type"] === "notification/send") {
|
|
3805
|
+
if (typeof request["cellId"] !== "string" || typeof request["text"] !== "string")
|
|
3806
|
+
throw new Error("Code-mode host returned an invalid notification");
|
|
3807
|
+
return {
|
|
3808
|
+
id,
|
|
3809
|
+
request: {
|
|
3810
|
+
type: "notification/send",
|
|
3811
|
+
cellId: request["cellId"],
|
|
3812
|
+
text: request["text"]
|
|
3813
|
+
}
|
|
3814
|
+
};
|
|
3815
|
+
}
|
|
3816
|
+
if (request["type"] !== "tool/invoke" || !isRecord(request["invocation"]))
|
|
3817
|
+
throw new Error("Code-mode host returned an invalid tool invocation");
|
|
3818
|
+
const invocation = request["invocation"];
|
|
3819
|
+
const toolName = invocation["tool_name"];
|
|
3820
|
+
const namespace = isRecord(toolName) ? toolName["namespace"] : undefined;
|
|
3821
|
+
if (typeof invocation["cell_id"] !== "string" || typeof invocation["runtime_tool_call_id"] !== "string" || !isRecord(toolName) || typeof toolName["name"] !== "string" || namespace !== undefined && namespace !== null && typeof namespace !== "string")
|
|
3822
|
+
throw new Error("Code-mode host returned an invalid tool invocation");
|
|
3823
|
+
return {
|
|
3824
|
+
id,
|
|
3825
|
+
request: {
|
|
3826
|
+
type: "tool/invoke",
|
|
3827
|
+
invocation: {
|
|
3828
|
+
cell_id: invocation["cell_id"],
|
|
3829
|
+
runtime_tool_call_id: invocation["runtime_tool_call_id"],
|
|
3830
|
+
tool_name: {
|
|
3831
|
+
name: toolName["name"],
|
|
3832
|
+
...typeof namespace === "string" ? { namespace } : {}
|
|
3833
|
+
},
|
|
3834
|
+
...invocation["input"] === undefined ? {} : { input: invocation["input"] }
|
|
3835
|
+
}
|
|
3836
|
+
}
|
|
3837
|
+
};
|
|
3838
|
+
}
|
|
3839
|
+
function parseHostResult(value) {
|
|
3840
|
+
if (!isRecord(value))
|
|
3841
|
+
throw new Error("Code-mode host returned an invalid operation result");
|
|
3842
|
+
if (value["status"] === "ok")
|
|
3843
|
+
return { status: "ok", value: value["value"] };
|
|
3844
|
+
if (value["status"] === "error" && typeof value["message"] === "string")
|
|
3845
|
+
return { status: "error", message: value["message"] };
|
|
3846
|
+
throw new Error("Code-mode host returned an invalid operation result");
|
|
3847
|
+
}
|
|
3848
|
+
function parseMessageId(value) {
|
|
3849
|
+
if (!Number.isSafeInteger(value) || Number(value) < 0)
|
|
3850
|
+
throw new Error("Code-mode host returned an invalid message id");
|
|
3851
|
+
return Number(value);
|
|
3852
|
+
}
|
|
3853
|
+
function isStringArray(value) {
|
|
3854
|
+
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
3855
|
+
}
|
|
3856
|
+
|
|
3857
|
+
// packages/code/src/host-session.ts
|
|
3858
|
+
import { randomUUID } from "node:crypto";
|
|
3859
|
+
|
|
3860
|
+
// packages/code/src/host-process.ts
|
|
3861
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
3862
|
+
var MAX_FRAME_BYTES = 64 * 1024 * 1024;
|
|
3863
|
+
var MAX_QUEUED_WRITE_BYTES = 128 * 1024 * 1024;
|
|
3864
|
+
|
|
3865
|
+
class CodeModeHostProcess {
|
|
3866
|
+
binary;
|
|
3867
|
+
onMessage;
|
|
3868
|
+
onFailure;
|
|
3869
|
+
child;
|
|
3870
|
+
buffer = Buffer.alloc(0);
|
|
3871
|
+
stderr = "";
|
|
3872
|
+
queuedWriteBytes = 0;
|
|
3873
|
+
constructor(options) {
|
|
3874
|
+
this.binary = options.binary;
|
|
3875
|
+
this.onMessage = options.onMessage;
|
|
3876
|
+
this.onFailure = options.onFailure;
|
|
3877
|
+
}
|
|
3878
|
+
get running() {
|
|
3879
|
+
return this.child !== undefined;
|
|
3880
|
+
}
|
|
3881
|
+
start() {
|
|
3882
|
+
const child = spawn2(this.binary, [], {
|
|
3883
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
3884
|
+
shell: false
|
|
3885
|
+
});
|
|
3886
|
+
this.child = child;
|
|
3887
|
+
this.buffer = Buffer.alloc(0);
|
|
3888
|
+
this.stderr = "";
|
|
3889
|
+
child.stdout.on("data", (chunk) => {
|
|
3890
|
+
if (this.child === child)
|
|
3891
|
+
this.onData(chunk);
|
|
3892
|
+
});
|
|
3893
|
+
child.stderr.on("data", (chunk) => {
|
|
3894
|
+
if (this.child === child)
|
|
3895
|
+
this.stderr = (this.stderr + chunk.toString()).slice(-16384);
|
|
3896
|
+
});
|
|
3897
|
+
child.on("error", (error) => {
|
|
3898
|
+
if (this.child === child)
|
|
3899
|
+
this.onFailure(error);
|
|
3900
|
+
});
|
|
3901
|
+
child.on("close", (code) => {
|
|
3902
|
+
if (this.child === child)
|
|
3903
|
+
this.onFailure(new Error(`Code-mode host exited with code ${code ?? "unknown"}${this.stderr.trim() ? `: ${this.stderr.trim()}` : ""}`));
|
|
3904
|
+
});
|
|
3905
|
+
}
|
|
3906
|
+
send(message) {
|
|
3907
|
+
const child = this.child;
|
|
3908
|
+
if (!child?.stdin.writable)
|
|
3909
|
+
throw new Error("Code-mode host is not running");
|
|
3910
|
+
const payload = Buffer.from(JSON.stringify(message));
|
|
3911
|
+
if (payload.length > MAX_FRAME_BYTES)
|
|
3912
|
+
throw new Error(`Code-mode frame exceeds ${MAX_FRAME_BYTES} bytes`);
|
|
3913
|
+
const header = Buffer.allocUnsafe(4);
|
|
3914
|
+
header.writeUInt32LE(payload.length);
|
|
3915
|
+
const frame = Buffer.concat([header, payload]);
|
|
3916
|
+
if (this.queuedWriteBytes + frame.length > MAX_QUEUED_WRITE_BYTES)
|
|
3917
|
+
throw new Error(`Code-mode write queue exceeds ${MAX_QUEUED_WRITE_BYTES} bytes`);
|
|
3918
|
+
this.queuedWriteBytes += frame.length;
|
|
3919
|
+
child.stdin.write(frame, (error) => {
|
|
3920
|
+
this.queuedWriteBytes = Math.max(0, this.queuedWriteBytes - frame.length);
|
|
3921
|
+
if (error && this.child === child)
|
|
3922
|
+
this.onFailure(error);
|
|
3923
|
+
});
|
|
3924
|
+
}
|
|
3925
|
+
kill() {
|
|
3926
|
+
this.queuedWriteBytes = 0;
|
|
3927
|
+
const child = this.child;
|
|
3928
|
+
this.child = undefined;
|
|
3929
|
+
if (child && !child.killed)
|
|
3930
|
+
child.kill();
|
|
3931
|
+
}
|
|
3932
|
+
onData(chunk) {
|
|
3933
|
+
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
3934
|
+
while (this.buffer.length >= 4) {
|
|
3935
|
+
const length = this.buffer.readUInt32LE(0);
|
|
3936
|
+
if (length > MAX_FRAME_BYTES) {
|
|
3937
|
+
this.onFailure(new Error(`Code-mode frame exceeds ${MAX_FRAME_BYTES} bytes`));
|
|
3938
|
+
return;
|
|
3939
|
+
}
|
|
3940
|
+
if (this.buffer.length < length + 4)
|
|
3941
|
+
return;
|
|
3942
|
+
const payload = this.buffer.subarray(4, length + 4);
|
|
3943
|
+
this.buffer = this.buffer.subarray(length + 4);
|
|
3944
|
+
try {
|
|
3945
|
+
this.onMessage(JSON.parse(payload.toString("utf8")));
|
|
3946
|
+
} catch (error) {
|
|
3947
|
+
this.onFailure(error instanceof Error ? error : new Error(String(error)));
|
|
3948
|
+
}
|
|
3949
|
+
}
|
|
3950
|
+
}
|
|
3951
|
+
}
|
|
3952
|
+
|
|
3953
|
+
// packages/code/src/host-connection.ts
|
|
3954
|
+
class CodeModeHostConnection {
|
|
3955
|
+
process;
|
|
3956
|
+
onMessage;
|
|
3957
|
+
onFailure;
|
|
3958
|
+
requestId = 0;
|
|
3959
|
+
ready;
|
|
3960
|
+
pending = new Map;
|
|
3961
|
+
initial = new Map;
|
|
3962
|
+
constructor(options) {
|
|
3963
|
+
this.onMessage = options.onMessage;
|
|
3964
|
+
this.onFailure = options.onFailure;
|
|
3965
|
+
this.process = new CodeModeHostProcess({
|
|
3966
|
+
binary: options.binary,
|
|
3967
|
+
onMessage: (message) => this.handleMessage(parseHostMessage(message)),
|
|
3968
|
+
onFailure: (error) => this.failAll(error)
|
|
3969
|
+
});
|
|
3970
|
+
}
|
|
3971
|
+
get running() {
|
|
3972
|
+
return this.process.running;
|
|
3973
|
+
}
|
|
3974
|
+
nextRequestId() {
|
|
3975
|
+
return ++this.requestId;
|
|
3976
|
+
}
|
|
3977
|
+
async start() {
|
|
3978
|
+
if (this.ready)
|
|
3979
|
+
return this.ready;
|
|
3980
|
+
const ready = this.startProcess();
|
|
3981
|
+
this.ready = ready;
|
|
3982
|
+
try {
|
|
3983
|
+
await ready;
|
|
3984
|
+
} catch (error) {
|
|
3985
|
+
this.failAll(error instanceof Error ? error : new Error(String(error)));
|
|
3986
|
+
throw error;
|
|
3987
|
+
}
|
|
3988
|
+
}
|
|
3989
|
+
async startProcess() {
|
|
3990
|
+
this.process.start();
|
|
3991
|
+
const handshake = new Promise((resolve, reject) => {
|
|
3992
|
+
this.pending.set(0, { resolve: () => resolve(), reject });
|
|
3993
|
+
});
|
|
3994
|
+
this.send({
|
|
3995
|
+
type: "connection/hello",
|
|
3996
|
+
supportedVersions: [1],
|
|
3997
|
+
requiredCapabilities: [],
|
|
3998
|
+
optionalCapabilities: []
|
|
3999
|
+
});
|
|
4000
|
+
await handshake;
|
|
4001
|
+
}
|
|
4002
|
+
request(request, onValue) {
|
|
4003
|
+
return this.requestWithId(this.nextRequestId(), request, onValue);
|
|
4004
|
+
}
|
|
4005
|
+
requestWithId(id, request, onValue) {
|
|
4006
|
+
return new Promise((resolve, reject) => {
|
|
4007
|
+
this.pending.set(id, { resolve, reject, onValue });
|
|
4008
|
+
try {
|
|
4009
|
+
this.send({ type: "operation/request", id, request });
|
|
4010
|
+
} catch (error) {
|
|
4011
|
+
this.pending.delete(id);
|
|
4012
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
4013
|
+
}
|
|
4014
|
+
});
|
|
4015
|
+
}
|
|
4016
|
+
expectInitial(id) {
|
|
4017
|
+
return new Promise((resolve, reject) => {
|
|
4018
|
+
this.initial.set(id, { resolve, reject });
|
|
4019
|
+
});
|
|
4020
|
+
}
|
|
4021
|
+
send(message) {
|
|
4022
|
+
this.process.send(message);
|
|
4023
|
+
}
|
|
4024
|
+
rejectOperation(id, error) {
|
|
4025
|
+
const pending = this.pending.get(id);
|
|
4026
|
+
this.pending.delete(id);
|
|
4027
|
+
pending?.reject(error);
|
|
4028
|
+
const initial = this.initial.get(id);
|
|
4029
|
+
this.initial.delete(id);
|
|
4030
|
+
initial?.reject(error);
|
|
4031
|
+
}
|
|
4032
|
+
close(error) {
|
|
4033
|
+
this.failAll(error);
|
|
4034
|
+
}
|
|
4035
|
+
handleMessage(message) {
|
|
4036
|
+
if (message.type === "connection/ready") {
|
|
4037
|
+
const pending = this.pending.get(0);
|
|
4038
|
+
this.pending.delete(0);
|
|
4039
|
+
pending?.resolve(undefined);
|
|
4040
|
+
return;
|
|
4041
|
+
}
|
|
4042
|
+
if (message.type === "connection/rejected") {
|
|
4043
|
+
const pending = this.pending.get(0);
|
|
4044
|
+
this.pending.delete(0);
|
|
4045
|
+
pending?.reject(new Error(`Code-mode handshake rejected: ${JSON.stringify(message.reason)}`));
|
|
4046
|
+
return;
|
|
4047
|
+
}
|
|
4048
|
+
if (message.type === "operation/response") {
|
|
4049
|
+
const pending = this.pending.get(message.id);
|
|
4050
|
+
this.pending.delete(message.id);
|
|
4051
|
+
if (!pending)
|
|
4052
|
+
return;
|
|
4053
|
+
if (message.result.status === "error") {
|
|
4054
|
+
pending.reject(new Error(message.result.message));
|
|
4055
|
+
return;
|
|
4056
|
+
}
|
|
4057
|
+
const value = message.result.value;
|
|
4058
|
+
try {
|
|
4059
|
+
pending.onValue?.(value);
|
|
4060
|
+
pending.resolve(value);
|
|
4061
|
+
} catch (error) {
|
|
4062
|
+
pending.reject(error instanceof Error ? error : new Error(String(error)));
|
|
4063
|
+
throw error;
|
|
4064
|
+
}
|
|
4065
|
+
return;
|
|
4066
|
+
}
|
|
4067
|
+
if (message.type === "execute/initialResponse") {
|
|
4068
|
+
const pending = this.initial.get(message.id);
|
|
4069
|
+
this.initial.delete(message.id);
|
|
4070
|
+
if (!pending)
|
|
4071
|
+
return;
|
|
4072
|
+
if (message.result.status === "error")
|
|
4073
|
+
pending.reject(new Error(message.result.message));
|
|
4074
|
+
else
|
|
4075
|
+
pending.resolve(message.result.value);
|
|
4076
|
+
return;
|
|
4077
|
+
}
|
|
4078
|
+
this.onMessage(message);
|
|
4079
|
+
}
|
|
4080
|
+
failAll(error) {
|
|
4081
|
+
for (const pending of [...this.pending.values(), ...this.initial.values()])
|
|
4082
|
+
pending.reject(error);
|
|
4083
|
+
this.pending.clear();
|
|
4084
|
+
this.initial.clear();
|
|
4085
|
+
this.ready = undefined;
|
|
4086
|
+
this.process.kill();
|
|
4087
|
+
this.onFailure(error);
|
|
4088
|
+
}
|
|
4089
|
+
}
|
|
4090
|
+
|
|
4091
|
+
// packages/code/src/host-session.ts
|
|
4092
|
+
var DEFAULT_SHUTDOWN_GRACE_MS = 250;
|
|
4093
|
+
|
|
4094
|
+
class CodeModeHostSession {
|
|
4095
|
+
id = randomUUID();
|
|
4096
|
+
connection;
|
|
4097
|
+
shutdownGraceMs;
|
|
4098
|
+
onFailure;
|
|
4099
|
+
ready;
|
|
4100
|
+
constructor(options) {
|
|
4101
|
+
this.shutdownGraceMs = options.shutdownGraceMs ?? DEFAULT_SHUTDOWN_GRACE_MS;
|
|
4102
|
+
this.onFailure = options.onFailure;
|
|
4103
|
+
this.connection = new CodeModeHostConnection({
|
|
4104
|
+
binary: options.binary,
|
|
4105
|
+
onMessage: options.onMessage,
|
|
4106
|
+
onFailure: (error) => {
|
|
4107
|
+
this.ready = undefined;
|
|
4108
|
+
this.onFailure(error);
|
|
4109
|
+
}
|
|
4110
|
+
});
|
|
4111
|
+
}
|
|
4112
|
+
async start() {
|
|
4113
|
+
if (this.ready)
|
|
4114
|
+
return this.ready;
|
|
4115
|
+
const ready = this.startSession();
|
|
4116
|
+
this.ready = ready;
|
|
4117
|
+
try {
|
|
4118
|
+
await ready;
|
|
4119
|
+
} catch (error) {
|
|
4120
|
+
this.connection.close(toError(error));
|
|
4121
|
+
throw error;
|
|
4122
|
+
}
|
|
4123
|
+
}
|
|
4124
|
+
async startSession() {
|
|
4125
|
+
await this.connection.start();
|
|
4126
|
+
await this.connection.request({
|
|
4127
|
+
method: "session/open",
|
|
4128
|
+
sessionId: this.id
|
|
4129
|
+
});
|
|
4130
|
+
}
|
|
4131
|
+
nextRequestId() {
|
|
4132
|
+
return this.connection.nextRequestId();
|
|
4133
|
+
}
|
|
4134
|
+
expectInitial(id) {
|
|
4135
|
+
return this.connection.expectInitial(id);
|
|
4136
|
+
}
|
|
4137
|
+
requestWithId(id, request, onValue) {
|
|
4138
|
+
return this.connection.requestWithId(id, request, onValue);
|
|
4139
|
+
}
|
|
4140
|
+
send(message) {
|
|
4141
|
+
this.connection.send(message);
|
|
4142
|
+
}
|
|
4143
|
+
rejectOperation(id, error) {
|
|
4144
|
+
this.connection.rejectOperation(id, error);
|
|
4145
|
+
}
|
|
4146
|
+
async shutdown() {
|
|
4147
|
+
if (!this.connection.running)
|
|
4148
|
+
return;
|
|
4149
|
+
try {
|
|
4150
|
+
await Promise.race([
|
|
4151
|
+
this.connection.request({
|
|
4152
|
+
method: "session/shutdown",
|
|
4153
|
+
sessionId: this.id
|
|
4154
|
+
}),
|
|
4155
|
+
shutdownDeadline(this.shutdownGraceMs)
|
|
4156
|
+
]);
|
|
4157
|
+
} catch {}
|
|
4158
|
+
this.connection.close(new Error("Code-mode host shut down"));
|
|
4159
|
+
}
|
|
4160
|
+
}
|
|
4161
|
+
function shutdownDeadline(delayMs) {
|
|
4162
|
+
return new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
4163
|
+
}
|
|
4164
|
+
function toError(error) {
|
|
4165
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
4166
|
+
}
|
|
4167
|
+
|
|
4168
|
+
// packages/code/src/runtime-response.ts
|
|
4169
|
+
function parseRuntimeResponse(value) {
|
|
4170
|
+
if (!isRecord2(value))
|
|
4171
|
+
throw new Error("Code-mode host returned an invalid runtime response");
|
|
4172
|
+
const kind = isRecord2(value["Yielded"]) ? "yielded" : isRecord2(value["Terminated"]) ? "terminated" : isRecord2(value["Result"]) ? "result" : undefined;
|
|
4173
|
+
if (!kind)
|
|
4174
|
+
throw new Error("Code-mode host returned an invalid runtime response");
|
|
4175
|
+
const body = value[kind === "yielded" ? "Yielded" : kind === "terminated" ? "Terminated" : "Result"];
|
|
4176
|
+
if (!isRecord2(body) || typeof body["cell_id"] !== "string")
|
|
4177
|
+
throw new Error("Code-mode host returned an invalid runtime response");
|
|
4178
|
+
const contentItems = parseContentItems(body["content_items"]);
|
|
4179
|
+
return {
|
|
4180
|
+
kind,
|
|
4181
|
+
cellId: body["cell_id"],
|
|
4182
|
+
contentItems,
|
|
4183
|
+
...kind === "result" && typeof body["error_text"] === "string" ? { errorText: body["error_text"] } : {}
|
|
4184
|
+
};
|
|
4185
|
+
}
|
|
4186
|
+
function parseContentItems(value) {
|
|
4187
|
+
if (value === undefined)
|
|
4188
|
+
return [];
|
|
4189
|
+
if (!Array.isArray(value))
|
|
4190
|
+
throw new Error("Code-mode host returned invalid content items");
|
|
4191
|
+
return value.map((item) => {
|
|
4192
|
+
if (!isRecord2(item))
|
|
4193
|
+
throw new Error("Code-mode host returned an invalid content item");
|
|
4194
|
+
if (item["type"] === "input_text" && typeof item["text"] === "string")
|
|
4195
|
+
return { type: "input_text", text: item["text"] };
|
|
4196
|
+
if (item["type"] === "input_image" && typeof item["image_url"] === "string" && isImageDetail(item["detail"]))
|
|
4197
|
+
return {
|
|
4198
|
+
type: "input_image",
|
|
4199
|
+
image_url: item["image_url"],
|
|
4200
|
+
...item["detail"] === undefined ? {} : { detail: item["detail"] }
|
|
4201
|
+
};
|
|
4202
|
+
if (item["type"] === "input_audio")
|
|
4203
|
+
throw new Error("Code-mode audio output is not supported by Pi");
|
|
4204
|
+
throw new Error("Code-mode host returned an invalid content item");
|
|
4205
|
+
});
|
|
4206
|
+
}
|
|
4207
|
+
function isImageDetail(value) {
|
|
4208
|
+
return value === undefined || value === null || value === "auto" || value === "low" || value === "high" || value === "original";
|
|
4209
|
+
}
|
|
4210
|
+
function isRecord2(value) {
|
|
4211
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
4212
|
+
}
|
|
4213
|
+
|
|
4214
|
+
// packages/code/src/host-runtime.ts
|
|
4215
|
+
class CodeHostRuntime {
|
|
4216
|
+
session;
|
|
4217
|
+
cells = new Map;
|
|
4218
|
+
delegates = new Map;
|
|
4219
|
+
closed = false;
|
|
4220
|
+
failure;
|
|
4221
|
+
failureController = new AbortController;
|
|
4222
|
+
get failureSignal() {
|
|
4223
|
+
return this.failureController.signal;
|
|
4224
|
+
}
|
|
4225
|
+
constructor(binary) {
|
|
4226
|
+
this.session = new CodeModeHostSession({
|
|
4227
|
+
binary,
|
|
4228
|
+
onMessage: (message) => this.handle(message),
|
|
4229
|
+
onFailure: (error) => {
|
|
4230
|
+
if (!this.closed) {
|
|
4231
|
+
this.failure = error;
|
|
4232
|
+
this.failureController.abort(error);
|
|
4233
|
+
}
|
|
4234
|
+
this.closed = true;
|
|
4235
|
+
this.clear();
|
|
4236
|
+
}
|
|
4237
|
+
});
|
|
4238
|
+
}
|
|
4239
|
+
async execute(source, tools, callbacks, signal, onStarted, yieldTimeMsOverride) {
|
|
4240
|
+
if (this.closed)
|
|
4241
|
+
throw new Error(this.failure ? `Code host stopped and session state was lost: ${this.failure.message}. Previous cell outcomes may be uncertain. Recreate the Code component before running new code` : "Code runtime is closed");
|
|
4242
|
+
signal?.throwIfAborted();
|
|
4243
|
+
const parsed = parseExecSource(source);
|
|
4244
|
+
await this.session.start();
|
|
4245
|
+
signal?.throwIfAborted();
|
|
4246
|
+
const id = this.session.nextRequestId();
|
|
4247
|
+
const initial = this.session.expectInitial(id);
|
|
4248
|
+
initial.catch(() => {
|
|
4249
|
+
return;
|
|
4250
|
+
});
|
|
4251
|
+
let cellId;
|
|
4252
|
+
let termination;
|
|
4253
|
+
const yieldMarker = `durable-yield-${randomUUID2()}`;
|
|
4254
|
+
const abort = () => {
|
|
4255
|
+
try {
|
|
4256
|
+
this.session.send({ type: "operation/cancel", id });
|
|
4257
|
+
} catch {}
|
|
4258
|
+
if (cellId) {
|
|
4259
|
+
termination ??= this.terminate(cellId);
|
|
4260
|
+
termination.catch(() => {
|
|
4261
|
+
return;
|
|
4262
|
+
});
|
|
4263
|
+
}
|
|
4264
|
+
};
|
|
4265
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
4266
|
+
try {
|
|
4267
|
+
await this.session.requestWithId(id, {
|
|
4268
|
+
method: "session/execute",
|
|
4269
|
+
sessionId: this.session.id,
|
|
4270
|
+
request: {
|
|
4271
|
+
tool_call_id: `exec-${id}`,
|
|
4272
|
+
enabled_tools: tools.map((tool, index) => ({
|
|
4273
|
+
name: `durable_tool_${index}`,
|
|
4274
|
+
tool_name: { name: tool.name, namespace: null },
|
|
4275
|
+
description: tool.description,
|
|
4276
|
+
kind: "function",
|
|
4277
|
+
input_schema: tool.inputSchema,
|
|
4278
|
+
output_schema: null
|
|
4279
|
+
})),
|
|
4280
|
+
source: toolBootstrap(tools, yieldMarker) + parsed.code,
|
|
4281
|
+
yield_time_ms: yieldTimeMsOverride ?? parsed.yieldTimeMs ?? 30000,
|
|
4282
|
+
max_output_tokens: parsed.maxOutputTokens
|
|
4283
|
+
}
|
|
4284
|
+
}, (value) => {
|
|
4285
|
+
cellId = executionCellId(value);
|
|
4286
|
+
if (!cellId)
|
|
4287
|
+
throw new Error("Code host did not return a started cell");
|
|
4288
|
+
this.cells.set(cellId, {
|
|
4289
|
+
tools: new Map(tools.map((tool) => [tool.name, tool])),
|
|
4290
|
+
callbacks,
|
|
4291
|
+
yieldMarker
|
|
4292
|
+
});
|
|
4293
|
+
onStarted?.(cellId);
|
|
4294
|
+
if (signal?.aborted)
|
|
4295
|
+
abort();
|
|
4296
|
+
});
|
|
4297
|
+
signal?.throwIfAborted();
|
|
4298
|
+
const response = parseRuntimeResponse(await initial);
|
|
4299
|
+
signal?.throwIfAborted();
|
|
4300
|
+
return response;
|
|
4301
|
+
} catch (error) {
|
|
4302
|
+
this.session.rejectOperation(id, error instanceof Error ? error : new Error(String(error)));
|
|
4303
|
+
signal?.throwIfAborted();
|
|
4304
|
+
throw error;
|
|
4305
|
+
} finally {
|
|
4306
|
+
signal?.removeEventListener("abort", abort);
|
|
4307
|
+
await termination?.catch(() => {
|
|
4308
|
+
return;
|
|
4309
|
+
});
|
|
4310
|
+
}
|
|
4311
|
+
}
|
|
4312
|
+
async wait(cellId, yieldTimeMs = 30000, signal) {
|
|
4313
|
+
signal?.throwIfAborted();
|
|
4314
|
+
const id = this.session.nextRequestId();
|
|
4315
|
+
let termination;
|
|
4316
|
+
const abort = () => {
|
|
4317
|
+
try {
|
|
4318
|
+
this.session.send({ type: "operation/cancel", id });
|
|
4319
|
+
} catch {}
|
|
4320
|
+
this.session.rejectOperation(id, new Error("Code wait aborted"));
|
|
4321
|
+
termination ??= this.terminate(cellId);
|
|
4322
|
+
termination.catch(() => {
|
|
4323
|
+
return;
|
|
4324
|
+
});
|
|
4325
|
+
};
|
|
4326
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
4327
|
+
try {
|
|
4328
|
+
const value = await this.session.requestWithId(id, {
|
|
4329
|
+
method: "session/wait",
|
|
4330
|
+
sessionId: this.session.id,
|
|
4331
|
+
request: { cell_id: cellId, yield_time_ms: yieldTimeMs }
|
|
4332
|
+
});
|
|
4333
|
+
const outcome = runtimeOutcome(value);
|
|
4334
|
+
if (!outcome)
|
|
4335
|
+
throw new Error("Code host returned an invalid wait outcome");
|
|
4336
|
+
const response = parseRuntimeResponse(outcome);
|
|
4337
|
+
signal?.throwIfAborted();
|
|
4338
|
+
return response;
|
|
4339
|
+
} finally {
|
|
4340
|
+
signal?.removeEventListener("abort", abort);
|
|
4341
|
+
await termination?.catch(() => {
|
|
4342
|
+
return;
|
|
4343
|
+
});
|
|
4344
|
+
}
|
|
4345
|
+
}
|
|
4346
|
+
async terminate(cellId) {
|
|
4347
|
+
this.cancelCell(cellId);
|
|
4348
|
+
const value = await this.session.requestWithId(this.session.nextRequestId(), {
|
|
4349
|
+
method: "session/terminate",
|
|
4350
|
+
sessionId: this.session.id,
|
|
4351
|
+
cellId
|
|
4352
|
+
});
|
|
4353
|
+
const outcome = runtimeOutcome(value);
|
|
4354
|
+
if (!outcome)
|
|
4355
|
+
throw new Error("Code host returned an invalid termination outcome");
|
|
4356
|
+
return parseRuntimeResponse(outcome);
|
|
4357
|
+
}
|
|
4358
|
+
async close() {
|
|
4359
|
+
if (this.closed)
|
|
4360
|
+
return;
|
|
4361
|
+
this.closed = true;
|
|
4362
|
+
this.clear();
|
|
4363
|
+
await this.session.shutdown();
|
|
4364
|
+
}
|
|
4365
|
+
clear() {
|
|
4366
|
+
for (const pending of this.delegates.values())
|
|
4367
|
+
pending.controller.abort();
|
|
4368
|
+
this.delegates.clear();
|
|
4369
|
+
this.cells.clear();
|
|
4370
|
+
}
|
|
4371
|
+
cancelCell(cellId) {
|
|
4372
|
+
for (const pending of this.delegates.values())
|
|
4373
|
+
if (pending.cellId === cellId)
|
|
4374
|
+
pending.controller.abort();
|
|
4375
|
+
}
|
|
4376
|
+
handle(message) {
|
|
4377
|
+
if (message.type === "delegate/cancel") {
|
|
4378
|
+
this.delegates.get(message.id)?.controller.abort();
|
|
4379
|
+
} else if (message.type === "cell/closed") {
|
|
4380
|
+
this.cancelCell(message.cellId);
|
|
4381
|
+
this.cells.delete(message.cellId);
|
|
4382
|
+
} else if (message.type === "delegate/request") {
|
|
4383
|
+
if (this.delegates.has(message.id))
|
|
4384
|
+
throw new Error(`Duplicate delegate request: ${message.id}`);
|
|
4385
|
+
const cellId = message.request.type === "notification/send" ? message.request.cellId : message.request.invocation.cell_id;
|
|
4386
|
+
const controller = new AbortController;
|
|
4387
|
+
this.delegates.set(message.id, { cellId, controller });
|
|
4388
|
+
this.invoke(message, controller.signal);
|
|
4389
|
+
}
|
|
4390
|
+
}
|
|
4391
|
+
async invoke(message, signal) {
|
|
4392
|
+
try {
|
|
4393
|
+
const request = message.request;
|
|
4394
|
+
const cellId = request.type === "notification/send" ? request.cellId : request.invocation.cell_id;
|
|
4395
|
+
const cell = this.cells.get(cellId);
|
|
4396
|
+
if (!cell)
|
|
4397
|
+
throw new Error("Code cell is no longer available");
|
|
4398
|
+
signal.throwIfAborted();
|
|
4399
|
+
let value;
|
|
4400
|
+
if (request.type === "notification/send") {
|
|
4401
|
+
if (request.text === cell.yieldMarker)
|
|
4402
|
+
await cell.callbacks.yield?.();
|
|
4403
|
+
else
|
|
4404
|
+
await cell.callbacks.notify(request.text.slice(0, 16384));
|
|
4405
|
+
value = { type: "notification/delivered" };
|
|
4406
|
+
} else {
|
|
4407
|
+
const tool = cell.tools.get(request.invocation.tool_name.name);
|
|
4408
|
+
if (!tool)
|
|
4409
|
+
throw new Error(`Unknown tool: ${request.invocation.tool_name.name}`);
|
|
4410
|
+
value = {
|
|
4411
|
+
type: "tool/result",
|
|
4412
|
+
result: await tool.invoke(request.invocation.input, signal, request.invocation.runtime_tool_call_id)
|
|
4413
|
+
};
|
|
4414
|
+
}
|
|
4415
|
+
this.respond(message.id, { status: "ok", value });
|
|
4416
|
+
} catch (error) {
|
|
4417
|
+
this.respond(message.id, {
|
|
4418
|
+
status: "error",
|
|
4419
|
+
message: error instanceof Error ? error.message : String(error)
|
|
4420
|
+
});
|
|
4421
|
+
} finally {
|
|
4422
|
+
this.delegates.delete(message.id);
|
|
4423
|
+
}
|
|
4424
|
+
}
|
|
4425
|
+
respond(id, result) {
|
|
4426
|
+
try {
|
|
4427
|
+
this.session.send({ type: "delegate/response", id, result });
|
|
4428
|
+
} catch (error) {
|
|
4429
|
+
try {
|
|
4430
|
+
this.session.send({
|
|
4431
|
+
type: "delegate/response",
|
|
4432
|
+
id,
|
|
4433
|
+
result: {
|
|
4434
|
+
status: "error",
|
|
4435
|
+
message: `Tool result serialization failed: ${String(error)}`
|
|
4436
|
+
}
|
|
4437
|
+
});
|
|
4438
|
+
} catch {}
|
|
4439
|
+
}
|
|
4440
|
+
}
|
|
4441
|
+
}
|
|
4442
|
+
function toolBootstrap(tools, yieldMarker) {
|
|
4443
|
+
const entries = tools.map((tool, index) => [
|
|
4444
|
+
tool.name,
|
|
4445
|
+
`durable_tool_${index}`
|
|
4446
|
+
]);
|
|
4447
|
+
const discovery = tools.map((tool) => ({
|
|
4448
|
+
name: tool.name,
|
|
4449
|
+
description: tool.description
|
|
4450
|
+
}));
|
|
4451
|
+
return `(()=>{const native=globalThis.tools;const registry=Object.create(null);for(const [name,wire] of ${JSON.stringify(entries)})registry[name]=native[wire];globalThis.tools=registry;globalThis.ALL_TOOLS=${JSON.stringify(discovery)};const emit=globalThis.notify;const yieldCell=globalThis.yield_control;globalThis.yield_control=()=>{emit(${JSON.stringify(yieldMarker)});return yieldCell();};})();`;
|
|
4452
|
+
}
|
|
4453
|
+
|
|
4454
|
+
// packages/code/src/runtime-tools.ts
|
|
4455
|
+
import { copyJson as copyJson12 } from "@earendil-works/chord";
|
|
4456
|
+
function runtimeTools(api, contracts, observation, context) {
|
|
4457
|
+
const publish = () => api.publish(observation.result(), context);
|
|
4458
|
+
const tools = api.registrations.map((registration, index) => ({
|
|
4459
|
+
name: registration.name,
|
|
4460
|
+
description: contracts[index]?.help ?? registration.description,
|
|
4461
|
+
inputSchema: contracts[index]?.inputSchema ?? registration.parameters,
|
|
4462
|
+
invoke: async (input, signal, callId) => {
|
|
4463
|
+
signal.throwIfAborted();
|
|
4464
|
+
const invoke = api.tools[registration.name];
|
|
4465
|
+
if (!invoke)
|
|
4466
|
+
throw new Error(`Tool ${registration.name} is unavailable`);
|
|
4467
|
+
const argumentsValue = copyJson12(input === undefined ? null : input);
|
|
4468
|
+
const trace = observation.trace(callId, registration.name, argumentsValue);
|
|
4469
|
+
await publish();
|
|
4470
|
+
try {
|
|
4471
|
+
const value = await invoke(argumentsValue, signal);
|
|
4472
|
+
trace.done(value, value.callId);
|
|
4473
|
+
signal.throwIfAborted();
|
|
4474
|
+
const projected = toolValue(value);
|
|
4475
|
+
await publish();
|
|
4476
|
+
return projected;
|
|
4477
|
+
} catch (error) {
|
|
4478
|
+
trace.failed(error);
|
|
4479
|
+
if (!api.signal.aborted)
|
|
4480
|
+
await publish();
|
|
4481
|
+
throw error;
|
|
4482
|
+
}
|
|
4483
|
+
}
|
|
4484
|
+
}));
|
|
4485
|
+
return tools;
|
|
4486
|
+
}
|
|
4487
|
+
|
|
4488
|
+
// packages/code/src/engine.ts
|
|
4489
|
+
class CodeEngine {
|
|
4490
|
+
sessions = new Map;
|
|
4491
|
+
options;
|
|
4492
|
+
deliveries = new Map;
|
|
4493
|
+
closed = false;
|
|
4494
|
+
constructor(options = {}) {
|
|
4495
|
+
this.options = options;
|
|
4496
|
+
}
|
|
4497
|
+
async run(input, api, context) {
|
|
4498
|
+
if (this.closed)
|
|
4499
|
+
throw new Error("Code component is closed");
|
|
4500
|
+
if (typeof input["code"] !== "string")
|
|
4501
|
+
throw new Error("exec requires JavaScript source in code");
|
|
4502
|
+
const source = input["code"];
|
|
4503
|
+
const parsed = parseExecSource(source);
|
|
4504
|
+
const maxTokens = MAX_CODE_MODE_OUTPUT_TOKENS;
|
|
4505
|
+
const contracts = api.registrations.map(readToolContract);
|
|
4506
|
+
const initialYieldMs = directToolYieldTime(parsed.code, contracts) ?? parsed.yieldTimeMs ?? 30000;
|
|
4507
|
+
const key = api.conversationId;
|
|
4508
|
+
let session = this.sessions.get(key);
|
|
4509
|
+
if (!session) {
|
|
4510
|
+
session = ensureHost(this.options, api.signal).then((binary) => new CodeHostRuntime(binary));
|
|
4511
|
+
this.sessions.set(key, session);
|
|
4512
|
+
session.catch(() => {
|
|
4513
|
+
if (this.sessions.get(key) === session)
|
|
4514
|
+
this.sessions.delete(key);
|
|
4515
|
+
});
|
|
4516
|
+
}
|
|
4517
|
+
const runtime = await session;
|
|
4518
|
+
if (this.closed) {
|
|
4519
|
+
await runtime.close();
|
|
4520
|
+
throw new Error("Code component is closed");
|
|
4521
|
+
}
|
|
4522
|
+
api.signal.throwIfAborted();
|
|
4523
|
+
const observationContext = withAbortSignal2(AbortSignal.any([api.signal, runtime.failureSignal]), context);
|
|
4524
|
+
let nativeId;
|
|
4525
|
+
const observation = new CodeCellOutput(maxTokens);
|
|
4526
|
+
const result = () => observation.result();
|
|
4527
|
+
const publish = () => api.publish(result(), context);
|
|
4528
|
+
const tools = runtimeTools(api, contracts, observation, context);
|
|
4529
|
+
let current;
|
|
4530
|
+
let termination;
|
|
4531
|
+
const abort = () => {
|
|
4532
|
+
if (nativeId) {
|
|
4533
|
+
termination = runtime.terminate(nativeId);
|
|
4534
|
+
termination.catch(() => {
|
|
4535
|
+
return;
|
|
4536
|
+
});
|
|
4537
|
+
}
|
|
4538
|
+
};
|
|
4539
|
+
api.signal.addEventListener("abort", abort, { once: true });
|
|
4540
|
+
try {
|
|
4541
|
+
current = await runtime.execute(source, tools, {
|
|
4542
|
+
notify: async (text) => {
|
|
4543
|
+
observation.notify(text);
|
|
4544
|
+
await publish();
|
|
4545
|
+
},
|
|
4546
|
+
yield: () => api.requestYield(context)
|
|
4547
|
+
}, api.signal, (cellId) => {
|
|
4548
|
+
nativeId = cellId;
|
|
4549
|
+
}, initialYieldMs);
|
|
4550
|
+
for (;; ) {
|
|
4551
|
+
observation.replaceObservation(current);
|
|
4552
|
+
this.deliveries.set(api.taskId, observation);
|
|
4553
|
+
await publish();
|
|
4554
|
+
if (current.kind !== "yielded")
|
|
4555
|
+
return result();
|
|
4556
|
+
if (observation.hasOutput)
|
|
4557
|
+
await awaitWithContext2(observation.delivered, observationContext);
|
|
4558
|
+
current = await runtime.wait(current.cellId, 30000, api.signal);
|
|
4559
|
+
}
|
|
4560
|
+
} catch (error) {
|
|
4561
|
+
if (api.signal.aborted)
|
|
4562
|
+
throw error;
|
|
4563
|
+
return {
|
|
4564
|
+
...result(),
|
|
4565
|
+
isError: true,
|
|
4566
|
+
diagnostics: [
|
|
4567
|
+
{
|
|
4568
|
+
severity: "error",
|
|
4569
|
+
code: "interrupted",
|
|
4570
|
+
message: `Code execution was interrupted: ${error instanceof Error ? error.message : String(error)}. Operations may already have executed. Code was not replayed`
|
|
4571
|
+
}
|
|
4572
|
+
]
|
|
4573
|
+
};
|
|
4574
|
+
} finally {
|
|
4575
|
+
api.signal.removeEventListener("abort", abort);
|
|
4576
|
+
this.deliveries.delete(api.taskId);
|
|
4577
|
+
await termination?.catch(() => {
|
|
4578
|
+
return;
|
|
4579
|
+
});
|
|
4580
|
+
}
|
|
4581
|
+
}
|
|
4582
|
+
acknowledge(taskId, revision) {
|
|
4583
|
+
return this.deliveries.get(taskId)?.acknowledge(revision) ?? true;
|
|
4584
|
+
}
|
|
4585
|
+
async close() {
|
|
4586
|
+
if (this.closed)
|
|
4587
|
+
return;
|
|
4588
|
+
this.closed = true;
|
|
4589
|
+
const sessions = [...this.sessions.values()];
|
|
4590
|
+
this.sessions.clear();
|
|
4591
|
+
await Promise.all(sessions.map(async (session) => {
|
|
4592
|
+
await (await session).close();
|
|
4593
|
+
}));
|
|
4594
|
+
}
|
|
4595
|
+
}
|
|
4596
|
+
|
|
4597
|
+
// packages/execution/src/command-backend.ts
|
|
4598
|
+
var MAX_OUTPUT_BYTES = 50 * 1024;
|
|
4599
|
+
// packages/execution/src/custom-command-config.ts
|
|
4600
|
+
import { parse } from "smol-toml";
|
|
4601
|
+
// packages/execution/src/custom-commands.ts
|
|
4602
|
+
import {
|
|
4603
|
+
defineExtension as defineExtension2,
|
|
4604
|
+
defineTool as defineTool2,
|
|
4605
|
+
GenerationTask as GenerationTask2,
|
|
4606
|
+
hook as hook3
|
|
4607
|
+
} from "@earendil-works/pi-durable";
|
|
4608
|
+
import { getOrThrow as getOrThrow2 } from "@earendil-works/pi-durable/env";
|
|
4609
|
+
import { Type as Type2 } from "typebox";
|
|
4610
|
+
var parameters = Type2.Object({ input: Type2.String() }, { additionalProperties: false });
|
|
4611
|
+
|
|
4612
|
+
// packages/code/src/index.ts
|
|
4613
|
+
var execSchema2 = Type3.Object({ code: Type3.String() });
|
|
4614
|
+
var waitSchema = Type3.Object({
|
|
4615
|
+
cell_id: Type3.String(),
|
|
4616
|
+
yield_time_ms: Type3.Optional(Type3.Integer({ minimum: 0, default: 1e4 })),
|
|
4617
|
+
max_tokens: Type3.Optional(Type3.Integer({ minimum: 1, maximum: 1e5, default: 1e4 })),
|
|
4618
|
+
terminate: Type3.Optional(Type3.Boolean())
|
|
4619
|
+
});
|
|
4620
|
+
function createCodeMode(options) {
|
|
4621
|
+
const shell = createShellRuntime(options.shell);
|
|
4622
|
+
const engine = new CodeEngine(options);
|
|
4623
|
+
const acknowledge = engine.acknowledge.bind(engine);
|
|
4624
|
+
const coordinator = createCellCoordinator({
|
|
4625
|
+
name: "code",
|
|
4626
|
+
engine,
|
|
4627
|
+
surfaceTools: ["exec", "wait"],
|
|
4628
|
+
cancelTask: options.cancelTask
|
|
4629
|
+
});
|
|
4630
|
+
const waitAttempts = new Map;
|
|
4631
|
+
const exec = defineTool3({
|
|
4632
|
+
name: "exec",
|
|
4633
|
+
description: "Run JavaScript; bare values are discarded",
|
|
4634
|
+
parameters: execSchema2,
|
|
4635
|
+
constrainedSampling: CODE_MODE_EXEC_CONSTRAINED_SAMPLING,
|
|
4636
|
+
replay: "unsafe",
|
|
4637
|
+
outputLimits: {
|
|
4638
|
+
maxBytes: 2 * 1024 * 1024,
|
|
4639
|
+
maxLines: Number.MAX_SAFE_INTEGER
|
|
4640
|
+
},
|
|
4641
|
+
prepareArguments: (args) => typeof args === "string" ? { code: args } : execArguments(args),
|
|
4642
|
+
async execute(args, api, context) {
|
|
4643
|
+
const parsed = parseExecSource(args.code);
|
|
4644
|
+
const contracts = (await api.agent(context)).callable.filter((tool) => tool.name !== "exec" && tool.name !== "wait").map(readToolContract).filter((contract) => !contract.nativeOnly);
|
|
4645
|
+
const yieldMs = directToolYieldTime(parsed.code, contracts) ?? parsed.yieldTimeMs ?? 30000;
|
|
4646
|
+
const id = await coordinator.start({ code: args.code, max_output_tokens: parsed.maxOutputTokens ?? 1e4 }, api, context);
|
|
4647
|
+
return observeCodeCell(await coordinator.wait(id, api, context, yieldMs, parsed.maxOutputTokens ?? 1e4), parsed.maxOutputTokens ?? 1e4, acknowledge);
|
|
4648
|
+
}
|
|
4649
|
+
});
|
|
4650
|
+
const wait = defineTool3({
|
|
4651
|
+
name: "wait",
|
|
4652
|
+
description: "Resume or terminate a yielded exec cell",
|
|
4653
|
+
parameters: waitSchema,
|
|
4654
|
+
replay: "unsafe",
|
|
4655
|
+
outputLimits: {
|
|
4656
|
+
maxBytes: 2 * 1024 * 1024,
|
|
4657
|
+
maxLines: Number.MAX_SAFE_INTEGER
|
|
4658
|
+
},
|
|
4659
|
+
async execute(args, api, context) {
|
|
4660
|
+
const value = Number(args.cell_id);
|
|
4661
|
+
if (!Number.isSafeInteger(value) || value <= 0)
|
|
4662
|
+
throw new Error("cell_id must be a valid yielded cell ID");
|
|
4663
|
+
const id = value;
|
|
4664
|
+
try {
|
|
4665
|
+
const observation = args.terminate ? await coordinator.cancel(id, api, context, args.max_tokens ?? 1e4) : await coordinator.wait(id, api, context, adaptiveWaitMs(args.yield_time_ms ?? 1e4, waitAttempts.get(id) ?? 0), args.max_tokens ?? 1e4, args.yield_time_ms ?? 1e4);
|
|
4666
|
+
if (observation.status === "running")
|
|
4667
|
+
waitAttempts.set(id, (waitAttempts.get(id) ?? 0) + 1);
|
|
4668
|
+
else
|
|
4669
|
+
waitAttempts.delete(id);
|
|
4670
|
+
return observeCodeCell(observation, args.max_tokens ?? 1e4, acknowledge);
|
|
4671
|
+
} catch (error) {
|
|
4672
|
+
waitAttempts.delete(id);
|
|
4673
|
+
throw error;
|
|
4674
|
+
}
|
|
4675
|
+
}
|
|
4676
|
+
});
|
|
4677
|
+
return {
|
|
4678
|
+
bind: coordinator.bind,
|
|
4679
|
+
extension: {
|
|
4680
|
+
...coordinator.extension,
|
|
4681
|
+
tools: [exec, wait, ...shell.tools],
|
|
4682
|
+
sections: [
|
|
4683
|
+
section("code", (input) => {
|
|
4684
|
+
const usage = input.agent.callable.filter((tool) => tool.name !== "exec" && tool.name !== "wait").map(readToolContract).filter((contract) => !contract.nativeOnly && !contract.deferLoading).map((contract) => contract.prompt).join(`
|
|
4685
|
+
`);
|
|
4686
|
+
return [
|
|
4687
|
+
nestedToolDiscoveryGuidance,
|
|
4688
|
+
'exec accepts JavaScript source with optional // @exec: {"yield_time_ms":30000,"max_output_tokens":10000}. Await work and emit with text(value), image(value), generatedImage(value), notify(value). tools contains ordinary registered tools. ALL_TOOLS lists callable contracts. store(key,value)/load(key) retain serializable values between cells. Cells have no filesystem, network or Node globals. Shell tools follow the conversation environment. Use wait for exec cells and tools.write_stdin for shell sessions.',
|
|
4689
|
+
usage
|
|
4690
|
+
].filter(Boolean).join(`
|
|
4691
|
+
`);
|
|
4692
|
+
})
|
|
4693
|
+
]
|
|
4694
|
+
},
|
|
4695
|
+
async close() {
|
|
4696
|
+
waitAttempts.clear();
|
|
4697
|
+
await Promise.all([coordinator.close(), shell.close()]);
|
|
4698
|
+
}
|
|
4699
|
+
};
|
|
4700
|
+
}
|
|
4701
|
+
function execArguments(value) {
|
|
4702
|
+
if (!value || typeof value !== "object" || !("code" in value) || typeof value.code !== "string")
|
|
4703
|
+
throw new Error("exec requires JavaScript source");
|
|
4704
|
+
return { code: value.code };
|
|
4705
|
+
}
|
|
4706
|
+
|
|
4707
|
+
// packages/code/src/activation.ts
|
|
4708
|
+
var configurationSchema = Type4.Object({
|
|
4709
|
+
hostPath: Type4.Optional(Type4.String({ minLength: 1 })),
|
|
4710
|
+
shell: Type4.Optional(Type4.Object({
|
|
4711
|
+
maxSessionBufferChars: Type4.Optional(Type4.Integer({ minimum: 1 })),
|
|
4712
|
+
defaultExecYieldTimeMs: Type4.Optional(Type4.Number({ minimum: 0 })),
|
|
4713
|
+
defaultWriteYieldTimeMs: Type4.Optional(Type4.Number({ minimum: 0 })),
|
|
4714
|
+
minNonInteractiveExecYieldTimeMs: Type4.Optional(Type4.Number({ minimum: 0 })),
|
|
4715
|
+
minEmptyWriteYieldTimeMs: Type4.Optional(Type4.Number({ minimum: 0 })),
|
|
4716
|
+
maxEmptyWriteYieldTimeMs: Type4.Optional(Type4.Number({ minimum: 0 })),
|
|
4717
|
+
waitForNonInteractiveExit: Type4.Optional(Type4.Boolean())
|
|
4718
|
+
}, { additionalProperties: false }))
|
|
4719
|
+
}, { additionalProperties: false });
|
|
4720
|
+
function baselineOptions(request) {
|
|
4721
|
+
const configuration = request.configuration;
|
|
4722
|
+
if (!Check(configurationSchema, configuration))
|
|
4723
|
+
throw new Error("Invalid Code component configuration");
|
|
4724
|
+
const native = request.capabilities.get(nodeExecutionCapability);
|
|
4725
|
+
const state = request.capabilities.get(stateCapability);
|
|
4726
|
+
return {
|
|
4727
|
+
...configuration,
|
|
4728
|
+
cacheDirectory: state.directory("code"),
|
|
4729
|
+
shell: { ...configuration.shell, backend: createNodeShellBackend(native) }
|
|
4730
|
+
};
|
|
4731
|
+
}
|
|
4732
|
+
var codeOptions = defineCapability("howaboua.code.options.v1", (value) => isCapabilityObject(value) && typeof value["cancelTask"] === "function" && isCapabilityObject(value["shell"]) && isCapabilityObject(value["shell"]["backend"]) && typeof value["shell"]["backend"]["environmentId"] === "string" && value["shell"]["backend"]["environmentId"].length > 0 && typeof value["shell"]["backend"]["spawn"] === "function" && typeof value["shell"]["backend"]["platform"] === "string" && typeof value["shell"]["backend"]["defaultShell"] === "string" && isCapabilityObject(value["shell"]["backend"]["env"]) && (value["hostPath"] === undefined || typeof value["hostPath"] === "string") && (value["cacheDirectory"] === undefined || typeof value["cacheDirectory"] === "string"));
|
|
4733
|
+
function createComponent(request) {
|
|
4734
|
+
const options = request.capabilities.has(codeOptions.id) ? request.capabilities.get(codeOptions) : baselineOptions(request);
|
|
4735
|
+
let owner;
|
|
4736
|
+
const api = createCodeMode({
|
|
4737
|
+
...options,
|
|
4738
|
+
cancelTask(id, context) {
|
|
4739
|
+
if (!owner)
|
|
4740
|
+
throw new Error("Code component must be bound before cancellation");
|
|
4741
|
+
return owner.abortTask(id, context);
|
|
4742
|
+
}
|
|
4743
|
+
});
|
|
4744
|
+
let closing;
|
|
4745
|
+
return {
|
|
4746
|
+
extensions: [api.extension],
|
|
4747
|
+
api,
|
|
4748
|
+
retention: "harness",
|
|
4749
|
+
bind({ harness }) {
|
|
4750
|
+
if (owner && owner !== harness)
|
|
4751
|
+
throw new Error("Code component is already bound to another Harness");
|
|
4752
|
+
api.bind(harness);
|
|
4753
|
+
owner = harness;
|
|
4754
|
+
},
|
|
4755
|
+
beforeClose() {
|
|
4756
|
+
return closing ??= api.close();
|
|
4757
|
+
},
|
|
4758
|
+
afterClose() {
|
|
4759
|
+
owner = undefined;
|
|
4760
|
+
}
|
|
4761
|
+
};
|
|
4762
|
+
}
|
|
4763
|
+
export {
|
|
4764
|
+
codeOptions,
|
|
4765
|
+
createComponent
|
|
4766
|
+
};
|