@earendil-works/pi-durable 1.1.0 → 1.3.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.
Files changed (216) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +164 -11
  3. package/dist/codemode/codemode.d.ts +173 -0
  4. package/dist/codemode/codemode.d.ts.map +1 -0
  5. package/dist/codemode/codemode.js +886 -0
  6. package/dist/codemode/codemode.js.map +1 -0
  7. package/dist/codemode/describe.d.ts +38 -0
  8. package/dist/codemode/describe.d.ts.map +1 -0
  9. package/dist/codemode/describe.js +119 -0
  10. package/dist/codemode/describe.js.map +1 -0
  11. package/dist/codemode/index.d.ts +3 -0
  12. package/dist/codemode/index.d.ts.map +1 -0
  13. package/dist/codemode/index.js +3 -0
  14. package/dist/codemode/index.js.map +1 -0
  15. package/dist/codemode/models.d.ts +28 -0
  16. package/dist/codemode/models.d.ts.map +1 -0
  17. package/dist/codemode/models.js +231 -0
  18. package/dist/codemode/models.js.map +1 -0
  19. package/dist/codemode/output.d.ts +41 -0
  20. package/dist/codemode/output.d.ts.map +1 -0
  21. package/dist/codemode/output.js +167 -0
  22. package/dist/codemode/output.js.map +1 -0
  23. package/dist/env/index.d.ts +43 -0
  24. package/dist/env/index.d.ts.map +1 -1
  25. package/dist/env/index.js.map +1 -1
  26. package/dist/errors.d.ts +20 -3
  27. package/dist/errors.d.ts.map +1 -1
  28. package/dist/errors.js +34 -5
  29. package/dist/errors.js.map +1 -1
  30. package/dist/harness/agent.d.ts +5 -2
  31. package/dist/harness/agent.d.ts.map +1 -1
  32. package/dist/harness/agent.js +69 -25
  33. package/dist/harness/agent.js.map +1 -1
  34. package/dist/harness/compaction.d.ts +6 -1
  35. package/dist/harness/compaction.d.ts.map +1 -1
  36. package/dist/harness/compaction.js +10 -7
  37. package/dist/harness/compaction.js.map +1 -1
  38. package/dist/harness/context.d.ts +5 -0
  39. package/dist/harness/context.d.ts.map +1 -1
  40. package/dist/harness/context.js +46 -12
  41. package/dist/harness/context.js.map +1 -1
  42. package/dist/harness/events.d.ts +35 -15
  43. package/dist/harness/events.d.ts.map +1 -1
  44. package/dist/harness/events.js +77 -23
  45. package/dist/harness/events.js.map +1 -1
  46. package/dist/harness/generation.d.ts +2 -0
  47. package/dist/harness/generation.d.ts.map +1 -1
  48. package/dist/harness/generation.js +31 -8
  49. package/dist/harness/generation.js.map +1 -1
  50. package/dist/harness/harness.d.ts +7 -0
  51. package/dist/harness/harness.d.ts.map +1 -1
  52. package/dist/harness/harness.js +53 -26
  53. package/dist/harness/harness.js.map +1 -1
  54. package/dist/harness/inbox.d.ts +16 -4
  55. package/dist/harness/inbox.d.ts.map +1 -1
  56. package/dist/harness/inbox.js +26 -3
  57. package/dist/harness/inbox.js.map +1 -1
  58. package/dist/harness/live.d.ts +74 -17
  59. package/dist/harness/live.d.ts.map +1 -1
  60. package/dist/harness/live.js +66 -14
  61. package/dist/harness/live.js.map +1 -1
  62. package/dist/harness/scheduler.d.ts +18 -5
  63. package/dist/harness/scheduler.d.ts.map +1 -1
  64. package/dist/harness/scheduler.js +696 -163
  65. package/dist/harness/scheduler.js.map +1 -1
  66. package/dist/harness/submissions.d.ts +7 -4
  67. package/dist/harness/submissions.d.ts.map +1 -1
  68. package/dist/harness/submissions.js +32 -13
  69. package/dist/harness/submissions.js.map +1 -1
  70. package/dist/harness/task-graph.d.ts +1 -1
  71. package/dist/harness/task-graph.d.ts.map +1 -1
  72. package/dist/harness/task-graph.js +15 -10
  73. package/dist/harness/task-graph.js.map +1 -1
  74. package/dist/harness/tool.d.ts +45 -5
  75. package/dist/harness/tool.d.ts.map +1 -1
  76. package/dist/harness/tool.js +378 -63
  77. package/dist/harness/tool.js.map +1 -1
  78. package/dist/harness/types.d.ts +153 -13
  79. package/dist/harness/types.d.ts.map +1 -1
  80. package/dist/harness/types.js.map +1 -1
  81. package/dist/harness/util.d.ts +6 -1
  82. package/dist/harness/util.d.ts.map +1 -1
  83. package/dist/harness/util.js +5 -2
  84. package/dist/harness/util.js.map +1 -1
  85. package/dist/harness/view.d.ts +6 -2
  86. package/dist/harness/view.d.ts.map +1 -1
  87. package/dist/harness/view.js +22 -12
  88. package/dist/harness/view.js.map +1 -1
  89. package/dist/images/cloudflare.d.ts +4 -0
  90. package/dist/images/cloudflare.d.ts.map +1 -0
  91. package/dist/images/cloudflare.js +9 -0
  92. package/dist/images/cloudflare.js.map +1 -0
  93. package/dist/images/exif.d.ts +3 -0
  94. package/dist/images/exif.d.ts.map +1 -0
  95. package/dist/images/exif.js +71 -0
  96. package/dist/images/exif.js.map +1 -0
  97. package/dist/images/index.d.ts +18 -0
  98. package/dist/images/index.d.ts.map +1 -0
  99. package/dist/images/index.js +125 -0
  100. package/dist/images/index.js.map +1 -0
  101. package/dist/images/node-worker.d.ts +17 -0
  102. package/dist/images/node-worker.d.ts.map +1 -0
  103. package/dist/images/node-worker.js +16 -0
  104. package/dist/images/node-worker.js.map +1 -0
  105. package/dist/images/node.d.ts +21 -0
  106. package/dist/images/node.d.ts.map +1 -0
  107. package/dist/images/node.js +121 -0
  108. package/dist/images/node.js.map +1 -0
  109. package/dist/index.d.ts +6 -6
  110. package/dist/index.d.ts.map +1 -1
  111. package/dist/index.js +3 -3
  112. package/dist/index.js.map +1 -1
  113. package/dist/search.d.ts +13 -0
  114. package/dist/search.d.ts.map +1 -0
  115. package/dist/search.js +85 -0
  116. package/dist/search.js.map +1 -0
  117. package/dist/session/observation.d.ts +10 -3
  118. package/dist/session/observation.d.ts.map +1 -1
  119. package/dist/session/observation.js +24 -34
  120. package/dist/session/observation.js.map +1 -1
  121. package/dist/session/session.d.ts +68 -5
  122. package/dist/session/session.d.ts.map +1 -1
  123. package/dist/session/session.js +461 -49
  124. package/dist/session/session.js.map +1 -1
  125. package/dist/session/transaction.d.ts.map +1 -1
  126. package/dist/session/transaction.js +1 -0
  127. package/dist/session/transaction.js.map +1 -1
  128. package/dist/storage/jsonl/storage.d.ts +4 -0
  129. package/dist/storage/jsonl/storage.d.ts.map +1 -1
  130. package/dist/storage/jsonl/storage.js +2 -1
  131. package/dist/storage/jsonl/storage.js.map +1 -1
  132. package/dist/storage/memory.d.ts.map +1 -1
  133. package/dist/storage/memory.js +8 -10
  134. package/dist/storage/memory.js.map +1 -1
  135. package/dist/storage/scan.d.ts.map +1 -1
  136. package/dist/storage/scan.js +5 -4
  137. package/dist/storage/scan.js.map +1 -1
  138. package/dist/storage/sqlite/cloudflare.d.ts +17 -5
  139. package/dist/storage/sqlite/cloudflare.d.ts.map +1 -1
  140. package/dist/storage/sqlite/cloudflare.js +57 -21
  141. package/dist/storage/sqlite/cloudflare.js.map +1 -1
  142. package/dist/storage/sqlite/index.d.ts +1 -1
  143. package/dist/storage/sqlite/index.d.ts.map +1 -1
  144. package/dist/storage/sqlite/index.js.map +1 -1
  145. package/dist/storage/sqlite/migrations.d.ts +5 -1
  146. package/dist/storage/sqlite/migrations.d.ts.map +1 -1
  147. package/dist/storage/sqlite/migrations.js +94 -84
  148. package/dist/storage/sqlite/migrations.js.map +1 -1
  149. package/dist/storage/sqlite/node.d.ts +6 -4
  150. package/dist/storage/sqlite/node.d.ts.map +1 -1
  151. package/dist/storage/sqlite/node.js +6 -2
  152. package/dist/storage/sqlite/node.js.map +1 -1
  153. package/dist/storage/sqlite/schema.d.ts +47 -0
  154. package/dist/storage/sqlite/schema.d.ts.map +1 -0
  155. package/dist/storage/sqlite/schema.js +57 -0
  156. package/dist/storage/sqlite/schema.js.map +1 -0
  157. package/dist/storage/sqlite/storage.d.ts +9 -1
  158. package/dist/storage/sqlite/storage.d.ts.map +1 -1
  159. package/dist/storage/sqlite/storage.js +56 -55
  160. package/dist/storage/sqlite/storage.js.map +1 -1
  161. package/dist/testing/env-conformance.d.ts.map +1 -1
  162. package/dist/testing/env-conformance.js +100 -0
  163. package/dist/testing/env-conformance.js.map +1 -1
  164. package/dist/testing/runner.d.ts +1 -1
  165. package/dist/testing/runner.d.ts.map +1 -1
  166. package/dist/testing/runner.js.map +1 -1
  167. package/dist/testing/storage-conformance.d.ts.map +1 -1
  168. package/dist/testing/storage-conformance.js +3 -2
  169. package/dist/testing/storage-conformance.js.map +1 -1
  170. package/dist/testing/types.d.ts +2 -0
  171. package/dist/testing/types.d.ts.map +1 -1
  172. package/dist/testing/types.js.map +1 -1
  173. package/dist/tool-search/index.d.ts +2 -0
  174. package/dist/tool-search/index.d.ts.map +1 -0
  175. package/dist/tool-search/index.js +2 -0
  176. package/dist/tool-search/index.js.map +1 -0
  177. package/dist/tool-search/tool-search.d.ts +23 -0
  178. package/dist/tool-search/tool-search.d.ts.map +1 -0
  179. package/dist/tool-search/tool-search.js +84 -0
  180. package/dist/tool-search/tool-search.js.map +1 -0
  181. package/dist/tools/bash.d.ts +10 -2
  182. package/dist/tools/bash.d.ts.map +1 -1
  183. package/dist/tools/bash.js +27 -9
  184. package/dist/tools/bash.js.map +1 -1
  185. package/dist/tools/edit.js +1 -1
  186. package/dist/tools/edit.js.map +1 -1
  187. package/dist/tools/image-processor.d.ts +50 -0
  188. package/dist/tools/image-processor.d.ts.map +1 -0
  189. package/dist/tools/image-processor.js +20 -0
  190. package/dist/tools/image-processor.js.map +1 -0
  191. package/dist/tools/image.d.ts +8 -0
  192. package/dist/tools/image.d.ts.map +1 -1
  193. package/dist/tools/image.js +47 -0
  194. package/dist/tools/image.js.map +1 -1
  195. package/dist/tools/index.d.ts +25 -2
  196. package/dist/tools/index.d.ts.map +1 -1
  197. package/dist/tools/index.js +13 -5
  198. package/dist/tools/index.js.map +1 -1
  199. package/dist/tools/read.d.ts +10 -2
  200. package/dist/tools/read.d.ts.map +1 -1
  201. package/dist/tools/read.js +88 -29
  202. package/dist/tools/read.js.map +1 -1
  203. package/dist/tools/write.js +1 -1
  204. package/dist/tools/write.js.map +1 -1
  205. package/dist/truncate.d.ts +3 -2
  206. package/dist/truncate.d.ts.map +1 -1
  207. package/dist/truncate.js +4 -34
  208. package/dist/truncate.js.map +1 -1
  209. package/dist/types.d.ts +59 -5
  210. package/dist/types.d.ts.map +1 -1
  211. package/dist/types.js.map +1 -1
  212. package/package.json +43 -4
  213. package/dist/harness/output.d.ts +0 -69
  214. package/dist/harness/output.d.ts.map +0 -1
  215. package/dist/harness/output.js +0 -318
  216. package/dist/harness/output.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../src/harness/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,QAAQ,EAAkB,MAAM,uBAAuB,CAAC;AAC/E,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,cAAc,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAYtF,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,OAAO,EAAiB,QAAQ,EAAE,MAAM,WAAW,CAAC;AACxF,OAAO,EAAE,WAAW,EAAE,YAAY,EAAqB,yBAAyB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAShH,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAczC;;;;GAIG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,UAAU,CAA+D;IAChG,IAAI,EAAE,SAAS;IACf,OAAO,EAAE,CAAC;IACV,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAClC,MAAM,EAAE;QACP,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE;YACtC,MAAM,IAAI,GAA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AK,MAAM,IAAI,IAAI,OAAO,EAAE,CAAC;QAC5B,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM;YAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;aACvC,IAAI,IAAI,KAAK,IAAI;YAAE,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IACtE,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,CAAC,YAAY,EAAE,YAAY,EAAE,OAAO,CAAC,YAAY,EAAE,CAAC;AACpG,CAAC;AAED,SAAS,SAAS,CAAC,KAAc;IAChC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import { type Context, copyJson, 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 { AssistantEntry, ToolResultEntry } from \"../entries.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\tTaskRuntime,\n\tTx,\n\tTypedEntry,\n} from \"../types.ts\";\nimport { assignJson } from \"./json.ts\";\nimport { clearProgress, finishSlot, LiveDoc, type ToolSlot, toolSlot } from \"./live.ts\";\nimport { boundOutput, OutputBuffer, type OutputLimits, PROGRESS_BYTES_PER_SECOND, Progress } from \"./output.ts\";\nimport type {\n\tToolControl,\n\tToolDiagnostic,\n\tToolExecutionApi,\n\tToolExecutionResult,\n\tToolHooks,\n\tToolRegistration,\n} from \"./types.ts\";\nimport { recordUsage } from \"./usage.ts\";\n\nexport type ToolTaskInput = { assistant: EntryId; callId: string };\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\nexport type ToolTaskResult = { entryId: EntryId; control?: ToolControl };\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 appends 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.\n */\nexport const ToolTask = defineTask<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>({\n\tname: \"pi.tool\",\n\tversion: 1,\n\tinitial: () => ({ phase: \"call\" }),\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 runtime.agent(context)).tools.find((each) => each.name === call.name);\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, 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) return settle(runtime, 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 = errorText(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, call, COMPLETED, () => blocked, context);\n\t\t\t}\n\t\t\tconst validated = validate(tool, call, args);\n\t\t\tif (\"error\" in validated) return settle(runtime, call, COMPLETED, () => invalid(validated.error), context);\n\t\t\tconst final = validated.args;\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\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, 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 runtime.agent(context)).tools.find((each) => each.name === call.name);\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, 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, 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\tconst message = `Tool ${call.name} was aborted`;\n\t\tawait settle(runtime, call, { status: \"aborted\" }, (slot) => fromSlot(slot, \"aborted\", message), context);\n\t},\n});\n\n/** The tool call `callId` of the assistant entry. */\nasync function readCall(runtime: Runtime, input: ToolTaskInput, context: Context): Promise<ToolCall> {\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: errorText(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: errorText(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\tcall: ToolCall,\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 progress = publishProgress(runtime, reported, context);\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\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\tlet id: TaskId<R> | undefined;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tid = await tx.createTask(task, input, options);\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};\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\", errorText(error))] };\n\t\t// A throw, from `execute()` or from building the environment, ends the task `failed`, which cancels what the call owned; it no longer supervises it. The error text\n\t\t// is already in the result entry.\n\t\tending = { status: \"failed\", message: `Tool ${call.name} threw` };\n\t}\n\tended = true;\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, call, result, reported, context);\n\t\tawait settle(runtime, 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 `pi.live.tools` slot, each writing only what changed since the\n * last one.\n */\nfunction publishProgress(runtime: Runtime, reported: Reported, context: Context): Progress {\n\tlet written = { text: \"\", details: undefined as JsonValue | undefined, diagnostics: 0 };\n\treturn new Progress(\n\t\tasync () => {\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, and explicit text bounded, with the Harness's truncation\n * diagnostic last.\n */\nasync function finalResult(\n\truntime: Runtime,\n\tcall: ToolCall,\n\tresult: ToolExecutionResult,\n\treported: Reported,\n\tcontext: Context,\n): Promise<ToolExecutionResult> {\n\tconst harness: ToolDiagnostic[] = [];\n\tconst retained = result.content === undefined ? reported.output.snapshot() : undefined;\n\tconst content: Content =\n\t\tretained === undefined ? result.content! : retained.text === \"\" ? [] : [{ type: \"text\", text: retained.text }];\n\tlet final: ToolExecutionResult = {\n\t\t...result,\n\t\tcontent,\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 content.\n\tif (retained !== undefined && retained.droppedBytes > 0 && final.content === content) {\n\t\tharness.push(truncated(retained, reported.limits.retain));\n\t}\n\tconst bounded = boundContent(final.content ?? [], reported.limits);\n\tif (bounded.droppedBytes > 0) harness.push(truncated(bounded, reported.limits.retain));\n\treturn { ...final, content: bounded.content, diagnostics: [...(final.diagnostics ?? []), ...harness] };\n}\n\n/**\n * Commit the tool's terminal state: append its result entry, mark its slot done, and complete or end aborted with the\n * entry ID. `build` receives the slot so interruption and abort can report the durable partial output.\n */\nasync function settle(\n\truntime: Runtime,\n\tcall: ToolCall,\n\tending: Ending,\n\tbuild: (slot: Readonly<ToolSlot> | undefined) => ToolExecutionResult,\n\tcontext: Context,\n\tdurationMs?: number,\n): Promise<void> {\n\tawait runtime.commit(async (tx) => {\n\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\tconst result = build(slot);\n\t\tconst entry = await appendToolResult(tx, runtime.conversationId, call, result, runtime.now(), durationMs);\n\t\tif (slot !== undefined) finishSlot(slot, entry.id);\n\t\tconst entryId = entry.id;\n\t\tif (ending.status === \"aborted\")\n\t\t\treturn { status: \"terminal\", outcome: { status: \"aborted\", result: { entryId } } };\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: { entryId } } };\n\t\t}\n\t\t// Tools build control objects freely; drop keys set to undefined so the task result is strict JSON.\n\t\tconst control =\n\t\t\tresult.control === undefined\n\t\t\t\t? {}\n\t\t\t\t: { control: copyJson(result.control as JsonValue, { omitUndefinedProperties: true }) as ToolControl };\n\t\treturn { status: \"terminal\", outcome: { status: \"completed\", result: { entryId, ...control } } };\n\t}, context);\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(slot: Readonly<ToolSlot> | undefined, code: string, message: string): 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\tcontent: 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 { content: [], 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/**\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\ttimestamp: number,\n\tdurationMs?: number,\n): Promise<TypedEntry<{ diagnostics: ToolDiagnostic[] }>> {\n\tconst diagnostics = [...(result.diagnostics ?? [])];\n\tconst content: Content = [...(result.content ?? [])];\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\nfunction errorText(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\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,GACR,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;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;AAWnB,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AA+BzC;;;GAGG;AACH,MAAM,iBAAi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AAG,CAAC,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 {\n\tboundOutput,\n\tOutputBuffer,\n\ttype OutputLimits,\n\tPROGRESS_BYTES_PER_SECOND,\n\tProgress,\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 { 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 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"]}
@@ -11,6 +11,14 @@ export type ModelRef = {
11
11
  readonly modelId: string;
12
12
  };
13
13
  export type UserInput = UserMessage["content"];
14
+ /**
15
+ * The entry an input is placed as, instead of `pi.user`: an application kind, and data the transcript shows, such as its
16
+ * author. Its model message is still the input's user message.
17
+ */
18
+ export type InputEntry = {
19
+ readonly kind: string;
20
+ readonly data?: JsonValue;
21
+ };
14
22
  /** Host submission: user input that may start a run, or a passive entry write. */
15
23
  export type SubmissionDraft = {
16
24
  readonly requestId?: string;
@@ -18,7 +26,8 @@ export type SubmissionDraft = {
18
26
  readonly type: "input";
19
27
  readonly content: UserInput;
20
28
  readonly whenBusy?: "steer" | "followUp" | "reject";
21
- readonly entry?: never;
29
+ /** Place the input as this entry; default `pi.user` without data. The kind must not start with `pi.`. */
30
+ readonly entry?: InputEntry;
22
31
  } | {
23
32
  readonly type: "write";
24
33
  readonly entry: EntryDraft;
@@ -90,9 +99,18 @@ export type ToolDiagnostic = {
90
99
  readonly message: string;
91
100
  readonly code?: string;
92
101
  };
102
+ /**
103
+ * What a tool returns, on three channels: `output` for the model, `structuredOutput` for programs that call the tool
104
+ * (`executeTool()` callers, code mode scripts), and `details` for UIs.
105
+ */
93
106
  export type ToolExecutionResult<TDetails extends JsonValue = JsonValue> = {
94
- /** Omitted: the retained `output()` text becomes the content. */
95
- readonly content?: ToolResultMessage["content"];
107
+ /** For the model. Omitted: the retained `output()` text. */
108
+ readonly output?: ToolResultMessage["content"];
109
+ /**
110
+ * For programs. Required unless `isError` when the tool declares `structuredOutputSchema`, and validated against it;
111
+ * not allowed without one, where programs get the output itself (`NestedToolExecutionResult.structuredOutput`).
112
+ */
113
+ readonly structuredOutput?: JsonValue;
96
114
  readonly isError?: boolean;
97
115
  /** Omitted: the last `details()` value becomes the details. */
98
116
  readonly details?: TDetails;
@@ -102,6 +120,28 @@ export type ToolExecutionResult<TDetails extends JsonValue = JsonValue> = {
102
120
  readonly usage?: Usage;
103
121
  readonly control?: ToolControl;
104
122
  };
123
+ /**
124
+ * Result of a nested call, as `executeTool()` returns it. Programs read `structuredOutput`; the output for the model
125
+ * is not kept, and `control` does not apply.
126
+ */
127
+ export type NestedToolExecutionResult = {
128
+ /** The nested call's tool task. */
129
+ readonly taskId: TaskId;
130
+ /**
131
+ * The tool's value for programs. A tool with `structuredOutputSchema`: its validated `structuredOutput`, also on an
132
+ * error result that has one; absent otherwise, and an error's text is then in an error diagnostic. A tool without:
133
+ * its bounded output, success or error, as a string for one text item, an `ImageContent` for one image, `""` for
134
+ * none, and the content list otherwise. Absent on an error result the Harness wrote itself (unavailable, invalid,
135
+ * blocked, interrupted, aborted); `diagnostics` say what went wrong.
136
+ */
137
+ readonly structuredOutput?: JsonValue;
138
+ readonly isError: boolean;
139
+ readonly details?: JsonValue;
140
+ readonly diagnostics: readonly ToolDiagnostic[];
141
+ readonly usage?: Usage;
142
+ /** Execution time of the attempt that produced the result; absent when it never executed. */
143
+ readonly durationMs?: number;
144
+ };
105
145
  /** Whether the tools of one round run at once or one after another in call order. */
106
146
  export type ToolExecutionMode = "parallel" | "sequential";
107
147
  /** How many queued items of one mode a boundary places: the first, or all of them. */
@@ -123,7 +163,7 @@ export interface ToolExecutionApi<TDetails extends JsonValue = JsonValue> extend
123
163
  /** Built by `HarnessOptions.env` for this call; `undefined` without an environment. */
124
164
  readonly env: ExecutionEnv | undefined;
125
165
  /**
126
- * Append running output; it becomes the result content when the result omits `content`. `skipped` counts output
166
+ * Append running output; it becomes the result's `output` when the result omits it. `skipped` counts output
127
167
  * omitted before the chunk, as reported by an environment given `outputWindow` (`ShellOutputInfo.skipped`).
128
168
  */
129
169
  output(chunk: string | Uint8Array, skipped?: ShellOutputSkip): void;
@@ -133,6 +173,14 @@ export interface ToolExecutionApi<TDetails extends JsonValue = JsonValue> extend
133
173
  * transforms text must also replace this with `undefined`, so skipped text cannot bypass its transform.
134
174
  */
135
175
  readonly outputWindow: ShellOutputWindow | undefined;
176
+ /**
177
+ * The output retained so far, as the model will see it when the result omits `output`, and whether earlier output was
178
+ * dropped; for a tool that also returns that text in its `structuredOutput`.
179
+ */
180
+ retainedOutput(): {
181
+ readonly text: string;
182
+ readonly truncated: boolean;
183
+ };
136
184
  /** Record a model-visible remark about this call. */
137
185
  diagnostic(diagnostic: ToolDiagnostic): void;
138
186
  /** Replace running details; the last value becomes the result details when the result omits `details`. */
@@ -140,6 +188,10 @@ export interface ToolExecutionApi<TDetails extends JsonValue = JsonValue> extend
140
188
  commit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T>;
141
189
  memo<T extends JsonValue>(name: string, context: Context): Promise<T | undefined>;
142
190
  memo<T extends JsonValue>(name: string, candidate: T, context: Context): Promise<T>;
191
+ /**
192
+ * Create a task in one commit. A child task of a tool that is not replay-safe defaults to `abandonOnRestart`: the
193
+ * tool never resumes after a restart, so nothing awaits the child then.
194
+ */
143
195
  createTask<I, S extends {
144
196
  phase: string;
145
197
  }, R, H extends object>(task: Task<I, S, R, H>, input: I, options: Omit<TaskOptions, "conversationId">, context: Context): Promise<TaskId<R>>;
@@ -147,6 +199,37 @@ export interface ToolExecutionApi<TDetails extends JsonValue = JsonValue> extend
147
199
  waitForTask<R>(id: TaskId<R>, context: Context): Promise<SettledTask<R>>;
148
200
  /** Invocation-bound handle of an existing conversation, such as one this tool created in `commit()`. */
149
201
  conversation(id: ConversationId, context: Context): Promise<ConversationHandle | undefined>;
202
+ /**
203
+ * Run tool `name` as a nested call of this one and wait for its result. The nested call is its own `pi.tool` task,
204
+ * owned by this call: it resolves the tool among the conversation's tools, validates, runs the `ToolTask` hooks (which
205
+ * see `call.parent`), applies output limits and the tool's replay policy, and reports progress in `pi.live.nestedTools`.
206
+ * Its result returns here instead of entering the transcript. A call that is blocked, invalid, throws, is interrupted,
207
+ * or is aborted returns an `isError` result.
208
+ *
209
+ * The nested call's key names it within this call; its call ID is `<callId>/<key>`. By default the key is the call's
210
+ * position among this invocation's nested calls, `1`, `2`, ... An explicit `key` must be non-empty, without `/`, not
211
+ * `__proto__`, and not a positive integer, so it never collides with a default one. A rerun of a replay-safe tool
212
+ * that makes a call with a used key, by calling in the same order or by passing the same `key`, gets that nested call
213
+ * back, finished or still running, instead of starting another. A nested call a crash interrupted before its result
214
+ * committed follows its own replay policy, so this is not exactly-once execution. Reusing a key with another tool or
215
+ * other arguments throws. A tool that is not replay-safe never reruns: after a restart, its unfinished nested calls
216
+ * are abandoned (`TaskOptions.abandonOnRestart`) before they run again.
217
+ *
218
+ * `progress: false` commits no running output, details, or diagnostics to the nested call's slot, only its status;
219
+ * the result still carries its details and diagnostics, and a schema-less tool's output as `structuredOutput`. An
220
+ * interrupted or aborted call's result is built from its slot, so it then has none of them. Either way, programs never
221
+ * get the partial output of an interrupted or aborted call.
222
+ *
223
+ * Nested calls run as soon as they are made, whatever their `executionMode`; the caller decides what runs at once by
224
+ * what it awaits. Cancelling `context` stops only the wait; the nested call runs on. When this call settles, nested
225
+ * calls it left running are aborted first. A nested result's `usage` is already counted under its tool; a result
226
+ * that passes it on counts it again. Rejects, instead of returning a result, once `execute()` has returned, when this
227
+ * call is aborted, or when the Harness closes.
228
+ */
229
+ executeTool(name: string, args: JsonObject, context: Context, options?: {
230
+ readonly key?: string;
231
+ readonly progress?: boolean;
232
+ }): Promise<NestedToolExecutionResult>;
150
233
  }
151
234
  /**
152
235
  * Executable tool registered in a registry. Only pi-ai `Tool` fields enter the transcript. `args` are typed by
@@ -163,6 +246,22 @@ export type ToolRegistration<TParameters extends TSchema = TSchema, TDetails ext
163
246
  * still validated against `parameters`.
164
247
  */
165
248
  prepareArguments?(args: unknown): Static<TParameters>;
249
+ /**
250
+ * Schema of `structuredOutput`, which programs that call the tool receive. Omitted: they receive the result's bounded
251
+ * output, success or error, as `NestedToolExecutionResult.structuredOutput` describes.
252
+ */
253
+ readonly structuredOutputSchema?: TSchema;
254
+ /**
255
+ * Who may call the tool: the model, other tools through `executeTool()`, or both (default). A code mode tool is
256
+ * `["model"]`, so scripts cannot start scripts; tools behind code mode, such as MCP tools, can be `["tools"]`, so the
257
+ * model is never offered them.
258
+ */
259
+ readonly callers?: readonly ("model" | "tools")[];
260
+ /**
261
+ * Not offered to the model until loaded: the model gets the tool only when `modelTools` names it, in its array or its
262
+ * `add`, which `control.addTools` (from a tool such as `tool_search`) writes. Other tools can call it any time.
263
+ */
264
+ readonly deferred?: true;
166
265
  readonly outputLimits?: {
167
266
  readonly maxBytes?: number;
168
267
  readonly maxLines?: number;
@@ -253,10 +352,23 @@ export type AgentState = {
253
352
  add?: string[];
254
353
  remove?: string[];
255
354
  };
256
- /** Filters the selected extensions' tools. An array offers exactly these, in order. */
355
+ /** Filters the selected extensions' tools: the enabled tools. An array enables exactly these, in order. */
257
356
  tools?: string[] | {
258
357
  remove: string[];
259
358
  };
359
+ /**
360
+ * Filters the enabled tools the model may call (`callers` includes `model`): the tools offered to it. Never widens:
361
+ * other tools can still call the ones it leaves out.
362
+ * - Unset: every such tool except deferred ones.
363
+ * - An array: exactly these, in order, deferred ones too.
364
+ * - An object: every such tool except deferred ones and those in `remove`, in registry order, followed by the
365
+ * deferred tools in `add` that are not in `remove`, in `add` order. Names of tools that are not deferred or not
366
+ * registered have no effect in `add`.
367
+ */
368
+ modelTools?: string[] | {
369
+ remove?: string[];
370
+ add?: string[];
371
+ };
260
372
  /** Rendered after every extension section, as the section `instructions`. */
261
373
  instructions?: string;
262
374
  /** Directory within the environment's file system, passed to `HarnessOptions.env`. */
@@ -273,6 +385,11 @@ export type AgentChange = {
273
385
  readonly tools?: readonly ToolRegistration[] | {
274
386
  readonly remove: readonly ToolRegistration[];
275
387
  } | null;
388
+ /** Replaces the stored filter as a whole; tools loaded with `control.addTools` are in its `add`. */
389
+ readonly modelTools?: readonly ToolRegistration[] | {
390
+ readonly remove?: readonly ToolRegistration[];
391
+ readonly add?: readonly ToolRegistration[];
392
+ } | null;
276
393
  readonly instructions?: string | null;
277
394
  readonly cwd?: string | null;
278
395
  };
@@ -281,8 +398,12 @@ export type Agent<Tool extends ToolRegistration = ToolRegistration> = {
281
398
  readonly model?: ModelRef;
282
399
  readonly thinkingLevel: ModelThinkingLevel;
283
400
  readonly extensions: readonly Extension<Tool>[];
284
- /** The tools a request offers, in order. */
401
+ /** The tools a request offers, in order: enabled, callable by the model, and selected by `modelTools`. */
285
402
  readonly tools: readonly Tool[];
403
+ /** The tools nested calls (`executeTool()`) resolve among, in order: enabled and callable by tools. */
404
+ readonly callable: readonly Tool[];
405
+ /** Enabled deferred tools the model may call and is not offered yet, in registry order: what `tool_search` loads. */
406
+ readonly deferred: readonly Tool[];
286
407
  /** Extension sections, then `instructions` when set. */
287
408
  readonly sections: readonly PromptSection<Tool>[];
288
409
  readonly instructions?: string;
@@ -367,6 +488,12 @@ export type HarnessSettings = {
367
488
  * Busy conversations always keep it; `0` drops it once the conversation is idle.
368
489
  */
369
490
  readonly contextRetentionMs?: number;
491
+ /**
492
+ * How long a loaded document that no watch or document state observes stays in memory after its last read or write;
493
+ * the next access loads it from Storage. Observed documents always stay. Default ten minutes; `0` drops one right
494
+ * after use; `Infinity` keeps them. Anything else that is not a number of milliseconds means the default.
495
+ */
496
+ readonly documentRetentionMs?: number;
370
497
  };
371
498
  /** Resolved settings: every field over its built-in default, object fields merged. */
372
499
  export type Settings = {
@@ -380,6 +507,7 @@ export type Settings = {
380
507
  readonly steeringMode: QueueMode;
381
508
  readonly followUpMode: QueueMode;
382
509
  readonly contextRetentionMs: number;
510
+ readonly documentRetentionMs: number;
383
511
  };
384
512
  /** What `HarnessOptions.env` builds an environment for. */
385
513
  export type EnvTarget = {
@@ -402,7 +530,10 @@ export type HarnessOptions<Tool extends ToolRegistration = ToolRegistration> = {
402
530
  */
403
531
  readonly conversationCreated?: (tx: Tx, conversation: ConversationRecord) => void | Promise<void>;
404
532
  readonly now?: () => number;
405
- /** Receives extension failures that do not fail the calling operation. Must not throw. */
533
+ /**
534
+ * Receives failures that do not fail the calling operation, such as a throwing hook or listener, and the error that
535
+ * fails the Session, once. Its own throw or rejection is dropped.
536
+ */
406
537
  readonly onReport?: (error: unknown) => void;
407
538
  };
408
539
  /** Live task and what the scheduler would do with it under the current registry. */
@@ -461,8 +592,10 @@ export interface Conversation {
461
592
  /** `configure()` in its own commit. */
462
593
  configure(change: AgentChange, context: Context): Promise<void>;
463
594
  /**
464
- * Durably admit user input or a passive entry write. A busy conversation, or one with queued items, queues it in
465
- * `pi.inbox`; `whenBusy: "reject"` rejects with `ConversationBusy` instead and writes nothing.
595
+ * Durably admit user input or a passive entry write. A busy conversation, or one with queued items, queues input and
596
+ * writes that affect model context in `pi.inbox`; `whenBusy: "reject"` rejects input with `ConversationBusy` instead
597
+ * and writes nothing. A write of only `kind` and `data` (no `model`, `head`, or `edits`) is appended at once,
598
+ * even mid-run, as it changes nothing the model sees.
466
599
  */
467
600
  submit(submission: SubmissionDraft, context: Context): Promise<Submission>;
468
601
  /**
@@ -568,15 +701,22 @@ export interface GenerationHooks {
568
701
  /** After every tool of the round is terminal; `results` are the round's result entries in call order. */
569
702
  afterTools(assistant: EntryId, results: readonly EntryId[], api: HookApi, context: Context): void | Promise<void>;
570
703
  }
571
- /** Hooks of the built-in tool task. */
704
+ /** A call as tool hooks see it; `parent` is set for a nested call, one a running tool made through `executeTool()`. */
705
+ export type ToolHookCall = ToolCall & {
706
+ readonly parent?: {
707
+ readonly taskId: TaskId;
708
+ readonly callId: string;
709
+ };
710
+ };
711
+ /** Hooks of the built-in tool task, for model-issued and nested calls. */
572
712
  export interface ToolHooks {
573
713
  /** Before intent; the first `block` wins, otherwise `arguments` replace the call's arguments. A throw blocks. */
574
- beforeTool(call: ToolCall, api: HookApi, context: Context): HookResult<{
714
+ beforeTool(call: ToolHookCall, api: HookApi, context: Context): HookResult<{
575
715
  readonly arguments?: JsonObject;
576
716
  readonly block?: string;
577
717
  }>;
578
- /** After execution, before the result entry; replaces the result. */
579
- afterTool(call: ToolCall, result: ToolExecutionResult, api: HookApi, context: Context): HookResult<ToolExecutionResult>;
718
+ /** After execution, before the result is committed; replaces the result. */
719
+ afterTool(call: ToolHookCall, result: ToolExecutionResult, api: HookApi, context: Context): HookResult<ToolExecutionResult>;
580
720
  }
581
721
  /** Hooks of the built-in compaction task. */
582
722
  export interface CompactionHooks {