@earendil-works/pi-durable 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/README.md +128 -3
- package/dist/codemode/codemode.d.ts.map +1 -1
- package/dist/codemode/codemode.js +12 -4
- package/dist/codemode/codemode.js.map +1 -1
- package/dist/codemode/models.d.ts.map +1 -1
- package/dist/codemode/models.js +2 -0
- package/dist/codemode/models.js.map +1 -1
- package/dist/documents.d.ts +1 -1
- package/dist/documents.d.ts.map +1 -1
- package/dist/documents.js.map +1 -1
- package/dist/env/index.d.ts +1 -0
- package/dist/env/index.d.ts.map +1 -1
- package/dist/env/index.js.map +1 -1
- package/dist/env/node.d.ts.map +1 -1
- package/dist/env/node.js +11 -3
- package/dist/env/node.js.map +1 -1
- package/dist/harness/agent.d.ts +13 -2
- package/dist/harness/agent.d.ts.map +1 -1
- package/dist/harness/agent.js +39 -5
- package/dist/harness/agent.js.map +1 -1
- package/dist/harness/compaction.d.ts +3 -1
- package/dist/harness/compaction.d.ts.map +1 -1
- package/dist/harness/compaction.js +19 -4
- package/dist/harness/compaction.js.map +1 -1
- package/dist/harness/context.d.ts +5 -0
- package/dist/harness/context.d.ts.map +1 -1
- package/dist/harness/context.js +46 -12
- package/dist/harness/context.js.map +1 -1
- package/dist/harness/generation.d.ts.map +1 -1
- package/dist/harness/generation.js +67 -27
- package/dist/harness/generation.js.map +1 -1
- package/dist/harness/harness.d.ts +5 -2
- package/dist/harness/harness.d.ts.map +1 -1
- package/dist/harness/harness.js +78 -13
- package/dist/harness/harness.js.map +1 -1
- package/dist/harness/inbox.d.ts +2 -2
- package/dist/harness/inbox.d.ts.map +1 -1
- package/dist/harness/inbox.js +3 -3
- package/dist/harness/inbox.js.map +1 -1
- package/dist/harness/prompt.d.ts +1 -1
- package/dist/harness/prompt.d.ts.map +1 -1
- package/dist/harness/prompt.js +1 -1
- package/dist/harness/prompt.js.map +1 -1
- package/dist/harness/scheduler.d.ts +55 -10
- package/dist/harness/scheduler.d.ts.map +1 -1
- package/dist/harness/scheduler.js +617 -124
- package/dist/harness/scheduler.js.map +1 -1
- package/dist/harness/submissions.d.ts +7 -2
- package/dist/harness/submissions.d.ts.map +1 -1
- package/dist/harness/submissions.js +48 -17
- package/dist/harness/submissions.js.map +1 -1
- package/dist/harness/task-graph.d.ts +18 -1
- package/dist/harness/task-graph.d.ts.map +1 -1
- package/dist/harness/task-graph.js +50 -11
- package/dist/harness/task-graph.js.map +1 -1
- package/dist/harness/telemetry.d.ts +307 -0
- package/dist/harness/telemetry.d.ts.map +1 -0
- package/dist/harness/telemetry.js +136 -0
- package/dist/harness/telemetry.js.map +1 -0
- package/dist/harness/tool.d.ts.map +1 -1
- package/dist/harness/tool.js +54 -8
- package/dist/harness/tool.js.map +1 -1
- package/dist/harness/types.d.ts +110 -15
- package/dist/harness/types.d.ts.map +1 -1
- package/dist/harness/types.js.map +1 -1
- package/dist/harness/util.d.ts +4 -0
- package/dist/harness/util.d.ts.map +1 -1
- package/dist/harness/util.js +4 -0
- package/dist/harness/util.js.map +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/session/session.d.ts +17 -6
- package/dist/session/session.d.ts.map +1 -1
- package/dist/session/session.js +64 -32
- package/dist/session/session.js.map +1 -1
- package/dist/session/transaction.d.ts +5 -1
- package/dist/session/transaction.d.ts.map +1 -1
- package/dist/session/transaction.js +26 -1
- package/dist/session/transaction.js.map +1 -1
- package/dist/storage/indexeddb.d.ts +60 -0
- package/dist/storage/indexeddb.d.ts.map +1 -0
- package/dist/storage/indexeddb.js +831 -0
- package/dist/storage/indexeddb.js.map +1 -0
- package/dist/storage/jsonl/storage.d.ts +16 -0
- package/dist/storage/jsonl/storage.d.ts.map +1 -1
- package/dist/storage/memory.js +1 -1
- package/dist/storage/memory.js.map +1 -1
- package/dist/storage/sqlite/cloudflare.d.ts +6 -43
- package/dist/storage/sqlite/cloudflare.d.ts.map +1 -1
- package/dist/storage/sqlite/cloudflare.js +6 -101
- package/dist/storage/sqlite/cloudflare.js.map +1 -1
- package/dist/storage/sqlite/database.d.ts +1 -36
- package/dist/storage/sqlite/database.d.ts.map +1 -1
- package/dist/storage/sqlite/database.js.map +1 -1
- package/dist/storage/sqlite/index.d.ts +2 -2
- package/dist/storage/sqlite/index.d.ts.map +1 -1
- package/dist/storage/sqlite/index.js.map +1 -1
- package/dist/storage/sqlite/migrations.d.ts +7 -6
- package/dist/storage/sqlite/migrations.d.ts.map +1 -1
- package/dist/storage/sqlite/migrations.js +116 -106
- package/dist/storage/sqlite/migrations.js.map +1 -1
- package/dist/storage/sqlite/node.d.ts +6 -39
- package/dist/storage/sqlite/node.d.ts.map +1 -1
- package/dist/storage/sqlite/node.js +8 -175
- package/dist/storage/sqlite/node.js.map +1 -1
- package/dist/storage/sqlite/schema.d.ts +45 -0
- package/dist/storage/sqlite/schema.d.ts.map +1 -0
- package/dist/storage/sqlite/schema.js +50 -0
- package/dist/storage/sqlite/schema.js.map +1 -0
- package/dist/storage/sqlite/storage.d.ts +10 -2
- package/dist/storage/sqlite/storage.d.ts.map +1 -1
- package/dist/storage/sqlite/storage.js +46 -43
- package/dist/storage/sqlite/storage.js.map +1 -1
- package/dist/testing/storage-conformance.d.ts.map +1 -1
- package/dist/testing/storage-conformance.js +17 -0
- package/dist/testing/storage-conformance.js.map +1 -1
- package/dist/timers.d.ts +21 -0
- package/dist/timers.d.ts.map +1 -0
- package/dist/timers.js +72 -0
- package/dist/timers.js.map +1 -0
- package/dist/tools/image-processor.d.ts +4 -1
- package/dist/tools/image-processor.d.ts.map +1 -1
- package/dist/tools/image-processor.js +8 -18
- package/dist/tools/image-processor.js.map +1 -1
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js +1 -1
- package/dist/tools/read.js.map +1 -1
- package/dist/truncate.d.ts +3 -2
- package/dist/truncate.d.ts.map +1 -1
- package/dist/truncate.js +4 -34
- package/dist/truncate.js.map +1 -1
- package/dist/types.d.ts +130 -9
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +15 -5
- package/dist/harness/output.d.ts +0 -69
- package/dist/harness/output.d.ts.map +0 -1
- package/dist/harness/output.js +0 -318
- package/dist/harness/output.js.map +0 -1
package/dist/harness/tool.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.js","sourceRoot":"","sources":["../../src/harness/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,QAAQ,EAAuD,MAAM,uBAAuB,CAAC;AACpH,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AAEtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAC/E,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAatF,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EACN,aAAa,EACb,UAAU,EACV,OAAO,EAGP,iBAAiB,EAEjB,QAAQ,GACR,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,WAAW,EAAE,YAAY,EAAqB,yBAAyB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAWhH,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AA+BzC;;;GAGG;AACH,MAAM,iBAAiB,GAAG,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C,8EAA8E,CACpH,CAAC;IACH,CAAC;AACF,CAAC;AAED,kEAAkE;AAClE,SAAS,SAAS,CAAC,CAAY,EAAE,CAAY;IAC5C,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACzB,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC7F,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1C,OAAO,CACN,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC,CAC7G,CAAC;IACH,CAAC;IACD,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC5B,OAAO,CACN,IAAI,CAAC,MAAM,KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,GAAG,CAAE,EAAE,CAAC,CAAC,GAAG,CAAE,CAAC,CAAC,CAClH,CAAC;AACH,CAAC","sourcesContent":["import { type Context, copyJson, type Draft, type JsonRepresentation, type JsonValue } from \"@earendil-works/chord\";\nimport { awaitWithContext } from \"@earendil-works/chord/context\";\nimport { overlap } from \"@earendil-works/chord/delta\";\nimport type { ImageContent, TextContent, ToolCall, ToolResultMessage } from \"@earendil-works/pi-ai\";\nimport { validateToolArguments } from \"@earendil-works/pi-ai/utils/validation\";\nimport { Compile } from \"typebox/compile\";\nimport { defineDocFamily } from \"../documents.ts\";\nimport { AssistantEntry, ToolResultEntry } from \"../entries.ts\";\nimport { errorMessage } from \"../errors.ts\";\nimport { defineTask } from \"../tasks.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, utf8ByteLength } from \"../truncate.ts\";\nimport type {\n\tConversationId,\n\tEntryId,\n\tJsonObject,\n\tTask,\n\tTaskId,\n\tTaskOptions,\n\tTaskOutcome,\n\tTaskRuntime,\n\tTx,\n\tTypedEntry,\n} from \"../types.ts\";\nimport { assignJson } from \"./json.ts\";\nimport {\n\tclearProgress,\n\tfinishSlot,\n\tLiveDoc,\n\ttype NestedToolSlot,\n\ttype NestedToolSummary,\n\tremoveNestedSlots,\n\ttype ToolSlot,\n\ttoolSlot,\n} from \"./live.ts\";\nimport { boundOutput, OutputBuffer, type OutputLimits, PROGRESS_BYTES_PER_SECOND, Progress } from \"./output.ts\";\nimport type {\n\tNestedToolExecutionResult,\n\tToolControl,\n\tToolDiagnostic,\n\tToolExecutionApi,\n\tToolExecutionResult,\n\tToolHookCall,\n\tToolHooks,\n\tToolRegistration,\n} from \"./types.ts\";\nimport { recordUsage } from \"./usage.ts\";\n\n/**\n * A model-issued call, read from its assistant entry, or a nested call a running tool made through `executeTool()`,\n * whose call the input carries because no entry holds it.\n */\nexport type ToolTaskInput =\n\t| { kind: \"model\"; assistant: EntryId; callId: string }\n\t| {\n\t\t\tkind: \"nested\";\n\t\t\tparent: TaskId;\n\t\t\tparentCallId: string;\n\t\t\tkey: string;\n\t\t\tcall: ToolCall;\n\t\t\t/** `false`: commit no running output, details, or diagnostics to the slot; the result still gets them. */\n\t\t\tprogress?: false;\n\t };\n\nexport type ToolTaskCheckpoint =\n\t| { phase: \"call\" }\n\t/** Durable intent: the final arguments and the replay policy recorded before execution. */\n\t| { phase: \"execute\"; arguments: JsonObject; replay: \"safe\" | \"unsafe\" };\n\n/**\n * A model-issued call's result is its transcript entry; a nested call's result is in its caller's\n * `NestedCallDoc`, so the receipt stays small and the result retires with the caller. A version 1 task that was\n * already holding its outcome as `completing` when the Harness upgraded finishes with a version 1 result,\n * `{ entryId, control? }` without `kind`; treat a result without `kind` as a model-issued call's.\n */\nexport type ToolTaskResult = { kind: \"model\"; entryId: EntryId; control?: ToolControl } | { kind: \"nested\" };\n\n/**\n * Memo of a tool task that made a nested call, in any attempt, committed before the first admission of each attempt:\n * only then can `pi.live` hold slots below it, which settling removes. A crash between the two only costs a scan.\n */\nconst MADE_NESTED_CALLS = \"pi.tool.madeNestedCalls\";\n\n/** One nested call of a running tool: its task, and once it ended, its result. */\nexport type NestedCallState = {\n\t/** Absent only inside the commit that creates the call; a creation that fails leaves no member. */\n\ttaskId?: TaskId<ToolTaskResult>;\n\t/** Exactly what `executeTool()` returns; absent while running, and for a call the scheduler faulted or orphaned. */\n\tresult?: JsonRepresentation<NestedToolExecutionResult>;\n};\n\n/**\n * 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\n * finds the calls it already made, and the caller reads each result. Created with the nested task; the nested call's\n * terminal commit adds its result. One document per call, so no commit rewrites the others. Retires with the caller.\n */\nexport const NestedCallDoc = defineDocFamily<NestedCallState, null>({\n\tkind: \"pi.tool.nested-call\",\n\tversion: 1,\n\tscope: \"task\",\n\tfamily: true,\n\tinitial: () => ({}),\n});\n\ntype Runtime = TaskRuntime<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>;\ntype Content = (TextContent | ImageContent)[];\n\n/**\n * Built-in tool task: resolves the called tool among its phase agent's tools, validates, runs `beforeTool`, records intent,\n * executes, runs `afterTool`, and settles the result, all in one `call` handler so nothing separates resolution from\n * settlement. `execute` is reached only by recovery and applies the replay rule. A model-issued call settles by\n * appending its result entry; a nested call by writing its result to its caller's `NestedCallDoc`.\n */\nexport const ToolTask = defineTask<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>({\n\tname: \"pi.tool\",\n\tversion: 2,\n\tinitial: () => ({ phase: \"call\" }),\n\t// Version 1 had only model-issued calls.\n\tmigrate: (input, checkpoint) => ({\n\t\tinput: { kind: \"model\", ...(input as { assistant: EntryId; callId: string }) },\n\t\tcheckpoint: checkpoint as ToolTaskCheckpoint,\n\t}),\n\tphases: {\n\t\tcall: async (task, runtime, context) => {\n\t\t\tconst call = await readCall(runtime, task.input, context);\n\t\t\tconst tool = await resolveTool(runtime, task.input, call.name, context);\n\t\t\tif (tool === undefined) {\n\t\t\t\tconst error = harnessError(\"tool_unavailable\", `Tool ${call.name} is not available`);\n\t\t\t\treturn settle(runtime, task.input, call, COMPLETED, () => error, context);\n\t\t\t}\n\t\t\tconst prepared = prepare(tool, call.arguments as JsonObject);\n\t\t\tconst checked = \"error\" in prepared ? prepared : validate(tool, call, prepared.args);\n\t\t\tif (\"error\" in checked)\n\t\t\t\treturn settle(runtime, task.input, call, COMPLETED, () => invalid(checked.error), context);\n\t\t\tlet args = checked.args;\n\t\t\tlet block: string | undefined;\n\t\t\tawait runtime.hooks.each(\"beforeTool\", async (hook) => {\n\t\t\t\tif (block !== undefined) return;\n\t\t\t\ttry {\n\t\t\t\t\tconst decision = await hook({ ...call, arguments: args }, runtime, context);\n\t\t\t\t\tif (decision?.block !== undefined) block = decision.block;\n\t\t\t\t\telse if (decision?.arguments !== undefined) args = decision.arguments;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (runtime.signal.aborted) throw error;\n\t\t\t\t\tblock = errorMessage(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (block !== undefined) {\n\t\t\t\tconst blocked = harnessError(\"blocked\", `Tool call blocked: ${block}`);\n\t\t\t\treturn settle(runtime, task.input, call, COMPLETED, () => blocked, context);\n\t\t\t}\n\t\t\tconst validated = validate(tool, call, args);\n\t\t\tif (\"error\" in validated)\n\t\t\t\treturn settle(runtime, task.input, call, COMPLETED, () => invalid(validated.error), context);\n\t\t\t// Strict JSON: repair may set optional properties to undefined, which the slot and checkpoint cannot hold.\n\t\t\tconst final = copyJson(validated.args, { omitUndefinedProperties: true }) as JsonObject;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\tif (slot !== undefined) slot.status = \"running\";\n\t\t\t\t// A nested slot shows the arguments the call runs with, which repair, hooks, and coercion may have changed.\n\t\t\t\t// Compared with the input, which the slot got at admission: reading the draft would track every leaf.\n\t\t\t\tconst changed = task.input.kind === \"nested\" && !jsonEqual(task.input.call.arguments as JsonValue, final);\n\t\t\t\tif (changed && slot !== undefined && \"parentTaskId\" in slot) slot.arguments = final;\n\t\t\t\tconst intent = { phase: \"execute\", arguments: final, replay: tool.replay ?? \"unsafe\" } as const;\n\t\t\t\treturn { status: \"running\", checkpoint: intent };\n\t\t\t}, context);\n\t\t\tawait run(runtime, task.input, call, tool, final, context);\n\t\t},\n\t\t/** Recovery after intent: rerun only when the stored and the current policy both say `safe`. */\n\t\texecute: async (task, runtime, context) => {\n\t\t\tconst { arguments: args, replay } = task.state.checkpoint;\n\t\t\tconst call = await readCall(runtime, task.input, context);\n\t\t\tconst tool = await resolveTool(runtime, task.input, call.name, context);\n\t\t\tif (replay === \"safe\" && tool?.replay === \"safe\") {\n\t\t\t\t// The rerun reports from scratch; clear what the interrupted attempt published.\n\t\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\t\tif (slot !== undefined) clearProgress(slot);\n\t\t\t\t\treturn undefined;\n\t\t\t\t}, context);\n\t\t\t\treturn run(runtime, task.input, call, tool, args, context);\n\t\t\t}\n\t\t\tconst message = `Tool ${call.name} was interrupted and may have partially run`;\n\t\t\t// `failed` records cancellation intent, so the call's owned conversations, left unsupervised, are aborted.\n\t\t\tconst ending = { status: \"failed\", message } as const;\n\t\t\tawait settle(runtime, task.input, call, ending, (slot) => fromSlot(slot, \"interrupted\", message), context);\n\t\t},\n\t},\n\tabort: async (task, runtime, context) => {\n\t\tconst call = await readCall(runtime, task.input, context);\n\t\t// Abandoned after a restart (`TaskOptions.abandonOnRestart`): say whether the call may have run.\n\t\tconst [code, message] =\n\t\t\ttask.abortReason !== \"restart\"\n\t\t\t\t? [\"aborted\", `Tool ${call.name} was aborted`]\n\t\t\t\t: task.state.checkpoint.phase === \"execute\"\n\t\t\t\t\t? [\"interrupted\", `Tool ${call.name} was interrupted by a restart and may have partially run`]\n\t\t\t\t\t: [\"abandoned\", `Tool ${call.name} was not started: its caller ended with a restart`];\n\t\tconst ending = { status: \"aborted\" } as const;\n\t\tawait settle(runtime, task.input, call, ending, (slot) => fromSlot(slot, code, message), context);\n\t},\n});\n\n/** The called tool: among the tools the model is offered for a model-issued call, else among those tools may call. */\nasync function resolveTool(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tname: string,\n\tcontext: Context,\n): Promise<ToolRegistration | undefined> {\n\tconst agent = await runtime.agent(context);\n\treturn (input.kind === \"model\" ? agent.tools : agent.callable).find((tool) => tool.name === name);\n}\n\n/** The call: from the input for a nested call, which hooks see with its parent, else from the assistant entry. */\nasync function readCall(runtime: Runtime, input: ToolTaskInput, context: Context): Promise<ToolHookCall> {\n\tif (input.kind === \"nested\") return { ...input.call, parent: { taskId: input.parent, callId: input.parentCallId } };\n\tconst entry = await runtime.entry(AssistantEntry, input.assistant, context);\n\tconst message = entry?.model?.[0];\n\tconst call =\n\t\tmessage?.role === \"assistant\"\n\t\t\t? message.content.find(\n\t\t\t\t\t(content): content is ToolCall => content.type === \"toolCall\" && content.id === input.callId,\n\t\t\t\t)\n\t\t\t: undefined;\n\tif (call === undefined) throw new Error(`Entry ${input.assistant} has no tool call ${input.callId}`);\n\treturn call;\n}\n\n/** Arguments, or why they are invalid. */\ntype Checked = { readonly args: JsonObject } | { readonly error: string };\n\n/** The call's arguments as repaired by the tool; a throwing repair makes them invalid. */\nfunction prepare(tool: ToolRegistration, args: JsonObject): Checked {\n\tif (tool.prepareArguments === undefined) return { args };\n\ttry {\n\t\treturn { args: tool.prepareArguments(args) as JsonObject };\n\t} catch (error) {\n\t\treturn { error: errorMessage(error) };\n\t}\n}\n\n/** Arguments validated and coerced against the implementation's schema. */\nfunction validate(tool: ToolRegistration, call: ToolCall, args: JsonObject): Checked {\n\ttry {\n\t\treturn { args: validateToolArguments(tool, { ...call, arguments: args }) as JsonObject };\n\t} catch (error) {\n\t\treturn { error: errorMessage(error) };\n\t}\n}\n\nfunction invalid(message: string): ToolExecutionResult {\n\treturn harnessError(\"invalid_arguments\", message);\n}\n\n/** What a running tool reported through its api: output, the last details, and diagnostics. */\ntype Reported = {\n\treadonly output: OutputBuffer;\n\treadonly limits: OutputLimits;\n\treadonly diagnostics: ToolDiagnostic[];\n\tdetails: JsonValue | undefined;\n};\n\n/** Execute with the resolved implementation, then settle its result. */\nasync function run(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tcall: ToolHookCall,\n\ttool: ToolRegistration,\n\targs: JsonObject,\n\tcontext: Context,\n): Promise<void> {\n\tconst limits: OutputLimits = {\n\t\tmaxBytes: tool.outputLimits?.maxBytes ?? DEFAULT_MAX_BYTES,\n\t\tmaxLines: tool.outputLimits?.maxLines ?? DEFAULT_MAX_LINES,\n\t\tretain: tool.outputLimits?.retain ?? \"head\",\n\t};\n\tconst reported: Reported = { output: new OutputBuffer(limits), limits, diagnostics: [], details: undefined };\n\tconst streams = input.kind === \"model\" || input.progress !== false;\n\tconst progress = publishProgress(runtime, reported, streams, context);\n\t/** Nested call admissions this invocation started; cleanup waits for them, so it sees every nested call. */\n\tconst admissions: Promise<unknown>[] = [];\n\t// A caller that can rerun reattaches to its nested calls and child tasks after a restart; any other caller never\n\t// resumes, so they are abandoned (`TaskOptions.abandonOnRestart`).\n\tconst resumes = tool.replay === \"safe\";\n\t/** Default keys: the order of this invocation's calls, so a rerun that calls in the same order reattaches. */\n\tlet sequence = 0;\n\t/** This attempt's commit of the `MADE_NESTED_CALLS` memo. */\n\tlet madeNestedMemo: Promise<unknown> | undefined;\n\tlet ended = false;\n\tconst assertLive = (): void => {\n\t\tif (ended) throw new Error(`Tool call ${call.id} has settled`);\n\t};\n\tconst api: Omit<ToolExecutionApi, \"env\"> = {\n\t\ttaskId: runtime.taskId,\n\t\tconversationId: runtime.conversationId,\n\t\tcallId: call.id,\n\t\tregistry: runtime.registry,\n\t\tagent: runtime.agent,\n\t\tmodels: runtime.models,\n\t\toutput: (chunk, skipped) => {\n\t\t\tassertLive();\n\t\t\tif (reported.output.push(chunk, skipped)) progress.mark();\n\t\t},\n\t\toutputWindow:\n\t\t\tlimits.retain === \"tail\"\n\t\t\t\t? {\n\t\t\t\t\t\tmaxBytes: limits.maxBytes,\n\t\t\t\t\t\tmaxLines: limits.maxLines,\n\t\t\t\t\t\tminIntervalMs: runtime.settings.progress.outputIntervalMs,\n\t\t\t\t\t\tbytesPerSecond: PROGRESS_BYTES_PER_SECOND,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\tretainedOutput: () => {\n\t\t\tassertLive();\n\t\t\tconst retained = reported.output.snapshot();\n\t\t\treturn { text: retained.text, truncated: retained.droppedBytes > 0 };\n\t\t},\n\t\tdiagnostic: (diagnostic) => {\n\t\t\tassertLive();\n\t\t\treported.diagnostics.push(copyJson(diagnostic, { omitUndefinedProperties: true }) as ToolDiagnostic);\n\t\t\tprogress.mark();\n\t\t},\n\t\tdetails: async (value, detailsContext) => {\n\t\t\tassertLive();\n\t\t\tdetailsContext.abortSignal?.throwIfAborted();\n\t\t\treported.details = copyJson(value, { omitUndefinedProperties: true });\n\t\t\tconst committed = progress.markAndWait();\n\t\t\t// Cancelling the wait leaves the update in place; the commit's own outcome stays observed.\n\t\t\tcommitted.catch(() => {});\n\t\t\treturn awaitWithContext(committed, detailsContext);\n\t\t},\n\t\tcommit: async (change, commitContext) => {\n\t\t\tlet result: Awaited<ReturnType<typeof change>> | undefined;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tresult = await change(tx);\n\t\t\t\treturn undefined;\n\t\t\t}, commitContext);\n\t\t\treturn result as Awaited<ReturnType<typeof change>>;\n\t\t},\n\t\tmemo: runtime.memo,\n\t\tcreateTask: async <I, S extends { phase: string }, R, H extends object>(\n\t\t\ttask: Task<I, S, R, H>,\n\t\t\tinput: I,\n\t\t\toptions: Omit<TaskOptions, \"conversationId\">,\n\t\t\ttaskContext: Context,\n\t\t): Promise<TaskId<R>> => {\n\t\t\tconst child = options.ownership.kind === \"task\" && !resumes ? { abandonOnRestart: true, ...options } : options;\n\t\t\tlet id: TaskId<R> | undefined;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tid = await tx.createTask(task, input, child);\n\t\t\t\treturn undefined;\n\t\t\t}, taskContext);\n\t\t\treturn id!;\n\t\t},\n\t\tgetTask: runtime.getTask,\n\t\twaitForTask: runtime.waitForTask,\n\t\tconversation: runtime.conversation,\n\t\tsnapshot: runtime.snapshot,\n\t\tsnapshotAsOf: runtime.snapshotAsOf,\n\t\twatchDoc: runtime.watchDoc,\n\t\texecuteTool: async (name, toolArgs, callContext, options = {}) => {\n\t\t\tassertLive();\n\t\t\tconst key = options.key ?? String(++sequence);\n\t\t\tif (options.key !== undefined) checkKey(options.key);\n\t\t\t// The memo first, once per attempt; a failed one is tried again by the next call.\n\t\t\tmadeNestedMemo ??= runtime.memo(MADE_NESTED_CALLS, true, callContext).catch((error: unknown) => {\n\t\t\t\tmadeNestedMemo = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\t// Registered now, so cleanup waits for it.\n\t\t\tconst admission = madeNestedMemo.then(() =>\n\t\t\t\tstartNestedCall(\n\t\t\t\t\truntime,\n\t\t\t\t\tcall.id,\n\t\t\t\t\tname,\n\t\t\t\t\ttoolArgs,\n\t\t\t\t\t{ key, progress: options.progress, abandonOnRestart: !resumes },\n\t\t\t\t\tcallContext,\n\t\t\t\t),\n\t\t\t);\n\t\t\tadmissions.push(admission);\n\t\t\tconst id = await admission;\n\t\t\tconst settled = await runtime.waitForTask(id, callContext);\n\t\t\tconst stored = (await runtime.snapshot(NestedCallDoc, runtime.taskId, key, callContext))?.result;\n\t\t\t// A copy the tool may change; a nested call the scheduler faulted or orphaned stored none.\n\t\t\treturn stored === undefined\n\t\t\t\t? fallbackResult(id, name, settled.state.outcome)\n\t\t\t\t: (copyJson(stored as unknown as JsonValue) as unknown as NestedToolExecutionResult);\n\t\t},\n\t};\n\n\tlet result: ToolExecutionResult;\n\tlet ending = COMPLETED;\n\t// Execution time of this attempt; a rerun after recovery measures only itself.\n\tlet durationMs: number | undefined;\n\ttry {\n\t\t// Built for this call, so a rerun after recovery gets the conversation's environment at that time.\n\t\tconst env = await runtime.env(context);\n\t\tconst startedAt = performance.now();\n\t\ttry {\n\t\t\tresult = await tool.execute(args, { ...api, env }, context);\n\t\t} finally {\n\t\t\tdurationMs = Math.round(performance.now() - startedAt);\n\t\t}\n\t} catch (error) {\n\t\tif (runtime.signal.aborted) {\n\t\t\tended = true;\n\t\t\tfor (const waiter of await progress.stop()) waiter.reject(error);\n\t\t\tthrow error;\n\t\t}\n\t\tresult = { isError: true, diagnostics: [toolDiagnostic(\"tool_error\", errorMessage(error))] };\n\t\t// A throw, from `execute()` or from building the environment, ends the task `failed`, which cancels what the call\n\t\t// owned; it no longer supervises it. The error text is already in the result.\n\t\tending = { status: \"failed\", message: `Tool ${call.name} threw` };\n\t}\n\tended = true;\n\t// No admission starts after `ended`; let those underway commit, so settlement aborts and lists their calls.\n\tawait Promise.allSettled(admissions);\n\treported.output.end();\n\t// Details still waiting for a progress commit settle with the terminal commit, the final flush.\n\tconst pending = await progress.stop();\n\ttry {\n\t\tconst settled = await finalResult(runtime, input, call, tool, result, reported, context);\n\t\tawait settle(runtime, input, call, ending, () => settled, context, durationMs);\n\t} catch (error) {\n\t\tfor (const waiter of pending) waiter.reject(error);\n\t\tthrow error;\n\t}\n\tfor (const waiter of pending) waiter.resolve();\n}\n\n/**\n * Throttled commits of what the tool reported into its slot, in `pi.live.tools` or `pi.live.nestedTools`, each writing\n * only what changed since the last one; none when `enabled` is false.\n */\nfunction publishProgress(runtime: Runtime, reported: Reported, enabled: boolean, context: Context): Progress {\n\tlet written = { text: \"\", details: undefined as JsonValue | undefined, diagnostics: 0 };\n\treturn new Progress(\n\t\tasync () => {\n\t\t\tif (!enabled) return 0;\n\t\t\t// Capture everything synchronously: the tool keeps reporting while the commit is in flight.\n\t\t\tconst snapshot = reported.output.snapshot();\n\t\t\tconst current = { text: snapshot.text, details: reported.details, diagnostics: reported.diagnostics.length };\n\t\t\tconst added = reported.diagnostics.slice(written.diagnostics, current.diagnostics);\n\t\t\tconst detailsChanged = current.details !== written.details;\n\t\t\t// What the commit writes, as Chord diffs the string: an append, a trim plus an append of what follows the shared\n\t\t\t// part, or the whole window when its bounded overlap search finds nothing.\n\t\t\tlet bytes = 0;\n\t\t\tif (snapshot.text !== written.text) {\n\t\t\t\tconst shared = snapshot.text.startsWith(written.text)\n\t\t\t\t\t? written.text.length\n\t\t\t\t\t: overlap(written.text, snapshot.text, 65_536);\n\t\t\t\tbytes += utf8ByteLength(snapshot.text.slice(shared));\n\t\t\t}\n\t\t\tif (detailsChanged) bytes += utf8ByteLength(JSON.stringify(current.details ?? null));\n\t\t\tif (added.length > 0) bytes += utf8ByteLength(JSON.stringify(added));\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\tif (slot === undefined) return undefined;\n\t\t\t\t// REMINDER: assign `output` as one string field. Chord then diffs it into an append, or a trim plus an\n\t\t\t\t// append for a sliding tail; replacing the slot object would record the whole window on every commit.\n\t\t\t\tif ((slot.output ?? \"\") !== snapshot.text) slot.output = snapshot.text;\n\t\t\t\tif (snapshot.droppedBytes > 0) slot.droppedBytes = snapshot.droppedBytes;\n\t\t\t\tif (snapshot.droppedLines > 0) slot.droppedLines = snapshot.droppedLines;\n\t\t\t\t// Diff details leaf by leaf and append new diagnostics, so each commit writes only what changed.\n\t\t\t\tif (detailsChanged && current.details !== undefined) {\n\t\t\t\t\tassignJson(slot as unknown as Record<string, JsonValue>, \"details\", current.details);\n\t\t\t\t}\n\t\t\t\tif (added.length > 0) {\n\t\t\t\t\tif (slot.diagnostics === undefined) slot.diagnostics = [];\n\t\t\t\t\tfor (const diagnostic of added) slot.diagnostics.push(diagnostic);\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t}, context);\n\t\t\twritten = current;\n\t\t\treturn bytes;\n\t\t},\n\t\t(error) => {\n\t\t\t// Rejections after an abort mark or close are expected; the committed state stays consistent.\n\t\t\tif (!runtime.signal.aborted) runtime.report(error);\n\t\t},\n\t\truntime.settings.progress.outputIntervalMs,\n\t);\n}\n\n/**\n * The settled result: the tool's result with the retained output and last details as fallbacks, its diagnostics after\n * those reported through the api, `afterTool` applied, explicit text bounded, and `structuredOutput` checked against the\n * tool's schema, with the Harness's diagnostics last. A nested call whose `structuredOutput` breaks the contract gets an\n * error result without it; a model-issued call only loses it, and the break is reported to the host.\n */\nasync function finalResult(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tcall: ToolHookCall,\n\ttool: ToolRegistration,\n\tresult: ToolExecutionResult,\n\treported: Reported,\n\tcontext: Context,\n): Promise<ToolExecutionResult> {\n\tconst harness: ToolDiagnostic[] = [];\n\tconst retained = result.output === undefined ? reported.output.snapshot() : undefined;\n\tconst output: Content =\n\t\tretained === undefined ? result.output! : retained.text === \"\" ? [] : [{ type: \"text\", text: retained.text }];\n\tlet final: ToolExecutionResult = {\n\t\t...result,\n\t\toutput,\n\t\tdetails: result.details === undefined ? reported.details : result.details,\n\t\tdiagnostics: [...reported.diagnostics, ...(result.diagnostics ?? [])],\n\t};\n\tawait runtime.hooks.each(\"afterTool\", async (hook) => {\n\t\tfinal = (await hook(call, final, runtime, context)) ?? final;\n\t});\n\t// The retained output's truncation applies only while afterTool kept that output.\n\tif (retained !== undefined && retained.droppedBytes > 0 && final.output === output) {\n\t\tharness.push(truncated(retained, reported.limits.retain));\n\t}\n\tconst bounded = boundContent(final.output ?? [], reported.limits);\n\tif (bounded.droppedBytes > 0) harness.push(truncated(bounded, reported.limits.retain));\n\tconst broken = structuredOutputError(tool, final);\n\tif (broken !== undefined) {\n\t\tconst { structuredOutput: _dropped, ...rest } = final;\n\t\tif (input.kind === \"nested\") {\n\t\t\tfinal = { ...rest, isError: true };\n\t\t\tharness.push(toolDiagnostic(\"invalid_structured_output\", broken));\n\t\t} else {\n\t\t\t// The model never sees structured output, so its call stands; the host learns of the broken tool.\n\t\t\tfinal = rest;\n\t\t\truntime.report(new Error(broken));\n\t\t}\n\t}\n\t// Programs get the tool's own value: without a schema, its output. The model reads only `output`, so model-issued\n\t// calls skip both.\n\tif (input.kind === \"nested\" && tool.structuredOutputSchema === undefined) {\n\t\tfinal = { ...final, structuredOutput: outputValue(bounded.content) as JsonValue };\n\t}\n\t// A schema tool's error result without structured output has its text only in the output, which programs never\n\t// get: it becomes an error diagnostic, as a thrown error's message does, unless one says what went wrong already.\n\tif (\n\t\tinput.kind === \"nested\" &&\n\t\ttool.structuredOutputSchema !== undefined &&\n\t\tfinal.isError === true &&\n\t\tfinal.structuredOutput === undefined &&\n\t\t![...(final.diagnostics ?? []), ...harness].some((diagnostic) => diagnostic.severity === \"error\")\n\t) {\n\t\tconst text = bounded.content.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n\t\tif (text !== \"\") harness.push(toolDiagnostic(\"tool_error\", text));\n\t}\n\treturn { ...final, output: bounded.content, diagnostics: [...(final.diagnostics ?? []), ...harness] };\n}\n\nconst structuredValidators = new WeakMap<object, ReturnType<typeof Compile>>();\n\n/** Why a result's `structuredOutput` breaks the tool's contract, or `undefined` when it keeps it. */\nfunction structuredOutputError(tool: ToolRegistration, result: ToolExecutionResult): string | undefined {\n\tconst schema = tool.structuredOutputSchema;\n\tconst value = result.structuredOutput;\n\tif (schema === undefined) {\n\t\treturn value === undefined\n\t\t\t? undefined\n\t\t\t: `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`;\n\t}\n\tif (value === undefined) {\n\t\treturn result.isError === true ? undefined : `Tool ${tool.name} returned no structuredOutput`;\n\t}\n\tlet validator = structuredValidators.get(schema);\n\tif (validator === undefined) {\n\t\tvalidator = Compile(schema);\n\t\tstructuredValidators.set(schema, validator);\n\t}\n\tif (validator.Check(value)) return undefined;\n\tconst [first] = validator.Errors(value);\n\tconst path = first?.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\") || \"root\";\n\treturn `Tool ${tool.name} returned structuredOutput that does not match its schema: ${path}: ${first?.message ?? \"invalid\"}`;\n}\n\n/**\n * Commit the tool's terminal state and mark its slot done. A model-issued call appends its result entry and ends with\n * the entry ID; a nested call writes its result to the caller's `NestedCallDoc`, records its usage, and ends with a\n * small receipt. Nested calls this call left running are aborted first, so they report into their slots before the\n * slots below the call leave `pi.live`. `build` receives the slot so interruption and abort can report the durable\n * partial output.\n */\nasync function settle(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tcall: ToolHookCall,\n\tending: Ending,\n\tbuild: (slot: Readonly<ToolSlot | NestedToolSlot> | undefined) => ToolExecutionResult,\n\tcontext: Context,\n\tdurationMs?: number,\n): Promise<void> {\n\t// A crash in between leaves the call in `execute`: a safe rerun reattaches to the calls, an interruption ends here.\n\t// Every live nested call the task owns, also those an earlier attempt made and this one never called again.\n\tconst nestedIds = (await runtime.ownedTasks(context))\n\t\t.filter((record) => record.kind === ToolTask.definition.name && (record.input as ToolTaskInput).kind === \"nested\")\n\t\t.map((record) => record.id);\n\t// Read before the settling commit: no admission starts after `ended`, and those underway were awaited.\n\tconst madeNested = (await runtime.memo(MADE_NESTED_CALLS, context)) === true;\n\t// Mark them all before waiting for any: one may run until a sibling is cancelled.\n\tawait Promise.all(nestedIds.map((id) => runtime.abortOwned(id, context)));\n\tawait runtime.commit(async (tx) => {\n\t\tconst conversationId = runtime.conversationId;\n\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\tconst slot = toolSlot(live, runtime.taskId);\n\t\tconst result = build(slot);\n\t\tlet settled: ToolTaskResult;\n\t\tif (input.kind === \"nested\") {\n\t\t\tconst nested = nestedResult(runtime.taskId, result, durationMs);\n\t\t\tif (nested.usage !== undefined) await recordUsage(tx, conversationId, \"tools\", call.name, nested.usage);\n\t\t\t// The caller is never terminal before its owned nested calls, so its document is open; another task in it is a\n\t\t\t// bug, not a race.\n\t\t\tconst state = await tx.doc(NestedCallDoc, input.parent, input.key, null);\n\t\t\tif (state.taskId !== runtime.taskId) throw new Error(`Nested call ${call.id} is not in its caller's index`);\n\t\t\tstate.result = nested as unknown as Draft<JsonRepresentation<NestedToolExecutionResult>>;\n\t\t\tif (slot !== undefined && \"parentTaskId\" in slot) {\n\t\t\t\tfinishSlot(slot);\n\t\t\t\tslot.summary = summaryOf(nested, result.output ?? []);\n\t\t\t}\n\t\t\tsettled = { kind: \"nested\" };\n\t\t} else {\n\t\t\tconst timing = { timestamp: runtime.now(), durationMs };\n\t\t\tconst entry = await appendToolResult(tx, conversationId, call, result, timing);\n\t\t\tif (slot !== undefined && !(\"parentTaskId\" in slot)) {\n\t\t\t\tfinishSlot(slot);\n\t\t\t\tslot.entry = entry.id;\n\t\t\t}\n\t\t\t// Tools build control objects freely; drop keys set to undefined so the task result is strict JSON.\n\t\t\tconst control =\n\t\t\t\tresult.control === undefined || ending.status !== \"completed\"\n\t\t\t\t\t? {}\n\t\t\t\t\t: { control: copyJson(result.control as JsonValue, { omitUndefinedProperties: true }) as ToolControl };\n\t\t\tsettled = { kind: \"model\", entryId: entry.id, ...control };\n\t\t}\n\t\t// A call that made no nested calls, in any attempt, has no slots below it; skipping the scan keeps many leaves\n\t\t// linear. Committed before the read: no nested call is admitted after `ended`.\n\t\tif (madeNested) removeNestedSlots(live, runtime.taskId);\n\t\tif (ending.status === \"aborted\") return { status: \"terminal\", outcome: { status: \"aborted\", result: settled } };\n\t\tif (ending.status === \"failed\") {\n\t\t\tconst error = { message: ending.message };\n\t\t\treturn { status: \"terminal\", outcome: { status: \"failed\", error, result: settled } };\n\t\t}\n\t\treturn { status: \"terminal\", outcome: { status: \"completed\", result: settled } };\n\t}, context);\n}\n\n/**\n * A nested call's result, as stored and returned: strict JSON, without `output`, which only the model reads, and\n * without `control`, which only model-issued calls apply.\n */\nfunction nestedResult(\n\ttaskId: TaskId,\n\tresult: ToolExecutionResult,\n\tdurationMs: number | undefined,\n): NestedToolExecutionResult {\n\tconst nested = {\n\t\ttaskId,\n\t\tstructuredOutput: result.structuredOutput,\n\t\tisError: result.isError ?? false,\n\t\tdetails: result.details,\n\t\tdiagnostics: result.diagnostics ?? [],\n\t\tusage: result.usage,\n\t\tdurationMs,\n\t};\n\treturn copyJson(nested as unknown as JsonValue, {\n\t\tomitUndefinedProperties: true,\n\t}) as unknown as NestedToolExecutionResult;\n}\n\n/**\n * Create nested call `key` of the call `parentCallId` in one commit: its tool task, owned by the calling task, its slot,\n * and its `NestedCallDoc`. A key already made returns that call's task when it names the same tool and arguments.\n */\nasync function startNestedCall(\n\truntime: Runtime,\n\tparentCallId: string,\n\tname: string,\n\targs: JsonObject,\n\toptions: { readonly key: string; readonly progress: boolean | undefined; readonly abandonOnRestart: boolean },\n\tcontext: Context,\n): Promise<TaskId<ToolTaskResult>> {\n\tconst key = options.key;\n\tconst call: ToolCall = {\n\t\ttype: \"toolCall\",\n\t\tid: `${parentCallId}/${key}`,\n\t\tname,\n\t\targuments: copyJson(args, { omitUndefinedProperties: true }) as JsonObject,\n\t};\n\tlet id: TaskId<ToolTaskResult> | undefined;\n\tawait runtime.commit(async (tx) => {\n\t\t// Opened, or created empty for a key not made yet.\n\t\tconst state = await tx.doc(NestedCallDoc, runtime.taskId, key, null);\n\t\tconst existing = state.taskId;\n\t\tif (existing !== undefined) {\n\t\t\tconst input = (await tx.task(existing))?.input as ToolTaskInput | undefined;\n\t\t\tconst same =\n\t\t\t\tinput?.kind === \"nested\" &&\n\t\t\t\tinput.call.name === name &&\n\t\t\t\tjsonEqual(input.call.arguments as JsonValue, call.arguments as JsonValue);\n\t\t\tif (!same) throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);\n\t\t\tid = existing as TaskId<ToolTaskResult>;\n\t\t\treturn undefined;\n\t\t}\n\t\tconst input: ToolTaskInput = {\n\t\t\tkind: \"nested\",\n\t\t\tparent: runtime.taskId,\n\t\t\tparentCallId,\n\t\t\tkey,\n\t\t\tcall,\n\t\t\t...(options.progress === false ? { progress: false } : {}),\n\t\t};\n\t\tconst created = await tx.createTask(ToolTask, input, {\n\t\t\townership: { kind: \"task\", taskId: runtime.taskId },\n\t\t\tabandonOnRestart: options.abandonOnRestart,\n\t\t});\n\t\tstate.taskId = created;\n\t\tconst live = await tx.doc(LiveDoc, runtime.conversationId);\n\t\tlive.nestedTools ??= [];\n\t\tconst slot: NestedToolSlot = {\n\t\t\tcallId: call.id,\n\t\t\tparentCallId,\n\t\t\tparentTaskId: runtime.taskId,\n\t\t\tname,\n\t\t\ttaskId: created,\n\t\t\targuments: call.arguments as JsonObject,\n\t\t\tstatus: \"pending\",\n\t\t};\n\t\tlive.nestedTools.push(slot as Draft<NestedToolSlot>);\n\t\tid = created;\n\t\treturn undefined;\n\t}, context);\n\treturn id!;\n}\n\n/**\n * What programs get of a tool's output when it declares no schema: one text item as its string, one image as itself,\n * nothing as `\"\"`, and anything else as the content list.\n */\nfunction outputValue(output: Content): string | ImageContent | Content {\n\tif (output.length === 0) return \"\";\n\tif (output.length > 1) return output;\n\tconst [only] = output;\n\treturn only!.type === \"text\" ? only!.text : only!;\n}\n\n/** What the caller gets for a nested call without a stored result: one the scheduler faulted or orphaned. */\nfunction fallbackResult(taskId: TaskId, name: string, outcome: TaskOutcome<ToolTaskResult>): NestedToolExecutionResult {\n\tconst message =\n\t\toutcome.status === \"faulted\"\n\t\t\t? `Tool ${name} failed: ${outcome.error.message}`\n\t\t\t: outcome.status === \"orphaned\"\n\t\t\t\t? `Tool ${name} could not resume: ${outcome.reason}`\n\t\t\t\t: `Tool ${name} ended without a result`;\n\tconst error = harnessError(outcome.status, message);\n\treturn { taskId, isError: true, diagnostics: error.diagnostics ?? [] };\n}\n\n/**\n * How a tool task ends; the result entry is appended either way. `failed` (execution threw or was interrupted)\n * records cancellation intent for the conversations the call owns; a result with `isError` still completes.\n */\ntype Ending = { readonly status: \"completed\" | \"aborted\" } | { readonly status: \"failed\"; readonly message: string };\n\nconst COMPLETED: Ending = { status: \"completed\" };\n\n/** An error result from the slot's durable partial output, details, and diagnostics. */\nfunction fromSlot(\n\tslot: Readonly<ToolSlot | NestedToolSlot> | undefined,\n\tcode: string,\n\tmessage: string,\n): ToolExecutionResult {\n\tconst diagnostics = [...(slot?.diagnostics ?? [])];\n\tconst droppedBytes = slot?.droppedBytes ?? 0;\n\tif (droppedBytes > 0) diagnostics.push(truncated({ droppedBytes, droppedLines: slot?.droppedLines ?? 0 }));\n\tdiagnostics.push(toolDiagnostic(code, message));\n\treturn {\n\t\toutput: slot?.output === undefined || slot.output === \"\" ? [] : [{ type: \"text\", text: slot.output }],\n\t\tisError: true,\n\t\t...(slot?.details === undefined ? {} : { details: slot.details }),\n\t\tdiagnostics,\n\t};\n}\n\n/** An error result the Harness writes itself: no content and one `error` diagnostic with `code`. */\nexport function harnessError(code: string, message: string): ToolExecutionResult {\n\treturn { output: [], isError: true, diagnostics: [toolDiagnostic(code, message)] };\n}\n\nfunction toolDiagnostic(code: string, message: string): ToolDiagnostic {\n\treturn { severity: \"error\", code, message };\n}\n\n/** The Harness's truncation diagnostic; `retain` is unknown when rebuilt from a slot after recovery. */\nfunction truncated(\n\tdropped: { readonly droppedLines: number; readonly droppedBytes: number },\n\tretain?: \"head\" | \"tail\",\n): ToolDiagnostic {\n\tconst kept = retain === undefined ? \"\" : ` to its ${retain === \"head\" ? \"beginning\" : \"end\"}`;\n\treturn {\n\t\tseverity: \"warn\",\n\t\tcode: \"truncated\",\n\t\tmessage: `Output truncated${kept}: ${dropped.droppedLines} lines, ${dropped.droppedBytes} bytes dropped`,\n\t};\n}\n\n/** Error text a nested call's summary keeps. */\nconst MAX_SUMMARY_ERROR_CHARS = 500;\n\n/** How a nested call ended, for its slot: error text, from its diagnostics or else its `output`, bounded. */\nfunction summaryOf(result: NestedToolExecutionResult, output: Content): NestedToolSummary {\n\tconst error = result.isError ? errorTextOf(result, output).slice(0, MAX_SUMMARY_ERROR_CHARS) : \"\";\n\treturn {\n\t\tisError: result.isError,\n\t\t...(result.durationMs === undefined ? {} : { durationMs: result.durationMs }),\n\t\t...(result.usage === undefined ? {} : { usage: result.usage }),\n\t\t...(error === \"\" ? {} : { error }),\n\t};\n}\n\n/** The error messages of a nested result, else the text items of its output, joined with newlines. */\nfunction errorTextOf(result: NestedToolExecutionResult, output: Content): string {\n\tconst errors = result.diagnostics.filter((diagnostic) => diagnostic.severity === \"error\");\n\tif (errors.length > 0) return errors.map((diagnostic) => diagnostic.message).join(\"\\n\");\n\treturn output.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n}\n\n/**\n * Append a `pi.tool-result` entry. The content ends with the rendered diagnostics, so the stored message is exactly\n * what the model sees; `data` keeps the structured list. A result's usage is added to `pi.usage` in the same commit.\n */\nexport async function appendToolResult(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tcall: ToolCall,\n\tresult: ToolExecutionResult,\n\tmeta: { readonly timestamp: number; readonly durationMs?: number },\n): Promise<TypedEntry<{ diagnostics: ToolDiagnostic[] }>> {\n\tconst { timestamp, durationMs } = meta;\n\tconst diagnostics = [...(result.diagnostics ?? [])];\n\tconst content: Content = [...(result.output ?? [])];\n\tif (diagnostics.length > 0) content.push({ type: \"text\", text: renderDiagnostics(diagnostics) });\n\tconst message = {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: call.id,\n\t\ttoolName: call.name,\n\t\tcontent,\n\t\t...(result.details === undefined ? {} : { details: result.details }),\n\t\t...(result.usage === undefined ? {} : { usage: result.usage }),\n\t\tisError: result.isError ?? false,\n\t\t...(durationMs === undefined ? {} : { durationMs }),\n\t\ttimestamp,\n\t} as ToolResultMessage;\n\tif (result.usage !== undefined) await recordUsage(tx, conversationId, \"tools\", call.name, result.usage);\n\treturn tx.appendEntry(ToolResultEntry, conversationId, { model: [message], data: { diagnostics } });\n}\n\nfunction renderDiagnostics(diagnostics: readonly ToolDiagnostic[]): string {\n\treturn `<harness>\\n${diagnostics.map((diagnostic) => `[${diagnostic.severity}] ${diagnostic.message}`).join(\"\\n\")}\\n</harness>`;\n}\n\n/**\n * Bound the text of result content. When the joined text exceeds the limits, the text items are replaced by one bounded\n * item at the position of the first (head) or last (tail) text item; other content is kept.\n */\nfunction boundContent(\n\tcontent: Content,\n\tlimits: OutputLimits,\n): { content: Content; droppedBytes: number; droppedLines: number } {\n\tconst texts = content.filter((item): item is TextContent => item.type === \"text\");\n\tconst bounded = boundOutput(texts.map((item) => item.text).join(\"\"), limits);\n\tif (bounded.droppedBytes === 0) return { content, droppedBytes: 0, droppedLines: 0 };\n\tconst keep = limits.retain === \"head\" ? texts[0] : texts.at(-1);\n\tconst result: Content = [];\n\tfor (const item of content) {\n\t\tif (item.type !== \"text\") result.push(item);\n\t\telse if (item === keep) result.push({ ...item, text: bounded.text });\n\t}\n\treturn { content: result, droppedBytes: bounded.droppedBytes, droppedLines: bounded.droppedLines };\n}\n\n/**\n * Explicit nested call keys are path segments of the call ID, so IDs of different nested calls never collide, and are\n * never plain positive integers, which default keys use. `__proto__` stays reserved, as it was when keys indexed a JSON object.\n */\nfunction checkKey(key: string): void {\n\tif (key === \"\" || key.includes(\"/\") || key === \"__proto__\" || /^[1-9][0-9]*$/.test(key)) {\n\t\tthrow new Error(\n\t\t\t`Nested call key ${JSON.stringify(key)} must be non-empty, without \"/\", not \"__proto__\", and not a positive integer`,\n\t\t);\n\t}\n}\n\n/** Structural JSON equality; object key order does not matter. */\nfunction jsonEqual(a: JsonValue, b: JsonValue): boolean {\n\tif (a === b) return true;\n\tif (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n\tif (Array.isArray(a) || Array.isArray(b)) {\n\t\treturn (\n\t\t\tArray.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => jsonEqual(item, b[i]!))\n\t\t);\n\t}\n\tconst keys = Object.keys(a);\n\treturn (\n\t\tkeys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && jsonEqual(a[key]!, b[key]!))\n\t);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tool.js","sourceRoot":"","sources":["../../src/harness/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,QAAQ,EAAuD,MAAM,uBAAuB,CAAC;AACpH,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AACtD,OAAO,EACN,WAAW,EACX,YAAY,EAEZ,yBAAyB,EACzB,QAAQ,GAER,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAC/E,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEhE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAatF,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EACN,aAAa,EACb,UAAU,EACV,OAAO,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KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,GAAG,CAAE,EAAE,CAAC,CAAC,GAAG,CAAE,CAAC,CAAC,CAClH,CAAC;AACH,CAAC","sourcesContent":["import { type Context, copyJson, type Draft, type JsonRepresentation, type JsonValue } from \"@earendil-works/chord\";\nimport { awaitWithContext } from \"@earendil-works/chord/context\";\nimport { overlap } from \"@earendil-works/chord/delta\";\nimport {\n\tboundOutput,\n\tOutputBuffer,\n\ttype OutputLimits,\n\tPROGRESS_BYTES_PER_SECOND,\n\tProgress,\n\ttype ProgressClock,\n} from \"@earendil-works/chord/output\";\nimport type { ImageContent, TextContent, ToolCall, ToolResultMessage } from \"@earendil-works/pi-ai\";\nimport { validateToolArguments } from \"@earendil-works/pi-ai/utils/validation\";\nimport { Compile } from \"typebox/compile\";\nimport { defineDocFamily } from \"../documents.ts\";\nimport { AssistantEntry, ToolResultEntry } from \"../entries.ts\";\nimport type { ExecutionEnv } from \"../env/index.ts\";\nimport { errorMessage } from \"../errors.ts\";\nimport { defineTask } from \"../tasks.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, utf8ByteLength } from \"../truncate.ts\";\nimport type {\n\tConversationId,\n\tEntryId,\n\tJsonObject,\n\tTask,\n\tTaskId,\n\tTaskOptions,\n\tTaskOutcome,\n\tTaskRuntime,\n\tTx,\n\tTypedEntry,\n} from \"../types.ts\";\nimport { toolExtension } from \"./agent.ts\";\nimport { assignJson } from \"./json.ts\";\nimport {\n\tclearProgress,\n\tfinishSlot,\n\tLiveDoc,\n\ttype NestedToolSlot,\n\ttype NestedToolSummary,\n\tremoveNestedSlots,\n\ttype ToolSlot,\n\ttoolSlot,\n} from \"./live.ts\";\nimport type {\n\tNestedToolExecutionResult,\n\tToolControl,\n\tToolDiagnostic,\n\tToolExecutionApi,\n\tToolExecutionResult,\n\tToolHookCall,\n\tToolHooks,\n\tToolRegistration,\n} from \"./types.ts\";\nimport { recordUsage } from \"./usage.ts\";\nimport { optionalExtension } from \"./util.ts\";\n\n/**\n * A model-issued call, read from its assistant entry, or a nested call a running tool made through `executeTool()`,\n * whose call the input carries because no entry holds it.\n */\nexport type ToolTaskInput =\n\t| { kind: \"model\"; assistant: EntryId; callId: string }\n\t| {\n\t\t\tkind: \"nested\";\n\t\t\tparent: TaskId;\n\t\t\tparentCallId: string;\n\t\t\tkey: string;\n\t\t\tcall: ToolCall;\n\t\t\t/** `false`: commit no running output, details, or diagnostics to the slot; the result still gets them. */\n\t\t\tprogress?: false;\n\t };\n\nexport type ToolTaskCheckpoint =\n\t| { phase: \"call\" }\n\t/** Durable intent: the final arguments and the replay policy recorded before execution. */\n\t| { phase: \"execute\"; arguments: JsonObject; replay: \"safe\" | \"unsafe\" };\n\n/**\n * A model-issued call's result is its transcript entry; a nested call's result is in its caller's\n * `NestedCallDoc`, so the receipt stays small and the result retires with the caller. A version 1 task that was\n * already holding its outcome as `completing` when the Harness upgraded finishes with a version 1 result,\n * `{ entryId, control? }` without `kind`; treat a result without `kind` as a model-issued call's.\n */\nexport type ToolTaskResult = { kind: \"model\"; entryId: EntryId; control?: ToolControl } | { kind: \"nested\" };\n\n/**\n * Memo of a tool task that made a nested call, in any attempt, committed before the first admission of each attempt:\n * only then can `pi.live` hold slots below it, which settling removes. A crash between the two only costs a scan.\n */\nconst MADE_NESTED_CALLS = \"pi.tool.madeNestedCalls\";\n\n/** One nested call of a running tool: its task, and once it ended, its result. */\nexport type NestedCallState = {\n\t/** Absent only inside the commit that creates the call; a creation that fails leaves no member. */\n\ttaskId?: TaskId<ToolTaskResult>;\n\t/** Exactly what `executeTool()` returns; absent while running, and for a call the scheduler faulted or orphaned. */\n\tresult?: JsonRepresentation<NestedToolExecutionResult>;\n};\n\n/**\n * 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\n * finds the calls it already made, and the caller reads each result. Created with the nested task; the nested call's\n * terminal commit adds its result. One document per call, so no commit rewrites the others. Retires with the caller.\n */\nexport const NestedCallDoc = defineDocFamily<NestedCallState, null>({\n\tkind: \"pi.tool.nested-call\",\n\tversion: 1,\n\tscope: \"task\",\n\tfamily: true,\n\tinitial: () => ({}),\n\t// The document retires with its task.\n\tcheckpointWhen: () => false,\n});\n\ntype Runtime = TaskRuntime<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>;\ntype Content = (TextContent | ImageContent)[];\n\n/**\n * Built-in tool task: resolves the called tool among its phase agent's tools, validates, runs `beforeTool`, records intent,\n * executes, runs `afterTool`, and settles the result, all in one `call` handler so nothing separates resolution from\n * settlement. `execute` is reached only by recovery and applies the replay rule. A model-issued call settles by\n * appending its result entry; a nested call by writing its result to its caller's `NestedCallDoc`.\n */\nexport const ToolTask = defineTask<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>({\n\tname: \"pi.tool\",\n\tversion: 2,\n\tinitial: () => ({ phase: \"call\" }),\n\t// Version 1 had only model-issued calls.\n\tmigrate: (input, checkpoint) => ({\n\t\tinput: { kind: \"model\", ...(input as { assistant: EntryId; callId: string }) },\n\t\tcheckpoint: checkpoint as ToolTaskCheckpoint,\n\t}),\n\tphases: {\n\t\tcall: async (task, runtime, context) => {\n\t\t\tconst call = await readCall(runtime, task.input, context);\n\t\t\tconst tool = await resolveTool(runtime, task.input, call.name, context);\n\t\t\tif (tool === undefined) {\n\t\t\t\tconst error = harnessError(\"tool_unavailable\", `Tool ${call.name} is not available`);\n\t\t\t\treturn settle(runtime, task.input, call, COMPLETED, () => error, context);\n\t\t\t}\n\t\t\tconst prepared = prepare(tool, call.arguments as JsonObject);\n\t\t\tconst checked = \"error\" in prepared ? prepared : validate(tool, call, prepared.args);\n\t\t\tif (\"error\" in checked)\n\t\t\t\treturn settle(runtime, task.input, call, COMPLETED, () => invalid(checked.error), context);\n\t\t\tlet args = checked.args;\n\t\t\tlet block: string | undefined;\n\t\t\tawait runtime.hooks.each(\"beforeTool\", async (hook) => {\n\t\t\t\tif (block !== undefined) return;\n\t\t\t\ttry {\n\t\t\t\t\tconst decision = await hook({ ...call, arguments: args }, runtime, context);\n\t\t\t\t\tif (decision?.block !== undefined) block = decision.block;\n\t\t\t\t\telse if (decision?.arguments !== undefined) args = decision.arguments;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (runtime.signal.aborted) throw error;\n\t\t\t\t\tblock = errorMessage(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (block !== undefined) {\n\t\t\t\tconst blocked = harnessError(\"blocked\", `Tool call blocked: ${block}`);\n\t\t\t\treturn settle(runtime, task.input, call, COMPLETED, () => blocked, context);\n\t\t\t}\n\t\t\tconst validated = validate(tool, call, args);\n\t\t\tif (\"error\" in validated)\n\t\t\t\treturn settle(runtime, task.input, call, COMPLETED, () => invalid(validated.error), context);\n\t\t\t// Strict JSON: repair may set optional properties to undefined, which the slot and checkpoint cannot hold.\n\t\t\tconst final = copyJson(validated.args, { omitUndefinedProperties: true }) as JsonObject;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\tif (slot !== undefined) slot.status = \"running\";\n\t\t\t\t// A nested slot shows the arguments the call runs with, which repair, hooks, and coercion may have changed.\n\t\t\t\t// Compared with the input, which the slot got at admission: reading the draft would track every leaf.\n\t\t\t\tconst changed = task.input.kind === \"nested\" && !jsonEqual(task.input.call.arguments as JsonValue, final);\n\t\t\t\tif (changed && slot !== undefined && \"parentTaskId\" in slot) slot.arguments = final;\n\t\t\t\tconst intent = { phase: \"execute\", arguments: final, replay: tool.replay ?? \"unsafe\" } as const;\n\t\t\t\treturn { status: \"running\", checkpoint: intent };\n\t\t\t}, context);\n\t\t\tawait run(runtime, task.input, call, tool, final, context);\n\t\t},\n\t\t/** Recovery after intent: rerun only when the stored and the current policy both say `safe`. */\n\t\texecute: async (task, runtime, context) => {\n\t\t\tconst { arguments: args, replay } = task.state.checkpoint;\n\t\t\tconst call = await readCall(runtime, task.input, context);\n\t\t\tconst tool = await resolveTool(runtime, task.input, call.name, context);\n\t\t\tif (replay === \"safe\" && tool?.replay === \"safe\") {\n\t\t\t\t// The rerun reports from scratch; clear what the interrupted attempt published.\n\t\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\t\tif (slot !== undefined) clearProgress(slot);\n\t\t\t\t\treturn undefined;\n\t\t\t\t}, context);\n\t\t\t\treturn run(runtime, task.input, call, tool, args, context);\n\t\t\t}\n\t\t\tconst message = `Tool ${call.name} was interrupted and may have partially run`;\n\t\t\t// `failed` records cancellation intent, so the call's owned conversations, left unsupervised, are aborted.\n\t\t\tconst ending = { status: \"failed\", message } as const;\n\t\t\tawait settle(runtime, task.input, call, ending, (slot) => fromSlot(slot, \"interrupted\", message), context);\n\t\t},\n\t},\n\tabort: async (task, runtime, context) => {\n\t\tconst call = await readCall(runtime, task.input, context);\n\t\t// Abandoned after a restart (`TaskOptions.abandonOnRestart`): say whether the call may have run.\n\t\tconst [code, message] =\n\t\t\ttask.abortReason !== \"restart\"\n\t\t\t\t? [\"aborted\", `Tool ${call.name} was aborted`]\n\t\t\t\t: task.state.checkpoint.phase === \"execute\"\n\t\t\t\t\t? [\"interrupted\", `Tool ${call.name} was interrupted by a restart and may have partially run`]\n\t\t\t\t\t: [\"abandoned\", `Tool ${call.name} was not started: its caller ended with a restart`];\n\t\tconst ending = { status: \"aborted\" } as const;\n\t\tawait settle(runtime, task.input, call, ending, (slot) => fromSlot(slot, code, message), context);\n\t},\n});\n\n/** The called tool: among the tools the model is offered for a model-issued call, else among those tools may call. */\nasync function resolveTool(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tname: string,\n\tcontext: Context,\n): Promise<ToolRegistration | undefined> {\n\tconst agent = await runtime.agent(context);\n\treturn (input.kind === \"model\" ? agent.tools : agent.callable).find((tool) => tool.name === name);\n}\n\n/** The call: from the input for a nested call, which hooks see with its parent, else from the assistant entry. */\nasync function readCall(runtime: Runtime, input: ToolTaskInput, context: Context): Promise<ToolHookCall> {\n\tif (input.kind === \"nested\") {\n\t\tcontext.telemetry.setAttributes({\n\t\t\t\"tool.name\": input.call.name,\n\t\t\t\"tool.call_id\": input.call.id,\n\t\t});\n\t\treturn { ...input.call, parent: { taskId: input.parent, callId: input.parentCallId } };\n\t}\n\tconst entry = await runtime.entry(AssistantEntry, input.assistant, context);\n\tconst message = entry?.model?.[0];\n\tconst call =\n\t\tmessage?.role === \"assistant\"\n\t\t\t? message.content.find(\n\t\t\t\t\t(content): content is ToolCall => content.type === \"toolCall\" && content.id === input.callId,\n\t\t\t\t)\n\t\t\t: undefined;\n\tif (call === undefined) throw new Error(`Entry ${input.assistant} has no tool call ${input.callId}`);\n\tcontext.telemetry.setAttributes({\n\t\t\"tool.name\": call.name,\n\t\t\"tool.call_id\": call.id,\n\t});\n\treturn call;\n}\n\n/** Arguments, or why they are invalid. */\ntype Checked = { readonly args: JsonObject } | { readonly error: string };\n\n/** The call's arguments as repaired by the tool; a throwing repair makes them invalid. */\nfunction prepare(tool: ToolRegistration, args: JsonObject): Checked {\n\tif (tool.prepareArguments === undefined) return { args };\n\ttry {\n\t\treturn { args: tool.prepareArguments(args) as JsonObject };\n\t} catch (error) {\n\t\treturn { error: errorMessage(error) };\n\t}\n}\n\n/** Arguments validated and coerced against the implementation's schema. */\nfunction validate(tool: ToolRegistration, call: ToolCall, args: JsonObject): Checked {\n\ttry {\n\t\treturn { args: validateToolArguments(tool, { ...call, arguments: args }) as JsonObject };\n\t} catch (error) {\n\t\treturn { error: errorMessage(error) };\n\t}\n}\n\nfunction invalid(message: string): ToolExecutionResult {\n\treturn harnessError(\"invalid_arguments\", message);\n}\n\n/** What a running tool reported through its api: output, the last details, and diagnostics. */\ntype Reported = {\n\treadonly output: OutputBuffer;\n\treadonly limits: OutputLimits;\n\treadonly diagnostics: ToolDiagnostic[];\n\tdetails: JsonValue | undefined;\n};\n\n/** Execute with the resolved implementation, then settle its result. */\nasync function run(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tcall: ToolHookCall,\n\ttool: ToolRegistration,\n\targs: JsonObject,\n\tcontext: Context,\n): Promise<void> {\n\tconst limits: OutputLimits = {\n\t\tmaxBytes: tool.outputLimits?.maxBytes ?? DEFAULT_MAX_BYTES,\n\t\tmaxLines: tool.outputLimits?.maxLines ?? DEFAULT_MAX_LINES,\n\t\tretain: tool.outputLimits?.retain ?? \"head\",\n\t};\n\tconst reported: Reported = { output: new OutputBuffer(limits), limits, diagnostics: [], details: undefined };\n\tconst streams = input.kind === \"model\" || input.progress !== false;\n\tconst progress = publishProgress(runtime, reported, streams, context);\n\t/** Nested call admissions this invocation started; cleanup waits for them, so it sees every nested call. */\n\tconst admissions: Promise<unknown>[] = [];\n\t// A caller that can rerun reattaches to its nested calls and child tasks after a restart; any other caller never\n\t// resumes, so they are abandoned (`TaskOptions.abandonOnRestart`).\n\tconst resumes = tool.replay === \"safe\";\n\t/** Default keys: the order of this invocation's calls, so a rerun that calls in the same order reattaches. */\n\tlet sequence = 0;\n\t/** This attempt's commit of the `MADE_NESTED_CALLS` memo. */\n\tlet madeNestedMemo: Promise<unknown> | undefined;\n\tlet ended = false;\n\tconst assertLive = (): void => {\n\t\tif (ended) throw new Error(`Tool call ${call.id} has settled`);\n\t};\n\t/** Built for this call, below, so a rerun after recovery gets the conversation's environment at that time. */\n\tlet env: ExecutionEnv | undefined;\n\tconst api: ToolExecutionApi = {\n\t\ttaskId: runtime.taskId,\n\t\tconversationId: runtime.conversationId,\n\t\tcallId: call.id,\n\t\tregistry: runtime.registry,\n\t\tagent: runtime.agent,\n\t\tget models() {\n\t\t\treturn runtime.models;\n\t\t},\n\t\tget env() {\n\t\t\treturn env;\n\t\t},\n\t\tnow: () => runtime.now(),\n\t\toutput: (chunk, skipped) => {\n\t\t\tassertLive();\n\t\t\tif (reported.output.push(chunk, skipped)) progress.mark();\n\t\t},\n\t\toutputWindow:\n\t\t\tlimits.retain === \"tail\"\n\t\t\t\t? {\n\t\t\t\t\t\tmaxBytes: limits.maxBytes,\n\t\t\t\t\t\tmaxLines: limits.maxLines,\n\t\t\t\t\t\tminIntervalMs: runtime.settings.progress.outputIntervalMs,\n\t\t\t\t\t\tbytesPerSecond: PROGRESS_BYTES_PER_SECOND,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\tretainedOutput: () => {\n\t\t\tassertLive();\n\t\t\tconst retained = reported.output.snapshot();\n\t\t\treturn { text: retained.text, truncated: retained.droppedBytes > 0 };\n\t\t},\n\t\tdiagnostic: (diagnostic) => {\n\t\t\tassertLive();\n\t\t\treported.diagnostics.push(copyJson(diagnostic, { omitUndefinedProperties: true }) as ToolDiagnostic);\n\t\t\tprogress.mark();\n\t\t},\n\t\tdetails: async (value, detailsContext) => {\n\t\t\tassertLive();\n\t\t\tdetailsContext.abortSignal?.throwIfAborted();\n\t\t\treported.details = copyJson(value, { omitUndefinedProperties: true });\n\t\t\tconst committed = progress.markAndWait();\n\t\t\t// Cancelling the wait leaves the update in place; the commit's own outcome stays observed.\n\t\t\tcommitted.catch(() => {});\n\t\t\treturn awaitWithContext(committed, detailsContext);\n\t\t},\n\t\tcommit: async (change, commitContext) => {\n\t\t\tlet result: Awaited<ReturnType<typeof change>> | undefined;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tresult = await change(tx);\n\t\t\t\treturn undefined;\n\t\t\t}, commitContext);\n\t\t\treturn result as Awaited<ReturnType<typeof change>>;\n\t\t},\n\t\tmemo: runtime.memo,\n\t\tcreateTask: async <I, S extends { phase: string }, R, H extends object>(\n\t\t\ttask: Task<I, S, R, H>,\n\t\t\tinput: I,\n\t\t\toptions: Omit<TaskOptions, \"conversationId\">,\n\t\t\ttaskContext: Context,\n\t\t): Promise<TaskId<R>> => {\n\t\t\tconst child = options.ownership.kind === \"task\" && !resumes ? { abandonOnRestart: true, ...options } : options;\n\t\t\tlet id: TaskId<R> | undefined;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tid = await tx.createTask(task, input, child);\n\t\t\t\treturn undefined;\n\t\t\t}, taskContext);\n\t\t\treturn id!;\n\t\t},\n\t\tgetTask: runtime.getTask,\n\t\twaitForTask: runtime.waitForTask,\n\t\tconversation: runtime.conversation,\n\t\tsnapshot: runtime.snapshot,\n\t\tsnapshotAsOf: runtime.snapshotAsOf,\n\t\twatchDoc: runtime.watchDoc,\n\t\texecuteTool: async (name, toolArgs, callContext, options = {}) => {\n\t\t\tassertLive();\n\t\t\tconst key = options.key ?? String(++sequence);\n\t\t\tif (options.key !== undefined) checkKey(options.key);\n\t\t\t// The memo first, once per attempt; a failed one is tried again by the next call.\n\t\t\tmadeNestedMemo ??= runtime.memo(MADE_NESTED_CALLS, true, callContext).catch((error: unknown) => {\n\t\t\t\tmadeNestedMemo = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\t// Registered now, so cleanup waits for it.\n\t\t\tconst admission = madeNestedMemo.then(() =>\n\t\t\t\tstartNestedCall(\n\t\t\t\t\truntime,\n\t\t\t\t\tcall.id,\n\t\t\t\t\tname,\n\t\t\t\t\ttoolArgs,\n\t\t\t\t\t{ key, progress: options.progress, abandonOnRestart: !resumes },\n\t\t\t\t\tcallContext,\n\t\t\t\t),\n\t\t\t);\n\t\t\tadmissions.push(admission);\n\t\t\tconst id = await admission;\n\t\t\tconst settled = await runtime.waitForTask(id, callContext);\n\t\t\tconst stored = (await runtime.snapshot(NestedCallDoc, runtime.taskId, key, callContext))?.result;\n\t\t\t// A copy the tool may change; a nested call the scheduler faulted or orphaned stored none.\n\t\t\treturn stored === undefined\n\t\t\t\t? fallbackResult(id, name, settled.state.outcome)\n\t\t\t\t: (copyJson(stored as unknown as JsonValue) as unknown as NestedToolExecutionResult);\n\t\t},\n\t};\n\n\tlet result: ToolExecutionResult;\n\tlet ending = COMPLETED;\n\t// Execution time of this attempt; a rerun after recovery measures only itself.\n\tlet durationMs: number | undefined;\n\ttry {\n\t\tenv = await runtime.env(context);\n\t\tconst startedAt = performance.now();\n\t\ttry {\n\t\t\tresult = await tool.execute(args, api, context);\n\t\t} finally {\n\t\t\tdurationMs = Math.round(performance.now() - startedAt);\n\t\t}\n\t} catch (error) {\n\t\tif (runtime.signal.aborted) {\n\t\t\tended = true;\n\t\t\tfor (const waiter of await progress.stop()) waiter.reject(error);\n\t\t\tthrow error;\n\t\t}\n\t\tresult = { isError: true, diagnostics: [toolDiagnostic(\"tool_error\", errorMessage(error))] };\n\t\t// A throw, from `execute()` or from building the environment, ends the task `failed`, which cancels what the call\n\t\t// owned; it no longer supervises it. The error text is already in the result.\n\t\tending = { status: \"failed\", message: `Tool ${call.name} threw` };\n\t}\n\tended = true;\n\t// No admission starts after `ended`; let those underway commit, so settlement aborts and lists their calls.\n\tawait Promise.allSettled(admissions);\n\treported.output.end();\n\t// Details still waiting for a progress commit settle with the terminal commit, the final flush.\n\tconst pending = await progress.stop();\n\ttry {\n\t\tconst settled = await finalResult(runtime, input, call, tool, result, reported, context);\n\t\tawait settle(runtime, input, call, ending, () => settled, context, durationMs);\n\t} catch (error) {\n\t\tfor (const waiter of pending) waiter.reject(error);\n\t\tthrow error;\n\t}\n\tfor (const waiter of pending) waiter.resolve();\n}\n\n/**\n * The Harness clock and timers for progress pacing. After the invocation ends nothing more commits, and the clock\n * answers with the last time it read.\n */\nfunction progressClock(runtime: Runtime): ProgressClock {\n\tlet last = 0;\n\treturn {\n\t\tnow: () => {\n\t\t\ttry {\n\t\t\t\tlast = runtime.now();\n\t\t\t} catch {\n\t\t\t\t// The invocation ended.\n\t\t\t}\n\t\t\treturn last;\n\t\t},\n\t\tsetTimer: (callback, delayMs) => runtime.setTimer(callback, delayMs),\n\t};\n}\n\n/**\n * Throttled commits of what the tool reported into its slot, in `pi.live.tools` or `pi.live.nestedTools`, each writing\n * only what changed since the last one; none when `enabled` is false.\n */\nfunction publishProgress(runtime: Runtime, reported: Reported, enabled: boolean, context: Context): Progress {\n\tlet written = { text: \"\", details: undefined as JsonValue | undefined, diagnostics: 0 };\n\treturn new Progress(\n\t\tasync () => {\n\t\t\tif (!enabled) return 0;\n\t\t\t// Capture everything synchronously: the tool keeps reporting while the commit is in flight.\n\t\t\tconst snapshot = reported.output.snapshot();\n\t\t\tconst current = { text: snapshot.text, details: reported.details, diagnostics: reported.diagnostics.length };\n\t\t\tconst added = reported.diagnostics.slice(written.diagnostics, current.diagnostics);\n\t\t\tconst detailsChanged = current.details !== written.details;\n\t\t\t// What the commit writes, as Chord diffs the string: an append, a trim plus an append of what follows the shared\n\t\t\t// part, or the whole window when its bounded overlap search finds nothing.\n\t\t\tlet bytes = 0;\n\t\t\tif (snapshot.text !== written.text) {\n\t\t\t\tconst shared = snapshot.text.startsWith(written.text)\n\t\t\t\t\t? written.text.length\n\t\t\t\t\t: overlap(written.text, snapshot.text, 65_536);\n\t\t\t\tbytes += utf8ByteLength(snapshot.text.slice(shared));\n\t\t\t}\n\t\t\tif (detailsChanged) bytes += utf8ByteLength(JSON.stringify(current.details ?? null));\n\t\t\tif (added.length > 0) bytes += utf8ByteLength(JSON.stringify(added));\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\tif (slot === undefined) return undefined;\n\t\t\t\t// REMINDER: assign `output` as one string field. Chord then diffs it into an append, or a trim plus an\n\t\t\t\t// append for a sliding tail; replacing the slot object would record the whole window on every commit.\n\t\t\t\tif ((slot.output ?? \"\") !== snapshot.text) slot.output = snapshot.text;\n\t\t\t\tif (snapshot.droppedBytes > 0) slot.droppedBytes = snapshot.droppedBytes;\n\t\t\t\tif (snapshot.droppedLines > 0) slot.droppedLines = snapshot.droppedLines;\n\t\t\t\t// Diff details leaf by leaf and append new diagnostics, so each commit writes only what changed.\n\t\t\t\tif (detailsChanged && current.details !== undefined) {\n\t\t\t\t\tassignJson(slot as unknown as Record<string, JsonValue>, \"details\", current.details);\n\t\t\t\t}\n\t\t\t\tif (added.length > 0) {\n\t\t\t\t\tif (slot.diagnostics === undefined) slot.diagnostics = [];\n\t\t\t\t\tfor (const diagnostic of added) slot.diagnostics.push(diagnostic);\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t}, context);\n\t\t\twritten = current;\n\t\t\treturn bytes;\n\t\t},\n\t\t(error) => {\n\t\t\t// Rejections after an abort mark or close are expected; the committed state stays consistent.\n\t\t\tif (!runtime.signal.aborted) runtime.report(error);\n\t\t},\n\t\truntime.settings.progress.outputIntervalMs,\n\t\tprogressClock(runtime),\n\t);\n}\n\n/**\n * The settled result: the tool's result with the retained output and last details as fallbacks, its diagnostics after\n * those reported through the api, `afterTool` applied, explicit text bounded, and `structuredOutput` checked against the\n * tool's schema, with the Harness's diagnostics last. A nested call whose `structuredOutput` breaks the contract gets an\n * error result without it; a model-issued call only loses it, and the break is reported to the host.\n */\nasync function finalResult(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tcall: ToolHookCall,\n\ttool: ToolRegistration,\n\tresult: ToolExecutionResult,\n\treported: Reported,\n\tcontext: Context,\n): Promise<ToolExecutionResult> {\n\tconst harness: ToolDiagnostic[] = [];\n\tconst retained = result.output === undefined ? reported.output.snapshot() : undefined;\n\tconst output: Content =\n\t\tretained === undefined ? result.output! : retained.text === \"\" ? [] : [{ type: \"text\", text: retained.text }];\n\tlet final: ToolExecutionResult = {\n\t\t...result,\n\t\toutput,\n\t\tdetails: result.details === undefined ? reported.details : result.details,\n\t\tdiagnostics: [...reported.diagnostics, ...(result.diagnostics ?? [])],\n\t};\n\tawait runtime.hooks.each(\"afterTool\", async (hook) => {\n\t\tfinal = (await hook(call, final, runtime, context)) ?? final;\n\t});\n\t// The retained output's truncation applies only while afterTool kept that output.\n\tif (retained !== undefined && retained.droppedBytes > 0 && final.output === output) {\n\t\tharness.push(truncated(retained, reported.limits.retain));\n\t}\n\tconst bounded = boundContent(final.output ?? [], reported.limits);\n\tif (bounded.droppedBytes > 0) harness.push(truncated(bounded, reported.limits.retain));\n\tconst broken = structuredOutputError(tool, final);\n\tif (broken !== undefined) {\n\t\tconst { structuredOutput: _dropped, ...rest } = final;\n\t\tif (input.kind === \"nested\") {\n\t\t\tfinal = { ...rest, isError: true };\n\t\t\tharness.push(toolDiagnostic(\"invalid_structured_output\", broken));\n\t\t} else {\n\t\t\t// The model never sees structured output, so its call stands; the host learns of the broken tool.\n\t\t\tfinal = rest;\n\t\t\t// Only names the extension: a failed resolution leaves the report without the name.\n\t\t\tconst extension = await runtime.agent(context).then(\n\t\t\t\t(agent) => toolExtension(agent, tool.name),\n\t\t\t\t() => undefined,\n\t\t\t);\n\t\t\truntime.report(new Error(broken), { type: \"extension\", ...optionalExtension(extension) });\n\t\t}\n\t}\n\t// Programs get the tool's own value: without a schema, its output. The model reads only `output`, so model-issued\n\t// calls skip both.\n\tif (input.kind === \"nested\" && tool.structuredOutputSchema === undefined) {\n\t\tfinal = { ...final, structuredOutput: outputValue(bounded.content) as JsonValue };\n\t}\n\t// A schema tool's error result without structured output has its text only in the output, which programs never\n\t// get: it becomes an error diagnostic, as a thrown error's message does, unless one says what went wrong already.\n\tif (\n\t\tinput.kind === \"nested\" &&\n\t\ttool.structuredOutputSchema !== undefined &&\n\t\tfinal.isError === true &&\n\t\tfinal.structuredOutput === undefined &&\n\t\t![...(final.diagnostics ?? []), ...harness].some((diagnostic) => diagnostic.severity === \"error\")\n\t) {\n\t\tconst text = bounded.content.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n\t\tif (text !== \"\") harness.push(toolDiagnostic(\"tool_error\", text));\n\t}\n\treturn { ...final, output: bounded.content, diagnostics: [...(final.diagnostics ?? []), ...harness] };\n}\n\nconst structuredValidators = new WeakMap<object, ReturnType<typeof Compile>>();\n\n/** Why a result's `structuredOutput` breaks the tool's contract, or `undefined` when it keeps it. */\nfunction structuredOutputError(tool: ToolRegistration, result: ToolExecutionResult): string | undefined {\n\tconst schema = tool.structuredOutputSchema;\n\tconst value = result.structuredOutput;\n\tif (schema === undefined) {\n\t\treturn value === undefined\n\t\t\t? undefined\n\t\t\t: `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`;\n\t}\n\tif (value === undefined) {\n\t\treturn result.isError === true ? undefined : `Tool ${tool.name} returned no structuredOutput`;\n\t}\n\tlet validator = structuredValidators.get(schema);\n\tif (validator === undefined) {\n\t\tvalidator = Compile(schema);\n\t\tstructuredValidators.set(schema, validator);\n\t}\n\tif (validator.Check(value)) return undefined;\n\tconst [first] = validator.Errors(value);\n\tconst path = first?.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\") || \"root\";\n\treturn `Tool ${tool.name} returned structuredOutput that does not match its schema: ${path}: ${first?.message ?? \"invalid\"}`;\n}\n\n/**\n * Commit the tool's terminal state and mark its slot done. A model-issued call appends its result entry and ends with\n * the entry ID; a nested call writes its result to the caller's `NestedCallDoc`, records its usage, and ends with a\n * small receipt. Nested calls this call left running are aborted first, so they report into their slots before the\n * slots below the call leave `pi.live`. `build` receives the slot so interruption and abort can report the durable\n * partial output.\n */\nasync function settle(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tcall: ToolHookCall,\n\tending: Ending,\n\tbuild: (slot: Readonly<ToolSlot | NestedToolSlot> | undefined) => ToolExecutionResult,\n\tcontext: Context,\n\tdurationMs?: number,\n): Promise<void> {\n\t// A crash in between leaves the call in `execute`: a safe rerun reattaches to the calls, an interruption ends here.\n\t// Every live nested call the task owns, also those an earlier attempt made and this one never called again.\n\tconst nestedIds = (await runtime.ownedTasks(context))\n\t\t.filter((record) => record.kind === ToolTask.definition.name && (record.input as ToolTaskInput).kind === \"nested\")\n\t\t.map((record) => record.id);\n\t// Read before the settling commit: no admission starts after `ended`, and those underway were awaited.\n\tconst madeNested = (await runtime.memo(MADE_NESTED_CALLS, context)) === true;\n\t// Mark them all before waiting for any: one may run until a sibling is cancelled.\n\tawait Promise.all(nestedIds.map((id) => runtime.abortOwned(id, context)));\n\tawait runtime.commit(async (tx) => {\n\t\tconst conversationId = runtime.conversationId;\n\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\tconst slot = toolSlot(live, runtime.taskId);\n\t\tconst result = build(slot);\n\t\tlet settled: ToolTaskResult;\n\t\tif (input.kind === \"nested\") {\n\t\t\tconst nested = nestedResult(runtime.taskId, result, durationMs);\n\t\t\tif (nested.usage !== undefined) await recordUsage(tx, conversationId, \"tools\", call.name, nested.usage);\n\t\t\t// The caller is never terminal before its owned nested calls, so its document is open; another task in it is a\n\t\t\t// bug, not a race.\n\t\t\tconst state = await tx.doc(NestedCallDoc, input.parent, input.key, null);\n\t\t\tif (state.taskId !== runtime.taskId) throw new Error(`Nested call ${call.id} is not in its caller's index`);\n\t\t\tstate.result = nested as unknown as Draft<JsonRepresentation<NestedToolExecutionResult>>;\n\t\t\tif (slot !== undefined && \"parentTaskId\" in slot) {\n\t\t\t\tfinishSlot(slot);\n\t\t\t\tslot.summary = summaryOf(nested, result.output ?? []);\n\t\t\t}\n\t\t\tsettled = { kind: \"nested\" };\n\t\t} else {\n\t\t\tconst timing = { timestamp: runtime.now(), durationMs };\n\t\t\tconst entry = await appendToolResult(tx, conversationId, call, result, timing);\n\t\t\tif (slot !== undefined && !(\"parentTaskId\" in slot)) {\n\t\t\t\tfinishSlot(slot);\n\t\t\t\tslot.entry = entry.id;\n\t\t\t}\n\t\t\t// Tools build control objects freely; drop keys set to undefined so the task result is strict JSON.\n\t\t\tconst control =\n\t\t\t\tresult.control === undefined || ending.status !== \"completed\"\n\t\t\t\t\t? {}\n\t\t\t\t\t: { control: copyJson(result.control as JsonValue, { omitUndefinedProperties: true }) as ToolControl };\n\t\t\tsettled = { kind: \"model\", entryId: entry.id, ...control };\n\t\t}\n\t\t// A call that made no nested calls, in any attempt, has no slots below it; skipping the scan keeps many leaves\n\t\t// linear. Committed before the read: no nested call is admitted after `ended`.\n\t\tif (madeNested) removeNestedSlots(live, runtime.taskId);\n\t\tif (ending.status === \"aborted\") return { status: \"terminal\", outcome: { status: \"aborted\", result: settled } };\n\t\tif (ending.status === \"failed\") {\n\t\t\tconst error = { message: ending.message };\n\t\t\treturn { status: \"terminal\", outcome: { status: \"failed\", error, result: settled } };\n\t\t}\n\t\treturn { status: \"terminal\", outcome: { status: \"completed\", result: settled } };\n\t}, context);\n}\n\n/**\n * A nested call's result, as stored and returned: strict JSON, without `output`, which only the model reads, and\n * without `control`, which only model-issued calls apply.\n */\nfunction nestedResult(\n\ttaskId: TaskId,\n\tresult: ToolExecutionResult,\n\tdurationMs: number | undefined,\n): NestedToolExecutionResult {\n\tconst nested = {\n\t\ttaskId,\n\t\tstructuredOutput: result.structuredOutput,\n\t\tisError: result.isError ?? false,\n\t\tdetails: result.details,\n\t\tdiagnostics: result.diagnostics ?? [],\n\t\tusage: result.usage,\n\t\tdurationMs,\n\t};\n\treturn copyJson(nested as unknown as JsonValue, {\n\t\tomitUndefinedProperties: true,\n\t}) as unknown as NestedToolExecutionResult;\n}\n\n/**\n * Create nested call `key` of the call `parentCallId` in one commit: its tool task, owned by the calling task, its slot,\n * and its `NestedCallDoc`. A key already made returns that call's task when it names the same tool and arguments.\n */\nasync function startNestedCall(\n\truntime: Runtime,\n\tparentCallId: string,\n\tname: string,\n\targs: JsonObject,\n\toptions: { readonly key: string; readonly progress: boolean | undefined; readonly abandonOnRestart: boolean },\n\tcontext: Context,\n): Promise<TaskId<ToolTaskResult>> {\n\tconst key = options.key;\n\tconst call: ToolCall = {\n\t\ttype: \"toolCall\",\n\t\tid: `${parentCallId}/${key}`,\n\t\tname,\n\t\targuments: copyJson(args, { omitUndefinedProperties: true }) as JsonObject,\n\t};\n\tlet id: TaskId<ToolTaskResult> | undefined;\n\tlet replayed = false;\n\tawait runtime.commit(async (tx) => {\n\t\t// Opened, or created empty for a key not made yet.\n\t\tconst state = await tx.doc(NestedCallDoc, runtime.taskId, key, null);\n\t\tconst existing = state.taskId;\n\t\tif (existing !== undefined) {\n\t\t\tconst input = (await tx.task(existing))?.input as ToolTaskInput | undefined;\n\t\t\tconst same =\n\t\t\t\tinput?.kind === \"nested\" &&\n\t\t\t\tinput.call.name === name &&\n\t\t\t\tjsonEqual(input.call.arguments as JsonValue, call.arguments as JsonValue);\n\t\t\tif (!same) throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);\n\t\t\tid = existing as TaskId<ToolTaskResult>;\n\t\t\treplayed = state.result !== undefined;\n\t\t\treturn undefined;\n\t\t}\n\t\tconst input: ToolTaskInput = {\n\t\t\tkind: \"nested\",\n\t\t\tparent: runtime.taskId,\n\t\t\tparentCallId,\n\t\t\tkey,\n\t\t\tcall,\n\t\t\t...(options.progress === false ? { progress: false } : {}),\n\t\t};\n\t\tconst created = await tx.createTask(ToolTask, input, {\n\t\t\townership: { kind: \"task\", taskId: runtime.taskId },\n\t\t\tabandonOnRestart: options.abandonOnRestart,\n\t\t});\n\t\tstate.taskId = created;\n\t\tconst live = await tx.doc(LiveDoc, runtime.conversationId);\n\t\tlive.nestedTools ??= [];\n\t\tconst slot: NestedToolSlot = {\n\t\t\tcallId: call.id,\n\t\t\tparentCallId,\n\t\t\tparentTaskId: runtime.taskId,\n\t\t\tname,\n\t\t\ttaskId: created,\n\t\t\targuments: call.arguments as JsonObject,\n\t\t\tstatus: \"pending\",\n\t\t};\n\t\tlive.nestedTools.push(slot as Draft<NestedToolSlot>);\n\t\tid = created;\n\t\treturn undefined;\n\t}, context);\n\tif (replayed) {\n\t\tcontext.telemetry.addEvent(\"pi.durable.replay\", { \"tool.name\": name });\n\t}\n\treturn id!;\n}\n\n/**\n * What programs get of a tool's output when it declares no schema: one text item as its string, one image as itself,\n * nothing as `\"\"`, and anything else as the content list.\n */\nfunction outputValue(output: Content): string | ImageContent | Content {\n\tif (output.length === 0) return \"\";\n\tif (output.length > 1) return output;\n\tconst [only] = output;\n\treturn only!.type === \"text\" ? only!.text : only!;\n}\n\n/** What the caller gets for a nested call without a stored result: one the scheduler faulted or orphaned. */\nfunction fallbackResult(taskId: TaskId, name: string, outcome: TaskOutcome<ToolTaskResult>): NestedToolExecutionResult {\n\tconst message =\n\t\toutcome.status === \"faulted\"\n\t\t\t? `Tool ${name} failed: ${outcome.error.message}`\n\t\t\t: outcome.status === \"orphaned\"\n\t\t\t\t? `Tool ${name} could not resume: ${outcome.reason}`\n\t\t\t\t: `Tool ${name} ended without a result`;\n\tconst error = harnessError(outcome.status, message);\n\treturn { taskId, isError: true, diagnostics: error.diagnostics ?? [] };\n}\n\n/**\n * How a tool task ends; the result entry is appended either way. `failed` (execution threw or was interrupted)\n * records cancellation intent for the conversations the call owns; a result with `isError` still completes.\n */\ntype Ending = { readonly status: \"completed\" | \"aborted\" } | { readonly status: \"failed\"; readonly message: string };\n\nconst COMPLETED: Ending = { status: \"completed\" };\n\n/** An error result from the slot's durable partial output, details, and diagnostics. */\nfunction fromSlot(\n\tslot: Readonly<ToolSlot | NestedToolSlot> | undefined,\n\tcode: string,\n\tmessage: string,\n): ToolExecutionResult {\n\tconst diagnostics = [...(slot?.diagnostics ?? [])];\n\tconst droppedBytes = slot?.droppedBytes ?? 0;\n\tif (droppedBytes > 0) diagnostics.push(truncated({ droppedBytes, droppedLines: slot?.droppedLines ?? 0 }));\n\tdiagnostics.push(toolDiagnostic(code, message));\n\treturn {\n\t\toutput: slot?.output === undefined || slot.output === \"\" ? [] : [{ type: \"text\", text: slot.output }],\n\t\tisError: true,\n\t\t...(slot?.details === undefined ? {} : { details: slot.details }),\n\t\tdiagnostics,\n\t};\n}\n\n/** An error result the Harness writes itself: no content and one `error` diagnostic with `code`. */\nexport function harnessError(code: string, message: string): ToolExecutionResult {\n\treturn { output: [], isError: true, diagnostics: [toolDiagnostic(code, message)] };\n}\n\nfunction toolDiagnostic(code: string, message: string): ToolDiagnostic {\n\treturn { severity: \"error\", code, message };\n}\n\n/** The Harness's truncation diagnostic; `retain` is unknown when rebuilt from a slot after recovery. */\nfunction truncated(\n\tdropped: { readonly droppedLines: number; readonly droppedBytes: number },\n\tretain?: \"head\" | \"tail\",\n): ToolDiagnostic {\n\tconst kept = retain === undefined ? \"\" : ` to its ${retain === \"head\" ? \"beginning\" : \"end\"}`;\n\treturn {\n\t\tseverity: \"warn\",\n\t\tcode: \"truncated\",\n\t\tmessage: `Output truncated${kept}: ${dropped.droppedLines} lines, ${dropped.droppedBytes} bytes dropped`,\n\t};\n}\n\n/** Error text a nested call's summary keeps. */\nconst MAX_SUMMARY_ERROR_CHARS = 500;\n\n/** How a nested call ended, for its slot: error text, from its diagnostics or else its `output`, bounded. */\nfunction summaryOf(result: NestedToolExecutionResult, output: Content): NestedToolSummary {\n\tconst error = result.isError ? errorTextOf(result, output).slice(0, MAX_SUMMARY_ERROR_CHARS) : \"\";\n\treturn {\n\t\tisError: result.isError,\n\t\t...(result.durationMs === undefined ? {} : { durationMs: result.durationMs }),\n\t\t...(result.usage === undefined ? {} : { usage: result.usage }),\n\t\t...(error === \"\" ? {} : { error }),\n\t};\n}\n\n/** The error messages of a nested result, else the text items of its output, joined with newlines. */\nfunction errorTextOf(result: NestedToolExecutionResult, output: Content): string {\n\tconst errors = result.diagnostics.filter((diagnostic) => diagnostic.severity === \"error\");\n\tif (errors.length > 0) return errors.map((diagnostic) => diagnostic.message).join(\"\\n\");\n\treturn output.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n}\n\n/**\n * Append a `pi.tool-result` entry. The content ends with the rendered diagnostics, so the stored message is exactly\n * what the model sees; `data` keeps the structured list. A result's usage is added to `pi.usage` in the same commit.\n */\nexport async function appendToolResult(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tcall: ToolCall,\n\tresult: ToolExecutionResult,\n\tmeta: { readonly timestamp: number; readonly durationMs?: number },\n): Promise<TypedEntry<{ diagnostics: ToolDiagnostic[] }>> {\n\tconst { timestamp, durationMs } = meta;\n\tconst diagnostics = [...(result.diagnostics ?? [])];\n\tconst content: Content = [...(result.output ?? [])];\n\tif (diagnostics.length > 0) content.push({ type: \"text\", text: renderDiagnostics(diagnostics) });\n\tconst message = {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: call.id,\n\t\ttoolName: call.name,\n\t\tcontent,\n\t\t...(result.details === undefined ? {} : { details: result.details }),\n\t\t...(result.usage === undefined ? {} : { usage: result.usage }),\n\t\tisError: result.isError ?? false,\n\t\t...(durationMs === undefined ? {} : { durationMs }),\n\t\ttimestamp,\n\t} as ToolResultMessage;\n\tif (result.usage !== undefined) await recordUsage(tx, conversationId, \"tools\", call.name, result.usage);\n\treturn tx.appendEntry(ToolResultEntry, conversationId, { model: [message], data: { diagnostics } });\n}\n\nfunction renderDiagnostics(diagnostics: readonly ToolDiagnostic[]): string {\n\treturn `<harness>\\n${diagnostics.map((diagnostic) => `[${diagnostic.severity}] ${diagnostic.message}`).join(\"\\n\")}\\n</harness>`;\n}\n\n/**\n * Bound the text of result content. When the joined text exceeds the limits, the text items are replaced by one bounded\n * item at the position of the first (head) or last (tail) text item; other content is kept.\n */\nfunction boundContent(\n\tcontent: Content,\n\tlimits: OutputLimits,\n): { content: Content; droppedBytes: number; droppedLines: number } {\n\tconst texts = content.filter((item): item is TextContent => item.type === \"text\");\n\tconst bounded = boundOutput(texts.map((item) => item.text).join(\"\"), limits);\n\tif (bounded.droppedBytes === 0) return { content, droppedBytes: 0, droppedLines: 0 };\n\tconst keep = limits.retain === \"head\" ? texts[0] : texts.at(-1);\n\tconst result: Content = [];\n\tfor (const item of content) {\n\t\tif (item.type !== \"text\") result.push(item);\n\t\telse if (item === keep) result.push({ ...item, text: bounded.text });\n\t}\n\treturn { content: result, droppedBytes: bounded.droppedBytes, droppedLines: bounded.droppedLines };\n}\n\n/**\n * Explicit nested call keys are path segments of the call ID, so IDs of different nested calls never collide, and are\n * never plain positive integers, which default keys use. `__proto__` stays reserved, as it was when keys indexed a JSON object.\n */\nfunction checkKey(key: string): void {\n\tif (key === \"\" || key.includes(\"/\") || key === \"__proto__\" || /^[1-9][0-9]*$/.test(key)) {\n\t\tthrow new Error(\n\t\t\t`Nested call key ${JSON.stringify(key)} must be non-empty, without \"/\", not \"__proto__\", and not a positive integer`,\n\t\t);\n\t}\n}\n\n/** Structural JSON equality; object key order does not matter. */\nfunction jsonEqual(a: JsonValue, b: JsonValue): boolean {\n\tif (a === b) return true;\n\tif (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n\tif (Array.isArray(a) || Array.isArray(b)) {\n\t\treturn (\n\t\t\tArray.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => jsonEqual(item, b[i]!))\n\t\t);\n\t}\n\tconst keys = Object.keys(a);\n\treturn (\n\t\tkeys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && jsonEqual(a[key]!, b[key]!))\n\t);\n}\n"]}
|
package/dist/harness/types.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { AttachedReplicatedState, Context, JsonValue } from "@earendil-works/chord";
|
|
2
|
-
import type { AssistantMessage, CacheRetention, Message, Models, ModelThinkingLevel, Static, Tool, ToolCall, ToolResultMessage, Transport, TSchema, Usage, UserMessage } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { AssistantMessage, CacheRetention, ClientIdentity, Message, Models, ModelThinkingLevel, Static, Tool, ToolCall, ToolResultMessage, Transport, TSchema, Usage, UserMessage } from "@earendil-works/pi-ai";
|
|
3
|
+
import type { TelemetryContext } from "@earendil-works/pi-telemetry";
|
|
3
4
|
import type { ExecutionEnv, ShellOutputSkip, ShellOutputWindow } from "../env/index.ts";
|
|
4
|
-
import type { ConversationId, ConversationOwnership, ConversationRecord, Cursor, DocumentObserver, DocumentReader, EntryDraft, EntryId, EntryQuery, EntryRecord, JsonObject, Page, Session, SubmissionId, SubmissionRecord, Task, TaskId, TaskOptions, TaskRecord, TaskState, Tx, WatchHandle } from "../types.ts";
|
|
5
|
+
import type { ConversationId, ConversationOwnership, ConversationRecord, Cursor, DocumentObserver, DocumentReader, EntryDraft, EntryId, EntryQuery, EntryRecord, JsonObject, Page, ReportInfo, Session, SetTimer, SubmissionId, SubmissionRecord, Task, TaskId, TaskOptions, TaskRecord, TaskState, Tx, WatchHandle } from "../types.ts";
|
|
5
6
|
import type { TaskGraph, TaskGraphWatch } from "./task-graph.ts";
|
|
6
7
|
import type { UsageState } from "./usage.ts";
|
|
7
8
|
import type { ConversationView } from "./view.ts";
|
|
@@ -90,7 +91,8 @@ export interface ConversationHandle {
|
|
|
90
91
|
/** Post-tools controls requested by a tool result. */
|
|
91
92
|
export type ToolControl = {
|
|
92
93
|
readonly addTools?: readonly string[];
|
|
93
|
-
|
|
94
|
+
/** End the run without another model request when every result of the round sets it to `true`; `false` is a no-op. */
|
|
95
|
+
readonly terminate?: boolean;
|
|
94
96
|
readonly handoff?: string;
|
|
95
97
|
};
|
|
96
98
|
/** Remark about a call for the model and the UI, such as truncation or a spill path; never part of the tool's data. */
|
|
@@ -158,10 +160,12 @@ export interface ToolExecutionApi<TDetails extends JsonValue = JsonValue> extend
|
|
|
158
160
|
readonly registry: RegistrySnapshot;
|
|
159
161
|
/** The calling conversation's agent, as the tool task's phase resolved it. */
|
|
160
162
|
agent(context: Context): Promise<Agent>;
|
|
161
|
-
/** `HarnessOptions.models
|
|
163
|
+
/** The current `HarnessOptions.models`, read at each access: the catalog, credentials, and request transforms. */
|
|
162
164
|
readonly models: Models;
|
|
163
165
|
/** Built by `HarnessOptions.env` for this call; `undefined` without an environment. */
|
|
164
166
|
readonly env: ExecutionEnv | undefined;
|
|
167
|
+
/** The Harness clock (`HarnessOptions.now`), for times a rerun after a restart compares against. */
|
|
168
|
+
now(): number;
|
|
165
169
|
/**
|
|
166
170
|
* Append running output; it becomes the result's `output` when the result omits it. `skipped` counts output
|
|
167
171
|
* omitted before the chunk, as reported by an environment given `outputWindow` (`ShellOutputInfo.skipped`).
|
|
@@ -452,6 +456,13 @@ export type CompactionPolicy = {
|
|
|
452
456
|
/** Background compaction starts `backgroundTokens` below the blocking threshold; `0` disables it. */
|
|
453
457
|
backgroundTokens: number;
|
|
454
458
|
};
|
|
459
|
+
/**
|
|
460
|
+
* Harness-wide compaction settings. `modelOverrides` is keyed by exact `"provider/modelId"`; each field it sets
|
|
461
|
+
* replaces the harness-wide one for that model, so small- and large-window models can share a harness.
|
|
462
|
+
*/
|
|
463
|
+
export type CompactionSettings = Partial<CompactionPolicy> & {
|
|
464
|
+
readonly modelOverrides?: Readonly<Record<string, Partial<CompactionPolicy>>>;
|
|
465
|
+
};
|
|
455
466
|
/**
|
|
456
467
|
* How often running progress is committed. Each progress commit is a storage write; a host whose storage is remote can
|
|
457
468
|
* commit less often, so live answers and tool output appear in larger steps.
|
|
@@ -478,7 +489,7 @@ export type HarnessSettings = {
|
|
|
478
489
|
readonly extensions?: readonly Extension[];
|
|
479
490
|
readonly stream?: ConversationStreamOptions;
|
|
480
491
|
readonly retry?: Partial<ConversationRetryPolicy>;
|
|
481
|
-
readonly compaction?:
|
|
492
|
+
readonly compaction?: CompactionSettings;
|
|
482
493
|
readonly progress?: Partial<ProgressPolicy>;
|
|
483
494
|
readonly toolExecution?: ToolExecutionMode;
|
|
484
495
|
readonly steeringMode?: QueueMode;
|
|
@@ -494,20 +505,37 @@ export type HarnessSettings = {
|
|
|
494
505
|
* after use; `Infinity` keeps them. Anything else that is not a number of milliseconds means the default.
|
|
495
506
|
*/
|
|
496
507
|
readonly documentRetentionMs?: number;
|
|
508
|
+
/**
|
|
509
|
+
* What a run that fails (`model_error`, `no_model`) does with the inputs queued behind it: `keep` leaves them
|
|
510
|
+
* queued until the next input or queued write, `continue` starts the next run with them, as an answer would, and
|
|
511
|
+
* `withdraw` settles them `unanswered` with reason `run_failed`. Default `keep`.
|
|
512
|
+
*/
|
|
513
|
+
readonly afterFailedRun?: AfterFailedRun;
|
|
514
|
+
/**
|
|
515
|
+
* How many times in a row a task may be cut off by a crash, eviction, or reset (a close does not count) without
|
|
516
|
+
* changing its state before it is parked as blocked (`restart_limit`) instead of run again; `Harness.retryTask()`
|
|
517
|
+
* runs it again. Default 5; `Infinity` never parks.
|
|
518
|
+
*/
|
|
519
|
+
readonly restartLimit?: number;
|
|
497
520
|
};
|
|
521
|
+
/** What a failed run does with the inputs queued behind it (`HarnessSettings.afterFailedRun`). */
|
|
522
|
+
export type AfterFailedRun = "keep" | "continue" | "withdraw";
|
|
498
523
|
/** Resolved settings: every field over its built-in default, object fields merged. */
|
|
499
524
|
export type Settings = {
|
|
500
525
|
/** Absent: every installed extension, in install order. */
|
|
501
526
|
readonly extensions?: readonly Extension[];
|
|
502
527
|
readonly stream: ConversationStreamOptions;
|
|
503
528
|
readonly retry: ConversationRetryPolicy;
|
|
504
|
-
|
|
529
|
+
/** Harness-wide policy over the defaults; per-model overrides apply where the model is known. */
|
|
530
|
+
readonly compaction: CompactionPolicy & Pick<CompactionSettings, "modelOverrides">;
|
|
505
531
|
readonly progress: ProgressPolicy;
|
|
506
532
|
readonly toolExecution: ToolExecutionMode;
|
|
507
533
|
readonly steeringMode: QueueMode;
|
|
508
534
|
readonly followUpMode: QueueMode;
|
|
509
535
|
readonly contextRetentionMs: number;
|
|
510
536
|
readonly documentRetentionMs: number;
|
|
537
|
+
readonly afterFailedRun: AfterFailedRun;
|
|
538
|
+
readonly restartLimit: number;
|
|
511
539
|
};
|
|
512
540
|
/** What `HarnessOptions.env` builds an environment for. */
|
|
513
541
|
export type EnvTarget = {
|
|
@@ -517,10 +545,23 @@ export type EnvTarget = {
|
|
|
517
545
|
readonly read: DocumentReader;
|
|
518
546
|
};
|
|
519
547
|
export type HarnessOptions<Tool extends ToolRegistration = ToolRegistration> = {
|
|
520
|
-
/**
|
|
521
|
-
readonly
|
|
548
|
+
/** Host-owned adapter for content-free admission/phase telemetry; propagation and metrics are optional. */
|
|
549
|
+
readonly telemetry?: TelemetryContext;
|
|
550
|
+
/**
|
|
551
|
+
* pi-ai model access used by generation, compaction, hooks and tools: a `Models`, or a function returning the current
|
|
552
|
+
* one, called at each use, so a host can replace its model configuration without reopening the Harness.
|
|
553
|
+
*/
|
|
554
|
+
readonly models: Models | (() => Models);
|
|
555
|
+
/**
|
|
556
|
+
* How model requests identify the app to providers, merged field by field over `DEFAULT_HARNESS_IDENTITY`
|
|
557
|
+
* (`{ attribution: PI_ATTRIBUTION }`, provider attribution to pi). It applies to every request through the Harness's
|
|
558
|
+
* models, including hooks and tools, and overrides the identity the `Models` was created with; a request's own
|
|
559
|
+
* `identity` overrides it. Pass `{ attribution: null }` to send no attribution headers.
|
|
560
|
+
*/
|
|
561
|
+
readonly identity?: ClientIdentity;
|
|
522
562
|
readonly registry: RegistryReader<Tool>;
|
|
523
|
-
|
|
563
|
+
/** Run settings, or a function returning the current ones; read at each use either way. */
|
|
564
|
+
readonly settings?: HarnessSettings | (() => HarnessSettings | undefined);
|
|
524
565
|
/** Builds a conversation's environment at each use. Never called on the Session line; may be async. */
|
|
525
566
|
readonly env?: (target: EnvTarget, context: Context) => ExecutionEnv | undefined | Promise<ExecutionEnv | undefined>;
|
|
526
567
|
/**
|
|
@@ -529,12 +570,46 @@ export type HarnessOptions<Tool extends ToolRegistration = ToolRegistration> = {
|
|
|
529
570
|
* Table reads throw `ReadAfterWrite`, as in `init`; a throw fails the creating commit.
|
|
530
571
|
*/
|
|
531
572
|
readonly conversationCreated?: (tx: Tx, conversation: ConversationRecord) => void | Promise<void>;
|
|
573
|
+
/**
|
|
574
|
+
* The Harness clock, epoch milliseconds; default `Date.now`. Sleeping tasks store deadlines on it, so every process
|
|
575
|
+
* that opens the same storage must use the same clock.
|
|
576
|
+
*/
|
|
532
577
|
readonly now?: () => number;
|
|
533
578
|
/**
|
|
534
|
-
*
|
|
535
|
-
*
|
|
579
|
+
* Arms the timers of the Session, the scheduler, and its tasks: pacing progress commits, freeing idle memory
|
|
580
|
+
* (`background`), and, without `onWake`, resuming sleeping tasks; and the timers of `TaskRuntime.setTimer()`. The
|
|
581
|
+
* Node.js environment, file watcher, and image worker keep their own timers. Default `setTimeout`, with background
|
|
582
|
+
* timers unreferenced, or declined in Cloudflare Workers and where they cannot be unreferenced. Tests can pass fake
|
|
583
|
+
* timers; a host can keep timers off a process that should hibernate.
|
|
536
584
|
*/
|
|
537
|
-
readonly
|
|
585
|
+
readonly setTimer?: SetTimer;
|
|
586
|
+
/**
|
|
587
|
+
* Wakes the process for sleeping tasks instead of a `setTimer` timer. Without it, while scheduling runs, a timer that
|
|
588
|
+
* keeps the process alive resumes sleeping tasks when they are due. With it, the Harness arms no timer for them: it
|
|
589
|
+
* calls `onWake` after open and whenever `Harness.wake()` changes, and the host arms its own wakeup, such as a
|
|
590
|
+
* Durable Object alarm, and calls `resume()` when it fires. Called off the Session line, after the commit that
|
|
591
|
+
* changed the value, so a host arms a recovery wakeup before calls that can start work. It may call `wake()` and
|
|
592
|
+
* `resume()`, and must not block. A throw is reported, and the value is offered again at the next change.
|
|
593
|
+
*/
|
|
594
|
+
readonly onWake?: (wake: Wake) => void;
|
|
595
|
+
/**
|
|
596
|
+
* Receives failures that do not fail the calling operation, such as a throwing hook or listener, a task that faulted,
|
|
597
|
+
* and the error that fails the Session, once. `info` says what happened: a host can tell a failed Session
|
|
598
|
+
* (`session_failed`, often a platform reset) from a faulted task (`task_faulted`) or a parked one (`task_parked`).
|
|
599
|
+
* Its own throw or rejection is dropped.
|
|
600
|
+
*/
|
|
601
|
+
readonly onReport?: (error: unknown, info: ReportInfo) => void;
|
|
602
|
+
};
|
|
603
|
+
/**
|
|
604
|
+
* When a Session next needs a running process (`Harness.wake()`). `active`: some task can run now or is running, or a
|
|
605
|
+
* reconcile pass such as open's recovery has not landed yet, so a process that dies must be woken again soon, for
|
|
606
|
+
* example by a recovery alarm. `at`: the earliest sleep not yet due,
|
|
607
|
+
* when there is one. Neither: nothing needs a process until new work is submitted. Tasks blocked on a missing or
|
|
608
|
+
* unmigratable definition, `completing` tasks, and waits on live tasks do not count; the work they wait for does.
|
|
609
|
+
*/
|
|
610
|
+
export type Wake = {
|
|
611
|
+
readonly active: boolean;
|
|
612
|
+
readonly at?: number;
|
|
538
613
|
};
|
|
539
614
|
/** Live task and what the scheduler would do with it under the current registry. */
|
|
540
615
|
export type TaskInspection = {
|
|
@@ -555,14 +630,22 @@ export type TaskInspection = {
|
|
|
555
630
|
readonly kind: "waiting";
|
|
556
631
|
readonly on: readonly TaskId[];
|
|
557
632
|
}
|
|
633
|
+
/** Sleeps until the Harness clock reaches `until`. */
|
|
634
|
+
| {
|
|
635
|
+
readonly kind: "sleeping";
|
|
636
|
+
readonly until: number;
|
|
637
|
+
}
|
|
558
638
|
/** Outcome held until its ordinary owned work drains. */
|
|
559
639
|
| {
|
|
560
640
|
readonly kind: "completing";
|
|
561
641
|
}
|
|
562
|
-
/**
|
|
642
|
+
/**
|
|
643
|
+
* Cannot run here: no registered definition can take it (aborting it settles it as `orphaned`), or it is parked by
|
|
644
|
+
* the restart limit (`retryTask()` runs it again).
|
|
645
|
+
*/
|
|
563
646
|
| {
|
|
564
647
|
readonly kind: "blocked";
|
|
565
|
-
readonly reason: "missing_task" | "task_too_old" | "migration_failed";
|
|
648
|
+
readonly reason: "missing_task" | "task_too_old" | "migration_failed" | "restart_limit";
|
|
566
649
|
readonly error?: unknown;
|
|
567
650
|
};
|
|
568
651
|
};
|
|
@@ -644,6 +727,13 @@ export interface Harness extends Session {
|
|
|
644
727
|
* `Harness.waitForIdle()`, and `Conversation.waitForIdle()`. Read-only viewers never do.
|
|
645
728
|
*/
|
|
646
729
|
resume(): void;
|
|
730
|
+
/**
|
|
731
|
+
* When this Session next needs a running process, from the scheduler's memory: `active` while some task can run now
|
|
732
|
+
* or is running, `at` for the earliest sleep. Answers also while scheduling is paused. A host that wakes the
|
|
733
|
+
* process itself, such as a Durable Object alarm, arms from it and calls `resume()` when woken; see
|
|
734
|
+
* `HarnessOptions.onWake`.
|
|
735
|
+
*/
|
|
736
|
+
wake(): Wake;
|
|
647
737
|
/** Return the reserved root conversation, creating it with `agent` and `init` in one commit when absent. */
|
|
648
738
|
root(context: Context, options?: {
|
|
649
739
|
readonly agent?: AgentChange;
|
|
@@ -663,6 +753,11 @@ export interface Harness extends Session {
|
|
|
663
753
|
* definition cannot take it settles as `orphaned` instead.
|
|
664
754
|
*/
|
|
665
755
|
abortTask(id: TaskId, context: Context): Promise<"marked" | "terminal">;
|
|
756
|
+
/**
|
|
757
|
+
* Run a task parked by `settings.restartLimit` again: clears its restart count and enables scheduling. Does nothing
|
|
758
|
+
* for a task that is not parked; rejects for an unknown one.
|
|
759
|
+
*/
|
|
760
|
+
retryTask(id: TaskId, context: Context): Promise<void>;
|
|
666
761
|
/** Resolve with the terminal receipt; cancelling `context` cancels only this wait. */
|
|
667
762
|
waitForTask<R>(id: TaskId<R>, context: Context): Promise<SettledTask<R>>;
|
|
668
763
|
/** Resolve when the ordinary ownership scope of every ownerless conversation has no live non-background task. */
|
|
@@ -678,7 +773,7 @@ export interface Harness extends Session {
|
|
|
678
773
|
export interface HookApi extends DocumentReader {
|
|
679
774
|
readonly taskId: TaskId;
|
|
680
775
|
readonly conversationId: ConversationId;
|
|
681
|
-
/** `HarnessOptions.models
|
|
776
|
+
/** The current `HarnessOptions.models`, read at each access. */
|
|
682
777
|
readonly models: Models;
|
|
683
778
|
memo<T extends JsonValue>(name: string, context: Context): Promise<T | undefined>;
|
|
684
779
|
memo<T extends JsonValue>(name: string, candidate: T, context: Context): Promise<T>;
|