@howaboua/pi-durable-worker-code 0.0.0-stage → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/NOTICE +49 -0
- package/README.md +71 -2
- package/dist/QUICKJS-LICENSE +47 -0
- package/dist/execution/src/cell-contract.d.ts +49 -0
- package/dist/execution/src/cell-observation.d.ts +7 -0
- package/dist/execution/src/cell-progress.d.ts +4 -0
- package/dist/execution/src/cell-task.d.ts +17 -0
- package/dist/execution/src/cell-tools.d.ts +8 -0
- package/dist/execution/src/cells.d.ts +14 -0
- package/dist/execution/src/controls.d.ts +3 -0
- package/dist/execution/src/exec-source.d.ts +21 -0
- package/dist/execution/src/forwarded-tools.d.ts +21 -0
- package/dist/execution/src/forwarding-hook.d.ts +6 -0
- package/dist/execution/src/forwarding.d.ts +15 -0
- package/dist/execution/src/history.d.ts +14 -0
- package/dist/execution/src/invocation-state.d.ts +26 -0
- package/dist/execution/src/invocation.d.ts +35 -0
- package/dist/execution/src/native-tools.d.ts +11 -0
- package/dist/execution/src/nested-call.d.ts +26 -0
- package/dist/execution/src/nested-result.d.ts +8 -0
- package/dist/execution/src/nested.d.ts +3 -0
- package/dist/execution/src/output.d.ts +48 -0
- package/dist/execution/src/presentation.d.ts +59 -0
- package/dist/execution/src/progress.d.ts +23 -0
- package/dist/execution/src/projection.d.ts +5 -0
- package/dist/execution/src/tool-contract.d.ts +34 -0
- package/dist/execution/src/tool-origin.d.ts +11 -0
- package/dist/execution/src/tool-value.d.ts +3 -0
- package/dist/execution/src/wait-session.d.ts +6 -0
- package/dist/history.js +315 -0
- package/dist/index.js +2771 -0
- package/dist/presentation.js +201 -0
- package/dist/quickjs.wasm +0 -0
- package/dist/worker-code/src/guest.d.ts +16 -0
- package/dist/worker-code/src/history.d.ts +6 -0
- package/dist/worker-code/src/index.d.ts +47 -0
- package/dist/worker-code/src/interpreter.d.ts +20 -0
- package/dist/worker-code/src/limits.d.ts +20 -0
- package/dist/worker-code/src/modules.d.ts +13 -0
- package/dist/worker-code/src/output.d.ts +6 -0
- package/dist/worker-code/src/presentation.d.ts +22 -0
- package/dist/worker-code/src/runtime.d.ts +17 -0
- package/dist/worker-code/src/tool-result.d.ts +3 -0
- package/package.json +50 -5
package/dist/index.js
ADDED
|
@@ -0,0 +1,2771 @@
|
|
|
1
|
+
// packages/worker-code/src/index.ts
|
|
2
|
+
import {
|
|
3
|
+
defineTool,
|
|
4
|
+
section
|
|
5
|
+
} from "@earendil-works/pi-durable";
|
|
6
|
+
import { Type as Type2 } from "typebox";
|
|
7
|
+
|
|
8
|
+
// packages/execution/src/cell-tools.ts
|
|
9
|
+
import { copyJson as copyJson5 } from "@earendil-works/chord";
|
|
10
|
+
import { withoutAbortSignal as withoutAbortSignal2 } from "@earendil-works/chord/context";
|
|
11
|
+
|
|
12
|
+
// packages/execution/src/forwarding.ts
|
|
13
|
+
import { copyJson as copyJson2 } from "@earendil-works/chord";
|
|
14
|
+
import {
|
|
15
|
+
LiveDoc,
|
|
16
|
+
NestedCallDoc,
|
|
17
|
+
ToolTask
|
|
18
|
+
} from "@earendil-works/pi-durable";
|
|
19
|
+
|
|
20
|
+
// packages/execution/src/invocation-state.ts
|
|
21
|
+
import {
|
|
22
|
+
copyJson
|
|
23
|
+
} from "@earendil-works/chord";
|
|
24
|
+
import {
|
|
25
|
+
defineDoc
|
|
26
|
+
} from "@earendil-works/pi-durable";
|
|
27
|
+
var InvocationDoc = defineDoc({
|
|
28
|
+
kind: "howaboua.execution.invocation",
|
|
29
|
+
version: 2,
|
|
30
|
+
scope: "task",
|
|
31
|
+
checkpointWhen: () => false,
|
|
32
|
+
initial: () => ({ result: {} }),
|
|
33
|
+
migrate: (value) => ({
|
|
34
|
+
...value,
|
|
35
|
+
result: storeResult(readStoredResult(value["result"]))
|
|
36
|
+
})
|
|
37
|
+
});
|
|
38
|
+
function readStoredResult(result) {
|
|
39
|
+
if (result.output !== undefined || !("content" in result))
|
|
40
|
+
return result;
|
|
41
|
+
const { content, ...rest } = result;
|
|
42
|
+
return {
|
|
43
|
+
...rest,
|
|
44
|
+
output: content
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function storeResult(result) {
|
|
48
|
+
return copyJson(result, { omitUndefinedProperties: true });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// packages/execution/src/output.ts
|
|
52
|
+
function utf8ByteLength(text) {
|
|
53
|
+
return new TextEncoder().encode(text).length;
|
|
54
|
+
}
|
|
55
|
+
var NEWLINE = 10;
|
|
56
|
+
var INVALID_OUTPUT = /[\x00-\x08\x0b-\x1f\ufff9-\ufffb]/g;
|
|
57
|
+
var encoder = new TextEncoder;
|
|
58
|
+
var decoder = new TextDecoder("utf-8", { ignoreBOM: true });
|
|
59
|
+
function sanitizeOutput(text) {
|
|
60
|
+
return text.replace(INVALID_OUTPUT, "");
|
|
61
|
+
}
|
|
62
|
+
function boundOutput(text, limits) {
|
|
63
|
+
const bytes = encoder.encode(text);
|
|
64
|
+
const [from, to] = limits.retain === "head" ? headRange(bytes, limits) : tailRange(bytes, limits);
|
|
65
|
+
const kept = bytes.subarray(from, to);
|
|
66
|
+
return {
|
|
67
|
+
text: kept.length === bytes.length ? text : decoder.decode(kept),
|
|
68
|
+
bytes: kept.length,
|
|
69
|
+
droppedBytes: bytes.length - kept.length,
|
|
70
|
+
droppedLines: lineCount(bytes) - lineCount(kept)
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function headRange(bytes, limits) {
|
|
74
|
+
if (limits.maxLines === 0 || limits.maxBytes === 0)
|
|
75
|
+
return [0, 0];
|
|
76
|
+
let end = bytes.length;
|
|
77
|
+
let lines = 0;
|
|
78
|
+
for (let index = bytes.indexOf(NEWLINE);index !== -1; index = bytes.indexOf(NEWLINE, index + 1)) {
|
|
79
|
+
if (++lines === limits.maxLines) {
|
|
80
|
+
end = index + 1;
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (end > limits.maxBytes) {
|
|
85
|
+
const newline = bytes.lastIndexOf(NEWLINE, limits.maxBytes - 1);
|
|
86
|
+
end = newline === -1 ? characterEnd(bytes, limits.maxBytes) : newline + 1;
|
|
87
|
+
}
|
|
88
|
+
return [0, end];
|
|
89
|
+
}
|
|
90
|
+
function tailRange(bytes, limits) {
|
|
91
|
+
if (limits.maxLines === 0 || limits.maxBytes === 0)
|
|
92
|
+
return [bytes.length, bytes.length];
|
|
93
|
+
const last = bytes[bytes.length - 1] === NEWLINE ? bytes.length - 2 : bytes.length - 1;
|
|
94
|
+
let start = 0;
|
|
95
|
+
let lines = 1;
|
|
96
|
+
for (let index = last < 0 ? -1 : bytes.lastIndexOf(NEWLINE, last);index !== -1; ) {
|
|
97
|
+
if (lines === limits.maxLines) {
|
|
98
|
+
start = index + 1;
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
lines++;
|
|
102
|
+
index = index === 0 ? -1 : bytes.lastIndexOf(NEWLINE, index - 1);
|
|
103
|
+
}
|
|
104
|
+
if (bytes.length - start > limits.maxBytes) {
|
|
105
|
+
const from = bytes.length - limits.maxBytes;
|
|
106
|
+
const newline = bytes.indexOf(NEWLINE, from - 1);
|
|
107
|
+
start = newline !== -1 && newline + 1 < bytes.length ? newline + 1 : characterStart(bytes, from);
|
|
108
|
+
}
|
|
109
|
+
return [start, bytes.length];
|
|
110
|
+
}
|
|
111
|
+
function characterEnd(bytes, index) {
|
|
112
|
+
let end = index;
|
|
113
|
+
while (end > 0 && ((bytes[end] ?? 0) & 192) === 128)
|
|
114
|
+
end--;
|
|
115
|
+
return end;
|
|
116
|
+
}
|
|
117
|
+
function characterStart(bytes, index) {
|
|
118
|
+
let start = index;
|
|
119
|
+
while (start < bytes.length && ((bytes[start] ?? 0) & 192) === 128)
|
|
120
|
+
start++;
|
|
121
|
+
return start;
|
|
122
|
+
}
|
|
123
|
+
function lineCount(bytes) {
|
|
124
|
+
if (bytes.length === 0)
|
|
125
|
+
return 0;
|
|
126
|
+
let newlines = 0;
|
|
127
|
+
for (let index = bytes.indexOf(NEWLINE);index !== -1; index = bytes.indexOf(NEWLINE, index + 1))
|
|
128
|
+
newlines++;
|
|
129
|
+
return newlines + (bytes[bytes.length - 1] === NEWLINE ? 0 : 1);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
class OutputBuffer {
|
|
133
|
+
#limits;
|
|
134
|
+
#decoder = new TextDecoder("utf-8", { ignoreBOM: true });
|
|
135
|
+
#started = false;
|
|
136
|
+
#chunks = [];
|
|
137
|
+
#storedBytes = 0;
|
|
138
|
+
#storedNewlines = 0;
|
|
139
|
+
#full = false;
|
|
140
|
+
#totalBytes = 0;
|
|
141
|
+
#totalNewlines = 0;
|
|
142
|
+
#endsWithNewline = true;
|
|
143
|
+
constructor(limits) {
|
|
144
|
+
this.#limits = limits;
|
|
145
|
+
}
|
|
146
|
+
get storedBytes() {
|
|
147
|
+
return this.#storedBytes;
|
|
148
|
+
}
|
|
149
|
+
push(chunk, skipped) {
|
|
150
|
+
const pending = typeof chunk === "string" || skipped !== undefined ? this.#decoder.decode() : "";
|
|
151
|
+
let text = typeof chunk === "string" ? chunk : this.#decoder.decode(chunk, { stream: true });
|
|
152
|
+
const first = !this.#started && pending === "" && skipped === undefined;
|
|
153
|
+
if (pending !== "" || text !== "" || skipped !== undefined)
|
|
154
|
+
this.#started = true;
|
|
155
|
+
if (first && typeof chunk !== "string" && text.startsWith("\uFEFF"))
|
|
156
|
+
text = text.slice(1);
|
|
157
|
+
if (skipped === undefined)
|
|
158
|
+
return this.#accept(pending + text);
|
|
159
|
+
if (this.#limits.retain !== "tail")
|
|
160
|
+
throw new Error("Skipped output requires tail retention");
|
|
161
|
+
this.#accept(pending);
|
|
162
|
+
this.#skip(skipped);
|
|
163
|
+
this.#accept(text);
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
#skip(skipped) {
|
|
167
|
+
if (skipped.bytes === 0)
|
|
168
|
+
return;
|
|
169
|
+
this.#totalBytes += skipped.bytes;
|
|
170
|
+
this.#totalNewlines += skipped.newlines;
|
|
171
|
+
this.#endsWithNewline = skipped.endsWithNewline;
|
|
172
|
+
this.#chunks = [];
|
|
173
|
+
this.#storedBytes = 0;
|
|
174
|
+
this.#storedNewlines = 0;
|
|
175
|
+
}
|
|
176
|
+
end() {
|
|
177
|
+
this.#accept(this.#decoder.decode());
|
|
178
|
+
}
|
|
179
|
+
#accept(text) {
|
|
180
|
+
if (text.length === 0)
|
|
181
|
+
return false;
|
|
182
|
+
const bytes = utf8ByteLength(text);
|
|
183
|
+
const newlines = countNewlines(text);
|
|
184
|
+
this.#totalBytes += bytes;
|
|
185
|
+
this.#totalNewlines += newlines;
|
|
186
|
+
this.#endsWithNewline = text.endsWith(`
|
|
187
|
+
`);
|
|
188
|
+
if (this.#full)
|
|
189
|
+
return true;
|
|
190
|
+
this.#chunks.push({ text, bytes, newlines });
|
|
191
|
+
this.#storedBytes += bytes;
|
|
192
|
+
this.#storedNewlines += newlines;
|
|
193
|
+
if (this.#limits.retain === "head") {
|
|
194
|
+
this.#full = this.#storedBytes > this.#limits.maxBytes || this.#storedNewlines >= this.#limits.maxLines;
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
while (this.#chunks.length > 1) {
|
|
198
|
+
const first = this.#chunks[0];
|
|
199
|
+
const bytesAfter = this.#storedBytes - first.bytes;
|
|
200
|
+
const newlinesAfter = this.#storedNewlines - first.newlines;
|
|
201
|
+
if (bytesAfter <= this.#limits.maxBytes + 1 && newlinesAfter <= this.#limits.maxLines + 1)
|
|
202
|
+
break;
|
|
203
|
+
this.#chunks.shift();
|
|
204
|
+
this.#storedBytes = bytesAfter;
|
|
205
|
+
this.#storedNewlines = newlinesAfter;
|
|
206
|
+
}
|
|
207
|
+
return true;
|
|
208
|
+
}
|
|
209
|
+
snapshot() {
|
|
210
|
+
const stored = this.#chunks.length === 1 ? this.#chunks[0].text : this.#chunks.map((chunk) => chunk.text).join("");
|
|
211
|
+
const kept = boundOutput(stored, this.#limits);
|
|
212
|
+
const storedLines = lines(this.#storedNewlines, stored === "" || stored.endsWith(`
|
|
213
|
+
`));
|
|
214
|
+
const keptLines = storedLines - kept.droppedLines;
|
|
215
|
+
if (this.#limits.retain === "tail" || this.#chunks.length > 1) {
|
|
216
|
+
const text = this.#limits.retain === "tail" ? tailMargin(stored, this.#limits) : stored;
|
|
217
|
+
const bytes = this.#limits.retain === "tail" ? utf8ByteLength(text) : this.#storedBytes;
|
|
218
|
+
this.#chunks = text === "" ? [] : [{ text, bytes, newlines: countNewlines(text) }];
|
|
219
|
+
this.#storedBytes = bytes;
|
|
220
|
+
this.#storedNewlines = this.#chunks[0]?.newlines ?? 0;
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
text: sanitizeOutput(kept.text),
|
|
224
|
+
droppedBytes: this.#totalBytes - kept.bytes,
|
|
225
|
+
droppedLines: lines(this.#totalNewlines, this.#endsWithNewline) - keptLines
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
function tailMargin(text, limits) {
|
|
230
|
+
const bytes = encoder.encode(text);
|
|
231
|
+
const byteStart = bytes.length > limits.maxBytes ? characterEnd(bytes, bytes.length - limits.maxBytes - 1) : 0;
|
|
232
|
+
let lineStart = 0;
|
|
233
|
+
let newlines = 0;
|
|
234
|
+
for (let index = bytes.lastIndexOf(NEWLINE);index !== -1; index = bytes.lastIndexOf(NEWLINE, index - 1)) {
|
|
235
|
+
if (++newlines > limits.maxLines) {
|
|
236
|
+
lineStart = index;
|
|
237
|
+
break;
|
|
238
|
+
}
|
|
239
|
+
if (index === 0)
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
const start = Math.max(byteStart, lineStart);
|
|
243
|
+
return start === 0 ? text : decoder.decode(bytes.subarray(start));
|
|
244
|
+
}
|
|
245
|
+
function lines(newlines, terminated) {
|
|
246
|
+
return newlines + (terminated ? 0 : 1);
|
|
247
|
+
}
|
|
248
|
+
function countNewlines(text) {
|
|
249
|
+
let count = 0;
|
|
250
|
+
for (let index = text.indexOf(`
|
|
251
|
+
`);index !== -1; index = text.indexOf(`
|
|
252
|
+
`, index + 1))
|
|
253
|
+
count++;
|
|
254
|
+
return count;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// packages/execution/src/forwarding.ts
|
|
258
|
+
var bytes = (value) => new TextEncoder().encode(JSON.stringify(value)).length;
|
|
259
|
+
function boundForwardedToolCalls(value, budget) {
|
|
260
|
+
const calls = [];
|
|
261
|
+
let remaining = budget;
|
|
262
|
+
let omittedCalls = value.omittedCalls;
|
|
263
|
+
for (const source of value.calls) {
|
|
264
|
+
let call = source;
|
|
265
|
+
if (bytes(call) > remaining && call.result !== null) {
|
|
266
|
+
call = {
|
|
267
|
+
...call,
|
|
268
|
+
result: null,
|
|
269
|
+
omittedFields: [...call.omittedFields, "result"]
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
if (bytes(call) > remaining && call.arguments !== undefined) {
|
|
273
|
+
const { arguments: _arguments, ...rest } = call;
|
|
274
|
+
call = { ...rest, omittedFields: [...call.omittedFields, "arguments"] };
|
|
275
|
+
}
|
|
276
|
+
const cost = bytes(call);
|
|
277
|
+
if (cost > remaining)
|
|
278
|
+
omittedCalls++;
|
|
279
|
+
else {
|
|
280
|
+
calls.push(call);
|
|
281
|
+
remaining -= cost;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return { ...value, calls, omittedCalls };
|
|
285
|
+
}
|
|
286
|
+
function displayResult(result, budget) {
|
|
287
|
+
let remaining = budget;
|
|
288
|
+
let omitted = false;
|
|
289
|
+
const content = [];
|
|
290
|
+
for (const item of result.output ?? []) {
|
|
291
|
+
if (item.type === "image") {
|
|
292
|
+
const cost = bytes(item);
|
|
293
|
+
if (cost <= remaining) {
|
|
294
|
+
content.push(item);
|
|
295
|
+
remaining -= cost;
|
|
296
|
+
} else
|
|
297
|
+
omitted = true;
|
|
298
|
+
} else {
|
|
299
|
+
const bounded = boundOutput(item.text, {
|
|
300
|
+
maxBytes: remaining,
|
|
301
|
+
maxLines: Number.MAX_SAFE_INTEGER,
|
|
302
|
+
retain: "head"
|
|
303
|
+
});
|
|
304
|
+
if (bounded.text)
|
|
305
|
+
content.push({ type: "text", text: bounded.text });
|
|
306
|
+
remaining -= bounded.bytes;
|
|
307
|
+
omitted ||= bounded.droppedBytes > 0;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return {
|
|
311
|
+
content,
|
|
312
|
+
isError: result.isError ?? false,
|
|
313
|
+
details: result.details ?? null,
|
|
314
|
+
diagnostics: [
|
|
315
|
+
...result.diagnostics ?? [],
|
|
316
|
+
...omitted ? [
|
|
317
|
+
{
|
|
318
|
+
severity: "warn",
|
|
319
|
+
code: "forwarded_display_truncated",
|
|
320
|
+
message: "Forwarded display output was truncated; the original tool result is unchanged"
|
|
321
|
+
}
|
|
322
|
+
] : []
|
|
323
|
+
]
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
function forwardedStatus(result, fallback) {
|
|
327
|
+
if (result.diagnostics?.some((item) => item.code === "interrupted"))
|
|
328
|
+
return "interrupted";
|
|
329
|
+
if (result.diagnostics?.some((item) => item.code === "aborted" || item.code === "abandoned"))
|
|
330
|
+
return "aborted";
|
|
331
|
+
return fallback;
|
|
332
|
+
}
|
|
333
|
+
async function forwardCall(tx, cellId, call, admission = false, nativeTask) {
|
|
334
|
+
if (cellId === undefined)
|
|
335
|
+
return;
|
|
336
|
+
const doc = await tx.doc(InvocationDoc, cellId);
|
|
337
|
+
const snapshot = doc.forwardedToolCalls;
|
|
338
|
+
if (snapshot === undefined)
|
|
339
|
+
return;
|
|
340
|
+
const position = snapshot.calls.findIndex((item) => item.callId === call.callId);
|
|
341
|
+
if (position === -1 && !admission)
|
|
342
|
+
return;
|
|
343
|
+
const calls = [...snapshot.calls];
|
|
344
|
+
if (position === -1)
|
|
345
|
+
calls.push(call);
|
|
346
|
+
else
|
|
347
|
+
calls[position] = call;
|
|
348
|
+
doc.forwardedToolCalls = copyJson2(boundForwardedToolCalls({ ...snapshot, calls }, doc.forwardingBudget ?? 40000), { omitUndefinedProperties: true });
|
|
349
|
+
const retained = new Set(doc.forwardedToolCalls.calls.map((item) => item.callId));
|
|
350
|
+
if (doc.forwardedNativeTasks !== undefined)
|
|
351
|
+
doc.forwardedNativeTasks = doc.forwardedNativeTasks.filter((item) => retained.has(item.callId));
|
|
352
|
+
if (nativeTask !== undefined && retained.has(call.callId) && !doc.forwardedNativeTasks?.some((item) => item.callId === call.callId)) {
|
|
353
|
+
doc.forwardedNativeTasks ??= [];
|
|
354
|
+
doc.forwardedNativeTasks.push({ callId: call.callId, ...nativeTask });
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
async function forwardInvocationResult(tx, taskId, result, status) {
|
|
358
|
+
const cellId = (await tx.doc(InvocationDoc, taskId)).forwardingCellId;
|
|
359
|
+
if (cellId === undefined || cellId === taskId)
|
|
360
|
+
return;
|
|
361
|
+
const doc = await tx.doc(InvocationDoc, cellId);
|
|
362
|
+
const previous = doc.forwardedToolCalls?.calls.find((call) => call.callId === `nested-${taskId}`);
|
|
363
|
+
if (previous === undefined)
|
|
364
|
+
return;
|
|
365
|
+
await forwardCall(tx, cellId, {
|
|
366
|
+
...previous,
|
|
367
|
+
status: forwardedStatus(result, status),
|
|
368
|
+
result: displayResult(result, doc.forwardingBudget ?? 40000),
|
|
369
|
+
omittedFields: previous.omittedFields.filter((field) => field !== "result")
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
async function captureNativeCalls(tx, conversationId, owner, cellId) {
|
|
373
|
+
if (cellId === undefined)
|
|
374
|
+
return;
|
|
375
|
+
const live = await tx.doc(LiveDoc, conversationId);
|
|
376
|
+
const owners = new Set([owner]);
|
|
377
|
+
const cell = await tx.doc(InvocationDoc, cellId);
|
|
378
|
+
const budget = cell.forwardingBudget ?? 40000;
|
|
379
|
+
const admitted = new Set(cell.forwardedToolCalls?.calls.map((call) => call.callId));
|
|
380
|
+
for (const slot of live.nestedTools ?? []) {
|
|
381
|
+
if (!owners.has(slot.parentTaskId) && !admitted.has(slot.callId))
|
|
382
|
+
continue;
|
|
383
|
+
owners.add(slot.taskId);
|
|
384
|
+
const key = slot.callId.slice(slot.parentCallId.length + 1);
|
|
385
|
+
const stored = (await tx.doc(NestedCallDoc, slot.parentTaskId, key, null)).result;
|
|
386
|
+
const record = await tx.task(slot.taskId);
|
|
387
|
+
const outcome = record?.state.status === "terminal" ? record.state.outcome : undefined;
|
|
388
|
+
const previous = cell.forwardedToolCalls?.calls.find((call) => call.callId === slot.callId);
|
|
389
|
+
if (stored === undefined && previous !== undefined && previous.status !== "pending" && previous.status !== "running")
|
|
390
|
+
continue;
|
|
391
|
+
const captured = previous !== undefined && previous.status !== "pending" && previous.status !== "running" && !previous.result?.diagnostics.some((item) => item.code === "forwarded_output_unavailable");
|
|
392
|
+
const terminal = stored !== undefined || outcome !== undefined || slot.status === "done";
|
|
393
|
+
const result = stored ?? {
|
|
394
|
+
...slot.output === undefined ? {} : { output: [{ type: "text", text: slot.output }] },
|
|
395
|
+
...slot.details === undefined ? {} : { details: slot.details },
|
|
396
|
+
...slot.diagnostics === undefined ? {} : { diagnostics: slot.diagnostics }
|
|
397
|
+
};
|
|
398
|
+
const receipt = stored === undefined ? displayResult(result, budget) : {
|
|
399
|
+
content: previous?.result?.content ?? [],
|
|
400
|
+
isError: stored.isError,
|
|
401
|
+
details: stored.details ?? null,
|
|
402
|
+
diagnostics: [
|
|
403
|
+
...stored.diagnostics,
|
|
404
|
+
...!captured ? [
|
|
405
|
+
{
|
|
406
|
+
severity: "warn",
|
|
407
|
+
code: "forwarded_output_unavailable",
|
|
408
|
+
message: "Native display output was not retained. Bind this execution component to its owning Harness before running native nested calls"
|
|
409
|
+
}
|
|
410
|
+
] : []
|
|
411
|
+
]
|
|
412
|
+
};
|
|
413
|
+
await forwardCall(tx, cellId, {
|
|
414
|
+
callId: slot.callId,
|
|
415
|
+
parentCallId: slot.parentCallId,
|
|
416
|
+
name: slot.name,
|
|
417
|
+
arguments: slot.arguments,
|
|
418
|
+
status: terminal ? forwardedStatus(result, outcome?.status === "aborted" ? "aborted" : outcome?.status === "completed" ? "completed" : "failed") : slot.status === "pending" ? "pending" : "running",
|
|
419
|
+
result: terminal && previous?.omittedFields.includes("result") ? null : receipt,
|
|
420
|
+
omittedFields: terminal && previous?.omittedFields.includes("result") ? ["result"] : []
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
const visible = new Set(live.nestedTools?.map((slot) => slot.callId));
|
|
424
|
+
for (const admitted of [...cell.forwardedNativeTasks ?? []]) {
|
|
425
|
+
if (visible.has(admitted.callId))
|
|
426
|
+
continue;
|
|
427
|
+
const record = await tx.task(admitted.taskId);
|
|
428
|
+
if (record === undefined || record.kind !== ToolTask.definition.name || record.owner !== admitted.ownerTaskId || record.conversationId !== conversationId)
|
|
429
|
+
throw new Error(`Native forwarded task ${admitted.taskId} does not match its admission`);
|
|
430
|
+
if (record.state.status !== "terminal")
|
|
431
|
+
continue;
|
|
432
|
+
const call = cell.forwardedToolCalls?.calls.find((item) => item.callId === admitted.callId);
|
|
433
|
+
if (call !== undefined) {
|
|
434
|
+
const outcome = record.state.outcome;
|
|
435
|
+
const unfinished = call.status === "pending" || call.status === "running";
|
|
436
|
+
const completedStatus = unfinished ? forwardedStatus({ diagnostics: call.result?.diagnostics ?? [] }, call.result?.isError ? "failed" : "completed") : call.status;
|
|
437
|
+
const status = record.abortReason === "restart" ? "interrupted" : outcome.status === "completed" ? completedStatus : outcome.status === "aborted" ? "aborted" : "failed";
|
|
438
|
+
if (unfinished || call.status !== status) {
|
|
439
|
+
const diagnostic = status === "completed" ? {
|
|
440
|
+
severity: "warn",
|
|
441
|
+
code: "forwarded_result_unavailable",
|
|
442
|
+
message: "Native task completed, but its final display result was not retained; the retained output may be partial"
|
|
443
|
+
} : {
|
|
444
|
+
severity: "error",
|
|
445
|
+
code: status,
|
|
446
|
+
message: `Native tool ${call.name} ${status}; external side effects may have partially run`
|
|
447
|
+
};
|
|
448
|
+
await forwardCall(tx, cellId, {
|
|
449
|
+
...call,
|
|
450
|
+
status,
|
|
451
|
+
result: call.omittedFields.includes("result") ? null : {
|
|
452
|
+
content: call.result?.content ?? [],
|
|
453
|
+
isError: status === "completed" ? call.result?.isError ?? false : true,
|
|
454
|
+
details: call.result?.details ?? null,
|
|
455
|
+
diagnostics: [...call.result?.diagnostics ?? [], diagnostic]
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
cell.forwardedNativeTasks = cell.forwardedNativeTasks?.filter((item) => item.callId !== admitted.callId) ?? [];
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// packages/execution/src/invocation.ts
|
|
465
|
+
import { copyJson as copyJson4 } from "@earendil-works/chord";
|
|
466
|
+
import { awaitWithContext } from "@earendil-works/chord/context";
|
|
467
|
+
|
|
468
|
+
// packages/execution/src/native-tools.ts
|
|
469
|
+
import { copyJson as copyJson3 } from "@earendil-works/chord";
|
|
470
|
+
import { withoutAbortSignal } from "@earendil-works/chord/context";
|
|
471
|
+
import {
|
|
472
|
+
LiveDoc as LiveDoc2,
|
|
473
|
+
NestedCallDoc as NestedCallDoc2,
|
|
474
|
+
ToolTask as ToolTask2
|
|
475
|
+
} from "@earendil-works/pi-durable";
|
|
476
|
+
import { Equal } from "typebox/value";
|
|
477
|
+
function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
478
|
+
let sequence = 0;
|
|
479
|
+
const admissions = [];
|
|
480
|
+
const execute = async (name, args, callContext, options = {}) => {
|
|
481
|
+
assertLive();
|
|
482
|
+
const key = options.key ?? String(++sequence);
|
|
483
|
+
if (options.key !== undefined && (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)))
|
|
484
|
+
throw new Error("Invalid nested call key");
|
|
485
|
+
const call = {
|
|
486
|
+
type: "toolCall",
|
|
487
|
+
id: `${callId}/${key}`,
|
|
488
|
+
name,
|
|
489
|
+
arguments: copyJson3(args, {
|
|
490
|
+
omitUndefinedProperties: true
|
|
491
|
+
})
|
|
492
|
+
};
|
|
493
|
+
const admission = runtime.commit(async (tx) => {
|
|
494
|
+
const slot = await tx.doc(NestedCallDoc2, runtime.taskId, key, null);
|
|
495
|
+
if (slot.taskId !== undefined) {
|
|
496
|
+
const input = (await tx.task(slot.taskId))?.input;
|
|
497
|
+
if (input?.kind !== "nested" || input.call.name !== name || !Equal(input.call.arguments, call.arguments))
|
|
498
|
+
throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
|
|
499
|
+
} else {
|
|
500
|
+
slot.taskId = await tx.createTask(ToolTask2, {
|
|
501
|
+
kind: "nested",
|
|
502
|
+
parent: runtime.taskId,
|
|
503
|
+
parentCallId: callId,
|
|
504
|
+
key,
|
|
505
|
+
call,
|
|
506
|
+
...options.progress === false ? { progress: false } : {}
|
|
507
|
+
}, {
|
|
508
|
+
ownership: { kind: "task", taskId: runtime.taskId },
|
|
509
|
+
abandonOnRestart: replay !== "safe"
|
|
510
|
+
});
|
|
511
|
+
const live = await tx.doc(LiveDoc2, runtime.conversationId);
|
|
512
|
+
live.nestedTools ??= [];
|
|
513
|
+
live.nestedTools.push({
|
|
514
|
+
callId: call.id,
|
|
515
|
+
parentCallId: callId,
|
|
516
|
+
parentTaskId: runtime.taskId,
|
|
517
|
+
name,
|
|
518
|
+
taskId: slot.taskId,
|
|
519
|
+
arguments: call.arguments,
|
|
520
|
+
status: "pending"
|
|
521
|
+
});
|
|
522
|
+
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
523
|
+
if (owner.forwardingCellId !== undefined) {
|
|
524
|
+
(await tx.doc(InvocationDoc, slot.taskId)).forwardingCellId = owner.forwardingCellId;
|
|
525
|
+
await forwardCall(tx, owner.forwardingCellId, {
|
|
526
|
+
callId: call.id,
|
|
527
|
+
parentCallId: callId,
|
|
528
|
+
name,
|
|
529
|
+
arguments: call.arguments,
|
|
530
|
+
status: "pending",
|
|
531
|
+
result: null,
|
|
532
|
+
omittedFields: []
|
|
533
|
+
}, true, { taskId: slot.taskId, ownerTaskId: runtime.taskId });
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
return;
|
|
537
|
+
}, callContext);
|
|
538
|
+
admissions.push(admission);
|
|
539
|
+
await admission;
|
|
540
|
+
const slot = await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext);
|
|
541
|
+
if (slot?.taskId === undefined)
|
|
542
|
+
throw new Error("Nested task creation did not commit");
|
|
543
|
+
const settled = await runtime.waitForTask(slot.taskId, callContext);
|
|
544
|
+
const result = (await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext))?.result;
|
|
545
|
+
await runtime.commit(async (tx) => {
|
|
546
|
+
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
547
|
+
await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
|
|
548
|
+
return;
|
|
549
|
+
}, callContext);
|
|
550
|
+
return result === undefined ? {
|
|
551
|
+
taskId: slot.taskId,
|
|
552
|
+
isError: true,
|
|
553
|
+
diagnostics: [
|
|
554
|
+
{
|
|
555
|
+
severity: "error",
|
|
556
|
+
code: settled.state.outcome.status,
|
|
557
|
+
message: `Tool ${name} did not return a result`
|
|
558
|
+
}
|
|
559
|
+
]
|
|
560
|
+
} : copyJson3(result);
|
|
561
|
+
};
|
|
562
|
+
return {
|
|
563
|
+
execute,
|
|
564
|
+
async finish() {
|
|
565
|
+
await Promise.allSettled(admissions);
|
|
566
|
+
await cleanupNativeCalls(runtime, withoutAbortSignal(context));
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
async function cleanupNativeCalls(runtime, context) {
|
|
571
|
+
await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask2.definition.name).map((child) => runtime.abortOwned(child.id, context)));
|
|
572
|
+
await runtime.commit(async (tx) => {
|
|
573
|
+
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
574
|
+
await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
|
|
575
|
+
const live = await tx.doc(LiveDoc2, runtime.conversationId);
|
|
576
|
+
const removed = new Set([runtime.taskId]);
|
|
577
|
+
for (const slot of live.nestedTools ?? [])
|
|
578
|
+
if (removed.has(slot.parentTaskId))
|
|
579
|
+
removed.add(slot.taskId);
|
|
580
|
+
if (live.nestedTools !== undefined) {
|
|
581
|
+
live.nestedTools = live.nestedTools.filter((slot) => !removed.has(slot.parentTaskId));
|
|
582
|
+
if (!live.nestedTools.length)
|
|
583
|
+
delete live.nestedTools;
|
|
584
|
+
}
|
|
585
|
+
return;
|
|
586
|
+
}, context);
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// packages/execution/src/progress.ts
|
|
590
|
+
var PROGRESS_BYTES_PER_SECOND = 100 * 1024;
|
|
591
|
+
|
|
592
|
+
class Progress {
|
|
593
|
+
#write;
|
|
594
|
+
#onError;
|
|
595
|
+
#minIntervalMs;
|
|
596
|
+
#waiters = [];
|
|
597
|
+
#timer;
|
|
598
|
+
#inFlight;
|
|
599
|
+
#nextAt = 0;
|
|
600
|
+
#dirty = false;
|
|
601
|
+
#stopped = false;
|
|
602
|
+
constructor(write, onError, minIntervalMs) {
|
|
603
|
+
this.#write = write;
|
|
604
|
+
this.#onError = onError;
|
|
605
|
+
this.#minIntervalMs = minIntervalMs;
|
|
606
|
+
}
|
|
607
|
+
mark() {
|
|
608
|
+
this.#dirty = true;
|
|
609
|
+
this.#schedule();
|
|
610
|
+
}
|
|
611
|
+
markAndWait() {
|
|
612
|
+
let resolve;
|
|
613
|
+
let reject;
|
|
614
|
+
const promise = new Promise((yes, no) => {
|
|
615
|
+
resolve = yes;
|
|
616
|
+
reject = no;
|
|
617
|
+
});
|
|
618
|
+
const waiter = { promise, resolve, reject };
|
|
619
|
+
this.#waiters.push(waiter);
|
|
620
|
+
this.mark();
|
|
621
|
+
return waiter.promise;
|
|
622
|
+
}
|
|
623
|
+
async stop() {
|
|
624
|
+
this.#stopped = true;
|
|
625
|
+
clearTimeout(this.#timer);
|
|
626
|
+
this.#timer = undefined;
|
|
627
|
+
await this.#inFlight;
|
|
628
|
+
return this.#waiters.splice(0);
|
|
629
|
+
}
|
|
630
|
+
#schedule() {
|
|
631
|
+
if (this.#stopped || this.#timer !== undefined || this.#inFlight !== undefined)
|
|
632
|
+
return;
|
|
633
|
+
const wait = this.#nextAt - Date.now();
|
|
634
|
+
if (wait <= 0)
|
|
635
|
+
this.#flush();
|
|
636
|
+
else
|
|
637
|
+
this.#timer = setTimeout(() => {
|
|
638
|
+
this.#timer = undefined;
|
|
639
|
+
this.#flush();
|
|
640
|
+
}, wait);
|
|
641
|
+
}
|
|
642
|
+
#flush() {
|
|
643
|
+
if (this.#stopped || !this.#dirty)
|
|
644
|
+
return;
|
|
645
|
+
this.#dirty = false;
|
|
646
|
+
const waiters = this.#waiters.splice(0);
|
|
647
|
+
const started = Date.now();
|
|
648
|
+
this.#inFlight = this.#write().then((bytes) => {
|
|
649
|
+
this.#nextAt = started + Math.max(this.#minIntervalMs, bytes * 1000 / PROGRESS_BYTES_PER_SECOND);
|
|
650
|
+
for (const waiter of waiters)
|
|
651
|
+
waiter.resolve();
|
|
652
|
+
}, (error) => {
|
|
653
|
+
this.#nextAt = started + this.#minIntervalMs;
|
|
654
|
+
for (const waiter of waiters)
|
|
655
|
+
waiter.reject(error);
|
|
656
|
+
this.#onError(error);
|
|
657
|
+
}).finally(() => {
|
|
658
|
+
this.#inFlight = undefined;
|
|
659
|
+
if (this.#dirty)
|
|
660
|
+
this.#schedule();
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// packages/execution/src/tool-origin.ts
|
|
666
|
+
import {
|
|
667
|
+
defineDoc as defineDoc2
|
|
668
|
+
} from "@earendil-works/pi-durable";
|
|
669
|
+
var ToolOriginDoc = defineDoc2({
|
|
670
|
+
kind: "howaboua.tool-origin",
|
|
671
|
+
version: 1,
|
|
672
|
+
scope: "task",
|
|
673
|
+
checkpointWhen: () => false,
|
|
674
|
+
initial: () => ({})
|
|
675
|
+
});
|
|
676
|
+
|
|
677
|
+
// packages/execution/src/invocation.ts
|
|
678
|
+
function executionError(code, message) {
|
|
679
|
+
return {
|
|
680
|
+
output: [],
|
|
681
|
+
isError: true,
|
|
682
|
+
diagnostics: [{ severity: "error", code, message }]
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
function errorText(error) {
|
|
686
|
+
return error instanceof Error ? error.message : String(error);
|
|
687
|
+
}
|
|
688
|
+
function createInvocation(runtime, tool, context) {
|
|
689
|
+
const limits = {
|
|
690
|
+
maxBytes: tool.outputLimits?.maxBytes ?? 50 * 1024,
|
|
691
|
+
maxLines: tool.outputLimits?.maxLines ?? 2000,
|
|
692
|
+
retain: tool.outputLimits?.retain ?? "head"
|
|
693
|
+
};
|
|
694
|
+
const output = new OutputBuffer(limits);
|
|
695
|
+
const diagnostics = [];
|
|
696
|
+
let details;
|
|
697
|
+
let ended = false;
|
|
698
|
+
const assertLive = () => {
|
|
699
|
+
if (ended)
|
|
700
|
+
throw new Error(`Invocation ${runtime.taskId} has settled`);
|
|
701
|
+
};
|
|
702
|
+
const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, assertLive, context);
|
|
703
|
+
const snapshot = () => {
|
|
704
|
+
const retained = output.snapshot();
|
|
705
|
+
return {
|
|
706
|
+
output: retained.text === "" ? [] : [{ type: "text", text: retained.text }],
|
|
707
|
+
...details === undefined ? {} : { details },
|
|
708
|
+
diagnostics: [...diagnostics]
|
|
709
|
+
};
|
|
710
|
+
};
|
|
711
|
+
const progress = new Progress(async () => {
|
|
712
|
+
const result = storeResult(snapshot());
|
|
713
|
+
const retained = output.snapshot();
|
|
714
|
+
await runtime.commit(async (tx) => {
|
|
715
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
716
|
+
doc.result = result;
|
|
717
|
+
doc.droppedBytes = retained.droppedBytes;
|
|
718
|
+
doc.droppedLines = retained.droppedLines;
|
|
719
|
+
await forwardInvocationResult(tx, runtime.taskId, result, "running");
|
|
720
|
+
return;
|
|
721
|
+
}, context);
|
|
722
|
+
return JSON.stringify(result).length;
|
|
723
|
+
}, (error) => {
|
|
724
|
+
if (!runtime.signal.aborted)
|
|
725
|
+
runtime.report(error);
|
|
726
|
+
}, runtime.settings.progress.outputIntervalMs);
|
|
727
|
+
const api = {
|
|
728
|
+
taskId: runtime.taskId,
|
|
729
|
+
conversationId: runtime.conversationId,
|
|
730
|
+
callId: `nested-${runtime.taskId}`,
|
|
731
|
+
registry: runtime.registry,
|
|
732
|
+
agent: runtime.agent,
|
|
733
|
+
env: undefined,
|
|
734
|
+
now: () => runtime.now(),
|
|
735
|
+
outputWindow: limits.retain === "tail" ? {
|
|
736
|
+
maxBytes: limits.maxBytes,
|
|
737
|
+
maxLines: limits.maxLines,
|
|
738
|
+
minIntervalMs: runtime.settings.progress.outputIntervalMs,
|
|
739
|
+
bytesPerSecond: PROGRESS_BYTES_PER_SECOND
|
|
740
|
+
} : undefined,
|
|
741
|
+
output: (chunk, skipped) => {
|
|
742
|
+
assertLive();
|
|
743
|
+
if (output.push(chunk, skipped))
|
|
744
|
+
progress.mark();
|
|
745
|
+
},
|
|
746
|
+
retainedOutput: () => {
|
|
747
|
+
assertLive();
|
|
748
|
+
const retained = output.snapshot();
|
|
749
|
+
return { text: retained.text, truncated: retained.droppedBytes > 0 };
|
|
750
|
+
},
|
|
751
|
+
executeTool: (...args) => native.execute(...args),
|
|
752
|
+
diagnostic: (value) => {
|
|
753
|
+
assertLive();
|
|
754
|
+
diagnostics.push(copyJson4(value, { omitUndefinedProperties: true }));
|
|
755
|
+
progress.mark();
|
|
756
|
+
},
|
|
757
|
+
details: async (value, detailContext) => {
|
|
758
|
+
assertLive();
|
|
759
|
+
detailContext.abortSignal?.throwIfAborted();
|
|
760
|
+
details = copyJson4(value, { omitUndefinedProperties: true });
|
|
761
|
+
const committed = progress.markAndWait();
|
|
762
|
+
committed.catch(() => {});
|
|
763
|
+
await awaitWithContext(committed, detailContext);
|
|
764
|
+
},
|
|
765
|
+
commit: async (change, commitContext) => {
|
|
766
|
+
assertLive();
|
|
767
|
+
let result;
|
|
768
|
+
await runtime.commit(async (tx) => {
|
|
769
|
+
result = await change(tx);
|
|
770
|
+
return;
|
|
771
|
+
}, commitContext);
|
|
772
|
+
return result;
|
|
773
|
+
},
|
|
774
|
+
memo: runtime.memo,
|
|
775
|
+
createTask: async (task, input, options, taskContext) => {
|
|
776
|
+
assertLive();
|
|
777
|
+
let id;
|
|
778
|
+
await runtime.commit(async (tx) => {
|
|
779
|
+
id = await tx.createTask(task, input, {
|
|
780
|
+
...options,
|
|
781
|
+
...options.abandonOnRestart === undefined && tool.replay !== "safe" && options.ownership.kind === "task" && options.ownership.taskId === runtime.taskId ? { abandonOnRestart: true } : {}
|
|
782
|
+
});
|
|
783
|
+
const source = await tx.doc(ToolOriginDoc, runtime.taskId);
|
|
784
|
+
if (source.origin !== undefined)
|
|
785
|
+
(await tx.doc(ToolOriginDoc, id)).origin = { ...source.origin };
|
|
786
|
+
return;
|
|
787
|
+
}, taskContext);
|
|
788
|
+
if (id === undefined)
|
|
789
|
+
throw new Error("Task creation did not commit");
|
|
790
|
+
return id;
|
|
791
|
+
},
|
|
792
|
+
getTask: runtime.getTask,
|
|
793
|
+
waitForTask: runtime.waitForTask,
|
|
794
|
+
conversation: runtime.conversation,
|
|
795
|
+
snapshot: runtime.snapshot,
|
|
796
|
+
snapshotAsOf: runtime.snapshotAsOf,
|
|
797
|
+
watchDoc: runtime.watchDoc
|
|
798
|
+
};
|
|
799
|
+
return {
|
|
800
|
+
async executionApi() {
|
|
801
|
+
return {
|
|
802
|
+
...api,
|
|
803
|
+
get models() {
|
|
804
|
+
return runtime.models;
|
|
805
|
+
},
|
|
806
|
+
env: await runtime.env(context)
|
|
807
|
+
};
|
|
808
|
+
},
|
|
809
|
+
async finish(result) {
|
|
810
|
+
ended = true;
|
|
811
|
+
await native.finish();
|
|
812
|
+
output.end();
|
|
813
|
+
const pending = await progress.stop();
|
|
814
|
+
const retained = output.snapshot();
|
|
815
|
+
const content = result.output ?? (retained.text === "" ? [] : [{ type: "text", text: retained.text }]);
|
|
816
|
+
const final = {
|
|
817
|
+
...result,
|
|
818
|
+
output: content,
|
|
819
|
+
...result.details === undefined && details !== undefined ? { details } : {},
|
|
820
|
+
diagnostics: [...diagnostics, ...result.diagnostics ?? []]
|
|
821
|
+
};
|
|
822
|
+
return { result: final, pending, retained, content };
|
|
823
|
+
},
|
|
824
|
+
async stop(error) {
|
|
825
|
+
ended = true;
|
|
826
|
+
for (const waiter of await progress.stop())
|
|
827
|
+
waiter.reject(error);
|
|
828
|
+
},
|
|
829
|
+
limits,
|
|
830
|
+
output,
|
|
831
|
+
progress
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
function boundResult(result, limits) {
|
|
835
|
+
const content = result.output ?? [];
|
|
836
|
+
const texts = content.filter((item) => item.type === "text");
|
|
837
|
+
const bounded = boundOutput(texts.map((item) => item.text).join(""), limits);
|
|
838
|
+
if (bounded.droppedBytes === 0)
|
|
839
|
+
return result;
|
|
840
|
+
const keep = limits.retain === "head" ? texts[0] : texts.at(-1);
|
|
841
|
+
return {
|
|
842
|
+
...result,
|
|
843
|
+
output: content.flatMap((item) => item.type !== "text" ? [item] : item === keep ? [{ ...item, text: bounded.text }] : []),
|
|
844
|
+
diagnostics: [
|
|
845
|
+
...result.diagnostics ?? [],
|
|
846
|
+
truncation(bounded, limits.retain)
|
|
847
|
+
]
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
function truncation(dropped, retain) {
|
|
851
|
+
const kept = retain === undefined ? "" : ` to its ${retain === "head" ? "beginning" : "end"}`;
|
|
852
|
+
return {
|
|
853
|
+
severity: "warn",
|
|
854
|
+
code: "truncated",
|
|
855
|
+
message: `Output truncated${kept}: ${dropped.droppedLines} lines, ${dropped.droppedBytes} bytes dropped`
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// packages/execution/src/cell-tools.ts
|
|
860
|
+
function cellTools(runtime, toolApi, registrations, nestedTask, controls, cancelTask, cellContext) {
|
|
861
|
+
const tools = Object.create(null);
|
|
862
|
+
for (const registration of registrations)
|
|
863
|
+
tools[registration.name] = async (args, signal) => {
|
|
864
|
+
signal?.throwIfAborted();
|
|
865
|
+
const owner = await toolApi.snapshot(InvocationDoc, runtime.taskId, cellContext);
|
|
866
|
+
const cellId = owner?.forwardingCellId;
|
|
867
|
+
const position = controls.length;
|
|
868
|
+
controls.push(undefined);
|
|
869
|
+
const id = await toolApi.createTask(nestedTask, {
|
|
870
|
+
name: registration.name,
|
|
871
|
+
arguments: copyJson5(args),
|
|
872
|
+
parent: { taskId: runtime.taskId, callId: toolApi.callId },
|
|
873
|
+
...cellId === undefined ? {} : { cellId }
|
|
874
|
+
}, {
|
|
875
|
+
ownership: { kind: "task", taskId: runtime.taskId },
|
|
876
|
+
abandonOnRestart: false
|
|
877
|
+
}, cellContext);
|
|
878
|
+
let cancelling;
|
|
879
|
+
const cancel = () => {
|
|
880
|
+
cancelling ??= cancelTask(id, withoutAbortSignal2(cellContext));
|
|
881
|
+
cancelling.catch((error) => {
|
|
882
|
+
if (!runtime.signal.aborted)
|
|
883
|
+
runtime.report(error);
|
|
884
|
+
});
|
|
885
|
+
};
|
|
886
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
887
|
+
if (signal?.aborted)
|
|
888
|
+
cancel();
|
|
889
|
+
try {
|
|
890
|
+
const settled = await runtime.waitForTask(id, cellContext);
|
|
891
|
+
const result = readStoredResult(settled.state.outcome.result ?? executionError(settled.state.outcome.status, "Nested tool did not return a result"));
|
|
892
|
+
controls[position] = result.control;
|
|
893
|
+
await toolApi.commit(async (tx) => {
|
|
894
|
+
const current = cellId === undefined ? undefined : (await tx.doc(InvocationDoc, cellId)).forwardedToolCalls?.calls.find((call) => call.callId === `nested-${id}`);
|
|
895
|
+
if (current !== undefined)
|
|
896
|
+
await forwardCall(tx, cellId, {
|
|
897
|
+
...current,
|
|
898
|
+
status: forwardedStatus(result, settled.state.outcome.status === "completed" ? "completed" : settled.state.outcome.status === "aborted" ? "aborted" : "failed"),
|
|
899
|
+
result: displayResult(result, owner?.forwardingBudget ?? 40000),
|
|
900
|
+
omittedFields: current.omittedFields.filter((field) => field !== "result")
|
|
901
|
+
});
|
|
902
|
+
}, cellContext);
|
|
903
|
+
return { ...result, callId: `nested-${id}` };
|
|
904
|
+
} finally {
|
|
905
|
+
signal?.removeEventListener("abort", cancel);
|
|
906
|
+
if (cancelling !== undefined)
|
|
907
|
+
await cancelling;
|
|
908
|
+
}
|
|
909
|
+
};
|
|
910
|
+
return tools;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
// packages/execution/src/cells.ts
|
|
914
|
+
import { copyJson as copyJson10 } from "@earendil-works/chord";
|
|
915
|
+
import { withCancel } from "@earendil-works/chord/context";
|
|
916
|
+
import {
|
|
917
|
+
defineExtension
|
|
918
|
+
} from "@earendil-works/pi-durable";
|
|
919
|
+
|
|
920
|
+
// packages/execution/src/cell-observation.ts
|
|
921
|
+
import {
|
|
922
|
+
defineDocFamily
|
|
923
|
+
} from "@earendil-works/pi-durable";
|
|
924
|
+
var CellStateDoc = defineDocFamily({
|
|
925
|
+
kind: "howaboua.execution.cells",
|
|
926
|
+
family: true,
|
|
927
|
+
version: 2,
|
|
928
|
+
scope: "conversation",
|
|
929
|
+
history: "latest",
|
|
930
|
+
fork: "initial",
|
|
931
|
+
checkpointWhen: () => true,
|
|
932
|
+
initial: () => ({ result: {} }),
|
|
933
|
+
migrate: (value) => ({
|
|
934
|
+
...value,
|
|
935
|
+
result: storeResult(readStoredResult(value["result"]))
|
|
936
|
+
})
|
|
937
|
+
});
|
|
938
|
+
async function observeCell(kind, id, api, context, budget) {
|
|
939
|
+
const record = await api.getTask(id, context);
|
|
940
|
+
if (record === undefined || record.kind !== kind || record.conversationId !== api.conversationId)
|
|
941
|
+
throw new Error(`Unknown cell ${id}`);
|
|
942
|
+
const doc = await api.snapshot(InvocationDoc, id, context) ?? await api.snapshot(CellStateDoc, api.conversationId, String(id), context);
|
|
943
|
+
const outcome = record.state.status === "terminal" ? record.state.outcome : undefined;
|
|
944
|
+
const result = readStoredResult(outcome?.result ?? doc?.result ?? {});
|
|
945
|
+
const interrupted = result.diagnostics?.some((each) => each.code === "interrupted") ?? false;
|
|
946
|
+
const status = interrupted ? "interrupted" : outcome?.status === "completed" ? "completed" : outcome?.status === "aborted" ? "aborted" : outcome !== undefined ? "failed" : "running";
|
|
947
|
+
return {
|
|
948
|
+
cellId: id,
|
|
949
|
+
status,
|
|
950
|
+
result,
|
|
951
|
+
...doc?.forwardedToolCalls === undefined ? {} : {
|
|
952
|
+
forwardedToolCalls: budget === undefined ? doc.forwardedToolCalls : boundForwardedToolCalls(doc.forwardedToolCalls, budget)
|
|
953
|
+
},
|
|
954
|
+
...doc?.checkpoint === undefined ? {} : { checkpoint: doc.checkpoint }
|
|
955
|
+
};
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
// packages/execution/src/cell-progress.ts
|
|
959
|
+
import { copyJson as copyJson6 } from "@earendil-works/chord";
|
|
960
|
+
import {
|
|
961
|
+
LiveDoc as LiveDoc3
|
|
962
|
+
} from "@earendil-works/pi-durable";
|
|
963
|
+
async function observeCellProgress(id, api, context, budget) {
|
|
964
|
+
const pending = new Set;
|
|
965
|
+
const publish = async (value) => {
|
|
966
|
+
if (value?.forwardedToolCalls === undefined)
|
|
967
|
+
return;
|
|
968
|
+
await api.details({
|
|
969
|
+
cell_id: String(id),
|
|
970
|
+
status: "running",
|
|
971
|
+
forwardedToolCalls: copyJson6(boundForwardedToolCalls(value.forwardedToolCalls, budget), { omitUndefinedProperties: true })
|
|
972
|
+
}, context);
|
|
973
|
+
};
|
|
974
|
+
const cell = await api.watchDoc(InvocationDoc, id, context);
|
|
975
|
+
if (cell === undefined) {
|
|
976
|
+
await publish(await api.snapshot(CellStateDoc, api.conversationId, String(id), context));
|
|
977
|
+
return async () => {};
|
|
978
|
+
}
|
|
979
|
+
const own = (action) => {
|
|
980
|
+
const work = action();
|
|
981
|
+
pending.add(work);
|
|
982
|
+
work.then(() => pending.delete(work), () => pending.delete(work));
|
|
983
|
+
return work;
|
|
984
|
+
};
|
|
985
|
+
const live = await api.watchDoc(LiveDoc3, api.conversationId, context);
|
|
986
|
+
cell.start((value) => own(() => publish(value)));
|
|
987
|
+
live?.start(() => own(async () => {
|
|
988
|
+
await api.commit(async (tx) => {
|
|
989
|
+
const record = await tx.task(id);
|
|
990
|
+
if (record === undefined || record.state.status === "terminal")
|
|
991
|
+
return;
|
|
992
|
+
await captureNativeCalls(tx, api.conversationId, id, id);
|
|
993
|
+
}, context);
|
|
994
|
+
}));
|
|
995
|
+
try {
|
|
996
|
+
await publish(cell.value);
|
|
997
|
+
} catch (error) {
|
|
998
|
+
await cell.stop();
|
|
999
|
+
await live?.stop();
|
|
1000
|
+
await Promise.allSettled([...pending]);
|
|
1001
|
+
throw error;
|
|
1002
|
+
}
|
|
1003
|
+
return async () => {
|
|
1004
|
+
const endings = await Promise.all([cell.stop(), live?.stop()]);
|
|
1005
|
+
await Promise.all([...pending]);
|
|
1006
|
+
for (const ending of endings)
|
|
1007
|
+
if (ending?.reason === "listener_error")
|
|
1008
|
+
throw ending.error;
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// packages/execution/src/cell-task.ts
|
|
1013
|
+
import { copyJson as copyJson8 } from "@earendil-works/chord";
|
|
1014
|
+
import { withAbortSignal } from "@earendil-works/chord/context";
|
|
1015
|
+
import {
|
|
1016
|
+
defineTask
|
|
1017
|
+
} from "@earendil-works/pi-durable";
|
|
1018
|
+
|
|
1019
|
+
// packages/execution/src/controls.ts
|
|
1020
|
+
function combineControls(controls, allowTermination = true) {
|
|
1021
|
+
const addTools = [
|
|
1022
|
+
...new Set(controls.flatMap((control) => control?.addTools ?? []))
|
|
1023
|
+
];
|
|
1024
|
+
const terminate = allowTermination && controls.some((control) => control?.terminate === true);
|
|
1025
|
+
const handoff = controls.find((control) => control?.handoff !== undefined)?.handoff;
|
|
1026
|
+
if (addTools.length === 0 && !terminate && handoff === undefined)
|
|
1027
|
+
return;
|
|
1028
|
+
return {
|
|
1029
|
+
...addTools.length === 0 ? {} : { addTools },
|
|
1030
|
+
...terminate ? { terminate: true } : {},
|
|
1031
|
+
...handoff === undefined ? {} : { handoff }
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
// packages/execution/src/tool-contract.ts
|
|
1036
|
+
import { copyJson as copyJson7 } from "@earendil-works/chord";
|
|
1037
|
+
function readToolContract(tool) {
|
|
1038
|
+
const candidate = "executionHints" in tool ? tool.executionHints : undefined;
|
|
1039
|
+
if (candidate !== undefined && (candidate === null || typeof candidate !== "object" || Array.isArray(candidate))) {
|
|
1040
|
+
throw new Error(`Tool ${tool.name} executionHints must be an object`);
|
|
1041
|
+
}
|
|
1042
|
+
const hints = candidate ?? {};
|
|
1043
|
+
const supported = new Set([
|
|
1044
|
+
"usage",
|
|
1045
|
+
"output",
|
|
1046
|
+
"deferLoading",
|
|
1047
|
+
"yieldTimeMs",
|
|
1048
|
+
"inputSchema",
|
|
1049
|
+
"nativeOnly",
|
|
1050
|
+
"discovery"
|
|
1051
|
+
]);
|
|
1052
|
+
for (const key of Object.keys(hints))
|
|
1053
|
+
if (!supported.has(key))
|
|
1054
|
+
throw new Error(`Tool ${tool.name} executionHints has unsupported field ${key}`);
|
|
1055
|
+
const usageHint = "usage" in hints ? hints.usage : undefined;
|
|
1056
|
+
const discovery = "discovery" in hints ? hints.discovery : undefined;
|
|
1057
|
+
if (discovery !== undefined && discovery !== "help")
|
|
1058
|
+
throw new Error(`Tool ${tool.name} executionHints.discovery must be help`);
|
|
1059
|
+
const output = "output" in hints ? hints.output : undefined;
|
|
1060
|
+
for (const [field, value] of [
|
|
1061
|
+
["usage", usageHint],
|
|
1062
|
+
["output", output]
|
|
1063
|
+
]) {
|
|
1064
|
+
if (value !== undefined && (typeof value !== "string" || !value.trim()))
|
|
1065
|
+
throw new Error(`Tool ${tool.name} executionHints.${field} must be a non-empty string`);
|
|
1066
|
+
}
|
|
1067
|
+
const deferred = "deferLoading" in hints ? hints.deferLoading : undefined;
|
|
1068
|
+
if (deferred !== undefined && typeof deferred !== "boolean")
|
|
1069
|
+
throw new Error(`Tool ${tool.name} executionHints.deferLoading must be a boolean`);
|
|
1070
|
+
const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
|
|
1071
|
+
if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
|
|
1072
|
+
throw new Error(`Tool ${tool.name} executionHints.nativeOnly must be a boolean`);
|
|
1073
|
+
const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
|
|
1074
|
+
if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
|
|
1075
|
+
throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
|
|
1076
|
+
const inputSchema = "inputSchema" in hints && hints.inputSchema !== undefined ? copyJson7(hints.inputSchema) : copyJson7(JSON.parse(JSON.stringify(tool.parameters)));
|
|
1077
|
+
const reference = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(tool.name) ? `tools.${tool.name}` : `tools[${JSON.stringify(tool.name)}]`;
|
|
1078
|
+
const usage = typeof usageHint === "string" ? usageHint : `await ${reference}(${discovery === "help" ? "" : "args"})`;
|
|
1079
|
+
const outputHint = typeof output === "string" ? output : undefined;
|
|
1080
|
+
return {
|
|
1081
|
+
name: tool.name,
|
|
1082
|
+
...discovery === "help" ? { discovery } : {},
|
|
1083
|
+
description: tool.description,
|
|
1084
|
+
usage,
|
|
1085
|
+
prompt: discovery === "help" ? `${reference}: ${tool.description}` : usage,
|
|
1086
|
+
inputSchema,
|
|
1087
|
+
deferLoading: typeof deferred === "boolean" ? deferred : true,
|
|
1088
|
+
nativeOnly: nativeOnly === true,
|
|
1089
|
+
...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
|
|
1090
|
+
...outputHint === undefined ? {} : { output: outputHint },
|
|
1091
|
+
help: [
|
|
1092
|
+
`Usage: ${usage}`,
|
|
1093
|
+
tool.description,
|
|
1094
|
+
`Schema: ${JSON.stringify(inputSchema)}`,
|
|
1095
|
+
...outputHint === undefined ? [] : [`Output: ${outputHint}`]
|
|
1096
|
+
].filter(Boolean).join(`
|
|
1097
|
+
`)
|
|
1098
|
+
};
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
// packages/execution/src/cell-task.ts
|
|
1102
|
+
function yieldSignal() {
|
|
1103
|
+
let resolve;
|
|
1104
|
+
const promise = new Promise((yes) => {
|
|
1105
|
+
resolve = yes;
|
|
1106
|
+
});
|
|
1107
|
+
return { promise, resolve };
|
|
1108
|
+
}
|
|
1109
|
+
function createCellTask(options, nestedTask) {
|
|
1110
|
+
let closed = false;
|
|
1111
|
+
let closing;
|
|
1112
|
+
const active = new Map;
|
|
1113
|
+
const yields = new Map;
|
|
1114
|
+
const yieldState = (id) => {
|
|
1115
|
+
let state = yields.get(id);
|
|
1116
|
+
if (state === undefined) {
|
|
1117
|
+
state = { yielded: false, wake: yieldSignal() };
|
|
1118
|
+
yields.set(id, state);
|
|
1119
|
+
}
|
|
1120
|
+
return state;
|
|
1121
|
+
};
|
|
1122
|
+
const excluded = new Set(options.surfaceTools.filter((name) => !options.callableSurfaceTools?.includes(name)));
|
|
1123
|
+
const task = defineTask({
|
|
1124
|
+
name: `howaboua.execution.cell.${options.name}`,
|
|
1125
|
+
version: 1,
|
|
1126
|
+
initial: () => ({ phase: "start" }),
|
|
1127
|
+
phases: {
|
|
1128
|
+
start: async (record, runtime, context) => {
|
|
1129
|
+
await runtime.commit(async (tx) => {
|
|
1130
|
+
await tx.doc(InvocationDoc, runtime.taskId);
|
|
1131
|
+
return { status: "running", checkpoint: { phase: "execute" } };
|
|
1132
|
+
}, context);
|
|
1133
|
+
const controller = new AbortController;
|
|
1134
|
+
const running = { controller, done: yieldSignal() };
|
|
1135
|
+
const yielding = yieldState(runtime.taskId);
|
|
1136
|
+
active.set(runtime.taskId, running);
|
|
1137
|
+
const signal = AbortSignal.any([runtime.signal, controller.signal]);
|
|
1138
|
+
const cellContext = withAbortSignal(signal, context);
|
|
1139
|
+
let invocation;
|
|
1140
|
+
let ending = "completed";
|
|
1141
|
+
let result;
|
|
1142
|
+
const controls = [];
|
|
1143
|
+
try {
|
|
1144
|
+
if (closed)
|
|
1145
|
+
throw new Error("Execution host is closed");
|
|
1146
|
+
invocation = createInvocation(runtime, {}, cellContext);
|
|
1147
|
+
const registrations = (await runtime.agent(cellContext)).callable.filter((tool) => !excluded.has(tool.name) && !readToolContract(tool).nativeOnly);
|
|
1148
|
+
const toolApi = await invocation.executionApi();
|
|
1149
|
+
const tools = cellTools(runtime, toolApi, registrations, nestedTask, controls, options.cancelTask, cellContext);
|
|
1150
|
+
const api = {
|
|
1151
|
+
taskId: runtime.taskId,
|
|
1152
|
+
conversationId: runtime.conversationId,
|
|
1153
|
+
signal,
|
|
1154
|
+
toolApi,
|
|
1155
|
+
registrations,
|
|
1156
|
+
tools,
|
|
1157
|
+
publish: async (value, publishContext) => {
|
|
1158
|
+
const result = storeResult(value);
|
|
1159
|
+
await runtime.commit(async (tx) => {
|
|
1160
|
+
(await tx.doc(InvocationDoc, runtime.taskId)).result = result;
|
|
1161
|
+
return;
|
|
1162
|
+
}, publishContext);
|
|
1163
|
+
},
|
|
1164
|
+
requestYield: async (yieldContext) => {
|
|
1165
|
+
await runtime.commit(async (tx) => {
|
|
1166
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1167
|
+
doc.yieldCount = (doc.yieldCount ?? 0) + 1;
|
|
1168
|
+
return;
|
|
1169
|
+
}, yieldContext);
|
|
1170
|
+
yielding.yielded = true;
|
|
1171
|
+
yielding.wake.resolve();
|
|
1172
|
+
yielding.wake = yieldSignal();
|
|
1173
|
+
},
|
|
1174
|
+
checkpoint: async (value, checkpointContext) => {
|
|
1175
|
+
const checkpoint = copyJson8(value);
|
|
1176
|
+
await runtime.commit(async (tx) => {
|
|
1177
|
+
(await tx.doc(InvocationDoc, runtime.taskId)).checkpoint = checkpoint;
|
|
1178
|
+
return;
|
|
1179
|
+
}, checkpointContext);
|
|
1180
|
+
}
|
|
1181
|
+
};
|
|
1182
|
+
result = await options.engine.run(record.input, api, cellContext);
|
|
1183
|
+
signal.throwIfAborted();
|
|
1184
|
+
} catch (error) {
|
|
1185
|
+
if (runtime.signal.aborted) {
|
|
1186
|
+
await invocation?.stop(error);
|
|
1187
|
+
throw error;
|
|
1188
|
+
}
|
|
1189
|
+
const partial = await runtime.snapshot(InvocationDoc, runtime.taskId, context);
|
|
1190
|
+
result = {
|
|
1191
|
+
...partial?.result ?? {},
|
|
1192
|
+
isError: true,
|
|
1193
|
+
diagnostics: [
|
|
1194
|
+
...partial?.result.diagnostics ?? [],
|
|
1195
|
+
{
|
|
1196
|
+
severity: "error",
|
|
1197
|
+
code: "cell_error",
|
|
1198
|
+
message: errorText(error)
|
|
1199
|
+
}
|
|
1200
|
+
]
|
|
1201
|
+
};
|
|
1202
|
+
ending = "failed";
|
|
1203
|
+
} finally {
|
|
1204
|
+
if (runtime.signal.aborted) {
|
|
1205
|
+
active.delete(runtime.taskId);
|
|
1206
|
+
yields.delete(runtime.taskId);
|
|
1207
|
+
running.done.resolve();
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
let finished;
|
|
1211
|
+
try {
|
|
1212
|
+
finished = await invocation?.finish(result);
|
|
1213
|
+
const finalResult = finished?.result ?? result;
|
|
1214
|
+
const control = combineControls([...controls, finalResult.control], ending === "completed" && !finalResult.isError);
|
|
1215
|
+
const { control: _driverControl, ...withoutControl } = finalResult;
|
|
1216
|
+
const final = control === undefined ? withoutControl : { ...withoutControl, control };
|
|
1217
|
+
await runtime.commit(async (tx) => {
|
|
1218
|
+
(await tx.doc(InvocationDoc, runtime.taskId)).result = storeResult(final);
|
|
1219
|
+
Object.assign(await tx.doc(CellStateDoc, runtime.conversationId, String(runtime.taskId), null), await tx.doc(InvocationDoc, runtime.taskId));
|
|
1220
|
+
return {
|
|
1221
|
+
status: "terminal",
|
|
1222
|
+
outcome: ending === "completed" ? { status: "completed", result: final } : {
|
|
1223
|
+
status: "failed",
|
|
1224
|
+
error: { message: "Cell execution failed" },
|
|
1225
|
+
result: final
|
|
1226
|
+
}
|
|
1227
|
+
};
|
|
1228
|
+
}, context);
|
|
1229
|
+
for (const waiter of finished?.pending ?? [])
|
|
1230
|
+
waiter.resolve();
|
|
1231
|
+
} catch (error) {
|
|
1232
|
+
for (const waiter of finished?.pending ?? [])
|
|
1233
|
+
waiter.reject(error);
|
|
1234
|
+
throw error;
|
|
1235
|
+
} finally {
|
|
1236
|
+
active.delete(runtime.taskId);
|
|
1237
|
+
yields.delete(runtime.taskId);
|
|
1238
|
+
running.done.resolve();
|
|
1239
|
+
}
|
|
1240
|
+
},
|
|
1241
|
+
execute: async (_record, runtime, context) => {
|
|
1242
|
+
await cleanupNativeCalls(runtime, context);
|
|
1243
|
+
await runtime.commit(async (tx) => {
|
|
1244
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1245
|
+
const error = executionError("interrupted", "Cell was interrupted and may have partially run. Code was not replayed");
|
|
1246
|
+
const result = {
|
|
1247
|
+
...doc.result,
|
|
1248
|
+
isError: true,
|
|
1249
|
+
diagnostics: [
|
|
1250
|
+
...doc.result.diagnostics ?? [],
|
|
1251
|
+
...error.diagnostics ?? []
|
|
1252
|
+
]
|
|
1253
|
+
};
|
|
1254
|
+
doc.result = storeResult(result);
|
|
1255
|
+
Object.assign(await tx.doc(CellStateDoc, runtime.conversationId, String(runtime.taskId), null), doc);
|
|
1256
|
+
return {
|
|
1257
|
+
status: "terminal",
|
|
1258
|
+
outcome: {
|
|
1259
|
+
status: "failed",
|
|
1260
|
+
error: { message: "Cell was interrupted" },
|
|
1261
|
+
result
|
|
1262
|
+
}
|
|
1263
|
+
};
|
|
1264
|
+
}, context);
|
|
1265
|
+
}
|
|
1266
|
+
},
|
|
1267
|
+
abort: async (_record, runtime, context) => {
|
|
1268
|
+
await cleanupNativeCalls(runtime, context);
|
|
1269
|
+
await runtime.commit(async (tx) => {
|
|
1270
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1271
|
+
const error = executionError("aborted", "Cell was aborted");
|
|
1272
|
+
const result = {
|
|
1273
|
+
...doc.result,
|
|
1274
|
+
isError: true,
|
|
1275
|
+
diagnostics: [
|
|
1276
|
+
...doc.result.diagnostics ?? [],
|
|
1277
|
+
...error.diagnostics ?? []
|
|
1278
|
+
]
|
|
1279
|
+
};
|
|
1280
|
+
doc.result = storeResult(result);
|
|
1281
|
+
Object.assign(await tx.doc(CellStateDoc, runtime.conversationId, String(runtime.taskId), null), doc);
|
|
1282
|
+
return { status: "terminal", outcome: { status: "aborted", result } };
|
|
1283
|
+
}, context);
|
|
1284
|
+
}
|
|
1285
|
+
});
|
|
1286
|
+
return {
|
|
1287
|
+
task,
|
|
1288
|
+
get closed() {
|
|
1289
|
+
return closed;
|
|
1290
|
+
},
|
|
1291
|
+
observeYield(id) {
|
|
1292
|
+
const yielding = yieldState(id);
|
|
1293
|
+
return {
|
|
1294
|
+
wake: yielding.wake.promise,
|
|
1295
|
+
consume() {
|
|
1296
|
+
const yielded = yielding.yielded;
|
|
1297
|
+
yielding.yielded = false;
|
|
1298
|
+
return yielded;
|
|
1299
|
+
}
|
|
1300
|
+
};
|
|
1301
|
+
},
|
|
1302
|
+
close() {
|
|
1303
|
+
if (closing !== undefined)
|
|
1304
|
+
return closing;
|
|
1305
|
+
closed = true;
|
|
1306
|
+
const invocations = [...active.values()];
|
|
1307
|
+
for (const running of invocations)
|
|
1308
|
+
running.controller.abort(new Error("Execution host closed"));
|
|
1309
|
+
closing = Promise.all([
|
|
1310
|
+
options.engine.close(),
|
|
1311
|
+
...invocations.map((running) => running.done.promise)
|
|
1312
|
+
]).then(() => {
|
|
1313
|
+
return;
|
|
1314
|
+
});
|
|
1315
|
+
return closing;
|
|
1316
|
+
}
|
|
1317
|
+
};
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// packages/execution/src/forwarding-hook.ts
|
|
1321
|
+
import {
|
|
1322
|
+
hook,
|
|
1323
|
+
LiveDoc as LiveDoc4,
|
|
1324
|
+
ToolTask as ToolTask3
|
|
1325
|
+
} from "@earendil-works/pi-durable";
|
|
1326
|
+
function forwardingHook() {
|
|
1327
|
+
let host;
|
|
1328
|
+
return {
|
|
1329
|
+
bind(harness) {
|
|
1330
|
+
if (host !== undefined && host !== harness)
|
|
1331
|
+
throw new Error("Create a separate execution component for each Harness");
|
|
1332
|
+
host = harness;
|
|
1333
|
+
},
|
|
1334
|
+
hook: hook(ToolTask3, {
|
|
1335
|
+
async beforeTool(call, api, context) {
|
|
1336
|
+
const parent = call.parent;
|
|
1337
|
+
if (parent === undefined || host === undefined)
|
|
1338
|
+
return;
|
|
1339
|
+
const source = await api.snapshot(InvocationDoc, parent.taskId, context);
|
|
1340
|
+
const cellId = source?.forwardingCellId;
|
|
1341
|
+
if (cellId === undefined)
|
|
1342
|
+
return;
|
|
1343
|
+
const conversation = await host.conversation(api.conversationId, context);
|
|
1344
|
+
if (conversation === undefined)
|
|
1345
|
+
throw new Error("Forwarded call conversation is unavailable");
|
|
1346
|
+
await conversation.commit(async (tx) => {
|
|
1347
|
+
if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
|
|
1348
|
+
return;
|
|
1349
|
+
const owner = await tx.doc(InvocationDoc, api.taskId);
|
|
1350
|
+
const admission = owner.forwardingCellId === undefined;
|
|
1351
|
+
owner.forwardingCellId = cellId;
|
|
1352
|
+
await forwardCall(tx, cellId, {
|
|
1353
|
+
callId: call.id,
|
|
1354
|
+
parentCallId: parent.callId,
|
|
1355
|
+
name: call.name,
|
|
1356
|
+
arguments: call.arguments,
|
|
1357
|
+
status: "pending",
|
|
1358
|
+
result: null,
|
|
1359
|
+
omittedFields: []
|
|
1360
|
+
}, admission, { taskId: api.taskId, ownerTaskId: parent.taskId });
|
|
1361
|
+
}, context);
|
|
1362
|
+
},
|
|
1363
|
+
async afterTool(call, result, api, context) {
|
|
1364
|
+
const parent = call.parent;
|
|
1365
|
+
if (parent === undefined || host === undefined)
|
|
1366
|
+
return;
|
|
1367
|
+
const source = await api.snapshot(InvocationDoc, api.taskId, context);
|
|
1368
|
+
if (source?.forwardingCellId === undefined)
|
|
1369
|
+
return;
|
|
1370
|
+
const conversation = await host.conversation(api.conversationId, context);
|
|
1371
|
+
if (conversation === undefined)
|
|
1372
|
+
throw new Error("Forwarded call conversation is unavailable");
|
|
1373
|
+
await conversation.commit(async (tx) => {
|
|
1374
|
+
if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
|
|
1375
|
+
return;
|
|
1376
|
+
const owner = await tx.doc(InvocationDoc, api.taskId);
|
|
1377
|
+
const cellId = owner.forwardingCellId;
|
|
1378
|
+
if (cellId === undefined)
|
|
1379
|
+
return;
|
|
1380
|
+
await captureNativeCalls(tx, api.conversationId, api.taskId, cellId);
|
|
1381
|
+
const slot = (await tx.doc(LiveDoc4, api.conversationId)).nestedTools?.find((slot) => slot.callId === call.id);
|
|
1382
|
+
const cell = await tx.doc(InvocationDoc, cellId);
|
|
1383
|
+
await forwardCall(tx, cellId, {
|
|
1384
|
+
callId: call.id,
|
|
1385
|
+
parentCallId: parent.callId,
|
|
1386
|
+
name: call.name,
|
|
1387
|
+
arguments: slot?.arguments ?? call.arguments,
|
|
1388
|
+
status: "completed",
|
|
1389
|
+
result: displayResult(result, cell.forwardingBudget ?? 40000),
|
|
1390
|
+
omittedFields: []
|
|
1391
|
+
});
|
|
1392
|
+
}, context);
|
|
1393
|
+
}
|
|
1394
|
+
})
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
// packages/execution/src/nested.ts
|
|
1399
|
+
import {
|
|
1400
|
+
defineTask as defineTask2
|
|
1401
|
+
} from "@earendil-works/pi-durable";
|
|
1402
|
+
import { Compile as Compile2 } from "typebox/compile";
|
|
1403
|
+
|
|
1404
|
+
// packages/execution/src/nested-call.ts
|
|
1405
|
+
import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
|
|
1406
|
+
import {
|
|
1407
|
+
ToolTask as ToolTask4
|
|
1408
|
+
} from "@earendil-works/pi-durable";
|
|
1409
|
+
import { Compile } from "typebox/compile";
|
|
1410
|
+
function nestedCall(runtime, input) {
|
|
1411
|
+
const args = input.arguments;
|
|
1412
|
+
return {
|
|
1413
|
+
type: "toolCall",
|
|
1414
|
+
id: `nested-${runtime.taskId}`,
|
|
1415
|
+
name: input.name,
|
|
1416
|
+
...input.parent === undefined ? {} : { parent: input.parent },
|
|
1417
|
+
arguments: args !== null && typeof args === "object" && !Array.isArray(args) ? args : {}
|
|
1418
|
+
};
|
|
1419
|
+
}
|
|
1420
|
+
function checked(tool, call, args) {
|
|
1421
|
+
return validateToolArguments(tool, {
|
|
1422
|
+
...call,
|
|
1423
|
+
arguments: args
|
|
1424
|
+
});
|
|
1425
|
+
}
|
|
1426
|
+
function prepareNestedInput(tool, input) {
|
|
1427
|
+
if (typeof input !== "string")
|
|
1428
|
+
return input;
|
|
1429
|
+
const contract = readToolContract(tool);
|
|
1430
|
+
if (Boolean(Compile(tool.parameters).Check(input)) || Boolean(Compile(contract.inputSchema).Check(input)))
|
|
1431
|
+
return input;
|
|
1432
|
+
const text = input.trim();
|
|
1433
|
+
if (contract.discovery === "help" && text === "help")
|
|
1434
|
+
return {};
|
|
1435
|
+
let parsed;
|
|
1436
|
+
try {
|
|
1437
|
+
parsed = JSON.parse(text);
|
|
1438
|
+
} catch {
|
|
1439
|
+
if (tool.prepareArguments !== undefined)
|
|
1440
|
+
return input;
|
|
1441
|
+
throw new Error(`Invalid ${tool.name} arguments; use a structured request or valid JSON`);
|
|
1442
|
+
}
|
|
1443
|
+
if (parsed === null || typeof parsed !== "object") {
|
|
1444
|
+
if (tool.prepareArguments !== undefined)
|
|
1445
|
+
return input;
|
|
1446
|
+
throw new Error(`Invalid ${tool.name} arguments; use a structured request or JSON object or array`);
|
|
1447
|
+
}
|
|
1448
|
+
return parsed;
|
|
1449
|
+
}
|
|
1450
|
+
async function eachHook(agent, name, api, invoke) {
|
|
1451
|
+
for (const extension of agent.extensions)
|
|
1452
|
+
for (const registration of extension.hooks ?? []) {
|
|
1453
|
+
if (registration.task !== ToolTask4.definition.name)
|
|
1454
|
+
continue;
|
|
1455
|
+
const handler = registration.handlers[name];
|
|
1456
|
+
if (handler === undefined)
|
|
1457
|
+
continue;
|
|
1458
|
+
try {
|
|
1459
|
+
await invoke(handler);
|
|
1460
|
+
} catch (error) {
|
|
1461
|
+
if (api.signal.aborted)
|
|
1462
|
+
throw error;
|
|
1463
|
+
api.report(error);
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
// packages/execution/src/nested-result.ts
|
|
1469
|
+
import { copyJson as copyJson9 } from "@earendil-works/chord";
|
|
1470
|
+
import {
|
|
1471
|
+
defineEntry,
|
|
1472
|
+
UsageDoc
|
|
1473
|
+
} from "@earendil-works/pi-durable";
|
|
1474
|
+
var NestedResultEntry = defineEntry("howaboua.execution.nested-result");
|
|
1475
|
+
async function interrupted(runtime, call, code, message, context) {
|
|
1476
|
+
await cleanupNativeCalls(runtime, context);
|
|
1477
|
+
const state = await runtime.snapshot(InvocationDoc, runtime.taskId, context);
|
|
1478
|
+
const partial = state?.result ?? {};
|
|
1479
|
+
const diagnostics = [...partial.diagnostics ?? []];
|
|
1480
|
+
if ((state?.droppedBytes ?? 0) > 0)
|
|
1481
|
+
diagnostics.push(truncation({
|
|
1482
|
+
droppedBytes: state?.droppedBytes ?? 0,
|
|
1483
|
+
droppedLines: state?.droppedLines ?? 0
|
|
1484
|
+
}));
|
|
1485
|
+
await settle(runtime, call, {
|
|
1486
|
+
...partial,
|
|
1487
|
+
isError: true,
|
|
1488
|
+
diagnostics: [
|
|
1489
|
+
...diagnostics,
|
|
1490
|
+
...executionError(code, message).diagnostics ?? []
|
|
1491
|
+
]
|
|
1492
|
+
}, code === "aborted" ? "aborted" : "failed", context);
|
|
1493
|
+
}
|
|
1494
|
+
async function settle(runtime, call, result, ending, context) {
|
|
1495
|
+
const stored = storeResult(result);
|
|
1496
|
+
await runtime.commit(async (tx, current) => {
|
|
1497
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1498
|
+
if (doc.forwardingCellId === undefined && current.input.cellId !== undefined) {
|
|
1499
|
+
doc.forwardingCellId = current.input.cellId;
|
|
1500
|
+
await forwardCall(tx, current.input.cellId, {
|
|
1501
|
+
callId: call.id,
|
|
1502
|
+
parentCallId: current.input.parent?.callId ?? `nested-${current.input.cellId}`,
|
|
1503
|
+
name: call.name,
|
|
1504
|
+
arguments: current.input.arguments,
|
|
1505
|
+
status: "pending",
|
|
1506
|
+
result: null,
|
|
1507
|
+
omittedFields: []
|
|
1508
|
+
}, true);
|
|
1509
|
+
}
|
|
1510
|
+
doc.result = stored;
|
|
1511
|
+
await forwardInvocationResult(tx, runtime.taskId, result, ending);
|
|
1512
|
+
await tx.appendEntry(NestedResultEntry, runtime.conversationId, {
|
|
1513
|
+
data: {
|
|
1514
|
+
taskId: runtime.taskId,
|
|
1515
|
+
callId: call.id,
|
|
1516
|
+
name: call.name,
|
|
1517
|
+
arguments: copyJson9(call.arguments),
|
|
1518
|
+
result: stored,
|
|
1519
|
+
...current.state.checkpoint.phase === "execute" ? {
|
|
1520
|
+
intent: {
|
|
1521
|
+
arguments: copyJson9(current.state.checkpoint.arguments),
|
|
1522
|
+
replay: current.state.checkpoint.replay
|
|
1523
|
+
}
|
|
1524
|
+
} : {}
|
|
1525
|
+
}
|
|
1526
|
+
});
|
|
1527
|
+
if (result.usage !== undefined) {
|
|
1528
|
+
const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
|
|
1529
|
+
const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
|
|
1530
|
+
totals[call.name] = copyJson9(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
|
|
1531
|
+
}
|
|
1532
|
+
const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
|
|
1533
|
+
status: ending,
|
|
1534
|
+
error: {
|
|
1535
|
+
message: `Tool ${call.name} ${result.diagnostics?.at(-1)?.code === "interrupted" ? "was interrupted" : "threw"}`
|
|
1536
|
+
},
|
|
1537
|
+
result: stored
|
|
1538
|
+
};
|
|
1539
|
+
return { status: "terminal", outcome };
|
|
1540
|
+
}, context);
|
|
1541
|
+
}
|
|
1542
|
+
function sumUsage(previous, added) {
|
|
1543
|
+
return {
|
|
1544
|
+
input: previous.input + added.input,
|
|
1545
|
+
output: previous.output + added.output,
|
|
1546
|
+
cacheRead: previous.cacheRead + added.cacheRead,
|
|
1547
|
+
cacheWrite: previous.cacheWrite + added.cacheWrite,
|
|
1548
|
+
totalTokens: previous.totalTokens + added.totalTokens,
|
|
1549
|
+
...previous.cacheWrite1h === undefined && added.cacheWrite1h === undefined ? {} : {
|
|
1550
|
+
cacheWrite1h: (previous.cacheWrite1h ?? 0) + (added.cacheWrite1h ?? 0)
|
|
1551
|
+
},
|
|
1552
|
+
...previous.reasoning === undefined && added.reasoning === undefined ? {} : { reasoning: (previous.reasoning ?? 0) + (added.reasoning ?? 0) },
|
|
1553
|
+
cost: {
|
|
1554
|
+
input: previous.cost.input + added.cost.input,
|
|
1555
|
+
output: previous.cost.output + added.cost.output,
|
|
1556
|
+
cacheRead: previous.cost.cacheRead + added.cost.cacheRead,
|
|
1557
|
+
cacheWrite: previous.cost.cacheWrite + added.cost.cacheWrite,
|
|
1558
|
+
total: previous.cost.total + added.cost.total
|
|
1559
|
+
}
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
// packages/execution/src/nested.ts
|
|
1564
|
+
function createNestedToolTask(name) {
|
|
1565
|
+
return defineTask2({
|
|
1566
|
+
name,
|
|
1567
|
+
version: 1,
|
|
1568
|
+
initial: () => ({ phase: "call" }),
|
|
1569
|
+
phases: {
|
|
1570
|
+
call: async (task, runtime, context) => {
|
|
1571
|
+
const call = nestedCall(runtime, task.input);
|
|
1572
|
+
await runtime.commit(async (tx) => {
|
|
1573
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1574
|
+
if (task.input.cellId !== undefined)
|
|
1575
|
+
doc.forwardingCellId = task.input.cellId;
|
|
1576
|
+
await forwardCall(tx, task.input.cellId, {
|
|
1577
|
+
callId: call.id,
|
|
1578
|
+
parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
|
|
1579
|
+
name: call.name,
|
|
1580
|
+
arguments: task.input.arguments,
|
|
1581
|
+
status: "pending",
|
|
1582
|
+
result: null,
|
|
1583
|
+
omittedFields: []
|
|
1584
|
+
}, true);
|
|
1585
|
+
return;
|
|
1586
|
+
}, context);
|
|
1587
|
+
const agent = await runtime.agent(context);
|
|
1588
|
+
const tool = agent.callable.find((each) => each.name === call.name);
|
|
1589
|
+
if (tool === undefined || readToolContract(tool).nativeOnly)
|
|
1590
|
+
return reject(runtime, call, executionError("tool_unavailable", `Tool ${call.name} is not available`), agent, tool, context);
|
|
1591
|
+
let args;
|
|
1592
|
+
try {
|
|
1593
|
+
const supplied = task.input.arguments === null && !Compile2(tool.parameters).Check(null) && Compile2(tool.parameters).Check({}) ? undefined : task.input.arguments;
|
|
1594
|
+
const prepared = tool.prepareArguments === undefined ? prepareNestedInput(tool, supplied) : tool.prepareArguments(prepareNestedInput(tool, supplied));
|
|
1595
|
+
args = checked(tool, call, prepared === undefined && Compile2(tool.parameters).Check({}) ? {} : prepared);
|
|
1596
|
+
if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
|
|
1597
|
+
call.arguments = args;
|
|
1598
|
+
} catch (error) {
|
|
1599
|
+
return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
|
|
1600
|
+
}
|
|
1601
|
+
let block;
|
|
1602
|
+
await eachHook(agent, "beforeTool", runtime, async (handler) => {
|
|
1603
|
+
if (block !== undefined)
|
|
1604
|
+
return;
|
|
1605
|
+
try {
|
|
1606
|
+
const decision = await handler({ ...call, arguments: args }, runtime, context);
|
|
1607
|
+
if (decision?.block !== undefined)
|
|
1608
|
+
block = decision.block;
|
|
1609
|
+
else if (decision?.arguments !== undefined)
|
|
1610
|
+
args = decision.arguments;
|
|
1611
|
+
} catch (error) {
|
|
1612
|
+
if (runtime.signal.aborted)
|
|
1613
|
+
throw error;
|
|
1614
|
+
block = errorText(error);
|
|
1615
|
+
}
|
|
1616
|
+
});
|
|
1617
|
+
if (block !== undefined)
|
|
1618
|
+
return reject(runtime, call, executionError("blocked", `Tool call blocked: ${block}`), agent, tool, context);
|
|
1619
|
+
try {
|
|
1620
|
+
args = checked(tool, call, args);
|
|
1621
|
+
} catch (error) {
|
|
1622
|
+
return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
|
|
1623
|
+
}
|
|
1624
|
+
await runtime.commit(async (tx) => {
|
|
1625
|
+
await tx.doc(InvocationDoc, runtime.taskId);
|
|
1626
|
+
await forwardCall(tx, task.input.cellId, {
|
|
1627
|
+
callId: call.id,
|
|
1628
|
+
parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
|
|
1629
|
+
name: call.name,
|
|
1630
|
+
arguments: args,
|
|
1631
|
+
status: "running",
|
|
1632
|
+
result: null,
|
|
1633
|
+
omittedFields: []
|
|
1634
|
+
});
|
|
1635
|
+
return {
|
|
1636
|
+
status: "running",
|
|
1637
|
+
checkpoint: {
|
|
1638
|
+
phase: "execute",
|
|
1639
|
+
arguments: args,
|
|
1640
|
+
replay: tool.replay ?? "unsafe"
|
|
1641
|
+
}
|
|
1642
|
+
};
|
|
1643
|
+
}, context);
|
|
1644
|
+
await run(runtime, call, tool, args, agent, context);
|
|
1645
|
+
},
|
|
1646
|
+
execute: async (task, runtime, context) => {
|
|
1647
|
+
const call = nestedCall(runtime, task.input);
|
|
1648
|
+
if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
|
|
1649
|
+
call.arguments = task.state.checkpoint.arguments;
|
|
1650
|
+
const agent = await runtime.agent(context);
|
|
1651
|
+
const tool = agent.callable.find((each) => each.name === call.name);
|
|
1652
|
+
if (task.state.checkpoint.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
|
|
1653
|
+
await runtime.commit(async (tx) => {
|
|
1654
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1655
|
+
doc.result = {};
|
|
1656
|
+
doc.droppedBytes = 0;
|
|
1657
|
+
doc.droppedLines = 0;
|
|
1658
|
+
return;
|
|
1659
|
+
}, context);
|
|
1660
|
+
return run(runtime, call, tool, task.state.checkpoint.arguments, agent, context);
|
|
1661
|
+
}
|
|
1662
|
+
await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
|
|
1663
|
+
}
|
|
1664
|
+
},
|
|
1665
|
+
abort: async (task, runtime, context) => {
|
|
1666
|
+
const call = nestedCall(runtime, task.input);
|
|
1667
|
+
await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
|
|
1668
|
+
}
|
|
1669
|
+
});
|
|
1670
|
+
}
|
|
1671
|
+
async function reject(runtime, call, result, agent, tool, context) {
|
|
1672
|
+
await eachHook(agent, "afterTool", runtime, async (handler) => {
|
|
1673
|
+
result = await handler(call, result, runtime, context) ?? result;
|
|
1674
|
+
});
|
|
1675
|
+
await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
|
|
1676
|
+
}
|
|
1677
|
+
async function run(runtime, call, tool, args, agent, context) {
|
|
1678
|
+
let invocation;
|
|
1679
|
+
let result;
|
|
1680
|
+
let ending = "completed";
|
|
1681
|
+
try {
|
|
1682
|
+
invocation = createInvocation(runtime, tool, context);
|
|
1683
|
+
result = await tool.execute(args, await invocation.executionApi(), context);
|
|
1684
|
+
} catch (error) {
|
|
1685
|
+
if (runtime.signal.aborted) {
|
|
1686
|
+
await invocation?.stop(error);
|
|
1687
|
+
throw error;
|
|
1688
|
+
}
|
|
1689
|
+
result = {
|
|
1690
|
+
isError: true,
|
|
1691
|
+
diagnostics: [
|
|
1692
|
+
{ severity: "error", code: "tool_error", message: errorText(error) }
|
|
1693
|
+
]
|
|
1694
|
+
};
|
|
1695
|
+
ending = "failed";
|
|
1696
|
+
}
|
|
1697
|
+
const finished = await invocation?.finish(result);
|
|
1698
|
+
let final = finished?.result ?? result;
|
|
1699
|
+
await eachHook(agent, "afterTool", runtime, async (handler) => {
|
|
1700
|
+
final = await handler(call, final, runtime, context) ?? final;
|
|
1701
|
+
});
|
|
1702
|
+
if (finished !== undefined && result.output === undefined && finished.retained.droppedBytes > 0 && final.output === finished.content) {
|
|
1703
|
+
final = {
|
|
1704
|
+
...final,
|
|
1705
|
+
diagnostics: [
|
|
1706
|
+
...final.diagnostics ?? [],
|
|
1707
|
+
truncation(finished.retained, invocation?.limits.retain)
|
|
1708
|
+
]
|
|
1709
|
+
};
|
|
1710
|
+
}
|
|
1711
|
+
final = finishResult(tool, call.name, final);
|
|
1712
|
+
try {
|
|
1713
|
+
await settle(runtime, call, final, ending, context);
|
|
1714
|
+
for (const waiter of finished?.pending ?? [])
|
|
1715
|
+
waiter.resolve();
|
|
1716
|
+
} catch (error) {
|
|
1717
|
+
for (const waiter of finished?.pending ?? [])
|
|
1718
|
+
waiter.reject(error);
|
|
1719
|
+
throw error;
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
function finishResult(tool, name, result) {
|
|
1723
|
+
let final = boundResult(result, {
|
|
1724
|
+
maxBytes: tool?.outputLimits?.maxBytes ?? 50 * 1024,
|
|
1725
|
+
maxLines: tool?.outputLimits?.maxLines ?? 2000,
|
|
1726
|
+
retain: tool?.outputLimits?.retain ?? "head"
|
|
1727
|
+
});
|
|
1728
|
+
try {
|
|
1729
|
+
if (tool?.structuredOutputSchema === undefined) {
|
|
1730
|
+
if (final.structuredOutput !== undefined)
|
|
1731
|
+
throw new Error(`Tool ${name} returned structuredOutput but declares no structuredOutputSchema`);
|
|
1732
|
+
} else if (final.structuredOutput === undefined) {
|
|
1733
|
+
if (!final.isError)
|
|
1734
|
+
throw new Error(`Tool ${name} returned no structuredOutput`);
|
|
1735
|
+
} else if (!Compile2(tool.structuredOutputSchema).Check(final.structuredOutput)) {
|
|
1736
|
+
throw new Error(`Tool ${name} returned structuredOutput that does not match its schema`);
|
|
1737
|
+
}
|
|
1738
|
+
} catch (error) {
|
|
1739
|
+
const { structuredOutput: _invalid, ...rest } = final;
|
|
1740
|
+
final = {
|
|
1741
|
+
...rest,
|
|
1742
|
+
isError: true,
|
|
1743
|
+
diagnostics: [
|
|
1744
|
+
...rest.diagnostics ?? [],
|
|
1745
|
+
{
|
|
1746
|
+
severity: "error",
|
|
1747
|
+
code: "invalid_structured_output",
|
|
1748
|
+
message: errorText(error)
|
|
1749
|
+
}
|
|
1750
|
+
]
|
|
1751
|
+
};
|
|
1752
|
+
}
|
|
1753
|
+
return final;
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
// packages/execution/src/projection.ts
|
|
1757
|
+
import { GenerationTask, hook as hook2 } from "@earendil-works/pi-durable";
|
|
1758
|
+
function projectToolSchemas(messages, visible) {
|
|
1759
|
+
return messages.map((message) => message.role !== "system" ? message : {
|
|
1760
|
+
...message,
|
|
1761
|
+
...message.toolsAdded === undefined ? {} : {
|
|
1762
|
+
toolsAdded: message.toolsAdded.filter((tool) => visible.has(tool.name))
|
|
1763
|
+
},
|
|
1764
|
+
...message.toolsRemoved === undefined ? {} : {
|
|
1765
|
+
toolsRemoved: message.toolsRemoved.filter((tool) => visible.has(tool.name))
|
|
1766
|
+
}
|
|
1767
|
+
});
|
|
1768
|
+
}
|
|
1769
|
+
function providerProjection(surfaceTools) {
|
|
1770
|
+
let host;
|
|
1771
|
+
return {
|
|
1772
|
+
bind(harness) {
|
|
1773
|
+
if (host !== undefined && host !== harness)
|
|
1774
|
+
throw new Error("Create a separate execution component for each Harness");
|
|
1775
|
+
host = harness;
|
|
1776
|
+
},
|
|
1777
|
+
hook: hook2(GenerationTask, {
|
|
1778
|
+
beforeRequest: async (request, api, context) => {
|
|
1779
|
+
const visible = new Set(surfaceTools);
|
|
1780
|
+
if (host !== undefined) {
|
|
1781
|
+
const conversation = await host.conversation(api.conversationId, context);
|
|
1782
|
+
if (conversation === undefined)
|
|
1783
|
+
throw new Error(`Conversation ${api.conversationId} is unavailable`);
|
|
1784
|
+
for (const tool of (await conversation.agent(context)).tools)
|
|
1785
|
+
if (readToolContract(tool).nativeOnly)
|
|
1786
|
+
visible.add(tool.name);
|
|
1787
|
+
}
|
|
1788
|
+
return { messages: projectToolSchemas(request.messages, visible) };
|
|
1789
|
+
}
|
|
1790
|
+
})
|
|
1791
|
+
};
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
// packages/execution/src/wait-session.ts
|
|
1795
|
+
import { withoutAbortSignal as withoutAbortSignal3 } from "@earendil-works/chord/context";
|
|
1796
|
+
|
|
1797
|
+
// packages/execution/src/tool-value.ts
|
|
1798
|
+
class NestedToolError extends Error {
|
|
1799
|
+
result;
|
|
1800
|
+
constructor(result, text) {
|
|
1801
|
+
super(result.diagnostics?.filter((item) => item.severity === "error").map((item) => item.message).join(`
|
|
1802
|
+
`) || text || "Tool failed");
|
|
1803
|
+
this.name = "NestedToolError";
|
|
1804
|
+
this.result = result;
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
function toolValue(result) {
|
|
1808
|
+
if (result.structuredOutput !== undefined)
|
|
1809
|
+
return result.structuredOutput;
|
|
1810
|
+
const texts = (result.output ?? []).filter((item) => item.type === "text").map((item) => item.text);
|
|
1811
|
+
if (result.isError)
|
|
1812
|
+
throw new NestedToolError(result, texts.join(`
|
|
1813
|
+
`));
|
|
1814
|
+
const images = (result.output ?? []).filter((item) => item.type === "image").map((item) => ({
|
|
1815
|
+
image_url: `data:${item.mimeType};base64,${item.data}`
|
|
1816
|
+
}));
|
|
1817
|
+
let value = result.details;
|
|
1818
|
+
const objectDetails = value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
|
|
1819
|
+
if (value === undefined || objectDetails !== undefined && Object.keys(objectDetails).length === 0) {
|
|
1820
|
+
const text = texts.join(`
|
|
1821
|
+
`);
|
|
1822
|
+
try {
|
|
1823
|
+
value = JSON.parse(text);
|
|
1824
|
+
} catch {
|
|
1825
|
+
value = text;
|
|
1826
|
+
}
|
|
1827
|
+
} else if (objectDetails !== undefined && (result.output?.length ?? 0) > 0) {
|
|
1828
|
+
value = {
|
|
1829
|
+
...objectDetails,
|
|
1830
|
+
[Object.hasOwn(objectDetails, "content") ? "toolResultContent" : "content"]: result.output
|
|
1831
|
+
};
|
|
1832
|
+
} else if ((result.output?.length ?? 0) > 0 && !(typeof value === "string" && images.length === 0 && texts.join(`
|
|
1833
|
+
`) === value)) {
|
|
1834
|
+
value = { value, content: result.output };
|
|
1835
|
+
}
|
|
1836
|
+
if (images.length)
|
|
1837
|
+
return {
|
|
1838
|
+
...value !== null && typeof value === "object" && !Array.isArray(value) ? value : { value },
|
|
1839
|
+
...images[0],
|
|
1840
|
+
...images.length > 1 ? { images } : {}
|
|
1841
|
+
};
|
|
1842
|
+
return value;
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
// packages/execution/src/wait-session.ts
|
|
1846
|
+
async function recoverWaitSession(cellId, yieldTimeMs, maxTokens, api, context, nestedTask, cancelTask) {
|
|
1847
|
+
if (!Number.isSafeInteger(cellId) || cellId < 0)
|
|
1848
|
+
return;
|
|
1849
|
+
const registration = (await api.agent(context)).callable.find((tool) => tool.name === "write_stdin" && !readToolContract(tool).nativeOnly);
|
|
1850
|
+
if (!registration)
|
|
1851
|
+
return;
|
|
1852
|
+
const id = await api.createTask(nestedTask, {
|
|
1853
|
+
name: registration.name,
|
|
1854
|
+
arguments: {
|
|
1855
|
+
session_id: cellId,
|
|
1856
|
+
yield_time_ms: yieldTimeMs,
|
|
1857
|
+
max_output_tokens: maxTokens
|
|
1858
|
+
},
|
|
1859
|
+
parent: { taskId: api.taskId, callId: api.callId }
|
|
1860
|
+
}, {
|
|
1861
|
+
ownership: { kind: "task", taskId: api.taskId },
|
|
1862
|
+
abandonOnRestart: false
|
|
1863
|
+
}, context);
|
|
1864
|
+
let cancelling;
|
|
1865
|
+
const abort = () => {
|
|
1866
|
+
cancelling ??= cancelTask(id, withoutAbortSignal3(context));
|
|
1867
|
+
cancelling.catch(() => {});
|
|
1868
|
+
};
|
|
1869
|
+
context.abortSignal?.addEventListener("abort", abort, { once: true });
|
|
1870
|
+
if (context.abortSignal?.aborted)
|
|
1871
|
+
abort();
|
|
1872
|
+
try {
|
|
1873
|
+
const settled = await api.waitForTask(id, context);
|
|
1874
|
+
const result = readStoredResult(settled.state.outcome.result ?? executionError(settled.state.outcome.status, "Shell continuation did not return a result"));
|
|
1875
|
+
let value;
|
|
1876
|
+
try {
|
|
1877
|
+
value = toolValue(result);
|
|
1878
|
+
} catch (error) {
|
|
1879
|
+
if (error instanceof Error && /unknown(?: or expired)? process id/i.test(error.message))
|
|
1880
|
+
return;
|
|
1881
|
+
throw error;
|
|
1882
|
+
}
|
|
1883
|
+
if (!value || typeof value !== "object" || !("output" in value))
|
|
1884
|
+
return;
|
|
1885
|
+
const output = typeof value.output === "string" ? value.output : "";
|
|
1886
|
+
const running = "session_id" in value && typeof value.session_id === "number";
|
|
1887
|
+
const exitCode = "exit_code" in value && typeof value.exit_code === "number" ? value.exit_code : undefined;
|
|
1888
|
+
return {
|
|
1889
|
+
cellId,
|
|
1890
|
+
status: "completed",
|
|
1891
|
+
recoveredSession: true,
|
|
1892
|
+
result: {
|
|
1893
|
+
...result,
|
|
1894
|
+
output: [
|
|
1895
|
+
{
|
|
1896
|
+
type: "text",
|
|
1897
|
+
text: `Recovered wait cell_id ${cellId} as exec_command session_id ${cellId} and continued it with write_stdin`
|
|
1898
|
+
},
|
|
1899
|
+
...output ? [{ type: "text", text: output }] : [],
|
|
1900
|
+
...exitCode === undefined ? [] : [
|
|
1901
|
+
{
|
|
1902
|
+
type: "text",
|
|
1903
|
+
text: `Process exited with code ${exitCode}`
|
|
1904
|
+
}
|
|
1905
|
+
],
|
|
1906
|
+
...running ? [
|
|
1907
|
+
{
|
|
1908
|
+
type: "text",
|
|
1909
|
+
text: `Session ${cellId} still running. Resume with write_stdin; set yield_time_ms near expected completion and lengthen later waits`
|
|
1910
|
+
}
|
|
1911
|
+
] : []
|
|
1912
|
+
]
|
|
1913
|
+
}
|
|
1914
|
+
};
|
|
1915
|
+
} finally {
|
|
1916
|
+
context.abortSignal?.removeEventListener("abort", abort);
|
|
1917
|
+
if (cancelling)
|
|
1918
|
+
await cancelling;
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
// packages/execution/src/cells.ts
|
|
1923
|
+
function assertSingleExecutionMode(agent) {
|
|
1924
|
+
const modes = agent.extensions.filter((extension) => extension.tasks?.some((task) => task.definition.name.startsWith("howaboua.execution.cell.")));
|
|
1925
|
+
if (modes.length > 1)
|
|
1926
|
+
throw new Error(`Select exactly one execution mode with conversation.configure({ extensions: [...] }). Selected: ${modes.map((mode) => mode.name).join(", ")}`);
|
|
1927
|
+
}
|
|
1928
|
+
function createCellCoordinator(options) {
|
|
1929
|
+
const nestedTask = createNestedToolTask(`howaboua.execution.nested-tool.${options.name}`);
|
|
1930
|
+
const driver = createCellTask(options, nestedTask);
|
|
1931
|
+
const task = driver.task;
|
|
1932
|
+
const projection = providerProjection(options.surfaceTools);
|
|
1933
|
+
const forwarding = forwardingHook();
|
|
1934
|
+
const extension = defineExtension({
|
|
1935
|
+
name: options.name,
|
|
1936
|
+
tasks: [task, nestedTask],
|
|
1937
|
+
hooks: [projection.hook, forwarding.hook]
|
|
1938
|
+
});
|
|
1939
|
+
return {
|
|
1940
|
+
extension,
|
|
1941
|
+
nestedTask,
|
|
1942
|
+
bind(harness) {
|
|
1943
|
+
projection.bind(harness);
|
|
1944
|
+
forwarding.bind(harness);
|
|
1945
|
+
},
|
|
1946
|
+
async start(input, api, context) {
|
|
1947
|
+
if (driver.closed)
|
|
1948
|
+
throw new Error("Execution host is closed");
|
|
1949
|
+
assertSingleExecutionMode(await api.agent(context));
|
|
1950
|
+
const copied = copyJson10(input);
|
|
1951
|
+
return api.commit(async (tx) => {
|
|
1952
|
+
const isolatedLimit = options.isolatedConcurrency ?? 0;
|
|
1953
|
+
const isolated = isolatedLimit > 0 && input["isolated"] === true;
|
|
1954
|
+
let isolatedCount = 0;
|
|
1955
|
+
let normalCount = 0;
|
|
1956
|
+
let activeCount = 0;
|
|
1957
|
+
for (const status of [
|
|
1958
|
+
"pending",
|
|
1959
|
+
"running",
|
|
1960
|
+
"waiting",
|
|
1961
|
+
"sleeping",
|
|
1962
|
+
"completing"
|
|
1963
|
+
]) {
|
|
1964
|
+
const live = await tx.scanTasks({
|
|
1965
|
+
conversationId: api.conversationId,
|
|
1966
|
+
kind: task.definition.name,
|
|
1967
|
+
status
|
|
1968
|
+
}, Math.max(isolatedLimit + (options.normalQueueLimit ?? 1), options.activeCellLimit ?? 1));
|
|
1969
|
+
for (const cell of live.items) {
|
|
1970
|
+
activeCount++;
|
|
1971
|
+
if ((await tx.doc(InvocationDoc, cell.id)).isolated)
|
|
1972
|
+
isolatedCount++;
|
|
1973
|
+
else if (!isolated && ++normalCount >= (options.normalQueueLimit ?? 1))
|
|
1974
|
+
throw new Error(`Cell ${cell.id} is still running. Wait or terminate it before starting another cell`);
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
if (options.activeCellLimit !== undefined && activeCount >= options.activeCellLimit)
|
|
1978
|
+
throw new Error(`Execution allows ${options.activeCellLimit} active cells at a time; wait for or terminate an earlier cell`);
|
|
1979
|
+
if (isolated && isolatedCount >= isolatedLimit)
|
|
1980
|
+
throw new Error(`Notebook allows ${options.isolatedConcurrency} isolated cells at a time; wait for or terminate an isolated cell first`);
|
|
1981
|
+
const id = await tx.createTask(task, copied, {
|
|
1982
|
+
ownership: { kind: "conversation" }
|
|
1983
|
+
});
|
|
1984
|
+
const doc = await tx.doc(InvocationDoc, id);
|
|
1985
|
+
if (isolated)
|
|
1986
|
+
doc.isolated = true;
|
|
1987
|
+
doc.forwardingCellId = id;
|
|
1988
|
+
doc.forwardingBudget = typeof input["max_output_tokens"] === "number" ? input["max_output_tokens"] * 4 : 40000;
|
|
1989
|
+
doc.forwardedToolCalls = {
|
|
1990
|
+
version: 1,
|
|
1991
|
+
cellId: String(id),
|
|
1992
|
+
calls: [],
|
|
1993
|
+
omittedCalls: 0
|
|
1994
|
+
};
|
|
1995
|
+
const inherited = await tx.doc(ToolOriginDoc, api.taskId);
|
|
1996
|
+
(await tx.doc(ToolOriginDoc, id)).origin = inherited.origin ?? {
|
|
1997
|
+
conversationId: api.conversationId,
|
|
1998
|
+
taskId: api.taskId,
|
|
1999
|
+
callId: api.callId
|
|
2000
|
+
};
|
|
2001
|
+
return id;
|
|
2002
|
+
}, context);
|
|
2003
|
+
},
|
|
2004
|
+
async wait(id, api, context, yieldTimeMs = 1e4, maxTokens = 1e4, sessionYieldTimeMs = yieldTimeMs) {
|
|
2005
|
+
if (!Number.isFinite(yieldTimeMs) || yieldTimeMs < 0)
|
|
2006
|
+
throw new Error("yieldTimeMs must be non-negative and finite");
|
|
2007
|
+
const record = await api.getTask(id, context);
|
|
2008
|
+
if (record === undefined || record.kind !== task.definition.name || record.conversationId !== api.conversationId) {
|
|
2009
|
+
const recovered = await recoverWaitSession(id, sessionYieldTimeMs, maxTokens, api, context, nestedTask, options.cancelTask);
|
|
2010
|
+
if (recovered)
|
|
2011
|
+
return recovered;
|
|
2012
|
+
}
|
|
2013
|
+
const initial = await observeCell(task.definition.name, id, api, context, maxTokens * 4);
|
|
2014
|
+
const stopProgress = await observeCellProgress(id, api, context, maxTokens * 4);
|
|
2015
|
+
try {
|
|
2016
|
+
if (initial.status !== "running" || yieldTimeMs === 0)
|
|
2017
|
+
return initial;
|
|
2018
|
+
await api.commit(async (tx) => {
|
|
2019
|
+
const inherited = (await tx.doc(ToolOriginDoc, api.taskId)).origin;
|
|
2020
|
+
(await tx.doc(ToolOriginDoc, id)).origin = inherited ?? {
|
|
2021
|
+
conversationId: api.conversationId,
|
|
2022
|
+
taskId: api.taskId,
|
|
2023
|
+
callId: api.callId
|
|
2024
|
+
};
|
|
2025
|
+
}, context);
|
|
2026
|
+
const yielding = driver.observeYield(id);
|
|
2027
|
+
if (yielding.consume()) {
|
|
2028
|
+
return initial;
|
|
2029
|
+
}
|
|
2030
|
+
const wait = withCancel(context);
|
|
2031
|
+
const timeout = new Error("Cell observation yielded");
|
|
2032
|
+
const timer = setTimeout(() => wait.cancel(timeout), Math.min(yieldTimeMs, 2147483647));
|
|
2033
|
+
try {
|
|
2034
|
+
await Promise.race([
|
|
2035
|
+
api.waitForTask(id, wait.context),
|
|
2036
|
+
yielding.wake
|
|
2037
|
+
]);
|
|
2038
|
+
yielding.consume();
|
|
2039
|
+
} catch (error) {
|
|
2040
|
+
if (wait.context.abortSignal?.reason !== timeout)
|
|
2041
|
+
throw error;
|
|
2042
|
+
} finally {
|
|
2043
|
+
clearTimeout(timer);
|
|
2044
|
+
wait.cancel();
|
|
2045
|
+
}
|
|
2046
|
+
return observeCell(task.definition.name, id, api, context, maxTokens * 4);
|
|
2047
|
+
} finally {
|
|
2048
|
+
await stopProgress();
|
|
2049
|
+
}
|
|
2050
|
+
},
|
|
2051
|
+
async cancel(id, api, context, maxTokens = 1e4) {
|
|
2052
|
+
await observeCell(task.definition.name, id, api, context);
|
|
2053
|
+
const stopProgress = await observeCellProgress(id, api, context, maxTokens * 4);
|
|
2054
|
+
try {
|
|
2055
|
+
await options.cancelTask(id, context);
|
|
2056
|
+
await api.waitForTask(id, context);
|
|
2057
|
+
return observeCell(task.definition.name, id, api, context, maxTokens * 4);
|
|
2058
|
+
} finally {
|
|
2059
|
+
await stopProgress();
|
|
2060
|
+
}
|
|
2061
|
+
},
|
|
2062
|
+
close: driver.close
|
|
2063
|
+
};
|
|
2064
|
+
}
|
|
2065
|
+
|
|
2066
|
+
// packages/execution/src/exec-source.ts
|
|
2067
|
+
var MAX_CODE_MODE_OUTPUT_TOKENS = 1e5;
|
|
2068
|
+
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.]";
|
|
2069
|
+
var CODE_MODE_EXEC_GRAMMAR = String.raw`
|
|
2070
|
+
start: pragma_source | plain_source
|
|
2071
|
+
pragma_source: PRAGMA_LINE NEWLINE SOURCE
|
|
2072
|
+
plain_source: SOURCE
|
|
2073
|
+
|
|
2074
|
+
PRAGMA_LINE: /[ \t]*\/\/ @exec:[^\r\n]*/
|
|
2075
|
+
NEWLINE: /\r?\n/
|
|
2076
|
+
SOURCE: /[\s\S]+/
|
|
2077
|
+
`;
|
|
2078
|
+
var CODE_MODE_EXEC_CONSTRAINED_SAMPLING = {
|
|
2079
|
+
type: "grammar",
|
|
2080
|
+
variants: { openai_lark: CODE_MODE_EXEC_GRAMMAR }
|
|
2081
|
+
};
|
|
2082
|
+
function parseExecSource(source, capabilities = {}) {
|
|
2083
|
+
if (!source.trim())
|
|
2084
|
+
throw new Error("exec requires non-empty JavaScript source");
|
|
2085
|
+
const [first, ...rest] = source.split(`
|
|
2086
|
+
`);
|
|
2087
|
+
const trimmed = first?.trimStart() ?? "";
|
|
2088
|
+
if (!trimmed.startsWith("// @exec:"))
|
|
2089
|
+
return {
|
|
2090
|
+
code: source,
|
|
2091
|
+
yieldTimeMs: null,
|
|
2092
|
+
maxOutputTokens: null,
|
|
2093
|
+
isolated: false
|
|
2094
|
+
};
|
|
2095
|
+
if (rest.join(`
|
|
2096
|
+
`).trim() === "")
|
|
2097
|
+
throw new Error("exec pragma must be followed by JavaScript source");
|
|
2098
|
+
const options = JSON.parse(trimmed.slice("// @exec:".length).trim());
|
|
2099
|
+
if (options === null || typeof options !== "object" || Array.isArray(options))
|
|
2100
|
+
throw new Error("exec pragma must be a JSON object");
|
|
2101
|
+
for (const key of Object.keys(options))
|
|
2102
|
+
if (key !== "yield_time_ms" && key !== "max_output_tokens" && !(key === "isolated" && capabilities.allowIsolated))
|
|
2103
|
+
throw new Error(`Unsupported exec pragma field: ${key}`);
|
|
2104
|
+
if ("isolated" in options && typeof options.isolated !== "boolean")
|
|
2105
|
+
throw new Error("isolated must be a boolean");
|
|
2106
|
+
return {
|
|
2107
|
+
isolated: "isolated" in options && options.isolated === true,
|
|
2108
|
+
code: rest.join(`
|
|
2109
|
+
`),
|
|
2110
|
+
yieldTimeMs: parseInteger("yield_time_ms" in options ? options.yield_time_ms : undefined, "yield_time_ms"),
|
|
2111
|
+
maxOutputTokens: parseInteger("max_output_tokens" in options ? options.max_output_tokens : undefined, "max_output_tokens", 1, MAX_CODE_MODE_OUTPUT_TOKENS)
|
|
2112
|
+
};
|
|
2113
|
+
}
|
|
2114
|
+
function parseInteger(value, name, minimum = 0, maximum = Number.MAX_SAFE_INTEGER) {
|
|
2115
|
+
if (value === undefined)
|
|
2116
|
+
return null;
|
|
2117
|
+
if (!Number.isSafeInteger(value) || Number(value) < minimum || Number(value) > maximum)
|
|
2118
|
+
throw new Error(`${name} must be a safe integer from ${minimum} to ${maximum}`);
|
|
2119
|
+
return Number(value);
|
|
2120
|
+
}
|
|
2121
|
+
|
|
2122
|
+
// packages/worker-code/src/interpreter.ts
|
|
2123
|
+
import {
|
|
2124
|
+
newQuickJSWASMModule,
|
|
2125
|
+
newVariant,
|
|
2126
|
+
RELEASE_SYNC
|
|
2127
|
+
} from "quickjs-emscripten";
|
|
2128
|
+
var interpreter;
|
|
2129
|
+
var WORKER_CODE_ISOLATE_BUDGET = Object.freeze({
|
|
2130
|
+
maxRuntimes: 4,
|
|
2131
|
+
maxReservedHeapBytes: 24 * 1024 * 1024,
|
|
2132
|
+
initialWasmBytes: 16 * 1024 * 1024,
|
|
2133
|
+
maxWasmBytes: 32 * 1024 * 1024
|
|
2134
|
+
});
|
|
2135
|
+
async function admitRuntime(wasm, heapBytes, signal) {
|
|
2136
|
+
signal.throwIfAborted();
|
|
2137
|
+
if (!interpreter) {
|
|
2138
|
+
const memory = new WebAssembly.Memory({ initial: 256, maximum: 512 });
|
|
2139
|
+
interpreter = {
|
|
2140
|
+
wasm,
|
|
2141
|
+
memory,
|
|
2142
|
+
module: newQuickJSWASMModule(newVariant(RELEASE_SYNC, { wasmModule: wasm, wasmMemory: memory })),
|
|
2143
|
+
active: 0,
|
|
2144
|
+
heap: 0
|
|
2145
|
+
};
|
|
2146
|
+
}
|
|
2147
|
+
const pool = interpreter;
|
|
2148
|
+
if (pool.wasm !== wasm)
|
|
2149
|
+
throw new Error("Worker Code already has a different compiled WASM module in this isolate");
|
|
2150
|
+
if (pool.active >= WORKER_CODE_ISOLATE_BUDGET.maxRuntimes || pool.heap + heapBytes > WORKER_CODE_ISOLATE_BUDGET.maxReservedHeapBytes)
|
|
2151
|
+
throw new Error("Worker Code isolate runtime budget exhausted. Wait for admitted work to finish");
|
|
2152
|
+
pool.active++;
|
|
2153
|
+
pool.heap += heapBytes;
|
|
2154
|
+
let released = false;
|
|
2155
|
+
const release = () => {
|
|
2156
|
+
if (released)
|
|
2157
|
+
return;
|
|
2158
|
+
released = true;
|
|
2159
|
+
pool.active--;
|
|
2160
|
+
pool.heap -= heapBytes;
|
|
2161
|
+
};
|
|
2162
|
+
try {
|
|
2163
|
+
const module = await pool.module;
|
|
2164
|
+
signal.throwIfAborted();
|
|
2165
|
+
return { runtime: module.newRuntime(), release };
|
|
2166
|
+
} catch (error) {
|
|
2167
|
+
release();
|
|
2168
|
+
throw error;
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
function interpreterBudget() {
|
|
2172
|
+
return {
|
|
2173
|
+
activeRuntimes: interpreter?.active ?? 0,
|
|
2174
|
+
reservedHeapBytes: interpreter?.heap ?? 0,
|
|
2175
|
+
wasmMemoryBytes: interpreter?.memory.buffer.byteLength ?? 0,
|
|
2176
|
+
...WORKER_CODE_ISOLATE_BUDGET
|
|
2177
|
+
};
|
|
2178
|
+
}
|
|
2179
|
+
|
|
2180
|
+
// packages/worker-code/src/limits.ts
|
|
2181
|
+
var DEFAULT_WORKER_CODE_LIMITS = Object.freeze({
|
|
2182
|
+
heapBytes: 8 * 1024 * 1024,
|
|
2183
|
+
stackBytes: 256 * 1024,
|
|
2184
|
+
fuel: 64,
|
|
2185
|
+
maxJobs: 4096,
|
|
2186
|
+
maxCalls: 128,
|
|
2187
|
+
maxPendingCalls: 32,
|
|
2188
|
+
maxSourceBytes: 65536,
|
|
2189
|
+
maxModuleBytes: 262144,
|
|
2190
|
+
maxModules: 128,
|
|
2191
|
+
maxArgumentBytes: 32768,
|
|
2192
|
+
maxResultBytes: 131072,
|
|
2193
|
+
maxOutputBytes: 262144,
|
|
2194
|
+
waitMs: 30000
|
|
2195
|
+
});
|
|
2196
|
+
function workerLimits(input = {}) {
|
|
2197
|
+
const limits = { ...DEFAULT_WORKER_CODE_LIMITS, ...input };
|
|
2198
|
+
for (const key of Object.keys(limits)) {
|
|
2199
|
+
const value = limits[key];
|
|
2200
|
+
const minimum = key === "heapBytes" ? 256 * 1024 : key === "stackBytes" ? 16 * 1024 : 1;
|
|
2201
|
+
if (!(key in DEFAULT_WORKER_CODE_LIMITS) || !Number.isSafeInteger(value) || value < minimum || value > DEFAULT_WORKER_CODE_LIMITS[key])
|
|
2202
|
+
throw new Error(`Invalid Worker Code limit ${key}. Expected an integer from ${minimum} to ${DEFAULT_WORKER_CODE_LIMITS[key]}`);
|
|
2203
|
+
}
|
|
2204
|
+
return Object.freeze(limits);
|
|
2205
|
+
}
|
|
2206
|
+
function boundedString(value, maxBytes, label) {
|
|
2207
|
+
if (value.length > maxBytes || new TextEncoder().encode(value).byteLength > maxBytes)
|
|
2208
|
+
throw new Error(`${label} byte limit exceeded`);
|
|
2209
|
+
return value;
|
|
2210
|
+
}
|
|
2211
|
+
function boundedJson(value, maxBytes, label) {
|
|
2212
|
+
const serialized = JSON.stringify(value);
|
|
2213
|
+
if (serialized === undefined)
|
|
2214
|
+
throw new Error(`${label} must be JSON`);
|
|
2215
|
+
return boundedString(serialized, maxBytes, label);
|
|
2216
|
+
}
|
|
2217
|
+
|
|
2218
|
+
// packages/worker-code/src/modules.ts
|
|
2219
|
+
function resolveModule(base, name) {
|
|
2220
|
+
if (!name.startsWith("/") && !name.startsWith("./") && !name.startsWith("../"))
|
|
2221
|
+
throw new Error(`Module ${name} is not in the workspace snapshot`);
|
|
2222
|
+
if (name.includes("\\") || name.includes("\x00") || name.includes(":"))
|
|
2223
|
+
throw new Error("Invalid workspace module path");
|
|
2224
|
+
const parts = [];
|
|
2225
|
+
const path = name.startsWith("/") ? name : `${base.slice(0, base.lastIndexOf("/") + 1)}${name}`;
|
|
2226
|
+
for (const part of path.split("/")) {
|
|
2227
|
+
if (part === "" || part === ".")
|
|
2228
|
+
continue;
|
|
2229
|
+
if (part === "..") {
|
|
2230
|
+
if (parts.length === 0)
|
|
2231
|
+
throw new Error("Workspace module path escapes root");
|
|
2232
|
+
parts.pop();
|
|
2233
|
+
} else
|
|
2234
|
+
parts.push(part);
|
|
2235
|
+
}
|
|
2236
|
+
return `/${parts.join("/")}`;
|
|
2237
|
+
}
|
|
2238
|
+
function moduleSnapshot(input, limits) {
|
|
2239
|
+
const entries = Object.entries(input);
|
|
2240
|
+
if (entries.length > limits.maxModules)
|
|
2241
|
+
throw new Error("Workspace module count limit exceeded");
|
|
2242
|
+
const sources = new Map;
|
|
2243
|
+
let bytes = 0;
|
|
2244
|
+
for (const [name, source] of entries) {
|
|
2245
|
+
if (!name.startsWith("/") || resolveModule("/", name) !== name || typeof source !== "string")
|
|
2246
|
+
throw new Error(`Workspace module ${name} must have a canonical absolute path and string source`);
|
|
2247
|
+
boundedString(source, limits.maxSourceBytes, "Module source");
|
|
2248
|
+
bytes += new TextEncoder().encode(name + source).byteLength;
|
|
2249
|
+
if (bytes > limits.maxModuleBytes)
|
|
2250
|
+
throw new Error("Workspace snapshot byte limit exceeded");
|
|
2251
|
+
sources.set(name, source);
|
|
2252
|
+
}
|
|
2253
|
+
return sources;
|
|
2254
|
+
}
|
|
2255
|
+
function moduleCode(request, limits, invoke) {
|
|
2256
|
+
if (!request.entry.startsWith("/") || resolveModule("/", request.entry) !== request.entry)
|
|
2257
|
+
throw new Error("Module entry must be a canonical absolute workspace path");
|
|
2258
|
+
const member = `(await import(${JSON.stringify(request.entry)}))[${boundedJson(request.exportName, 256, "Export name")}]`;
|
|
2259
|
+
return `return ${member}${invoke ? `(${boundedJson(request.args ?? null, limits.maxArgumentBytes, "Module arguments")})` : ""};`;
|
|
2260
|
+
}
|
|
2261
|
+
|
|
2262
|
+
// packages/worker-code/src/output.ts
|
|
2263
|
+
import { copyJson as copyJson11 } from "@earendil-works/chord";
|
|
2264
|
+
function guestContent(kind, value) {
|
|
2265
|
+
if (kind === "text")
|
|
2266
|
+
return {
|
|
2267
|
+
type: "text",
|
|
2268
|
+
text: typeof value === "string" ? value : JSON.stringify(value)
|
|
2269
|
+
};
|
|
2270
|
+
if (value === null || typeof value !== "object" || Array.isArray(value) || typeof value["data"] !== "string" || typeof value["mimeType"] !== "string" || !/^image\/(png|jpeg|webp|gif)$/.test(value["mimeType"]) || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value["data"]))
|
|
2271
|
+
throw new Error("image requires {data: base64, mimeType: image/png|jpeg|webp|gif}");
|
|
2272
|
+
return { type: "image", data: value["data"], mimeType: value["mimeType"] };
|
|
2273
|
+
}
|
|
2274
|
+
function observeWorkerCell(observation, maxTokens, delivered) {
|
|
2275
|
+
const details = observation.result.details;
|
|
2276
|
+
const fields = details !== null && typeof details === "object" && !Array.isArray(details) ? details : {};
|
|
2277
|
+
const revision = fields["revision"];
|
|
2278
|
+
const fresh = typeof revision !== "number" || delivered.get(observation.cellId) !== revision;
|
|
2279
|
+
if (typeof revision === "number" && observation.status === "running")
|
|
2280
|
+
delivered.set(observation.cellId, revision);
|
|
2281
|
+
if (observation.status !== "running")
|
|
2282
|
+
delivered.delete(observation.cellId);
|
|
2283
|
+
let remaining = maxTokens * 4;
|
|
2284
|
+
const content = [];
|
|
2285
|
+
let truncated = false;
|
|
2286
|
+
for (const item of fresh || observation.status !== "running" ? observation.result.output ?? [] : []) {
|
|
2287
|
+
const cost = item.type === "text" ? item.text.length : item.data.length;
|
|
2288
|
+
if (cost <= remaining) {
|
|
2289
|
+
content.push(item);
|
|
2290
|
+
remaining -= cost;
|
|
2291
|
+
} else {
|
|
2292
|
+
if (item.type === "text" && remaining > 0)
|
|
2293
|
+
content.push({ ...item, text: item.text.slice(0, remaining) });
|
|
2294
|
+
truncated = true;
|
|
2295
|
+
remaining = 0;
|
|
2296
|
+
}
|
|
2297
|
+
}
|
|
2298
|
+
if (truncated)
|
|
2299
|
+
content.push({
|
|
2300
|
+
type: "text",
|
|
2301
|
+
text: TRUNCATED_OUTPUT_NOTICE
|
|
2302
|
+
});
|
|
2303
|
+
if (observation.status === "running")
|
|
2304
|
+
content.unshift({
|
|
2305
|
+
type: "text",
|
|
2306
|
+
text: `Still running (exec cell "${observation.cellId}"). Use wait to observe or terminate it`
|
|
2307
|
+
});
|
|
2308
|
+
return {
|
|
2309
|
+
...observation.result,
|
|
2310
|
+
output: content,
|
|
2311
|
+
details: {
|
|
2312
|
+
...fields,
|
|
2313
|
+
cellId: observation.cellId,
|
|
2314
|
+
...observation.forwardedToolCalls === undefined ? {} : {
|
|
2315
|
+
forwardedToolCalls: copyJson11(observation.forwardedToolCalls, {
|
|
2316
|
+
omitUndefinedProperties: true
|
|
2317
|
+
})
|
|
2318
|
+
},
|
|
2319
|
+
status: observation.status
|
|
2320
|
+
}
|
|
2321
|
+
};
|
|
2322
|
+
}
|
|
2323
|
+
|
|
2324
|
+
// packages/worker-code/src/guest.ts
|
|
2325
|
+
async function runGuest(wasm, code, sources, limits, signal, capabilities = {}) {
|
|
2326
|
+
boundedString(code, limits.maxSourceBytes, "Source");
|
|
2327
|
+
const owner = new AbortController;
|
|
2328
|
+
const combined = AbortSignal.any([owner.signal, signal]);
|
|
2329
|
+
const admitted = await admitRuntime(wasm, limits.heapBytes, combined);
|
|
2330
|
+
const runtime = admitted.runtime;
|
|
2331
|
+
try {
|
|
2332
|
+
runtime.setMemoryLimit(limits.heapBytes);
|
|
2333
|
+
runtime.setMaxStackSize(limits.stackBytes);
|
|
2334
|
+
let polls = 0, calls = 0, jobs = 0, closed = false;
|
|
2335
|
+
runtime.setInterruptHandler(() => combined.aborted || ++polls > limits.fuel);
|
|
2336
|
+
runtime.setModuleLoader((name) => sources.get(name) ?? {
|
|
2337
|
+
error: new Error(`Module ${name} is not in the workspace snapshot`)
|
|
2338
|
+
}, (base, name) => {
|
|
2339
|
+
try {
|
|
2340
|
+
return resolveModule(base, name);
|
|
2341
|
+
} catch (error) {
|
|
2342
|
+
return {
|
|
2343
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
2344
|
+
};
|
|
2345
|
+
}
|
|
2346
|
+
});
|
|
2347
|
+
const vm = runtime.newContext();
|
|
2348
|
+
const pending = new Map;
|
|
2349
|
+
let promise;
|
|
2350
|
+
let timer;
|
|
2351
|
+
let onAbort;
|
|
2352
|
+
let outputBytes = 0;
|
|
2353
|
+
let outputFailure;
|
|
2354
|
+
try {
|
|
2355
|
+
const failure = (error) => ({
|
|
2356
|
+
error: vm.newError(error instanceof Error ? error.message : String(error))
|
|
2357
|
+
});
|
|
2358
|
+
const bridge = vm.newFunction("dispatch", (kindHandle, nameHandle, argsHandle) => {
|
|
2359
|
+
try {
|
|
2360
|
+
combined.throwIfAborted();
|
|
2361
|
+
const kind = vm.getString(kindHandle);
|
|
2362
|
+
const name = vm.getString(nameHandle);
|
|
2363
|
+
const serialized = boundedString(vm.getString(argsHandle), kind === "tool" ? limits.maxArgumentBytes : limits.maxOutputBytes, "Bridge input");
|
|
2364
|
+
const args = JSON.parse(serialized);
|
|
2365
|
+
if (pending.size >= limits.maxPendingCalls)
|
|
2366
|
+
throw new Error("Guest pending call limit exceeded");
|
|
2367
|
+
let perform;
|
|
2368
|
+
if (kind === "tool") {
|
|
2369
|
+
if (++calls > limits.maxCalls)
|
|
2370
|
+
throw new Error("Guest tool call limit exceeded");
|
|
2371
|
+
const tool = Object.hasOwn(capabilities.tools ?? {}, name) ? capabilities.tools?.[name] : undefined;
|
|
2372
|
+
if (!tool)
|
|
2373
|
+
throw new Error(`Tool ${name} is unavailable`);
|
|
2374
|
+
perform = () => tool(args, combined);
|
|
2375
|
+
} else if ((kind === "text" || kind === "image") && capabilities.emit) {
|
|
2376
|
+
outputBytes += new TextEncoder().encode(serialized).byteLength;
|
|
2377
|
+
if (outputBytes > limits.maxOutputBytes)
|
|
2378
|
+
throw new Error("Guest output byte limit exceeded");
|
|
2379
|
+
perform = () => capabilities.emit?.(kind, args) ?? Promise.resolve();
|
|
2380
|
+
} else if (kind === "yield" && capabilities.yield) {
|
|
2381
|
+
perform = capabilities.yield;
|
|
2382
|
+
} else
|
|
2383
|
+
throw new Error(`Guest capability ${kind} is unavailable`);
|
|
2384
|
+
const deferred = vm.newPromise();
|
|
2385
|
+
const work = Promise.resolve().then(async () => {
|
|
2386
|
+
try {
|
|
2387
|
+
const result = await perform();
|
|
2388
|
+
const serialized = boundedJson(result ?? null, limits.maxResultBytes, "Bridge result");
|
|
2389
|
+
if (!closed) {
|
|
2390
|
+
const value = vm.newString(serialized);
|
|
2391
|
+
try {
|
|
2392
|
+
deferred.resolve(value);
|
|
2393
|
+
} finally {
|
|
2394
|
+
value.dispose();
|
|
2395
|
+
}
|
|
2396
|
+
}
|
|
2397
|
+
} catch (error) {
|
|
2398
|
+
if (kind !== "tool")
|
|
2399
|
+
outputFailure = error;
|
|
2400
|
+
if (!closed) {
|
|
2401
|
+
const value = vm.newError(error instanceof Error ? error.message : String(error));
|
|
2402
|
+
try {
|
|
2403
|
+
deferred.reject(value);
|
|
2404
|
+
} finally {
|
|
2405
|
+
value.dispose();
|
|
2406
|
+
}
|
|
2407
|
+
}
|
|
2408
|
+
} finally {
|
|
2409
|
+
pending.delete(work);
|
|
2410
|
+
deferred.dispose();
|
|
2411
|
+
}
|
|
2412
|
+
});
|
|
2413
|
+
pending.set(work, deferred);
|
|
2414
|
+
return deferred.handle.dup();
|
|
2415
|
+
} catch (error) {
|
|
2416
|
+
if (vm.getString(kindHandle) !== "tool")
|
|
2417
|
+
outputFailure = error;
|
|
2418
|
+
return failure(error);
|
|
2419
|
+
}
|
|
2420
|
+
});
|
|
2421
|
+
vm.setProp(vm.global, "__dispatch", bridge);
|
|
2422
|
+
bridge.dispose();
|
|
2423
|
+
if (capabilities.inventory !== undefined) {
|
|
2424
|
+
const inventory = vm.newString(boundedJson(capabilities.inventory, limits.maxResultBytes, "Tool inventory"));
|
|
2425
|
+
try {
|
|
2426
|
+
vm.setProp(vm.global, "__inventory", inventory);
|
|
2427
|
+
} finally {
|
|
2428
|
+
inventory.dispose();
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
vm.unwrapResult(vm.evalCode(`(() => {
|
|
2432
|
+
const dispatch = globalThis.__dispatch;
|
|
2433
|
+
delete globalThis.__dispatch;
|
|
2434
|
+
const call = async (kind, name, value) => JSON.parse(await dispatch(kind, name, JSON.stringify(value ?? null)));
|
|
2435
|
+
globalThis.tools = Object.create(null);
|
|
2436
|
+
for (const name of ${JSON.stringify(Object.keys(capabilities.tools ?? {}))})
|
|
2437
|
+
tools[name] = args => call("tool", name, args);
|
|
2438
|
+
Object.freeze(tools);
|
|
2439
|
+
${capabilities.inventory !== undefined ? "globalThis.ALL_TOOLS = JSON.parse(globalThis.__inventory); delete globalThis.__inventory;" : ""}
|
|
2440
|
+
${capabilities.emit ? 'globalThis.text = value => call("text", "", value); globalThis.image = value => call("image", "", value);' : ""}
|
|
2441
|
+
${capabilities.yield ? 'globalThis.yield_control = () => call("yield", "", null);' : ""}
|
|
2442
|
+
})()`)).dispose();
|
|
2443
|
+
combined.throwIfAborted();
|
|
2444
|
+
promise = vm.unwrapResult(vm.evalCode(`(async () => {
|
|
2445
|
+
${code}
|
|
2446
|
+
})().then(value => JSON.stringify(value ?? null))`, "/cell.js"));
|
|
2447
|
+
const aborted = new Promise((_, reject) => {
|
|
2448
|
+
onAbort = () => reject(combined.reason);
|
|
2449
|
+
combined.addEventListener("abort", onAbort, { once: true });
|
|
2450
|
+
if (combined.aborted)
|
|
2451
|
+
onAbort();
|
|
2452
|
+
});
|
|
2453
|
+
const timeout = new Promise((_, reject) => {
|
|
2454
|
+
timer = setTimeout(() => reject(new Error("Guest host wait limit exceeded")), limits.waitMs);
|
|
2455
|
+
});
|
|
2456
|
+
while (true) {
|
|
2457
|
+
combined.throwIfAborted();
|
|
2458
|
+
if (outputFailure !== undefined)
|
|
2459
|
+
throw outputFailure;
|
|
2460
|
+
if (jobs >= limits.maxJobs)
|
|
2461
|
+
throw new Error("Guest job limit exceeded");
|
|
2462
|
+
const executed = runtime.executePendingJobs(Math.min(64, limits.maxJobs - jobs));
|
|
2463
|
+
if (executed.error) {
|
|
2464
|
+
try {
|
|
2465
|
+
throw new Error(JSON.stringify(vm.dump(executed.error)));
|
|
2466
|
+
} finally {
|
|
2467
|
+
executed.error.dispose();
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
jobs += executed.value;
|
|
2471
|
+
const state = vm.getPromiseState(promise);
|
|
2472
|
+
if (state.type === "rejected") {
|
|
2473
|
+
try {
|
|
2474
|
+
throw new Error(JSON.stringify(vm.dump(state.error)));
|
|
2475
|
+
} finally {
|
|
2476
|
+
state.error.dispose();
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
if (state.type === "fulfilled") {
|
|
2480
|
+
try {
|
|
2481
|
+
if (!pending.size && !runtime.hasPendingJob()) {
|
|
2482
|
+
const serialized = boundedString(vm.getString(state.value), limits.maxResultBytes, "Return value");
|
|
2483
|
+
return { value: JSON.parse(serialized), polls, jobs, calls };
|
|
2484
|
+
}
|
|
2485
|
+
} finally {
|
|
2486
|
+
state.value.dispose();
|
|
2487
|
+
}
|
|
2488
|
+
}
|
|
2489
|
+
if (runtime.hasPendingJob())
|
|
2490
|
+
continue;
|
|
2491
|
+
if (!pending.size)
|
|
2492
|
+
throw new Error("Guest promise has no owned host work");
|
|
2493
|
+
await Promise.race([...pending.keys(), aborted, timeout]);
|
|
2494
|
+
}
|
|
2495
|
+
} finally {
|
|
2496
|
+
closed = true;
|
|
2497
|
+
clearTimeout(timer);
|
|
2498
|
+
if (onAbort)
|
|
2499
|
+
combined.removeEventListener("abort", onAbort);
|
|
2500
|
+
owner.abort(new Error("Guest execution ended"));
|
|
2501
|
+
await Promise.allSettled(pending.keys());
|
|
2502
|
+
promise?.dispose();
|
|
2503
|
+
vm.dispose();
|
|
2504
|
+
}
|
|
2505
|
+
} finally {
|
|
2506
|
+
try {
|
|
2507
|
+
runtime.dispose();
|
|
2508
|
+
} finally {
|
|
2509
|
+
admitted.release();
|
|
2510
|
+
}
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
|
|
2514
|
+
// packages/worker-code/src/runtime.ts
|
|
2515
|
+
class WorkerRuntime {
|
|
2516
|
+
closed = false;
|
|
2517
|
+
active = new Map;
|
|
2518
|
+
wasm;
|
|
2519
|
+
limits;
|
|
2520
|
+
modules;
|
|
2521
|
+
constructor(wasm, limits, modules) {
|
|
2522
|
+
this.wasm = wasm;
|
|
2523
|
+
this.limits = limits;
|
|
2524
|
+
this.modules = modules;
|
|
2525
|
+
}
|
|
2526
|
+
async evaluate(code, modules, signal, capabilities) {
|
|
2527
|
+
if (this.closed)
|
|
2528
|
+
throw new Error("Worker Code is closed");
|
|
2529
|
+
const owner = new AbortController;
|
|
2530
|
+
const combined = signal ? AbortSignal.any([owner.signal, signal]) : owner.signal;
|
|
2531
|
+
const work = runGuest(this.wasm, code, modules, this.limits, combined, capabilities);
|
|
2532
|
+
this.active.set(owner, work);
|
|
2533
|
+
try {
|
|
2534
|
+
return await work;
|
|
2535
|
+
} finally {
|
|
2536
|
+
this.active.delete(owner);
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
async run(input, api, context) {
|
|
2540
|
+
if (typeof input["code"] !== "string")
|
|
2541
|
+
throw new Error("exec requires JavaScript source");
|
|
2542
|
+
const modules = this.modules();
|
|
2543
|
+
const content = [];
|
|
2544
|
+
let revision = 0;
|
|
2545
|
+
let publishing = Promise.resolve();
|
|
2546
|
+
const snapshot = () => ({
|
|
2547
|
+
output: [...content],
|
|
2548
|
+
details: { workerCode: true, revision }
|
|
2549
|
+
});
|
|
2550
|
+
const enqueue = (operation) => {
|
|
2551
|
+
const next = publishing.then(operation);
|
|
2552
|
+
publishing = next;
|
|
2553
|
+
return next;
|
|
2554
|
+
};
|
|
2555
|
+
const result = await this.evaluate(input["code"], modules, api.signal, {
|
|
2556
|
+
tools: api.tools,
|
|
2557
|
+
inventory: api.registrations.map(readToolContract).map((tool) => ({
|
|
2558
|
+
name: tool.name,
|
|
2559
|
+
description: tool.description,
|
|
2560
|
+
parameters: tool.inputSchema,
|
|
2561
|
+
usage: tool.usage
|
|
2562
|
+
})),
|
|
2563
|
+
emit: (kind, value) => enqueue(async () => {
|
|
2564
|
+
content.push(guestContent(kind, value));
|
|
2565
|
+
revision++;
|
|
2566
|
+
await api.publish(snapshot(), context);
|
|
2567
|
+
}),
|
|
2568
|
+
yield: () => enqueue(async () => {
|
|
2569
|
+
await api.publish(snapshot(), context);
|
|
2570
|
+
await api.requestYield(context);
|
|
2571
|
+
})
|
|
2572
|
+
});
|
|
2573
|
+
return {
|
|
2574
|
+
...snapshot(),
|
|
2575
|
+
details: {
|
|
2576
|
+
workerCode: true,
|
|
2577
|
+
revision: revision + 1,
|
|
2578
|
+
polls: result.polls,
|
|
2579
|
+
jobs: result.jobs,
|
|
2580
|
+
calls: result.calls
|
|
2581
|
+
}
|
|
2582
|
+
};
|
|
2583
|
+
}
|
|
2584
|
+
async close() {
|
|
2585
|
+
this.closed = true;
|
|
2586
|
+
for (const owner of this.active.keys())
|
|
2587
|
+
owner.abort(new Error("Worker Code closed"));
|
|
2588
|
+
await Promise.allSettled(this.active.values());
|
|
2589
|
+
}
|
|
2590
|
+
}
|
|
2591
|
+
|
|
2592
|
+
// packages/worker-code/src/tool-result.ts
|
|
2593
|
+
import { Type } from "typebox";
|
|
2594
|
+
import { Check } from "typebox/value";
|
|
2595
|
+
var number = Type.Number({ minimum: 0 });
|
|
2596
|
+
var resultSchema = Type.Object({
|
|
2597
|
+
output: Type.Optional(Type.Array(Type.Union([
|
|
2598
|
+
Type.Object({ type: Type.Literal("text"), text: Type.String() }),
|
|
2599
|
+
Type.Object({
|
|
2600
|
+
type: Type.Literal("image"),
|
|
2601
|
+
data: Type.String(),
|
|
2602
|
+
mimeType: Type.String()
|
|
2603
|
+
})
|
|
2604
|
+
]))),
|
|
2605
|
+
structuredOutput: Type.Optional(Type.Unknown()),
|
|
2606
|
+
isError: Type.Optional(Type.Boolean()),
|
|
2607
|
+
details: Type.Optional(Type.Unknown()),
|
|
2608
|
+
diagnostics: Type.Optional(Type.Array(Type.Object({
|
|
2609
|
+
severity: Type.Union([
|
|
2610
|
+
Type.Literal("info"),
|
|
2611
|
+
Type.Literal("warn"),
|
|
2612
|
+
Type.Literal("error")
|
|
2613
|
+
]),
|
|
2614
|
+
message: Type.String(),
|
|
2615
|
+
code: Type.Optional(Type.String())
|
|
2616
|
+
}))),
|
|
2617
|
+
usage: Type.Optional(Type.Object({
|
|
2618
|
+
input: number,
|
|
2619
|
+
output: number,
|
|
2620
|
+
cacheRead: number,
|
|
2621
|
+
cacheWrite: number,
|
|
2622
|
+
cacheWrite1h: Type.Optional(number),
|
|
2623
|
+
reasoning: Type.Optional(number),
|
|
2624
|
+
totalTokens: number,
|
|
2625
|
+
cost: Type.Object({
|
|
2626
|
+
input: number,
|
|
2627
|
+
output: number,
|
|
2628
|
+
cacheRead: number,
|
|
2629
|
+
cacheWrite: number,
|
|
2630
|
+
total: number
|
|
2631
|
+
}, { additionalProperties: false })
|
|
2632
|
+
}, { additionalProperties: false })),
|
|
2633
|
+
control: Type.Optional(Type.Object({
|
|
2634
|
+
addTools: Type.Optional(Type.Array(Type.String())),
|
|
2635
|
+
terminate: Type.Optional(Type.Literal(true)),
|
|
2636
|
+
handoff: Type.Optional(Type.String())
|
|
2637
|
+
}))
|
|
2638
|
+
}, { additionalProperties: false });
|
|
2639
|
+
function guestToolResult(value) {
|
|
2640
|
+
if (!Check(resultSchema, value))
|
|
2641
|
+
throw new Error("Guest handler must return a valid ToolExecutionResult JSON object");
|
|
2642
|
+
return value;
|
|
2643
|
+
}
|
|
2644
|
+
// packages/worker-code/src/index.ts
|
|
2645
|
+
function createWorkerCode(options) {
|
|
2646
|
+
const limits = workerLimits(options.limits);
|
|
2647
|
+
const source = options.modules ?? {};
|
|
2648
|
+
let modules;
|
|
2649
|
+
if (typeof source === "function")
|
|
2650
|
+
modules = () => moduleSnapshot(source(), limits);
|
|
2651
|
+
else {
|
|
2652
|
+
const snapshot = moduleSnapshot(source, limits);
|
|
2653
|
+
modules = () => snapshot;
|
|
2654
|
+
}
|
|
2655
|
+
const engine = new WorkerRuntime(options.wasmModule, limits, modules);
|
|
2656
|
+
const coordinator = createCellCoordinator({
|
|
2657
|
+
name: "worker-code",
|
|
2658
|
+
engine,
|
|
2659
|
+
surfaceTools: ["exec", "wait"],
|
|
2660
|
+
cancelTask: options.cancelTask
|
|
2661
|
+
});
|
|
2662
|
+
const delivered = new Map;
|
|
2663
|
+
const exec = defineTool({
|
|
2664
|
+
name: "exec",
|
|
2665
|
+
description: "Run bounded JavaScript; bare values are discarded",
|
|
2666
|
+
parameters: Type2.Object({ code: Type2.String() }),
|
|
2667
|
+
constrainedSampling: CODE_MODE_EXEC_CONSTRAINED_SAMPLING,
|
|
2668
|
+
replay: "unsafe",
|
|
2669
|
+
outputLimits: {
|
|
2670
|
+
maxBytes: limits.maxOutputBytes,
|
|
2671
|
+
maxLines: Number.MAX_SAFE_INTEGER
|
|
2672
|
+
},
|
|
2673
|
+
prepareArguments: (args) => {
|
|
2674
|
+
if (typeof args === "string")
|
|
2675
|
+
return { code: args };
|
|
2676
|
+
if (args === null || typeof args !== "object" || !("code" in args) || typeof args.code !== "string")
|
|
2677
|
+
throw new Error("exec requires JavaScript source");
|
|
2678
|
+
return { code: args.code };
|
|
2679
|
+
},
|
|
2680
|
+
async execute(args, api, context) {
|
|
2681
|
+
const parsed = parseExecSource(args.code);
|
|
2682
|
+
const id = await coordinator.start({
|
|
2683
|
+
code: parsed.code,
|
|
2684
|
+
max_output_tokens: parsed.maxOutputTokens ?? 1e4
|
|
2685
|
+
}, api, context);
|
|
2686
|
+
return observeWorkerCell(await coordinator.wait(id, api, context, parsed.yieldTimeMs ?? 1e4, parsed.maxOutputTokens ?? 1e4), parsed.maxOutputTokens ?? 1e4, delivered);
|
|
2687
|
+
}
|
|
2688
|
+
});
|
|
2689
|
+
const wait = defineTool({
|
|
2690
|
+
name: "wait",
|
|
2691
|
+
description: "Observe or terminate a yielded exec cell",
|
|
2692
|
+
parameters: Type2.Object({
|
|
2693
|
+
cell_id: Type2.String(),
|
|
2694
|
+
yield_time_ms: Type2.Optional(Type2.Integer({ minimum: 0, maximum: 30000, default: 1e4 })),
|
|
2695
|
+
max_tokens: Type2.Optional(Type2.Integer({ minimum: 1, maximum: 1e5, default: 1e4 })),
|
|
2696
|
+
terminate: Type2.Optional(Type2.Boolean())
|
|
2697
|
+
}),
|
|
2698
|
+
replay: "unsafe",
|
|
2699
|
+
outputLimits: {
|
|
2700
|
+
maxBytes: limits.maxOutputBytes,
|
|
2701
|
+
maxLines: Number.MAX_SAFE_INTEGER
|
|
2702
|
+
},
|
|
2703
|
+
async execute(args, api, context) {
|
|
2704
|
+
const value = Number(args.cell_id);
|
|
2705
|
+
if (!Number.isSafeInteger(value) || value <= 0)
|
|
2706
|
+
throw new Error("cell_id must be a valid yielded cell ID");
|
|
2707
|
+
const id = value;
|
|
2708
|
+
const observed = args.terminate ? await coordinator.cancel(id, api, context, args.max_tokens ?? 1e4) : await coordinator.wait(id, api, context, args.yield_time_ms ?? 1e4, args.max_tokens ?? 1e4);
|
|
2709
|
+
return observeWorkerCell(observed, args.max_tokens ?? 1e4, delivered);
|
|
2710
|
+
}
|
|
2711
|
+
});
|
|
2712
|
+
return {
|
|
2713
|
+
extension: {
|
|
2714
|
+
...coordinator.extension,
|
|
2715
|
+
tools: [exec, wait],
|
|
2716
|
+
sections: [
|
|
2717
|
+
section("worker-code", (input) => [
|
|
2718
|
+
"exec runs fresh bounded JavaScript. Await tools[name](args) and emit with text(value) or image({data,mimeType}). ALL_TOOLS lists callable contracts with original names. await yield_control() wakes the observer. Use wait for running cells. Guest globals and imports do not persist. No shell, ambient network or native globals.",
|
|
2719
|
+
...input.agent.callable.filter((tool) => tool.name !== "exec" && tool.name !== "wait").map(readToolContract).filter((contract) => !contract.nativeOnly && !contract.deferLoading).map((contract) => contract.usage)
|
|
2720
|
+
].join(`
|
|
2721
|
+
`))
|
|
2722
|
+
]
|
|
2723
|
+
},
|
|
2724
|
+
bind: coordinator.bind,
|
|
2725
|
+
budget: interpreterBudget,
|
|
2726
|
+
async evaluateModule(request, invocation = {}) {
|
|
2727
|
+
const sources = moduleSnapshot(request.modules, limits);
|
|
2728
|
+
return (await engine.evaluate(moduleCode(request, limits, Object.hasOwn(request, "args")), sources, invocation.signal)).value;
|
|
2729
|
+
},
|
|
2730
|
+
async executeToolModule(request, api, context, grants = {}) {
|
|
2731
|
+
const sources = moduleSnapshot(request.modules, limits);
|
|
2732
|
+
const allowed = new Set(grants.allowedTools ?? []);
|
|
2733
|
+
const registrations = (await api.agent(context)).callable.filter((tool) => allowed.has(tool.name) && tool.name !== "exec" && tool.name !== "wait" && !readToolContract(tool).nativeOnly);
|
|
2734
|
+
const controls = [];
|
|
2735
|
+
const signal = context.abortSignal ?? new AbortController().signal;
|
|
2736
|
+
const tools = cellTools({
|
|
2737
|
+
taskId: api.taskId,
|
|
2738
|
+
signal,
|
|
2739
|
+
waitForTask: api.waitForTask.bind(api),
|
|
2740
|
+
report: (error) => api.diagnostic({
|
|
2741
|
+
severity: "error",
|
|
2742
|
+
code: "nested_cancel_error",
|
|
2743
|
+
message: error instanceof Error ? error.message : String(error)
|
|
2744
|
+
})
|
|
2745
|
+
}, api, registrations, coordinator.nestedTask, controls, options.cancelTask, context);
|
|
2746
|
+
const output = [];
|
|
2747
|
+
const evaluated = await engine.evaluate(moduleCode(request, limits, true), sources, signal, {
|
|
2748
|
+
tools,
|
|
2749
|
+
emit: async (kind, value) => {
|
|
2750
|
+
output.push(guestContent(kind, value));
|
|
2751
|
+
}
|
|
2752
|
+
});
|
|
2753
|
+
const result = guestToolResult(evaluated.value);
|
|
2754
|
+
const control = combineControls([...controls, result.control]);
|
|
2755
|
+
return {
|
|
2756
|
+
...result,
|
|
2757
|
+
...result.output === undefined && output.length ? { output } : {},
|
|
2758
|
+
...control === undefined ? {} : { control }
|
|
2759
|
+
};
|
|
2760
|
+
},
|
|
2761
|
+
async close() {
|
|
2762
|
+
delivered.clear();
|
|
2763
|
+
await coordinator.close();
|
|
2764
|
+
}
|
|
2765
|
+
};
|
|
2766
|
+
}
|
|
2767
|
+
export {
|
|
2768
|
+
DEFAULT_WORKER_CODE_LIMITS,
|
|
2769
|
+
WORKER_CODE_ISOLATE_BUDGET,
|
|
2770
|
+
createWorkerCode
|
|
2771
|
+
};
|