返回源码地图

packages/durable/src/harness/tool.ts

v1.3.0 · 71023aec1546 · 11:完整读取intent/outcome、双safe恢复、嵌套附件、输出与usage

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import { type Context, copyJson, type Draft, type JsonRepresentation, type JsonValue } from "@earendil-works/chord";
2import { awaitWithContext } from "@earendil-works/chord/context";
3import { overlap } from "@earendil-works/chord/delta";
4import {
5 boundOutput,
6 OutputBuffer,
7 type OutputLimits,
8 PROGRESS_BYTES_PER_SECOND,
9 Progress,
10} from "@earendil-works/chord/output";
11import type { ImageContent, TextContent, ToolCall, ToolResultMessage } from "@earendil-works/pi-ai";
12import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
13import { Compile } from "typebox/compile";
14import { defineDocFamily } from "../documents.ts";
15import { AssistantEntry, ToolResultEntry } from "../entries.ts";
16import { errorMessage } from "../errors.ts";
17import { defineTask } from "../tasks.ts";
18import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, utf8ByteLength } from "../truncate.ts";
19import type {
20 ConversationId,
21 EntryId,
22 JsonObject,
23 Task,
24 TaskId,
25 TaskOptions,
26 TaskOutcome,
27 TaskRuntime,
28 Tx,
29 TypedEntry,
30} from "../types.ts";
31import { assignJson } from "./json.ts";
32import {
33 clearProgress,
34 finishSlot,
35 LiveDoc,
36 type NestedToolSlot,
37 type NestedToolSummary,
38 removeNestedSlots,
39 type ToolSlot,
40 toolSlot,
41} from "./live.ts";
42import type {
43 NestedToolExecutionResult,
44 ToolControl,
45 ToolDiagnostic,
46 ToolExecutionApi,
47 ToolExecutionResult,
48 ToolHookCall,
49 ToolHooks,
50 ToolRegistration,
51} from "./types.ts";
52import { recordUsage } from "./usage.ts";
53
54/**
55 * A model-issued call, read from its assistant entry, or a nested call a running tool made through `executeTool()`,
56 * whose call the input carries because no entry holds it.
57 */
58export type ToolTaskInput =
59 | { kind: "model"; assistant: EntryId; callId: string }
60 | {
61 kind: "nested";
62 parent: TaskId;
63 parentCallId: string;
64 key: string;
65 call: ToolCall;
66 /** `false`: commit no running output, details, or diagnostics to the slot; the result still gets them. */
67 progress?: false;
68 };
69
70export type ToolTaskCheckpoint =
71 | { phase: "call" }
72 /** Durable intent: the final arguments and the replay policy recorded before execution. */
73 | { phase: "execute"; arguments: JsonObject; replay: "safe" | "unsafe" };
74
75/**
76 * A model-issued call's result is its transcript entry; a nested call's result is in its caller's
77 * `NestedCallDoc`, so the receipt stays small and the result retires with the caller. A version 1 task that was
78 * already holding its outcome as `completing` when the Harness upgraded finishes with a version 1 result,
79 * `{ entryId, control? }` without `kind`; treat a result without `kind` as a model-issued call's.
80 */
81export type ToolTaskResult = { kind: "model"; entryId: EntryId; control?: ToolControl } | { kind: "nested" };
82
83/**
84 * Memo of a tool task that made a nested call, in any attempt, committed before the first admission of each attempt:
85 * only then can `pi.live` hold slots below it, which settling removes. A crash between the two only costs a scan.
86 */
87const MADE_NESTED_CALLS = "pi.tool.madeNestedCalls";
88
89/** One nested call of a running tool: its task, and once it ended, its result. */
90export type NestedCallState = {
91 /** Absent only inside the commit that creates the call; a creation that fails leaves no member. */
92 taskId?: TaskId<ToolTaskResult>;
93 /** Exactly what `executeTool()` returns; absent while running, and for a call the scheduler faulted or orphaned. */
94 result?: JsonRepresentation<NestedToolExecutionResult>;
95};
96
97/**
98 * The nested calls of a tool call, a task-scoped family of the calling task keyed by the nested call's key: so a rerun
99 * finds the calls it already made, and the caller reads each result. Created with the nested task; the nested call's
100 * terminal commit adds its result. One document per call, so no commit rewrites the others. Retires with the caller.
101 */
102export const NestedCallDoc = defineDocFamily<NestedCallState, null>({
103 kind: "pi.tool.nested-call",
104 version: 1,
105 scope: "task",
106 family: true,
107 initial: () => ({}),
108});
109
110type Runtime = TaskRuntime<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>;
111type Content = (TextContent | ImageContent)[];
112
113/**
114 * Built-in tool task: resolves the called tool among its phase agent's tools, validates, runs `beforeTool`, records intent,
115 * executes, runs `afterTool`, and settles the result, all in one `call` handler so nothing separates resolution from
116 * settlement. `execute` is reached only by recovery and applies the replay rule. A model-issued call settles by
117 * appending its result entry; a nested call by writing its result to its caller's `NestedCallDoc`.
118 */
119export const ToolTask = defineTask<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>({
120 name: "pi.tool",
121 version: 2,
122 initial: () => ({ phase: "call" }),
123 // Version 1 had only model-issued calls.
124 migrate: (input, checkpoint) => ({
125 input: { kind: "model", ...(input as { assistant: EntryId; callId: string }) },
126 checkpoint: checkpoint as ToolTaskCheckpoint,
127 }),
128 phases: {
129 call: async (task, runtime, context) => {
130 const call = await readCall(runtime, task.input, context);
131 const tool = await resolveTool(runtime, task.input, call.name, context);
132 if (tool === undefined) {
133 const error = harnessError("tool_unavailable", `Tool ${call.name} is not available`);
134 return settle(runtime, task.input, call, COMPLETED, () => error, context);
135 }
136 const prepared = prepare(tool, call.arguments as JsonObject);
137 const checked = "error" in prepared ? prepared : validate(tool, call, prepared.args);
138 if ("error" in checked)
139 return settle(runtime, task.input, call, COMPLETED, () => invalid(checked.error), context);
140 let args = checked.args;
141 let block: string | undefined;
142 await runtime.hooks.each("beforeTool", async (hook) => {
143 if (block !== undefined) return;
144 try {
145 const decision = await hook({ ...call, arguments: args }, runtime, context);
146 if (decision?.block !== undefined) block = decision.block;
147 else if (decision?.arguments !== undefined) args = decision.arguments;
148 } catch (error) {
149 if (runtime.signal.aborted) throw error;
150 block = errorMessage(error);
151 }
152 });
153 if (block !== undefined) {
154 const blocked = harnessError("blocked", `Tool call blocked: ${block}`);
155 return settle(runtime, task.input, call, COMPLETED, () => blocked, context);
156 }
157 const validated = validate(tool, call, args);
158 if ("error" in validated)
159 return settle(runtime, task.input, call, COMPLETED, () => invalid(validated.error), context);
160 // Strict JSON: repair may set optional properties to undefined, which the slot and checkpoint cannot hold.
161 const final = copyJson(validated.args, { omitUndefinedProperties: true }) as JsonObject;
162 await runtime.commit(async (tx) => {
163 const slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);
164 if (slot !== undefined) slot.status = "running";
165 // A nested slot shows the arguments the call runs with, which repair, hooks, and coercion may have changed.
166 // Compared with the input, which the slot got at admission: reading the draft would track every leaf.
167 const changed = task.input.kind === "nested" && !jsonEqual(task.input.call.arguments as JsonValue, final);
168 if (changed && slot !== undefined && "parentTaskId" in slot) slot.arguments = final;
169 const intent = { phase: "execute", arguments: final, replay: tool.replay ?? "unsafe" } as const;
170 return { status: "running", checkpoint: intent };
171 }, context);
172 await run(runtime, task.input, call, tool, final, context);
173 },
174 /** Recovery after intent: rerun only when the stored and the current policy both say `safe`. */
175 execute: async (task, runtime, context) => {
176 const { arguments: args, replay } = task.state.checkpoint;
177 const call = await readCall(runtime, task.input, context);
178 const tool = await resolveTool(runtime, task.input, call.name, context);
179 if (replay === "safe" && tool?.replay === "safe") {
180 // The rerun reports from scratch; clear what the interrupted attempt published.
181 await runtime.commit(async (tx) => {
182 const slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);
183 if (slot !== undefined) clearProgress(slot);
184 return undefined;
185 }, context);
186 return run(runtime, task.input, call, tool, args, context);
187 }
188 const message = `Tool ${call.name} was interrupted and may have partially run`;
189 // `failed` records cancellation intent, so the call's owned conversations, left unsupervised, are aborted.
190 const ending = { status: "failed", message } as const;
191 await settle(runtime, task.input, call, ending, (slot) => fromSlot(slot, "interrupted", message), context);
192 },
193 },
194 abort: async (task, runtime, context) => {
195 const call = await readCall(runtime, task.input, context);
196 // Abandoned after a restart (`TaskOptions.abandonOnRestart`): say whether the call may have run.
197 const [code, message] =
198 task.abortReason !== "restart"
199 ? ["aborted", `Tool ${call.name} was aborted`]
200 : task.state.checkpoint.phase === "execute"
201 ? ["interrupted", `Tool ${call.name} was interrupted by a restart and may have partially run`]
202 : ["abandoned", `Tool ${call.name} was not started: its caller ended with a restart`];
203 const ending = { status: "aborted" } as const;
204 await settle(runtime, task.input, call, ending, (slot) => fromSlot(slot, code, message), context);
205 },
206});
207
208/** The called tool: among the tools the model is offered for a model-issued call, else among those tools may call. */
209async function resolveTool(
210 runtime: Runtime,
211 input: ToolTaskInput,
212 name: string,
213 context: Context,
214): Promise<ToolRegistration | undefined> {
215 const agent = await runtime.agent(context);
216 return (input.kind === "model" ? agent.tools : agent.callable).find((tool) => tool.name === name);
217}
218
219/** The call: from the input for a nested call, which hooks see with its parent, else from the assistant entry. */
220async function readCall(runtime: Runtime, input: ToolTaskInput, context: Context): Promise<ToolHookCall> {
221 if (input.kind === "nested") return { ...input.call, parent: { taskId: input.parent, callId: input.parentCallId } };
222 const entry = await runtime.entry(AssistantEntry, input.assistant, context);
223 const message = entry?.model?.[0];
224 const call =
225 message?.role === "assistant"
226 ? message.content.find(
227 (content): content is ToolCall => content.type === "toolCall" && content.id === input.callId,
228 )
229 : undefined;
230 if (call === undefined) throw new Error(`Entry ${input.assistant} has no tool call ${input.callId}`);
231 return call;
232}
233
234/** Arguments, or why they are invalid. */
235type Checked = { readonly args: JsonObject } | { readonly error: string };
236
237/** The call's arguments as repaired by the tool; a throwing repair makes them invalid. */
238function prepare(tool: ToolRegistration, args: JsonObject): Checked {
239 if (tool.prepareArguments === undefined) return { args };
240 try {
241 return { args: tool.prepareArguments(args) as JsonObject };
242 } catch (error) {
243 return { error: errorMessage(error) };
244 }
245}
246
247/** Arguments validated and coerced against the implementation's schema. */
248function validate(tool: ToolRegistration, call: ToolCall, args: JsonObject): Checked {
249 try {
250 return { args: validateToolArguments(tool, { ...call, arguments: args }) as JsonObject };
251 } catch (error) {
252 return { error: errorMessage(error) };
253 }
254}
255
256function invalid(message: string): ToolExecutionResult {
257 return harnessError("invalid_arguments", message);
258}
259
260/** What a running tool reported through its api: output, the last details, and diagnostics. */
261type Reported = {
262 readonly output: OutputBuffer;
263 readonly limits: OutputLimits;
264 readonly diagnostics: ToolDiagnostic[];
265 details: JsonValue | undefined;
266};
267
268/** Execute with the resolved implementation, then settle its result. */
269async function run(
270 runtime: Runtime,
271 input: ToolTaskInput,
272 call: ToolHookCall,
273 tool: ToolRegistration,
274 args: JsonObject,
275 context: Context,
276): Promise<void> {
277 const limits: OutputLimits = {
278 maxBytes: tool.outputLimits?.maxBytes ?? DEFAULT_MAX_BYTES,
279 maxLines: tool.outputLimits?.maxLines ?? DEFAULT_MAX_LINES,
280 retain: tool.outputLimits?.retain ?? "head",
281 };
282 const reported: Reported = { output: new OutputBuffer(limits), limits, diagnostics: [], details: undefined };
283 const streams = input.kind === "model" || input.progress !== false;
284 const progress = publishProgress(runtime, reported, streams, context);
285 /** Nested call admissions this invocation started; cleanup waits for them, so it sees every nested call. */
286 const admissions: Promise<unknown>[] = [];
287 // A caller that can rerun reattaches to its nested calls and child tasks after a restart; any other caller never
288 // resumes, so they are abandoned (`TaskOptions.abandonOnRestart`).
289 const resumes = tool.replay === "safe";
290 /** Default keys: the order of this invocation's calls, so a rerun that calls in the same order reattaches. */
291 let sequence = 0;
292 /** This attempt's commit of the `MADE_NESTED_CALLS` memo. */
293 let madeNestedMemo: Promise<unknown> | undefined;
294 let ended = false;
295 const assertLive = (): void => {
296 if (ended) throw new Error(`Tool call ${call.id} has settled`);
297 };
298 const api: Omit<ToolExecutionApi, "env"> = {
299 taskId: runtime.taskId,
300 conversationId: runtime.conversationId,
301 callId: call.id,
302 registry: runtime.registry,
303 agent: runtime.agent,
304 models: runtime.models,
305 output: (chunk, skipped) => {
306 assertLive();
307 if (reported.output.push(chunk, skipped)) progress.mark();
308 },
309 outputWindow:
310 limits.retain === "tail"
311 ? {
312 maxBytes: limits.maxBytes,
313 maxLines: limits.maxLines,
314 minIntervalMs: runtime.settings.progress.outputIntervalMs,
315 bytesPerSecond: PROGRESS_BYTES_PER_SECOND,
316 }
317 : undefined,
318 retainedOutput: () => {
319 assertLive();
320 const retained = reported.output.snapshot();
321 return { text: retained.text, truncated: retained.droppedBytes > 0 };
322 },
323 diagnostic: (diagnostic) => {
324 assertLive();
325 reported.diagnostics.push(copyJson(diagnostic, { omitUndefinedProperties: true }) as ToolDiagnostic);
326 progress.mark();
327 },
328 details: async (value, detailsContext) => {
329 assertLive();
330 detailsContext.abortSignal?.throwIfAborted();
331 reported.details = copyJson(value, { omitUndefinedProperties: true });
332 const committed = progress.markAndWait();
333 // Cancelling the wait leaves the update in place; the commit's own outcome stays observed.
334 committed.catch(() => {});
335 return awaitWithContext(committed, detailsContext);
336 },
337 commit: async (change, commitContext) => {
338 let result: Awaited<ReturnType<typeof change>> | undefined;
339 await runtime.commit(async (tx) => {
340 result = await change(tx);
341 return undefined;
342 }, commitContext);
343 return result as Awaited<ReturnType<typeof change>>;
344 },
345 memo: runtime.memo,
346 createTask: async <I, S extends { phase: string }, R, H extends object>(
347 task: Task<I, S, R, H>,
348 input: I,
349 options: Omit<TaskOptions, "conversationId">,
350 taskContext: Context,
351 ): Promise<TaskId<R>> => {
352 const child = options.ownership.kind === "task" && !resumes ? { abandonOnRestart: true, ...options } : options;
353 let id: TaskId<R> | undefined;
354 await runtime.commit(async (tx) => {
355 id = await tx.createTask(task, input, child);
356 return undefined;
357 }, taskContext);
358 return id!;
359 },
360 getTask: runtime.getTask,
361 waitForTask: runtime.waitForTask,
362 conversation: runtime.conversation,
363 snapshot: runtime.snapshot,
364 snapshotAsOf: runtime.snapshotAsOf,
365 watchDoc: runtime.watchDoc,
366 executeTool: async (name, toolArgs, callContext, options = {}) => {
367 assertLive();
368 const key = options.key ?? String(++sequence);
369 if (options.key !== undefined) checkKey(options.key);
370 // The memo first, once per attempt; a failed one is tried again by the next call.
371 madeNestedMemo ??= runtime.memo(MADE_NESTED_CALLS, true, callContext).catch((error: unknown) => {
372 madeNestedMemo = undefined;
373 throw error;
374 });
375 // Registered now, so cleanup waits for it.
376 const admission = madeNestedMemo.then(() =>
377 startNestedCall(
378 runtime,
379 call.id,
380 name,
381 toolArgs,
382 { key, progress: options.progress, abandonOnRestart: !resumes },
383 callContext,
384 ),
385 );
386 admissions.push(admission);
387 const id = await admission;
388 const settled = await runtime.waitForTask(id, callContext);
389 const stored = (await runtime.snapshot(NestedCallDoc, runtime.taskId, key, callContext))?.result;
390 // A copy the tool may change; a nested call the scheduler faulted or orphaned stored none.
391 return stored === undefined
392 ? fallbackResult(id, name, settled.state.outcome)
393 : (copyJson(stored as unknown as JsonValue) as unknown as NestedToolExecutionResult);
394 },
395 };
396
397 let result: ToolExecutionResult;
398 let ending = COMPLETED;
399 // Execution time of this attempt; a rerun after recovery measures only itself.
400 let durationMs: number | undefined;
401 try {
402 // Built for this call, so a rerun after recovery gets the conversation's environment at that time.
403 const env = await runtime.env(context);
404 const startedAt = performance.now();
405 try {
406 result = await tool.execute(args, { ...api, env }, context);
407 } finally {
408 durationMs = Math.round(performance.now() - startedAt);
409 }
410 } catch (error) {
411 if (runtime.signal.aborted) {
412 ended = true;
413 for (const waiter of await progress.stop()) waiter.reject(error);
414 throw error;
415 }
416 result = { isError: true, diagnostics: [toolDiagnostic("tool_error", errorMessage(error))] };
417 // A throw, from `execute()` or from building the environment, ends the task `failed`, which cancels what the call
418 // owned; it no longer supervises it. The error text is already in the result.
419 ending = { status: "failed", message: `Tool ${call.name} threw` };
420 }
421 ended = true;
422 // No admission starts after `ended`; let those underway commit, so settlement aborts and lists their calls.
423 await Promise.allSettled(admissions);
424 reported.output.end();
425 // Details still waiting for a progress commit settle with the terminal commit, the final flush.
426 const pending = await progress.stop();
427 try {
428 const settled = await finalResult(runtime, input, call, tool, result, reported, context);
429 await settle(runtime, input, call, ending, () => settled, context, durationMs);
430 } catch (error) {
431 for (const waiter of pending) waiter.reject(error);
432 throw error;
433 }
434 for (const waiter of pending) waiter.resolve();
435}
436
437/**
438 * Throttled commits of what the tool reported into its slot, in `pi.live.tools` or `pi.live.nestedTools`, each writing
439 * only what changed since the last one; none when `enabled` is false.
440 */
441function publishProgress(runtime: Runtime, reported: Reported, enabled: boolean, context: Context): Progress {
442 let written = { text: "", details: undefined as JsonValue | undefined, diagnostics: 0 };
443 return new Progress(
444 async () => {
445 if (!enabled) return 0;
446 // Capture everything synchronously: the tool keeps reporting while the commit is in flight.
447 const snapshot = reported.output.snapshot();
448 const current = { text: snapshot.text, details: reported.details, diagnostics: reported.diagnostics.length };
449 const added = reported.diagnostics.slice(written.diagnostics, current.diagnostics);
450 const detailsChanged = current.details !== written.details;
451 // What the commit writes, as Chord diffs the string: an append, a trim plus an append of what follows the shared
452 // part, or the whole window when its bounded overlap search finds nothing.
453 let bytes = 0;
454 if (snapshot.text !== written.text) {
455 const shared = snapshot.text.startsWith(written.text)
456 ? written.text.length
457 : overlap(written.text, snapshot.text, 65_536);
458 bytes += utf8ByteLength(snapshot.text.slice(shared));
459 }
460 if (detailsChanged) bytes += utf8ByteLength(JSON.stringify(current.details ?? null));
461 if (added.length > 0) bytes += utf8ByteLength(JSON.stringify(added));
462 await runtime.commit(async (tx) => {
463 const slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);
464 if (slot === undefined) return undefined;
465 // REMINDER: assign `output` as one string field. Chord then diffs it into an append, or a trim plus an
466 // append for a sliding tail; replacing the slot object would record the whole window on every commit.
467 if ((slot.output ?? "") !== snapshot.text) slot.output = snapshot.text;
468 if (snapshot.droppedBytes > 0) slot.droppedBytes = snapshot.droppedBytes;
469 if (snapshot.droppedLines > 0) slot.droppedLines = snapshot.droppedLines;
470 // Diff details leaf by leaf and append new diagnostics, so each commit writes only what changed.
471 if (detailsChanged && current.details !== undefined) {
472 assignJson(slot as unknown as Record<string, JsonValue>, "details", current.details);
473 }
474 if (added.length > 0) {
475 if (slot.diagnostics === undefined) slot.diagnostics = [];
476 for (const diagnostic of added) slot.diagnostics.push(diagnostic);
477 }
478 return undefined;
479 }, context);
480 written = current;
481 return bytes;
482 },
483 (error) => {
484 // Rejections after an abort mark or close are expected; the committed state stays consistent.
485 if (!runtime.signal.aborted) runtime.report(error);
486 },
487 runtime.settings.progress.outputIntervalMs,
488 );
489}
490
491/**
492 * The settled result: the tool's result with the retained output and last details as fallbacks, its diagnostics after
493 * those reported through the api, `afterTool` applied, explicit text bounded, and `structuredOutput` checked against the
494 * tool's schema, with the Harness's diagnostics last. A nested call whose `structuredOutput` breaks the contract gets an
495 * error result without it; a model-issued call only loses it, and the break is reported to the host.
496 */
497async function finalResult(
498 runtime: Runtime,
499 input: ToolTaskInput,
500 call: ToolHookCall,
501 tool: ToolRegistration,
502 result: ToolExecutionResult,
503 reported: Reported,
504 context: Context,
505): Promise<ToolExecutionResult> {
506 const harness: ToolDiagnostic[] = [];
507 const retained = result.output === undefined ? reported.output.snapshot() : undefined;
508 const output: Content =
509 retained === undefined ? result.output! : retained.text === "" ? [] : [{ type: "text", text: retained.text }];
510 let final: ToolExecutionResult = {
511 ...result,
512 output,
513 details: result.details === undefined ? reported.details : result.details,
514 diagnostics: [...reported.diagnostics, ...(result.diagnostics ?? [])],
515 };
516 await runtime.hooks.each("afterTool", async (hook) => {
517 final = (await hook(call, final, runtime, context)) ?? final;
518 });
519 // The retained output's truncation applies only while afterTool kept that output.
520 if (retained !== undefined && retained.droppedBytes > 0 && final.output === output) {
521 harness.push(truncated(retained, reported.limits.retain));
522 }
523 const bounded = boundContent(final.output ?? [], reported.limits);
524 if (bounded.droppedBytes > 0) harness.push(truncated(bounded, reported.limits.retain));
525 const broken = structuredOutputError(tool, final);
526 if (broken !== undefined) {
527 const { structuredOutput: _dropped, ...rest } = final;
528 if (input.kind === "nested") {
529 final = { ...rest, isError: true };
530 harness.push(toolDiagnostic("invalid_structured_output", broken));
531 } else {
532 // The model never sees structured output, so its call stands; the host learns of the broken tool.
533 final = rest;
534 runtime.report(new Error(broken));
535 }
536 }
537 // Programs get the tool's own value: without a schema, its output. The model reads only `output`, so model-issued
538 // calls skip both.
539 if (input.kind === "nested" && tool.structuredOutputSchema === undefined) {
540 final = { ...final, structuredOutput: outputValue(bounded.content) as JsonValue };
541 }
542 // A schema tool's error result without structured output has its text only in the output, which programs never
543 // get: it becomes an error diagnostic, as a thrown error's message does, unless one says what went wrong already.
544 if (
545 input.kind === "nested" &&
546 tool.structuredOutputSchema !== undefined &&
547 final.isError === true &&
548 final.structuredOutput === undefined &&
549 ![...(final.diagnostics ?? []), ...harness].some((diagnostic) => diagnostic.severity === "error")
550 ) {
551 const text = bounded.content.flatMap((item) => (item.type === "text" ? [item.text] : [])).join("\n");
552 if (text !== "") harness.push(toolDiagnostic("tool_error", text));
553 }
554 return { ...final, output: bounded.content, diagnostics: [...(final.diagnostics ?? []), ...harness] };
555}
556
557const structuredValidators = new WeakMap<object, ReturnType<typeof Compile>>();
558
559/** Why a result's `structuredOutput` breaks the tool's contract, or `undefined` when it keeps it. */
560function structuredOutputError(tool: ToolRegistration, result: ToolExecutionResult): string | undefined {
561 const schema = tool.structuredOutputSchema;
562 const value = result.structuredOutput;
563 if (schema === undefined) {
564 return value === undefined
565 ? undefined
566 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`;
567 }
568 if (value === undefined) {
569 return result.isError === true ? undefined : `Tool ${tool.name} returned no structuredOutput`;
570 }
571 let validator = structuredValidators.get(schema);
572 if (validator === undefined) {
573 validator = Compile(schema);
574 structuredValidators.set(schema, validator);
575 }
576 if (validator.Check(value)) return undefined;
577 const [first] = validator.Errors(value);
578 const path = first?.instancePath.replace(/^\//, "").replace(/\//g, ".") || "root";
579 return `Tool ${tool.name} returned structuredOutput that does not match its schema: ${path}: ${first?.message ?? "invalid"}`;
580}
581
582/**
583 * Commit the tool's terminal state and mark its slot done. A model-issued call appends its result entry and ends with
584 * the entry ID; a nested call writes its result to the caller's `NestedCallDoc`, records its usage, and ends with a
585 * small receipt. Nested calls this call left running are aborted first, so they report into their slots before the
586 * slots below the call leave `pi.live`. `build` receives the slot so interruption and abort can report the durable
587 * partial output.
588 */
589async function settle(
590 runtime: Runtime,
591 input: ToolTaskInput,
592 call: ToolHookCall,
593 ending: Ending,
594 build: (slot: Readonly<ToolSlot | NestedToolSlot> | undefined) => ToolExecutionResult,
595 context: Context,
596 durationMs?: number,
597): Promise<void> {
598 // A crash in between leaves the call in `execute`: a safe rerun reattaches to the calls, an interruption ends here.
599 // Every live nested call the task owns, also those an earlier attempt made and this one never called again.
600 const nestedIds = (await runtime.ownedTasks(context))
601 .filter((record) => record.kind === ToolTask.definition.name && (record.input as ToolTaskInput).kind === "nested")
602 .map((record) => record.id);
603 // Read before the settling commit: no admission starts after `ended`, and those underway were awaited.
604 const madeNested = (await runtime.memo(MADE_NESTED_CALLS, context)) === true;
605 // Mark them all before waiting for any: one may run until a sibling is cancelled.
606 await Promise.all(nestedIds.map((id) => runtime.abortOwned(id, context)));
607 await runtime.commit(async (tx) => {
608 const conversationId = runtime.conversationId;
609 const live = await tx.doc(LiveDoc, conversationId);
610 const slot = toolSlot(live, runtime.taskId);
611 const result = build(slot);
612 let settled: ToolTaskResult;
613 if (input.kind === "nested") {
614 const nested = nestedResult(runtime.taskId, result, durationMs);
615 if (nested.usage !== undefined) await recordUsage(tx, conversationId, "tools", call.name, nested.usage);
616 // The caller is never terminal before its owned nested calls, so its document is open; another task in it is a
617 // bug, not a race.
618 const state = await tx.doc(NestedCallDoc, input.parent, input.key, null);
619 if (state.taskId !== runtime.taskId) throw new Error(`Nested call ${call.id} is not in its caller's index`);
620 state.result = nested as unknown as Draft<JsonRepresentation<NestedToolExecutionResult>>;
621 if (slot !== undefined && "parentTaskId" in slot) {
622 finishSlot(slot);
623 slot.summary = summaryOf(nested, result.output ?? []);
624 }
625 settled = { kind: "nested" };
626 } else {
627 const timing = { timestamp: runtime.now(), durationMs };
628 const entry = await appendToolResult(tx, conversationId, call, result, timing);
629 if (slot !== undefined && !("parentTaskId" in slot)) {
630 finishSlot(slot);
631 slot.entry = entry.id;
632 }
633 // Tools build control objects freely; drop keys set to undefined so the task result is strict JSON.
634 const control =
635 result.control === undefined || ending.status !== "completed"
636 ? {}
637 : { control: copyJson(result.control as JsonValue, { omitUndefinedProperties: true }) as ToolControl };
638 settled = { kind: "model", entryId: entry.id, ...control };
639 }
640 // A call that made no nested calls, in any attempt, has no slots below it; skipping the scan keeps many leaves
641 // linear. Committed before the read: no nested call is admitted after `ended`.
642 if (madeNested) removeNestedSlots(live, runtime.taskId);
643 if (ending.status === "aborted") return { status: "terminal", outcome: { status: "aborted", result: settled } };
644 if (ending.status === "failed") {
645 const error = { message: ending.message };
646 return { status: "terminal", outcome: { status: "failed", error, result: settled } };
647 }
648 return { status: "terminal", outcome: { status: "completed", result: settled } };
649 }, context);
650}
651
652/**
653 * A nested call's result, as stored and returned: strict JSON, without `output`, which only the model reads, and
654 * without `control`, which only model-issued calls apply.
655 */
656function nestedResult(
657 taskId: TaskId,
658 result: ToolExecutionResult,
659 durationMs: number | undefined,
660): NestedToolExecutionResult {
661 const nested = {
662 taskId,
663 structuredOutput: result.structuredOutput,
664 isError: result.isError ?? false,
665 details: result.details,
666 diagnostics: result.diagnostics ?? [],
667 usage: result.usage,
668 durationMs,
669 };
670 return copyJson(nested as unknown as JsonValue, {
671 omitUndefinedProperties: true,
672 }) as unknown as NestedToolExecutionResult;
673}
674
675/**
676 * Create nested call `key` of the call `parentCallId` in one commit: its tool task, owned by the calling task, its slot,
677 * and its `NestedCallDoc`. A key already made returns that call's task when it names the same tool and arguments.
678 */
679async function startNestedCall(
680 runtime: Runtime,
681 parentCallId: string,
682 name: string,
683 args: JsonObject,
684 options: { readonly key: string; readonly progress: boolean | undefined; readonly abandonOnRestart: boolean },
685 context: Context,
686): Promise<TaskId<ToolTaskResult>> {
687 const key = options.key;
688 const call: ToolCall = {
689 type: "toolCall",
690 id: `${parentCallId}/${key}`,
691 name,
692 arguments: copyJson(args, { omitUndefinedProperties: true }) as JsonObject,
693 };
694 let id: TaskId<ToolTaskResult> | undefined;
695 await runtime.commit(async (tx) => {
696 // Opened, or created empty for a key not made yet.
697 const state = await tx.doc(NestedCallDoc, runtime.taskId, key, null);
698 const existing = state.taskId;
699 if (existing !== undefined) {
700 const input = (await tx.task(existing))?.input as ToolTaskInput | undefined;
701 const same =
702 input?.kind === "nested" &&
703 input.call.name === name &&
704 jsonEqual(input.call.arguments as JsonValue, call.arguments as JsonValue);
705 if (!same) throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
706 id = existing as TaskId<ToolTaskResult>;
707 return undefined;
708 }
709 const input: ToolTaskInput = {
710 kind: "nested",
711 parent: runtime.taskId,
712 parentCallId,
713 key,
714 call,
715 ...(options.progress === false ? { progress: false } : {}),
716 };
717 const created = await tx.createTask(ToolTask, input, {
718 ownership: { kind: "task", taskId: runtime.taskId },
719 abandonOnRestart: options.abandonOnRestart,
720 });
721 state.taskId = created;
722 const live = await tx.doc(LiveDoc, runtime.conversationId);
723 live.nestedTools ??= [];
724 const slot: NestedToolSlot = {
725 callId: call.id,
726 parentCallId,
727 parentTaskId: runtime.taskId,
728 name,
729 taskId: created,
730 arguments: call.arguments as JsonObject,
731 status: "pending",
732 };
733 live.nestedTools.push(slot as Draft<NestedToolSlot>);
734 id = created;
735 return undefined;
736 }, context);
737 return id!;
738}
739
740/**
741 * What programs get of a tool's output when it declares no schema: one text item as its string, one image as itself,
742 * nothing as `""`, and anything else as the content list.
743 */
744function outputValue(output: Content): string | ImageContent | Content {
745 if (output.length === 0) return "";
746 if (output.length > 1) return output;
747 const [only] = output;
748 return only!.type === "text" ? only!.text : only!;
749}
750
751/** What the caller gets for a nested call without a stored result: one the scheduler faulted or orphaned. */
752function fallbackResult(taskId: TaskId, name: string, outcome: TaskOutcome<ToolTaskResult>): NestedToolExecutionResult {
753 const message =
754 outcome.status === "faulted"
755 ? `Tool ${name} failed: ${outcome.error.message}`
756 : outcome.status === "orphaned"
757 ? `Tool ${name} could not resume: ${outcome.reason}`
758 : `Tool ${name} ended without a result`;
759 const error = harnessError(outcome.status, message);
760 return { taskId, isError: true, diagnostics: error.diagnostics ?? [] };
761}
762
763/**
764 * How a tool task ends; the result entry is appended either way. `failed` (execution threw or was interrupted)
765 * records cancellation intent for the conversations the call owns; a result with `isError` still completes.
766 */
767type Ending = { readonly status: "completed" | "aborted" } | { readonly status: "failed"; readonly message: string };
768
769const COMPLETED: Ending = { status: "completed" };
770
771/** An error result from the slot's durable partial output, details, and diagnostics. */
772function fromSlot(
773 slot: Readonly<ToolSlot | NestedToolSlot> | undefined,
774 code: string,
775 message: string,
776): ToolExecutionResult {
777 const diagnostics = [...(slot?.diagnostics ?? [])];
778 const droppedBytes = slot?.droppedBytes ?? 0;
779 if (droppedBytes > 0) diagnostics.push(truncated({ droppedBytes, droppedLines: slot?.droppedLines ?? 0 }));
780 diagnostics.push(toolDiagnostic(code, message));
781 return {
782 output: slot?.output === undefined || slot.output === "" ? [] : [{ type: "text", text: slot.output }],
783 isError: true,
784 ...(slot?.details === undefined ? {} : { details: slot.details }),
785 diagnostics,
786 };
787}
788
789/** An error result the Harness writes itself: no content and one `error` diagnostic with `code`. */
790export function harnessError(code: string, message: string): ToolExecutionResult {
791 return { output: [], isError: true, diagnostics: [toolDiagnostic(code, message)] };
792}
793
794function toolDiagnostic(code: string, message: string): ToolDiagnostic {
795 return { severity: "error", code, message };
796}
797
798/** The Harness's truncation diagnostic; `retain` is unknown when rebuilt from a slot after recovery. */
799function truncated(
800 dropped: { readonly droppedLines: number; readonly droppedBytes: number },
801 retain?: "head" | "tail",
802): ToolDiagnostic {
803 const kept = retain === undefined ? "" : ` to its ${retain === "head" ? "beginning" : "end"}`;
804 return {
805 severity: "warn",
806 code: "truncated",
807 message: `Output truncated${kept}: ${dropped.droppedLines} lines, ${dropped.droppedBytes} bytes dropped`,
808 };
809}
810
811/** Error text a nested call's summary keeps. */
812const MAX_SUMMARY_ERROR_CHARS = 500;
813
814/** How a nested call ended, for its slot: error text, from its diagnostics or else its `output`, bounded. */
815function summaryOf(result: NestedToolExecutionResult, output: Content): NestedToolSummary {
816 const error = result.isError ? errorTextOf(result, output).slice(0, MAX_SUMMARY_ERROR_CHARS) : "";
817 return {
818 isError: result.isError,
819 ...(result.durationMs === undefined ? {} : { durationMs: result.durationMs }),
820 ...(result.usage === undefined ? {} : { usage: result.usage }),
821 ...(error === "" ? {} : { error }),
822 };
823}
824
825/** The error messages of a nested result, else the text items of its output, joined with newlines. */
826function errorTextOf(result: NestedToolExecutionResult, output: Content): string {
827 const errors = result.diagnostics.filter((diagnostic) => diagnostic.severity === "error");
828 if (errors.length > 0) return errors.map((diagnostic) => diagnostic.message).join("\n");
829 return output.flatMap((item) => (item.type === "text" ? [item.text] : [])).join("\n");
830}
831
832/**
833 * Append a `pi.tool-result` entry. The content ends with the rendered diagnostics, so the stored message is exactly
834 * what the model sees; `data` keeps the structured list. A result's usage is added to `pi.usage` in the same commit.
835 */
836export async function appendToolResult(
837 tx: Tx,
838 conversationId: ConversationId,
839 call: ToolCall,
840 result: ToolExecutionResult,
841 meta: { readonly timestamp: number; readonly durationMs?: number },
842): Promise<TypedEntry<{ diagnostics: ToolDiagnostic[] }>> {
843 const { timestamp, durationMs } = meta;
844 const diagnostics = [...(result.diagnostics ?? [])];
845 const content: Content = [...(result.output ?? [])];
846 if (diagnostics.length > 0) content.push({ type: "text", text: renderDiagnostics(diagnostics) });
847 const message = {
848 role: "toolResult",
849 toolCallId: call.id,
850 toolName: call.name,
851 content,
852 ...(result.details === undefined ? {} : { details: result.details }),
853 ...(result.usage === undefined ? {} : { usage: result.usage }),
854 isError: result.isError ?? false,
855 ...(durationMs === undefined ? {} : { durationMs }),
856 timestamp,
857 } as ToolResultMessage;
858 if (result.usage !== undefined) await recordUsage(tx, conversationId, "tools", call.name, result.usage);
859 return tx.appendEntry(ToolResultEntry, conversationId, { model: [message], data: { diagnostics } });
860}
861
862function renderDiagnostics(diagnostics: readonly ToolDiagnostic[]): string {
863 return `<harness>\n${diagnostics.map((diagnostic) => `[${diagnostic.severity}] ${diagnostic.message}`).join("\n")}\n</harness>`;
864}
865
866/**
867 * Bound the text of result content. When the joined text exceeds the limits, the text items are replaced by one bounded
868 * item at the position of the first (head) or last (tail) text item; other content is kept.
869 */
870function boundContent(
871 content: Content,
872 limits: OutputLimits,
873): { content: Content; droppedBytes: number; droppedLines: number } {
874 const texts = content.filter((item): item is TextContent => item.type === "text");
875 const bounded = boundOutput(texts.map((item) => item.text).join(""), limits);
876 if (bounded.droppedBytes === 0) return { content, droppedBytes: 0, droppedLines: 0 };
877 const keep = limits.retain === "head" ? texts[0] : texts.at(-1);
878 const result: Content = [];
879 for (const item of content) {
880 if (item.type !== "text") result.push(item);
881 else if (item === keep) result.push({ ...item, text: bounded.text });
882 }
883 return { content: result, droppedBytes: bounded.droppedBytes, droppedLines: bounded.droppedLines };
884}
885
886/**
887 * Explicit nested call keys are path segments of the call ID, so IDs of different nested calls never collide, and are
888 * never plain positive integers, which default keys use. `__proto__` stays reserved, as it was when keys indexed a JSON object.
889 */
890function checkKey(key: string): void {
891 if (key === "" || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)) {
892 throw new Error(
893 `Nested call key ${JSON.stringify(key)} must be non-empty, without "/", not "__proto__", and not a positive integer`,
894 );
895 }
896}
897
898/** Structural JSON equality; object key order does not matter. */
899function jsonEqual(a: JsonValue, b: JsonValue): boolean {
900 if (a === b) return true;
901 if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
902 if (Array.isArray(a) || Array.isArray(b)) {
903 return (
904 Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => jsonEqual(item, b[i]!))
905 );
906 }
907 const keys = Object.keys(a);
908 return (
909 keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && jsonEqual(a[key]!, b[key]!))
910 );
911}