@earendil-works/pi-durable 1.4.0 → 1.5.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 (221) hide show
  1. package/CHANGELOG.md +186 -0
  2. package/README.md +181 -84
  3. package/dist/codemode/codemode.d.ts +4 -4
  4. package/dist/codemode/codemode.d.ts.map +1 -1
  5. package/dist/codemode/codemode.js +9 -12
  6. package/dist/codemode/codemode.js.map +1 -1
  7. package/dist/codemode/models.js +4 -4
  8. package/dist/codemode/models.js.map +1 -1
  9. package/dist/env/index.d.ts +12 -10
  10. package/dist/env/index.d.ts.map +1 -1
  11. package/dist/env/index.js.map +1 -1
  12. package/dist/env/node-watch.d.ts +3 -3
  13. package/dist/env/node-watch.d.ts.map +1 -1
  14. package/dist/env/node-watch.js +18 -16
  15. package/dist/env/node-watch.js.map +1 -1
  16. package/dist/env/node.d.ts +2 -2
  17. package/dist/env/node.d.ts.map +1 -1
  18. package/dist/env/node.js +1 -1
  19. package/dist/env/node.js.map +1 -1
  20. package/dist/errors.d.ts +18 -2
  21. package/dist/errors.d.ts.map +1 -1
  22. package/dist/errors.js +26 -3
  23. package/dist/errors.js.map +1 -1
  24. package/dist/harness/agent.d.ts.map +1 -1
  25. package/dist/harness/agent.js +10 -2
  26. package/dist/harness/agent.js.map +1 -1
  27. package/dist/harness/compaction.d.ts.map +1 -1
  28. package/dist/harness/compaction.js +19 -2
  29. package/dist/harness/compaction.js.map +1 -1
  30. package/dist/harness/context.d.ts +23 -7
  31. package/dist/harness/context.d.ts.map +1 -1
  32. package/dist/harness/context.js +71 -25
  33. package/dist/harness/context.js.map +1 -1
  34. package/dist/harness/define.d.ts +7 -3
  35. package/dist/harness/define.d.ts.map +1 -1
  36. package/dist/harness/define.js +4 -0
  37. package/dist/harness/define.js.map +1 -1
  38. package/dist/harness/generation.d.ts +38 -5
  39. package/dist/harness/generation.d.ts.map +1 -1
  40. package/dist/harness/generation.js +445 -96
  41. package/dist/harness/generation.js.map +1 -1
  42. package/dist/harness/harness.d.ts +2 -0
  43. package/dist/harness/harness.d.ts.map +1 -1
  44. package/dist/harness/harness.js +87 -62
  45. package/dist/harness/harness.js.map +1 -1
  46. package/dist/harness/inbox.d.ts +5 -1
  47. package/dist/harness/inbox.d.ts.map +1 -1
  48. package/dist/harness/inbox.js +4 -1
  49. package/dist/harness/inbox.js.map +1 -1
  50. package/dist/harness/json.d.ts +20 -4
  51. package/dist/harness/json.d.ts.map +1 -1
  52. package/dist/harness/json.js +23 -5
  53. package/dist/harness/json.js.map +1 -1
  54. package/dist/harness/live.d.ts +122 -16
  55. package/dist/harness/live.d.ts.map +1 -1
  56. package/dist/harness/live.js +93 -12
  57. package/dist/harness/live.js.map +1 -1
  58. package/dist/harness/partial-changes.d.ts +54 -0
  59. package/dist/harness/partial-changes.d.ts.map +1 -0
  60. package/dist/harness/partial-changes.js +162 -0
  61. package/dist/harness/partial-changes.js.map +1 -0
  62. package/dist/harness/registry-reader.d.ts +11 -0
  63. package/dist/harness/registry-reader.d.ts.map +1 -0
  64. package/dist/harness/registry-reader.js +25 -0
  65. package/dist/harness/registry-reader.js.map +1 -0
  66. package/dist/harness/scheduler.d.ts +46 -19
  67. package/dist/harness/scheduler.d.ts.map +1 -1
  68. package/dist/harness/scheduler.js +973 -376
  69. package/dist/harness/scheduler.js.map +1 -1
  70. package/dist/harness/submissions.d.ts +17 -10
  71. package/dist/harness/submissions.d.ts.map +1 -1
  72. package/dist/harness/submissions.js +62 -25
  73. package/dist/harness/submissions.js.map +1 -1
  74. package/dist/harness/task-graph.d.ts +12 -9
  75. package/dist/harness/task-graph.d.ts.map +1 -1
  76. package/dist/harness/task-graph.js +38 -28
  77. package/dist/harness/task-graph.js.map +1 -1
  78. package/dist/harness/telemetry.d.ts +11 -11
  79. package/dist/harness/telemetry.d.ts.map +1 -1
  80. package/dist/harness/telemetry.js +7 -7
  81. package/dist/harness/telemetry.js.map +1 -1
  82. package/dist/harness/tool.d.ts +2 -0
  83. package/dist/harness/tool.d.ts.map +1 -1
  84. package/dist/harness/tool.js +171 -55
  85. package/dist/harness/tool.js.map +1 -1
  86. package/dist/harness/transcript.d.ts +72 -0
  87. package/dist/harness/transcript.d.ts.map +1 -0
  88. package/dist/harness/transcript.js +264 -0
  89. package/dist/harness/transcript.js.map +1 -0
  90. package/dist/harness/types.d.ts +218 -59
  91. package/dist/harness/types.d.ts.map +1 -1
  92. package/dist/harness/types.js.map +1 -1
  93. package/dist/harness/util.d.ts +3 -1
  94. package/dist/harness/util.d.ts.map +1 -1
  95. package/dist/harness/util.js +9 -0
  96. package/dist/harness/util.js.map +1 -1
  97. package/dist/harness/view.d.ts +43 -22
  98. package/dist/harness/view.d.ts.map +1 -1
  99. package/dist/harness/view.js +130 -71
  100. package/dist/harness/view.js.map +1 -1
  101. package/dist/index.d.ts +9 -7
  102. package/dist/index.d.ts.map +1 -1
  103. package/dist/index.js +4 -3
  104. package/dist/index.js.map +1 -1
  105. package/dist/search.d.ts +19 -3
  106. package/dist/search.d.ts.map +1 -1
  107. package/dist/search.js +107 -44
  108. package/dist/search.js.map +1 -1
  109. package/dist/session/cached-storage.d.ts +71 -0
  110. package/dist/session/cached-storage.d.ts.map +1 -0
  111. package/dist/session/cached-storage.js +269 -0
  112. package/dist/session/cached-storage.js.map +1 -0
  113. package/dist/session/conversation-tails.d.ts +33 -0
  114. package/dist/session/conversation-tails.d.ts.map +1 -0
  115. package/dist/session/conversation-tails.js +101 -0
  116. package/dist/session/conversation-tails.js.map +1 -0
  117. package/dist/session/keys.d.ts +68 -0
  118. package/dist/session/keys.d.ts.map +1 -0
  119. package/dist/session/keys.js +161 -0
  120. package/dist/session/keys.js.map +1 -0
  121. package/dist/session/session.d.ts +167 -26
  122. package/dist/session/session.d.ts.map +1 -1
  123. package/dist/session/session.js +1029 -171
  124. package/dist/session/session.js.map +1 -1
  125. package/dist/session/transaction.d.ts +81 -3
  126. package/dist/session/transaction.d.ts.map +1 -1
  127. package/dist/session/transaction.js +224 -37
  128. package/dist/session/transaction.js.map +1 -1
  129. package/dist/session/writer.d.ts +74 -0
  130. package/dist/session/writer.d.ts.map +1 -0
  131. package/dist/session/writer.js +294 -0
  132. package/dist/session/writer.js.map +1 -0
  133. package/dist/storage/indexeddb.d.ts +10 -2
  134. package/dist/storage/indexeddb.d.ts.map +1 -1
  135. package/dist/storage/indexeddb.js +91 -41
  136. package/dist/storage/indexeddb.js.map +1 -1
  137. package/dist/storage/jsonl/storage.d.ts +14 -2
  138. package/dist/storage/jsonl/storage.d.ts.map +1 -1
  139. package/dist/storage/jsonl/storage.js +88 -24
  140. package/dist/storage/jsonl/storage.js.map +1 -1
  141. package/dist/storage/memory.d.ts +7 -2
  142. package/dist/storage/memory.d.ts.map +1 -1
  143. package/dist/storage/memory.js +28 -2
  144. package/dist/storage/memory.js.map +1 -1
  145. package/dist/storage/sqlite/storage.d.ts +14 -2
  146. package/dist/storage/sqlite/storage.d.ts.map +1 -1
  147. package/dist/storage/sqlite/storage.js +110 -36
  148. package/dist/storage/sqlite/storage.js.map +1 -1
  149. package/dist/storage/store/commit.d.ts +33 -0
  150. package/dist/storage/store/commit.d.ts.map +1 -0
  151. package/dist/storage/store/commit.js +286 -0
  152. package/dist/storage/store/commit.js.map +1 -0
  153. package/dist/storage/store/documents.d.ts +43 -0
  154. package/dist/storage/store/documents.d.ts.map +1 -0
  155. package/dist/storage/store/documents.js +102 -0
  156. package/dist/storage/store/documents.js.map +1 -0
  157. package/dist/storage/store/index.d.ts +2 -0
  158. package/dist/storage/store/index.d.ts.map +1 -0
  159. package/dist/storage/store/index.js +2 -0
  160. package/dist/storage/store/index.js.map +1 -0
  161. package/dist/storage/store/queries.d.ts +49 -0
  162. package/dist/storage/store/queries.d.ts.map +1 -0
  163. package/dist/storage/store/queries.js +93 -0
  164. package/dist/storage/store/queries.js.map +1 -0
  165. package/dist/storage/store/storage.d.ts +59 -0
  166. package/dist/storage/store/storage.d.ts.map +1 -0
  167. package/dist/storage/store/storage.js +438 -0
  168. package/dist/storage/store/storage.js.map +1 -0
  169. package/dist/storage/store/tables.d.ts +54 -0
  170. package/dist/storage/store/tables.d.ts.map +1 -0
  171. package/dist/storage/store/tables.js +108 -0
  172. package/dist/storage/store/tables.js.map +1 -0
  173. package/dist/testing/commit-writes.d.ts +5 -0
  174. package/dist/testing/commit-writes.d.ts.map +1 -0
  175. package/dist/testing/commit-writes.js +12 -0
  176. package/dist/testing/commit-writes.js.map +1 -0
  177. package/dist/testing/env-conformance.js +7 -7
  178. package/dist/testing/env-conformance.js.map +1 -1
  179. package/dist/testing/index.d.ts +1 -0
  180. package/dist/testing/index.d.ts.map +1 -1
  181. package/dist/testing/index.js +1 -0
  182. package/dist/testing/index.js.map +1 -1
  183. package/dist/testing/storage-benchmark.d.ts.map +1 -1
  184. package/dist/testing/storage-benchmark.js +18 -17
  185. package/dist/testing/storage-benchmark.js.map +1 -1
  186. package/dist/testing/storage-conformance.d.ts.map +1 -1
  187. package/dist/testing/storage-conformance.js +354 -69
  188. package/dist/testing/storage-conformance.js.map +1 -1
  189. package/dist/tool-search/tool-search.d.ts +6 -12
  190. package/dist/tool-search/tool-search.d.ts.map +1 -1
  191. package/dist/tool-search/tool-search.js +7 -7
  192. package/dist/tool-search/tool-search.js.map +1 -1
  193. package/dist/tools/bash.d.ts +12 -12
  194. package/dist/tools/bash.d.ts.map +1 -1
  195. package/dist/tools/bash.js +16 -15
  196. package/dist/tools/bash.js.map +1 -1
  197. package/dist/tools/edit.d.ts +7 -7
  198. package/dist/tools/edit.d.ts.map +1 -1
  199. package/dist/tools/edit.js +9 -9
  200. package/dist/tools/edit.js.map +1 -1
  201. package/dist/tools/index.d.ts +32 -32
  202. package/dist/tools/read.d.ts +6 -6
  203. package/dist/tools/read.d.ts.map +1 -1
  204. package/dist/tools/read.js +19 -8
  205. package/dist/tools/read.js.map +1 -1
  206. package/dist/tools/write.d.ts +4 -4
  207. package/dist/tools/write.d.ts.map +1 -1
  208. package/dist/tools/write.js +5 -5
  209. package/dist/tools/write.js.map +1 -1
  210. package/dist/types.d.ts +223 -77
  211. package/dist/types.d.ts.map +1 -1
  212. package/dist/types.js.map +1 -1
  213. package/package.json +19 -12
  214. package/dist/harness/events.d.ts +0 -186
  215. package/dist/harness/events.d.ts.map +0 -1
  216. package/dist/harness/events.js +0 -373
  217. package/dist/harness/events.js.map +0 -1
  218. package/dist/session/observation.d.ts +0 -42
  219. package/dist/session/observation.d.ts.map +0 -1
  220. package/dist/session/observation.js +0 -281
  221. package/dist/session/observation.js.map +0 -1
@@ -35,9 +35,10 @@
35
35
  * call with an error result.
36
36
  */
37
37
  import { copyJson } from "@earendil-works/chord";
38
- import { toCodemodeIdentifier, } from "@earendil-works/pi-codemode/portable";
38
+ import { ownedSlice } from "@earendil-works/chord/delta";
39
+ import { toCodemodeIdentifier } from "@earendil-works/pi-codemode/declarations";
39
40
  import { CODEMODE_SOURCE_GRAMMAR, parseCodemodeSource } from "@earendil-works/pi-codemode/source";
40
- import { Type } from "typebox";
41
+ import { obj, str } from "@earendil-works/pi-schema";
41
42
  import { defineDoc } from "../documents.js";
42
43
  import { errorMessage } from "../errors.js";
43
44
  import { defineExtension, defineTool, section } from "../harness/define.js";
@@ -84,9 +85,10 @@ export const CodemodeStoreDoc = defineDoc({
84
85
  const ARGS_PREVIEW_CHARS = 200;
85
86
  const ERROR_PREVIEW_CHARS = 500;
86
87
  function cut(text, max) {
87
- return text.length > max ? `${text.slice(0, max - 3)}...` : text;
88
+ // A copy: the row outlives the arguments or error text it previews.
89
+ return text.length > max ? `${ownedSlice(text, 0, max - 3)}...` : text;
88
90
  }
89
- const codemodeSchema = Type.Object({ code: Type.String({ description: "Raw JavaScript source." }) });
91
+ const codemodeSchema = obj({ code: str({ description: "Raw JavaScript source." }) }, { open: true });
90
92
  /** Outputs bounded by the script's own token budget; the Harness's limits only stop a runaway. */
91
93
  const OUTPUT_LIMITS = { maxBytes: 4 * 1024 * 1024, maxLines: 100_000 };
92
94
  /** Globals for finding tools, answered from the start data, so a replay sees what the first run saw. */
@@ -797,14 +799,9 @@ class CodemodeCall {
797
799
  const own = namespaceOfTool(tool.name);
798
800
  if (typeof namespace === "string" && (own === undefined || !matchesNamespace(own, namespace)))
799
801
  return [];
800
- const text = [
801
- tool.name,
802
- tool.name.replaceAll("_", " "),
803
- tool.description,
804
- own?.name ?? "",
805
- own?.description ?? "",
806
- ];
807
- return [{ name: tool.name, text: text.join(" ") }];
802
+ const namespaceText = own === undefined ? "" : [own.name, own.description ?? "", own.instructions ?? ""].join(" ");
803
+ // `description` is the tool's sample: its description and declaration, with the parameters' names and descriptions.
804
+ return [{ name: tool.name, text: tool.description, namespaceText }];
808
805
  });
809
806
  return rankDocuments(query, documents, limit).map((name) => {
810
807
  const tool = tools.find((candidate) => candidate.name === name);
@@ -1 +1 @@
1
- {"version":3,"file":"codemode.js","sourceRoot":"","sources":["../../src/codemode/codemode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,OAAO,EAAgB,QAAQ,EAAkB,MAAM,uBAAuB,CAAC;AAE/E,OAAO,EAMN,oBAAoB,GACpB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAClG,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,aAAa,EAAsB,MAAM,oBAAoB,CAAC;AAQvE,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,OAAO,EAEN,mBAAmB,EACnB,eAAe,EACf,8BAA8B,EAC9B,WAAW,EACX,QAAQ,GACR,MAAM,eAAe,CAAC;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AC,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,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAC3G,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;QACrC,IAAI,CAAC,KAAK,CACT,CAAC,GAAG,EAAE,EAAE,CACP,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,QAAQ,CAAE,CAA6B,CAAC,GAAG,CAAC,EAAG,CAA6B,CAAC,GAAG,CAAC,CAAC,CAC5G,CACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Durable code mode: a tool that runs model-written JavaScript in a QuickJS sandbox, whose script survives a restart.\n *\n * Problem: a script is in-memory VM state. A restart while\n *\n * const results = await Promise.all(paths.map((path) => tools.read({ path })));\n *\n * waits for the last of 200 reads would lose the script and every read it made.\n *\n * Solution: deterministic replay (`CodemodeSandboxBase.start()` in pi-codemode). The VM only runs when the host hands\n * it a result; given the same start data, clock, seed, and results in the same order, it makes the same calls with\n * the same arguments. The tool is replay-safe: after a restart, `execute()` runs again, starts the script again from\n * the stored start data, and hands it the results it got before, in the order it got them, from a journal written\n * before each delivery. Nested tool calls reattach to their tasks by key (`c<VM call id>`), so they never run twice\n * unless their own replay policy reruns them; their results come from `NestedCallDoc`. Then the script continues live.\n *\n * Documents, scoped to the code mode call's task and gone when it settles:\n * - `pi.codemode.run`: the start data, written once before the VM starts, and the outcome, written once when the call\n * decides it (with the store writes, in one transaction), so a rerun after that returns it without a VM.\n * - `pi.codemode.journal`: one entry per delivered result, in delivery order: the VM call ID, the clock value, the\n * calls the VM had issued after processing it (once acknowledged), and a global's outcome, which nothing else stores.\n *\n * Each result's acknowledged call count is recorded with the next journal commit, or at once when the VM has processed\n * everything delivered: a script waiting on a long call is where a restart usually finds it. A sequential script\n * therefore costs one journal commit and one count commit per result, on top of its nested calls' own; that is the\n * price of checking the most common crash point.\n *\n * A call is launched only once the count of calls issued in the drain that made it is committed. So every key an earlier\n * attempt admitted is at most its last recorded count; a replay checks every recorded count, so when it releases its\n * calls it has made every call an earlier attempt could have admitted, and later calls are new.\n *\n * A rerun refuses to replay (no new nested calls; nested calls admitted earlier may still resume on their own and are\n * aborted by the call's cleanup) when this module's version or the VM's fingerprint changed, when the deadline passed,\n * or when the script diverges: it makes another call, or calls in another order, than the journal says. Each ends the\n * call with an error result.\n */\nimport { type Context, copyJson, type JsonValue } from \"@earendil-works/chord\";\nimport type { TextContent } from \"@earendil-works/pi-ai\";\nimport {\n\ttype CodemodeHostCall,\n\ttype CodemodeOutcome,\n\ttype CodemodeResult,\n\ttype CodemodeRun,\n\ttype CodemodeSandboxBase,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode/portable\";\nimport { CODEMODE_SOURCE_GRAMMAR, parseCodemodeSource } from \"@earendil-works/pi-codemode/source\";\nimport { type Static, Type } from \"typebox\";\nimport { defineDoc } from \"../documents.ts\";\nimport type { ExecutionEnv } from \"../env/index.ts\";\nimport { errorMessage } from \"../errors.ts\";\nimport { defineExtension, defineTool, section } from \"../harness/define.ts\";\nimport { NestedCallDoc, type ToolTaskInput } from \"../harness/tool.ts\";\nimport type {\n\tExtension,\n\tNestedToolExecutionResult,\n\tToolExecutionApi,\n\tToolExecutionResult,\n\tToolRegistration,\n} from \"../harness/types.ts\";\nimport { rankDocuments } from \"../search.ts\";\nimport type { JsonObject } from \"../types.ts\";\nimport {\n\ttype CodemodeNamespace,\n\tcodemodeDescription,\n\tcodemodeSection,\n\tDEFAULT_CODEMODE_INLINE_BUDGET,\n\tnamespaceOf,\n\tsampleOf,\n} from \"./describe.ts\";\nimport {\n\tCATALOG_GLOBALS,\n\tCODEMODE_INTERNAL_PREFIX,\n\tcatalogCall,\n\tcreateModelTools,\n\tGENERATE_IMAGES_TOOL,\n\tMAX_CONCURRENT_MODEL_CALLS,\n\tMODEL_CALLS,\n} from \"./models.ts\";\nimport { DEFAULT_MAX_OUTPUT_TOKENS, formatResult, type OutputFile } from \"./output.ts\";\n\n/**\n * Version of everything in this module that turns stored results into what a script sees: result mapping, globals,\n * start data. Bump it when that changes, so a call started before an upgrade is not replayed by different code.\n */\nexport const CODEMODE_MODULE_VERSION = 2;\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\n\n/** One tool as the script sees it: `tools.<jsName>`. */\n/**\n * `structured`: the tool declares `structuredOutputSchema`, so an error result with a value resolves with it.\n * `hidden`: an internal tool of this extension (`pi.codemode.*`), which scripts reach only through a global such as\n * `models.classify()`; never in `tools`, `ALL_TOOLS`, or tool search.\n */\ntype DeclaredTool = { name: string; jsName: string; description: string; structured?: true; hidden?: true };\n\n/** What a call starts with; a rerun starts the VM from exactly this. */\ntype Start = {\n\tversion: number;\n\tstartedAt: number;\n\tseed: number;\n\t/** The VM's fingerprint, recorded by the first run before any call is admitted. */\n\tfingerprint?: string;\n\t/** `startedAt + timeout_ms` when the script set one. */\n\tdeadline?: number;\n\ttools: DeclaredTool[];\n\t/** The namespaces of the tools, as `describeNamespace()` and `searchTools()` see them. */\n\tnamespaces: { name: string; description?: string; instructions?: string; tools: string[] }[];\n\tglobals: { name: string; spread: boolean }[];\n\t/** `max_output_tokens` of the script's options line, or the default. */\n\tmaxOutputTokens: number;\n\tstore: Record<string, JsonValue>;\n};\n\ntype RunState = {\n\tstart?: Start;\n\t/** Directory of the result's files (the full output, images), created once: a rerun writes the same files again. */\n\toutputDir?: string;\n\t/** The outcome, decided once. */\n\tresult?: JsonObject;\n};\n\nexport const CodemodeRunDoc = defineDoc<RunState>({\n\tkind: \"pi.codemode.run\",\n\tversion: 1,\n\tscope: \"task\",\n\tinitial: () => ({}),\n\t// The document retires with its task.\n\tcheckpointWhen: () => false,\n});\n\ntype JournalEntry = {\n\t/** The VM's call ID. Its result is the entry's position + 1 (`seq`). */\n\tid: number;\n\t/** The VM clock while it processes this result. */\n\tat: number;\n\t/** Calls the VM had issued after processing this result; absent until acknowledged. */\n\tissuedAfter?: number;\n\t/** A global's call and outcome; a tool's result is its nested call's. */\n\tglobal?: { name: string; args?: JsonValue; outcome: JsonObject };\n};\n\ntype JournalState = {\n\tentries: JournalEntry[];\n\t/** Calls the VM had issued after the script's first run, before any result; absent until acknowledged. */\n\tfirstIssued?: number;\n};\n\nexport const CodemodeJournalDoc = defineDoc<JournalState>({\n\tkind: \"pi.codemode.journal\",\n\tversion: 1,\n\tscope: \"task\",\n\tinitial: () => ({ entries: [] }),\n\t// The document retires with its task.\n\tcheckpointWhen: () => false,\n});\n\n/**\n * What scripts keep with `store()` and read with `load()`, per conversation. Rewindable and copied as of the fork\n * point, so a fork sees the values as they were when its entry was committed.\n */\nexport const CodemodeStoreDoc = defineDoc<{ values: Record<string, JsonValue> }>({\n\tkind: \"pi.codemode.store\",\n\tversion: 1,\n\tscope: \"conversation\",\n\thistory: \"rewindable\",\n\tfork: \"asOf\",\n\tinitial: () => ({ values: {} }),\n\tcheckpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,\n});\n\n/** One tool call a script made, as the code mode call's details show it. */\nexport type CodemodeNestedCall = {\n\t/** The VM's number for the call; its nested call ID is `<callId>/c<id>`. */\n\tid: number;\n\tname: string;\n\t/** Compact JSON of the arguments, cut for display. */\n\targs: string;\n\tstatus: \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\tdurationMs?: number;\n\t/** Error text, cut for display. */\n\terror?: string;\n};\n\n/**\n * The code mode call's details, in its result: its tool calls in the order it made them, with their status. Calls to\n * globals are not listed. While the script runs, UIs show its nested calls from `pi.live.nestedTools`, so the list is\n * written once, with the result.\n */\nexport type CodemodeToolDetails = {\n\tcalls: CodemodeNestedCall[];\n\t/** Temp file with the complete text output, when the output was cut to its token budget. */\n\tfullOutputPath?: string;\n};\n\nconst ARGS_PREVIEW_CHARS = 200;\nconst ERROR_PREVIEW_CHARS = 500;\n\nfunction cut(text: string, max: number): string {\n\treturn text.length > max ? `${text.slice(0, max - 3)}...` : text;\n}\n\n/** A function scripts call as a top-level global; its result is journaled. */\nexport type CodemodeGlobal = {\n\treadonly name: string;\n\treadonly spread?: boolean;\n\texecute(args: unknown, api: ToolExecutionApi, context: Context): Promise<JsonValue | undefined>;\n};\n\nconst codemodeSchema = Type.Object({ code: Type.String({ description: \"Raw JavaScript source.\" }) });\n\nexport type CodemodeToolInput = Static<typeof codemodeSchema>;\n\nexport type CodemodeToolOptions = {\n\t/** Runs the scripts: `CodemodeSandbox` on Node, `RemoteCodemodeSandbox` on Cloudflare. */\n\treadonly sandbox: CodemodeSandboxBase;\n\t/** Groups of tools by name prefix, such as MCP servers, for the `codemode` section and tool search. */\n\treadonly namespaces?: readonly CodemodeNamespace[];\n\t/** Estimated tokens the tool declarations in the `codemode` section may use. Default 3000. */\n\treadonly inlineBudget?: number;\n\t/** Give scripts `models.*`: the model catalog, classifiers, and image generation. Default true. */\n\treadonly models?: boolean;\n\t/** @internal Host functions scripts call as globals. */\n\treadonly globals?: readonly CodemodeGlobal[];\n};\n\n/** Outputs bounded by the script's own token budget; the Harness's limits only stop a runaway. */\nconst OUTPUT_LIMITS = { maxBytes: 4 * 1024 * 1024, maxLines: 100_000 } as const;\n\n/** Globals for finding tools, answered from the start data, so a replay sees what the first run saw. */\nconst DISCOVERY_GLOBALS = [\"searchTools\", \"describeTool\", \"describeNamespace\"] as const;\nconst DEFAULT_SEARCH_LIMIT = 8;\n\n/** The code mode tool. Scripts call the conversation's callable tools as `tools.<name>(args)`. */\nexport function createCodemodeTool(options: CodemodeToolOptions): ToolRegistration<typeof codemodeSchema> {\n\treturn defineTool({\n\t\tname: CODEMODE_TOOL_NAME,\n\t\tdescription: codemodeDescription(options.models !== false),\n\t\tparameters: codemodeSchema,\n\t\toutputLimits: OUTPUT_LIMITS,\n\t\t// Capable models write the script as raw text instead of a JSON-escaped string; pi-ai applies it only for them.\n\t\tconstrainedSampling: { type: \"grammar\", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },\n\t\tcallers: [\"model\"],\n\t\treplay: \"safe\",\n\t\texecute: (args, api, context) => new CodemodeCall(options, api, context).execute(args.code),\n\t});\n}\n\n/**\n * The `codemode` extension: the code mode tool, and the `codemode` prompt section listing the tools scripts can call.\n */\nexport function createCodemodeExtension(options: CodemodeToolOptions): Extension {\n\treturn defineExtension({\n\t\tname: \"codemode\",\n\t\ttools: [createCodemodeTool(options), ...(options.models === false ? [] : createModelTools())],\n\t\tsections: [\n\t\t\tsection(\"codemode\", (input) =>\n\t\t\t\tcodemodeSection(\n\t\t\t\t\t// Deferred tools are found with `searchTools()`, as the coding agent leaves them out too.\n\t\t\t\t\tinput.agent.callable.filter(\n\t\t\t\t\t\t(tool) => !tool.name.startsWith(CODEMODE_INTERNAL_PREFIX) && tool.deferred !== true,\n\t\t\t\t\t),\n\t\t\t\t\toptions.namespaces ?? [],\n\t\t\t\t\toptions.inlineBudget ?? DEFAULT_CODEMODE_INLINE_BUDGET,\n\t\t\t\t),\n\t\t\t),\n\t\t],\n\t});\n}\n\n/**\n * What a script gets for a nested call, as in the coding agent. A tool with a schema resolves with its value, also on\n * an error result that carries one (`bash`'s `{ output, exitCode }` for a nonzero exit); a schema-less tool\n * resolves with its text output, images left out, as its declaration says. Any other error rejects, with its text: a\n * schema-less tool's output, else its error diagnostics.\n */\nfunction outcomeOf(name: string, structured: boolean, result: NestedToolExecutionResult): CodemodeOutcome {\n\tconst value = structured ? result.structuredOutput : textOf(result.structuredOutput);\n\tif (!result.isError || (structured && value !== undefined)) return { ok: true, value };\n\tconst message = structured ? \"\" : (value as string);\n\tconst diagnostics = result.diagnostics\n\t\t.filter((diagnostic) => diagnostic.severity === \"error\")\n\t\t.map((diagnostic) => diagnostic.message)\n\t\t.join(\"\\n\");\n\treturn {\n\t\tok: false,\n\t\tmessage: message || diagnostics || `Tool ${name} failed`,\n\t\t...(value === undefined ? {} : { properties: { structuredOutput: value } }),\n\t};\n}\n\n/** The text of a schema-less tool's collapsed output: a string, one image, or an array of text and image blocks. */\nfunction textOf(value: JsonValue | undefined): string {\n\tif (typeof value === \"string\") return value;\n\tif (!Array.isArray(value)) return \"\";\n\treturn value.flatMap((item) => (isText(item) ? [item.text] : [])).join(\"\\n\");\n}\n\nfunction isText(item: unknown): item is TextContent {\n\treturn typeof item === \"object\" && item !== null && (item as TextContent).type === \"text\";\n}\n\nfunction errorResult(message: string): ToolExecutionResult {\n\treturn { output: [{ type: \"text\", text: message }], isError: true };\n}\n\n/** One execution of the code mode tool: a first run, or a rerun after a restart that replays the journal. */\nclass CodemodeCall {\n\tprivate readonly options: CodemodeToolOptions;\n\tprivate readonly api: ToolExecutionApi;\n\tprivate readonly context: Context;\n\tprivate readonly controller = new AbortController();\n\tprivate run!: CodemodeRun;\n\tprivate start!: Start;\n\t/** The journal as this attempt found it; replay delivers exactly these. */\n\tprivate replayed: JournalEntry[] = [];\n\t/** Entries in the journal, replayed and live; the next delivery is `length + 1`. */\n\tprivate journalLength = 0;\n\t/** Replayed entries delivered so far. */\n\tprivate nextReplayed = 0;\n\tprivate replaying = false;\n\t/** Whether an earlier attempt ran this call: its nested call keys may already exist. */\n\tprivate rerun = false;\n\t/** Whether live calls may launch; before, they are held (see `release()`). */\n\tprivate released = false;\n\t/** The count an earlier attempt recorded after the script's first run. */\n\tprivate firstIssued: number | undefined;\n\t/** The highest issued count known to be committed: calls up to it may launch. */\n\tprivate durableIssued = 0;\n\t/** Live calls waiting for their issued count to be committed. */\n\tprivate waiting: CodemodeHostCall[] = [];\n\t/** Journal index of each replayed call ID. */\n\tprivate replayIndex = new Map<number, number>();\n\t/** Calls the VM issued so far; its call IDs are 1, 2, ... */\n\tprivate issued = 0;\n\t/** Replay: results of journaled calls, ready to deliver in journal order. */\n\tprivate readonly ready = new Map<number, CodemodeOutcome>();\n\t/** Replay: calls the journal does not have, admitted once replay is done. */\n\tprivate held: CodemodeHostCall[] = [];\n\t/** Live: finished calls waiting for their journal commit. */\n\tprivate queue: { id: number; at: number; outcome: CodemodeOutcome; global?: JournalEntry[\"global\"] }[] = [];\n\t/** Acknowledged counts to record, by result number (0: the script's first run). */\n\tprivate readonly acks = new Map<number, number>();\n\tprivate committing = false;\n\t/** Set once the call decided an outcome other than the script's own (divergence, mismatch) or failed. */\n\tprivate ended: ToolExecutionResult | undefined;\n\tprivate failure: unknown;\n\t/** `models.classify()`/`generateImages()` calls in flight, and those waiting for a slot. */\n\tprivate modelCalls = 0;\n\tprivate readonly modelWaiters: (() => void)[] = [];\n\t/** Images `models.generateImages()` returned, to notice a script that never shows them. */\n\tprivate generatedImages = 0;\n\t/** The script's tool calls for `details`, by VM call ID. */\n\tprivate readonly rows = new Map<number, CodemodeNestedCall>();\n\t/** Resolves once the VM's fingerprint is checked or recorded; nothing is delivered or admitted before. */\n\tprivate gate!: Promise<void>;\n\tprivate openGate!: () => void;\n\n\tconstructor(options: CodemodeToolOptions, api: ToolExecutionApi, context: Context) {\n\t\tthis.options = options;\n\t\tthis.api = api;\n\t\tthis.context = context;\n\t\tthis.gate = new Promise((resolve) => {\n\t\t\tthis.openGate = resolve;\n\t\t});\n\t}\n\n\tasync execute(source: string): Promise<ToolExecutionResult> {\n\t\tconst { code, options: sourceOptions } = parseCodemodeSource(source);\n\t\tconst { api, context } = this;\n\t\tconst agent = await api.agent(context);\n\t\tconst tools: DeclaredTool[] = agent.callable.map((tool) => ({\n\t\t\tname: tool.name,\n\t\t\tjsName: toCodemodeIdentifier(tool.name),\n\t\t\tdescription: sampleOf(tool),\n\t\t\t...(tool.structuredOutputSchema === undefined ? {} : { structured: true as const }),\n\t\t\t...(tool.name.startsWith(CODEMODE_INTERNAL_PREFIX) ? { hidden: true as const } : {}),\n\t\t}));\n\t\tconst callable = agent.callable.filter((tool) => !tool.name.startsWith(CODEMODE_INTERNAL_PREFIX));\n\t\tconst models = this.options.models === false ? [] : [...CATALOG_GLOBALS, ...Object.keys(MODEL_CALLS)];\n\t\tconst globals = [\n\t\t\t...DISCOVERY_GLOBALS.map((name) => ({ name, spread: true })),\n\t\t\t...models.map((name) => ({ name, spread: true })),\n\t\t\t...(this.options.globals ?? []).map((global) => ({ name: global.name, spread: global.spread === true })),\n\t\t];\n\t\tconst namespaces: Start[\"namespaces\"] = [];\n\t\tfor (const tool of callable) {\n\t\t\tconst namespace = namespaceOf(tool.name, this.options.namespaces ?? []);\n\t\t\tif (namespace === undefined) continue;\n\t\t\tlet entry = namespaces.find((candidate) => candidate.name === namespace.name);\n\t\t\tif (entry === undefined) {\n\t\t\t\tentry = {\n\t\t\t\t\tname: namespace.name,\n\t\t\t\t\t...(namespace.description === undefined ? {} : { description: namespace.description }),\n\t\t\t\t\t...(namespace.instructions === undefined ? {} : { instructions: namespace.instructions }),\n\t\t\t\t\ttools: [],\n\t\t\t\t};\n\t\t\t\tnamespaces.push(entry);\n\t\t\t}\n\t\t\tentry.tools.push(tool.name);\n\t\t}\n\t\tconst now = api.now();\n\t\tconst seed = crypto.getRandomValues(new Uint32Array(1))[0]!;\n\t\ttype Found =\n\t\t\t| { done: ToolExecutionResult }\n\t\t\t| { start: Start; journal: JournalEntry[]; firstIssued: number | undefined; rerun: boolean };\n\t\tconst found = await api.commit(async (tx): Promise<Found> => {\n\t\t\tconst run = await tx.doc(CodemodeRunDoc, api.taskId);\n\t\t\tif (run.result !== undefined) return { done: copyJson(run.result as JsonValue) as ToolExecutionResult };\n\t\t\tconst rerun = run.start !== undefined;\n\t\t\tif (run.start === undefined) {\n\t\t\t\tconst store = await tx.doc(CodemodeStoreDoc, api.conversationId);\n\t\t\t\tconst timeout = sourceOptions.timeoutMs;\n\t\t\t\trun.start = {\n\t\t\t\t\tversion: CODEMODE_MODULE_VERSION,\n\t\t\t\t\tstartedAt: now,\n\t\t\t\t\tseed,\n\t\t\t\t\t...(timeout === undefined ? {} : { deadline: now + timeout }),\n\t\t\t\t\ttools,\n\t\t\t\t\tnamespaces,\n\t\t\t\t\tglobals,\n\t\t\t\t\tmaxOutputTokens: sourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,\n\t\t\t\t\tstore: copyJson(store.values as JsonValue) as Record<string, JsonValue>,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst journal = await tx.doc(CodemodeJournalDoc, api.taskId);\n\t\t\treturn {\n\t\t\t\tstart: copyJson(run.start as unknown as JsonValue) as unknown as Start,\n\t\t\t\tjournal: copyJson(journal.entries as unknown as JsonValue) as unknown as JournalEntry[],\n\t\t\t\tfirstIssued: journal.firstIssued,\n\t\t\t\trerun,\n\t\t\t};\n\t\t}, context);\n\t\tif (\"done\" in found) return found.done;\n\t\tthis.start = found.start;\n\t\tthis.replayed = found.journal;\n\t\tthis.replayIndex = new Map(found.journal.map((entry, index) => [entry.id, index]));\n\t\tthis.journalLength = found.journal.length;\n\t\tthis.replaying = found.journal.length > 0;\n\t\tthis.rerun = found.rerun;\n\t\tthis.firstIssued = found.firstIssued;\n\t\t// A loop, not spread arguments: a journal can hold more entries than a call takes arguments.\n\t\tthis.durableIssued = found.journal.reduce(\n\t\t\t(max, entry) => Math.max(max, entry.issuedAfter ?? 0),\n\t\t\tfound.firstIssued ?? 0,\n\t\t);\n\n\t\tif (this.start.version !== CODEMODE_MODULE_VERSION) {\n\t\t\treturn this.decide(\n\t\t\t\terrorResult(\n\t\t\t\t\t`The script cannot resume: it started under code mode version ${this.start.version}, this is ${CODEMODE_MODULE_VERSION}.`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tconst remaining = this.start.deadline === undefined ? undefined : this.start.deadline - this.api.now();\n\t\tif (remaining !== undefined && remaining <= 0) {\n\t\t\treturn this.decide(errorResult(`Script timed out: its deadline passed while it was interrupted.`));\n\t\t}\n\n\t\tconst onAbort = () => this.controller.abort(context.abortSignal?.reason);\n\t\tcontext.abortSignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tif (context.abortSignal?.aborted) onAbort();\n\t\ttry {\n\t\t\tthis.run = this.options.sandbox.start(code, {\n\t\t\t\tstartedAt: this.start.startedAt,\n\t\t\t\tseed: this.start.seed,\n\t\t\t\ttools: this.start.tools.filter((tool) => tool.hidden !== true),\n\t\t\t\tglobals: this.start.globals,\n\t\t\t\tstore: this.start.store,\n\t\t\t\tsignal: this.controller.signal,\n\t\t\t\t...(remaining === undefined ? {} : { timeoutMs: remaining }),\n\t\t\t\tonStarted: (fingerprint) => void this.checkFingerprint(fingerprint),\n\t\t\t\tonCall: (call) => this.onCall(call),\n\t\t\t\tonIdle: (seq, issued) => this.onIdle(seq, issued),\n\t\t\t});\n\t\t\tconst result = await this.run.result;\n\t\t\tif (this.failure !== undefined) throw this.failure;\n\t\t\tif (this.ended !== undefined) return this.ended;\n\t\t\tcontext.abortSignal?.throwIfAborted();\n\t\t\t// Aborted, but not by this call: the host closed the sandbox, for example while shutting down before closing the\n\t\t\t// Harness. That decides nothing about the script: store nothing and end with this invocation, so a later attempt\n\t\t\t// replays it.\n\t\t\tif (!result.ok && result.error.kind === \"aborted\" && !this.controller.signal.aborted) {\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tif (context.abortSignal === undefined || context.abortSignal.aborted) resolve();\n\t\t\t\t\telse context.abortSignal.addEventListener(\"abort\", () => resolve(), { once: true });\n\t\t\t\t});\n\t\t\t\tcontext.abortSignal?.throwIfAborted();\n\t\t\t\tthrow new Error(\"The code mode sandbox was closed while the script ran\");\n\t\t\t}\n\t\t\t// A replay that ends where the live run went on is a divergence (design §4.3).\n\t\t\tconst during = result.during;\n\t\t\t// Within the replayed part, the first run included: a rerun without journal entries replays that much too.\n\t\t\tif (this.rerun && during !== undefined && during.seq <= this.replayed.length) {\n\t\t\t\t// The live run went on: it acknowledged that result, or it made a call that later results answer, which the\n\t\t\t\t// replay never made.\n\t\t\t\tconst continued =\n\t\t\t\t\t(during.seq === 0\n\t\t\t\t\t\t? this.replayed.length > 0 || this.firstIssued !== undefined\n\t\t\t\t\t\t: this.replayed[during.seq - 1]?.issuedAfter !== undefined) ||\n\t\t\t\t\tthis.replayed.slice(during.seq).some((entry) => entry.id > during.issued);\n\t\t\t\tif (continued) {\n\t\t\t\t\treturn this.decide(\n\t\t\t\t\t\terrorResult(\n\t\t\t\t\t\t\t`The script took a different path when resumed after a restart: it ended after result ${during.seq}, where it went on before.`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this.complete(result);\n\t\t} finally {\n\t\t\tcontext.abortSignal?.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t}\n\n\t/** Store an outcome the call decided, and end the VM if it runs; returns the outcome. */\n\tprivate async decide(decided: ToolExecutionResult): Promise<ToolExecutionResult> {\n\t\tconst result = { ...decided, details: this.details() as unknown as JsonValue };\n\t\tawait this.api.commit(async (tx) => {\n\t\t\tconst run = await tx.doc(CodemodeRunDoc, this.api.taskId);\n\t\t\trun.result ??= copyJson(result as unknown as JsonValue, { omitUndefinedProperties: true }) as JsonObject;\n\t\t}, this.context);\n\t\treturn result;\n\t}\n\n\t/** End the call with `message`: store it as the outcome, then stop the VM with an error the script cannot catch. */\n\tprivate diverge(message: string): void {\n\t\tif (this.ended !== undefined || this.failure !== undefined) return;\n\t\tconst result = errorResult(`The script took a different path when resumed after a restart: ${message}`);\n\t\tthis.ended = result;\n\t\tthis.decide(result).then(\n\t\t\t() => this.controller.abort(new Error(message)),\n\t\t\t(error: unknown) => this.fail(error),\n\t\t);\n\t}\n\n\t/** Whether nothing more may happen: the run has its outcome, or the call decided or failed. */\n\tprivate get stopped(): boolean {\n\t\treturn this.ended !== undefined || this.failure !== undefined || this.run?.finished === true;\n\t}\n\n\tprivate fail(error: unknown): void {\n\t\tif (this.failure !== undefined) return;\n\t\tthis.failure = error;\n\t\tthis.controller.abort(error);\n\t}\n\n\t/** The script's own outcome, stored with its store writes in one transaction. */\n\tprivate async complete(result: CodemodeResult): Promise<ToolExecutionResult> {\n\t\tconst details = this.details();\n\t\tconst formatted = await formatResult(result, {\n\t\t\tgeneratedImages: this.generatedImages,\n\t\t\twallMs: this.api.now() - this.start.startedAt,\n\t\t\tmaxOutputTokens: this.start.maxOutputTokens,\n\t\t\tcalls: details.calls,\n\t\t\tlimits: OUTPUT_LIMITS,\n\t\t\twrite: this.outputFiles(),\n\t\t});\n\t\tconst tool: ToolExecutionResult = {\n\t\t\toutput: formatted.content,\n\t\t\tisError: !result.ok,\n\t\t\tdetails: {\n\t\t\t\t...details,\n\t\t\t\t...(formatted.fullOutputPath === undefined ? {} : { fullOutputPath: formatted.fullOutputPath }),\n\t\t\t} as unknown as JsonValue,\n\t\t};\n\t\tconst writes = result.ok ? result.storeWrites : undefined;\n\t\treturn this.api.commit(async (tx) => {\n\t\t\tconst run = await tx.doc(CodemodeRunDoc, this.api.taskId);\n\t\t\tif (run.result !== undefined) return run.result as ToolExecutionResult;\n\t\t\trun.result = copyJson(tool as unknown as JsonValue, { omitUndefinedProperties: true }) as JsonObject;\n\t\t\tif (writes !== undefined && (Object.keys(writes.set).length > 0 || writes.delete.length > 0)) {\n\t\t\t\tconst store = await tx.doc(CodemodeStoreDoc, this.api.conversationId);\n\t\t\t\tfor (const key of writes.delete) delete store.values[key];\n\t\t\t\tfor (const [key, value] of Object.entries(writes.set)) store.values[key] = value as JsonValue;\n\t\t\t}\n\t\t\treturn tool;\n\t\t}, this.context);\n\t}\n\n\t/** Writes the result's files under fixed names into the run's output directory, so a rerun overwrites them. */\n\tprivate outputFiles(): OutputFile {\n\t\tconst env = this.api.env;\n\t\tlet directory: Promise<string> | undefined;\n\t\treturn async (name, data) => {\n\t\t\tif (env === undefined) return { error: \"no execution environment\" };\n\t\t\ttry {\n\t\t\t\tdirectory ??= this.outputDir(env);\n\t\t\t\tconst path = `${await directory}/${name}`;\n\t\t\t\tconst written = await env.writeFile(path, data, this.context);\n\t\t\t\treturn written.ok ? { path } : { error: written.error.message };\n\t\t\t} catch (error) {\n\t\t\t\treturn { error: errorMessage(error) };\n\t\t\t}\n\t\t};\n\t}\n\n\t/** The run's output directory: the recorded one, else a new temp directory, recorded before any file is written. */\n\tprivate async outputDir(env: ExecutionEnv): Promise<string> {\n\t\tconst recorded = await this.api.commit(\n\t\t\tasync (tx) => (await tx.doc(CodemodeRunDoc, this.api.taskId)).outputDir,\n\t\t\tthis.context,\n\t\t);\n\t\tif (recorded !== undefined) return recorded;\n\t\tconst created = await env.createTempDir(\"pi-codemode-\", this.context);\n\t\tif (!created.ok) throw new Error(created.error.message);\n\t\treturn this.api.commit(async (tx) => {\n\t\t\tconst run = await tx.doc(CodemodeRunDoc, this.api.taskId);\n\t\t\trun.outputDir ??= created.value;\n\t\t\treturn run.outputDir!;\n\t\t}, this.context);\n\t}\n\n\tprivate async checkFingerprint(fingerprint: string): Promise<void> {\n\t\tconst recorded = this.start.fingerprint;\n\t\tif (recorded !== undefined) {\n\t\t\tif (recorded !== fingerprint) {\n\t\t\t\tthis.ended = errorResult(\n\t\t\t\t\t`The script cannot resume: the sandbox changed since it started (${recorded} -> ${fingerprint}).`,\n\t\t\t\t);\n\t\t\t\tawait this.decide(this.ended).catch((error: unknown) => this.fail(error));\n\t\t\t\tthis.controller.abort(new Error(\"Sandbox fingerprint changed\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tawait this.api.commit(async (tx) => {\n\t\t\t\t\tconst run = await tx.doc(CodemodeRunDoc, this.api.taskId);\n\t\t\t\t\tif (run.start !== undefined) run.start.fingerprint = fingerprint;\n\t\t\t\t}, this.context);\n\t\t\t} catch (error) {\n\t\t\t\tthis.fail(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tthis.openGate();\n\t\t// Nothing was delivered before the gate: start now. A rerun without a journal releases its calls at the\n\t\t// script's first acknowledgment instead.\n\t\tif (this.replaying) this.deliverReplayed();\n\t\telse if (!this.rerun) void this.release();\n\t}\n\n\tprivate onCall(made: CodemodeHostCall): void {\n\t\tif (this.stopped) return;\n\t\tconst call = asToolCall(made);\n\t\tif (call.target === \"tool\") this.started(call);\n\t\tthis.issued = Math.max(this.issued, call.id);\n\t\tconst index = this.replaying ? (this.replayIndex.get(call.id) ?? -1) : -1;\n\t\tif (index === -1) {\n\t\t\tif (this.released) {\n\t\t\t\tthis.waiting.push(call);\n\t\t\t\tthis.launchCovered();\n\t\t\t} else this.held.push(call);\n\t\t\treturn;\n\t\t}\n\t\tconst entry = this.replayed[index]!;\n\t\tif (entry.global !== undefined) {\n\t\t\tif (call.target !== \"global\" || call.name !== entry.global.name || !sameJson(call.args, entry.global.args)) {\n\t\t\t\tthis.diverge(`call ${call.id} is ${describe(call)}, but was a call to ${entry.global.name}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.ready.set(call.id, entry.global.outcome as CodemodeOutcome);\n\t\t\tvoid this.gate.then(() => this.deliverReplayed());\n\t\t\treturn;\n\t\t}\n\t\tif (call.target !== \"tool\") {\n\t\t\tthis.diverge(`call ${call.id} is ${describe(call)}, but was a tool call`);\n\t\t\treturn;\n\t\t}\n\t\tvoid this.gate\n\t\t\t.then(() => this.callTool(call))\n\t\t\t.then(\n\t\t\t\t(outcome) => {\n\t\t\t\t\tthis.ready.set(call.id, outcome);\n\t\t\t\t\tthis.deliverReplayed();\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tif (this.stopped) return;\n\t\t\t\t\tif (this.context.abortSignal?.aborted) this.fail(error);\n\t\t\t\t\t// The key names another tool or other arguments.\n\t\t\t\t\telse this.diverge(`call ${call.id} is ${describe(call)}: ${errorMessage(error)}`);\n\t\t\t\t},\n\t\t\t);\n\t}\n\n\t/** Replay: deliver journaled results in journal order, each once the VM has issued its call. */\n\tprivate deliverReplayed(): void {\n\t\twhile (this.nextReplayed < this.replayed.length && !this.stopped) {\n\t\t\tconst entry = this.replayed[this.nextReplayed]!;\n\t\t\tconst outcome = this.ready.get(entry.id);\n\t\t\tif (entry.id > this.issued || outcome === undefined) return;\n\t\t\tthis.ready.delete(entry.id);\n\t\t\tthis.nextReplayed++;\n\t\t\tthis.run.deliver(this.nextReplayed, entry.at, entry.id, outcome);\n\t\t}\n\t}\n\n\tprivate onIdle(seq: number, issued: number): void {\n\t\tif (this.stopped) return;\n\t\t// A count an earlier attempt recorded must match; a missing one is recorded now.\n\t\tif (this.rerun && seq <= this.replayed.length) {\n\t\t\tconst recorded = seq === 0 ? this.firstIssued : this.replayed[seq - 1]!.issuedAfter;\n\t\t\tif (recorded !== undefined && recorded !== issued) {\n\t\t\t\tthis.diverge(\n\t\t\t\t\tseq === 0\n\t\t\t\t\t\t? `its first run made ${issued} calls, where it had made ${recorded}`\n\t\t\t\t\t\t: `after result ${seq} it had made ${issued} calls, where it had made ${recorded}`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tthis.acks.set(seq, issued);\n\t\tif (!this.replaying) {\n\t\t\t// A rerun without a journal: every call an earlier attempt could have admitted is made by now.\n\t\t\tif (seq === 0 && this.rerun) void this.release();\n\t\t\t// Committed at once when the script has processed everything delivered: calls it made wait for it, and a script\n\t\t\t// waiting on a long call is where a restart usually finds it. Otherwise with the next commit; the VM catches up\n\t\t\t// without waiting on anything.\n\t\t\tif (seq === this.journalLength) void this.pump();\n\t\t\treturn;\n\t\t}\n\t\t// Caught up: the VM processed everything delivered and waits.\n\t\tif (seq !== this.nextReplayed) return;\n\t\tconst next = this.replayed[seq];\n\t\tif (next !== undefined) {\n\t\t\tif (next.id > issued) this.diverge(`it waits without making call ${next.id}, which it made before`);\n\t\t\treturn;\n\t\t}\n\t\t// The last replayed result is acknowledged: continue live, admitting the calls the journal did not have once their\n\t\t// count is committed.\n\t\tthis.replaying = false;\n\t\tvoid this.pump();\n\t\tvoid this.release();\n\t}\n\n\t/**\n\t * Let the held calls launch, and later live calls, each once its issued count is committed. On a rerun, an earlier\n\t * attempt may have admitted some of them under their keys, as other calls: when the replay releases (idle after the\n\t * last journaled result, or after its first run without a journal) its counts matched every recorded one, so it has\n\t * made every call an earlier attempt could have admitted. All held calls are checked first, whatever their target,\n\t * and a divergence launches none. Calls made after this are new.\n\t */\n\tprivate async release(): Promise<void> {\n\t\tawait this.gate;\n\t\tif (this.stopped || this.released) return;\n\t\tconst calls = this.held.splice(0);\n\t\tif (this.rerun) {\n\t\t\tfor (const call of calls) {\n\t\t\t\tlet other: string | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tother = await this.earlier(call);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.fail(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (this.stopped) return;\n\t\t\t\tif (other !== undefined) {\n\t\t\t\t\tthis.diverge(`call ${call.id} is ${describe(call)}, but was ${other}`);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.released = true;\n\t\tthis.waiting.push(...calls, ...this.held.splice(0));\n\t\tthis.launchCovered();\n\t}\n\n\t/** Launch the waiting calls whose issued count is committed. */\n\tprivate launchCovered(): void {\n\t\tif (!this.released || this.stopped) return;\n\t\tconst covered = this.waiting.filter((call) => call.id <= this.durableIssued);\n\t\tif (covered.length === 0) return;\n\t\tthis.waiting = this.waiting.filter((call) => call.id > this.durableIssued);\n\t\tfor (const call of covered) this.launch(call);\n\t}\n\n\t/** The call an earlier attempt made under this call's key, when it is another one: another target, tool, or arguments. */\n\tprivate async earlier(call: CodemodeHostCall): Promise<string | undefined> {\n\t\tconst { api, context } = this;\n\t\tconst taskId = (await api.snapshot(NestedCallDoc, api.taskId, `c${call.id}`, context))?.taskId;\n\t\tif (taskId === undefined) return undefined;\n\t\tconst input = (await api.getTask(taskId, context))?.input as ToolTaskInput | undefined;\n\t\tif (input?.kind !== \"nested\") return undefined;\n\t\tconst made = input.call;\n\t\tif (call.target === \"tool\" && made.name === call.name && sameJson(made.arguments, call.args ?? {}))\n\t\t\treturn undefined;\n\t\treturn `tools.${made.name}(${JSON.stringify(made.arguments)})`;\n\t}\n\n\t/** Run one live call and journal its result. */\n\tprivate launch(call: CodemodeHostCall): void {\n\t\tif (this.stopped) return;\n\t\tconst running: Promise<{ outcome: CodemodeOutcome; global?: JournalEntry[\"global\"] }> =\n\t\t\tcall.target === \"tool\"\n\t\t\t\t? this.callTool(call).then((outcome) => ({ outcome }))\n\t\t\t\t: this.callGlobal(call).then((outcome) => ({\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\tglobal: {\n\t\t\t\t\t\t\tname: call.name,\n\t\t\t\t\t\t\t...(call.args === undefined ? {} : { args: call.args as JsonValue }),\n\t\t\t\t\t\t\toutcome: outcome as JsonObject,\n\t\t\t\t\t\t},\n\t\t\t\t\t}));\n\t\trunning.then(\n\t\t\t(done) => {\n\t\t\t\t// A result after the outcome is decided has nowhere to go, and the call's API has ended.\n\t\t\t\tif (this.stopped) return;\n\t\t\t\tthis.queue.push({ id: call.id, at: this.api.now(), ...done });\n\t\t\t\tvoid this.pump();\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\t// Stopped meanwhile: the outcome is decided, or a waiting model call gave up.\n\t\t\t\tif (this.stopped) return;\n\t\t\t\tif (this.context.abortSignal?.aborted) this.fail(error);\n\t\t\t\t// A key an earlier attempt admitted with another tool or other arguments: this attempt took another path.\n\t\t\t\telse this.diverge(`call ${call.id} is ${describe(call)}: ${errorMessage(error)}`);\n\t\t\t},\n\t\t);\n\t}\n\n\tprivate async callTool(call: CodemodeHostCall): Promise<CodemodeOutcome> {\n\t\t// Passed as the script gave them; validation reports arguments that are not an object.\n\t\tconst args = (call.args ?? {}) as JsonObject;\n\t\tconst model = call.name.startsWith(CODEMODE_INTERNAL_PREFIX);\n\t\tif (model) {\n\t\t\tawait this.modelSlot();\n\t\t\t// The call may have stopped while this one waited: a finished script admits no new paid call.\n\t\t\tif (this.stopped) {\n\t\t\t\tthis.releaseModelSlot();\n\t\t\t\tthrow new Error(\"The script has ended\");\n\t\t\t}\n\t\t}\n\t\tlet result: NestedToolExecutionResult;\n\t\ttry {\n\t\t\tresult = await this.api.executeTool(call.name, args, this.context, { key: `c${call.id}` });\n\t\t} finally {\n\t\t\tif (model) this.releaseModelSlot();\n\t\t}\n\t\tif (call.name === GENERATE_IMAGES_TOOL) this.generatedImages += countImages(result.structuredOutput);\n\t\tconst structured = this.start.tools.find((tool) => tool.name === call.name)?.structured === true;\n\t\tconst outcome = outcomeOf(call.name, structured, result);\n\t\tthis.finishRow(call.id, outcome, result);\n\t\treturn outcome;\n\t}\n\n\t/** The script made a tool call: its row appears, running, also while it waits to launch. */\n\tprivate started(call: CodemodeHostCall): void {\n\t\tif (this.rows.has(call.id)) return;\n\t\tconst args = call.args === undefined ? \"\" : (JSON.stringify(call.args) ?? \"\");\n\t\tconst name = call.name.startsWith(CODEMODE_INTERNAL_PREFIX)\n\t\t\t? call.name.slice(CODEMODE_INTERNAL_PREFIX.length)\n\t\t\t: call.name;\n\t\tthis.rows.set(call.id, { id: call.id, name, args: cut(args, ARGS_PREVIEW_CHARS), status: \"running\" });\n\t}\n\n\t/** A tool call ended: its row gets its status, duration, and error. */\n\t/** The call ended: an error result is an error row, also when the script got its value (bash's nonzero exit). */\n\tprivate finishRow(id: number, outcome: CodemodeOutcome, result: NestedToolExecutionResult): void {\n\t\tconst row = this.rows.get(id);\n\t\tif (row === undefined) return;\n\t\trow.status = result.isError ? \"error\" : \"ok\";\n\t\tif (result.durationMs !== undefined) row.durationMs = result.durationMs;\n\t\tconst errors = result.diagnostics.filter((diagnostic) => diagnostic.severity === \"error\");\n\t\tconst error = !outcome.ok ? outcome.message : errors.map((diagnostic) => diagnostic.message).join(\"\\n\");\n\t\tif (result.isError && error !== \"\") row.error = cut(error, ERROR_PREVIEW_CHARS);\n\t}\n\n\t/** The rows in call order; calls still running when the script ended were cancelled. */\n\tprivate details(): CodemodeToolDetails {\n\t\tconst calls = [...this.rows.values()]\n\t\t\t.sort((a, b) => a.id - b.id)\n\t\t\t.map((row) => (row.status === \"running\" ? { ...row, status: \"cancelled\" as const } : row));\n\t\treturn { calls };\n\t}\n\n\tprivate async callGlobal(call: CodemodeHostCall): Promise<CodemodeOutcome> {\n\t\tconst discovery = (DISCOVERY_GLOBALS as readonly string[]).includes(call.name);\n\t\tconst catalog = (CATALOG_GLOBALS as readonly string[]).includes(call.name);\n\t\tconst global =\n\t\t\tdiscovery || catalog ? undefined : this.options.globals?.find((candidate) => candidate.name === call.name);\n\t\tif (!discovery && !catalog && global === undefined) return { ok: false, message: `Unknown global ${call.name}` };\n\t\ttry {\n\t\t\t// `undefined` stays undefined: the journal omits the value, and a replay resolves with undefined again.\n\t\t\tconst value = discovery\n\t\t\t\t? this.discover(call)\n\t\t\t\t: catalog\n\t\t\t\t\t? await catalogCall(call.name, call.args, this.api.models, this.context)\n\t\t\t\t\t: await global!.execute(call.args, this.api, this.context);\n\t\t\treturn { ok: true, value };\n\t\t} catch (error) {\n\t\t\tif (this.context.abortSignal?.aborted) throw error;\n\t\t\treturn { ok: false, message: errorMessage(error) };\n\t\t}\n\t}\n\n\tprivate async modelSlot(): Promise<void> {\n\t\tif (this.modelCalls >= MAX_CONCURRENT_MODEL_CALLS) {\n\t\t\tawait new Promise<void>((resolve) => this.modelWaiters.push(resolve));\n\t\t}\n\t\tthis.modelCalls++;\n\t}\n\n\tprivate releaseModelSlot(): void {\n\t\tthis.modelCalls--;\n\t\tthis.modelWaiters.shift()?.();\n\t}\n\n\t/** `searchTools()`, `describeTool()`, `describeNamespace()`: answered from the start data. */\n\tprivate discover(call: CodemodeHostCall): JsonValue | undefined {\n\t\tconst args = Array.isArray(call.args) ? call.args : [];\n\t\tconst { namespaces } = this.start;\n\t\tconst tools = this.start.tools.filter((tool) => tool.hidden !== true);\n\t\tconst namespaceOfTool = (name: string) => namespaces.find((namespace) => namespace.tools.includes(name));\n\t\tconst matchesNamespace = (namespace: Start[\"namespaces\"][number], query: string) =>\n\t\t\tnamespace.name === query || toCodemodeIdentifier(namespace.name) === toCodemodeIdentifier(query);\n\t\tif (call.name === \"describeTool\") {\n\t\t\tconst [name] = args;\n\t\t\tif (typeof name !== \"string\") throw new Error(\"describeTool() expects a tool name\");\n\t\t\treturn tools.find((tool) => tool.name === name || tool.jsName === name)?.description;\n\t\t}\n\t\tif (call.name === \"describeNamespace\") {\n\t\t\tconst [name] = args;\n\t\t\tif (typeof name !== \"string\") throw new Error(\"describeNamespace() expects a namespace name\");\n\t\t\tconst namespace = namespaces.find((candidate) => matchesNamespace(candidate, name));\n\t\t\tif (namespace === undefined) return undefined;\n\t\t\treturn {\n\t\t\t\tname: namespace.name,\n\t\t\t\t...(namespace.description === undefined ? {} : { description: namespace.description }),\n\t\t\t\t...(namespace.instructions === undefined ? {} : { instructions: namespace.instructions }),\n\t\t\t\ttools: namespace.tools.map((tool) => toCodemodeIdentifier(tool)),\n\t\t\t};\n\t\t}\n\t\tconst [query, options] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];\n\t\tif (typeof query !== \"string\") throw new Error(\"searchTools() expects a query string\");\n\t\tconst limit = options?.limit ?? DEFAULT_SEARCH_LIMIT;\n\t\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit <= 0) {\n\t\t\tthrow new Error(\"searchTools() limit must be a positive integer\");\n\t\t}\n\t\tconst namespace = options?.namespace;\n\t\tif (namespace !== undefined && namespace !== null && typeof namespace !== \"string\") {\n\t\t\tthrow new Error(\"searchTools() namespace must be a string\");\n\t\t}\n\t\tconst documents = tools.flatMap((tool) => {\n\t\t\tconst own = namespaceOfTool(tool.name);\n\t\t\tif (typeof namespace === \"string\" && (own === undefined || !matchesNamespace(own, namespace))) return [];\n\t\t\tconst text = [\n\t\t\t\ttool.name,\n\t\t\t\ttool.name.replaceAll(\"_\", \" \"),\n\t\t\t\ttool.description,\n\t\t\t\town?.name ?? \"\",\n\t\t\t\town?.description ?? \"\",\n\t\t\t];\n\t\t\treturn [{ name: tool.name, text: text.join(\" \") }];\n\t\t});\n\t\treturn rankDocuments(query, documents, limit).map((name) => {\n\t\t\tconst tool = tools.find((candidate) => candidate.name === name)!;\n\t\t\treturn { name: tool.jsName, description: tool.description };\n\t\t});\n\t}\n\n\t/**\n\t * Journal finished calls and acknowledged counts in one commit, then deliver the calls and launch the calls the\n\t * counts cover; one commit in flight at a time, so what arrives meanwhile goes into the next.\n\t */\n\tprivate async pump(): Promise<void> {\n\t\tif (this.committing || this.stopped) return;\n\t\tif (this.queue.length === 0 && this.acks.size === 0) return;\n\t\tthis.committing = true;\n\t\tconst batch = this.queue.splice(0);\n\t\tconst acks = [...this.acks];\n\t\tthis.acks.clear();\n\t\ttry {\n\t\t\tawait this.api.commit(async (tx) => {\n\t\t\t\tconst journal = await tx.doc(CodemodeJournalDoc, this.api.taskId);\n\t\t\t\tfor (const [seq, issued] of acks) {\n\t\t\t\t\tif (seq === 0) journal.firstIssued ??= issued;\n\t\t\t\t\telse {\n\t\t\t\t\t\tconst entry = journal.entries[seq - 1];\n\t\t\t\t\t\tif (entry !== undefined && entry.issuedAfter === undefined) entry.issuedAfter = issued;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const item of batch) {\n\t\t\t\t\tconst entry = {\n\t\t\t\t\t\tid: item.id,\n\t\t\t\t\t\tat: item.at,\n\t\t\t\t\t\t...(item.global === undefined ? {} : { global: item.global }),\n\t\t\t\t\t};\n\t\t\t\t\tjournal.entries.push(\n\t\t\t\t\t\tcopyJson(entry as unknown as JsonValue, { omitUndefinedProperties: true }) as unknown as JournalEntry,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}, this.context);\n\t\t} catch (error) {\n\t\t\tthis.fail(error);\n\t\t\treturn;\n\t\t}\n\t\tfor (const [, issued] of acks) this.durableIssued = Math.max(this.durableIssued, issued);\n\t\tfor (const item of batch) {\n\t\t\tthis.journalLength++;\n\t\t\tif (!this.run.finished) this.run.deliver(this.journalLength, item.at, item.id, item.outcome);\n\t\t}\n\t\tthis.launchCovered();\n\t\tthis.committing = false;\n\t\tvoid this.pump();\n\t}\n}\n\n/** A script's call of `models.classify()` or `models.generateImages()` as the call of its internal tool. */\nfunction asToolCall(call: CodemodeHostCall): CodemodeHostCall {\n\tconst tool = call.target === \"global\" ? MODEL_CALLS[call.name] : undefined;\n\tif (tool === undefined) return call;\n\tconst [model, context] = Array.isArray(call.args) ? call.args : [];\n\treturn { id: call.id, target: \"tool\", name: tool, args: { model: model ?? null, context: context ?? null } };\n}\n\n/** Image blocks in a `models.generateImages()` result. */\nfunction countImages(value: unknown): number {\n\tconst output = typeof value === \"object\" && value !== null ? (value as { output?: unknown }).output : undefined;\n\treturn Array.isArray(output) ? output.filter((item) => (item as { type?: unknown })?.type === \"image\").length : 0;\n}\n\nfunction describe(call: CodemodeHostCall): string {\n\treturn `${call.target === \"tool\" ? \"tools.\" : \"\"}${call.name}(${JSON.stringify(call.args) ?? \"\"})`;\n}\n\n/** Structural JSON equality; key order does not matter. */\nfunction sameJson(a: unknown, b: unknown): 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) => sameJson(item, b[i]))\n\t\t);\n\t}\n\tconst keys = Object.keys(a);\n\treturn (\n\t\tkeys.length === Object.keys(b).length &&\n\t\tkeys.every(\n\t\t\t(key) =>\n\t\t\t\tObject.hasOwn(b, key) && sameJson((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n\t\t)\n\t);\n}\n"]}
1
+ {"version":3,"file":"codemode.js","sourceRoot":"","sources":["../../src/cod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CACN,IAAI,CAAC,MAAM,KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM;QACrC,IAAI,CAAC,KAAK,CACT,CAAC,GAAG,EAAE,EAAE,CACP,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,QAAQ,CAAE,CAA6B,CAAC,GAAG,CAAC,EAAG,CAA6B,CAAC,GAAG,CAAC,CAAC,CAC5G,CACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Durable code mode: a tool that runs model-written JavaScript in a QuickJS sandbox, whose script survives a restart.\n *\n * Problem: a script is in-memory VM state. A restart while\n *\n * const results = await Promise.all(paths.map((path) => tools.read({ path })));\n *\n * waits for the last of 200 reads would lose the script and every read it made.\n *\n * Solution: deterministic replay (`CodemodeSandboxBase.start()` in pi-codemode). The VM only runs when the host hands\n * it a result; given the same start data, clock, seed, and results in the same order, it makes the same calls with\n * the same arguments. The tool is replay-safe: after a restart, `execute()` runs again, starts the script again from\n * the stored start data, and hands it the results it got before, in the order it got them, from a journal written\n * before each delivery. Nested tool calls reattach to their tasks by key (`c<VM call id>`), so they never run twice\n * unless their own replay policy reruns them; their results come from `NestedCallDoc`. Then the script continues live.\n *\n * Documents, scoped to the code mode call's task and gone when it settles:\n * - `pi.codemode.run`: the start data, written once before the VM starts, and the outcome, written once when the call\n * decides it (with the store writes, in one transaction), so a rerun after that returns it without a VM.\n * - `pi.codemode.journal`: one entry per delivered result, in delivery order: the VM call ID, the clock value, the\n * calls the VM had issued after processing it (once acknowledged), and a global's outcome, which nothing else stores.\n *\n * Each result's acknowledged call count is recorded with the next journal commit, or at once when the VM has processed\n * everything delivered: a script waiting on a long call is where a restart usually finds it. A sequential script\n * therefore costs one journal commit and one count commit per result, on top of its nested calls' own; that is the\n * price of checking the most common crash point.\n *\n * A call is launched only once the count of calls issued in the drain that made it is committed. So every key an earlier\n * attempt admitted is at most its last recorded count; a replay checks every recorded count, so when it releases its\n * calls it has made every call an earlier attempt could have admitted, and later calls are new.\n *\n * A rerun refuses to replay (no new nested calls; nested calls admitted earlier may still resume on their own and are\n * aborted by the call's cleanup) when this module's version or the VM's fingerprint changed, when the deadline passed,\n * or when the script diverges: it makes another call, or calls in another order, than the journal says. Each ends the\n * call with an error result.\n */\nimport { type Context, copyJson, type JsonValue } from \"@earendil-works/chord\";\nimport { ownedSlice } from \"@earendil-works/chord/delta\";\nimport type { TextContent } from \"@earendil-works/pi-ai\";\nimport { toCodemodeIdentifier } from \"@earendil-works/pi-codemode/declarations\";\nimport type {\n\tCodemodeHostCall,\n\tCodemodeOutcome,\n\tCodemodeResult,\n\tCodemodeRun,\n\tCodemodeSandboxBase,\n} from \"@earendil-works/pi-codemode/portable\";\nimport { CODEMODE_SOURCE_GRAMMAR, parseCodemodeSource } from \"@earendil-works/pi-codemode/source\";\nimport { obj, type Static, str } from \"@earendil-works/pi-schema\";\nimport { defineDoc } from \"../documents.ts\";\nimport type { ExecutionEnv } from \"../env/index.ts\";\nimport { errorMessage } from \"../errors.ts\";\nimport { defineExtension, defineTool, section } from \"../harness/define.ts\";\nimport { NestedCallDoc, type ToolTaskInput } from \"../harness/tool.ts\";\nimport type {\n\tExtension,\n\tNestedToolExecutionResult,\n\tToolExecutionApi,\n\tToolExecutionResult,\n\tToolRegistration,\n} from \"../harness/types.ts\";\nimport { rankDocuments } from \"../search.ts\";\nimport type { JsonObject } from \"../types.ts\";\nimport {\n\ttype CodemodeNamespace,\n\tcodemodeDescription,\n\tcodemodeSection,\n\tDEFAULT_CODEMODE_INLINE_BUDGET,\n\tnamespaceOf,\n\tsampleOf,\n} from \"./describe.ts\";\nimport {\n\tCATALOG_GLOBALS,\n\tCODEMODE_INTERNAL_PREFIX,\n\tcatalogCall,\n\tcreateModelTools,\n\tGENERATE_IMAGES_TOOL,\n\tMAX_CONCURRENT_MODEL_CALLS,\n\tMODEL_CALLS,\n} from \"./models.ts\";\nimport { DEFAULT_MAX_OUTPUT_TOKENS, formatResult, type OutputFile } from \"./output.ts\";\n\n/**\n * Version of everything in this module that turns stored results into what a script sees: result mapping, globals,\n * start data. Bump it when that changes, so a call started before an upgrade is not replayed by different code.\n */\nexport const CODEMODE_MODULE_VERSION = 2;\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\n\n/** One tool as the script sees it: `tools.<jsName>`. */\n/**\n * `structured`: the tool declares `structuredOutputSchema`, so an error result with a value resolves with it.\n * `hidden`: an internal tool of this extension (`pi.codemode.*`), which scripts reach only through a global such as\n * `models.classify()`; never in `tools`, `ALL_TOOLS`, or tool search.\n */\ntype DeclaredTool = { name: string; jsName: string; description: string; structured?: true; hidden?: true };\n\n/** What a call starts with; a rerun starts the VM from exactly this. */\ntype Start = {\n\tversion: number;\n\tstartedAt: number;\n\tseed: number;\n\t/** The VM's fingerprint, recorded by the first run before any call is admitted. */\n\tfingerprint?: string;\n\t/** `startedAt + timeout_ms` when the script set one. */\n\tdeadline?: number;\n\ttools: DeclaredTool[];\n\t/** The namespaces of the tools, as `describeNamespace()` and `searchTools()` see them. */\n\tnamespaces: { name: string; description?: string; instructions?: string; tools: string[] }[];\n\tglobals: { name: string; spread: boolean }[];\n\t/** `max_output_tokens` of the script's options line, or the default. */\n\tmaxOutputTokens: number;\n\tstore: Record<string, JsonValue>;\n};\n\ntype RunState = {\n\tstart?: Start;\n\t/** Directory of the result's files (the full output, images), created once: a rerun writes the same files again. */\n\toutputDir?: string;\n\t/** The outcome, decided once. */\n\tresult?: JsonObject;\n};\n\nexport const CodemodeRunDoc = defineDoc<RunState>({\n\tkind: \"pi.codemode.run\",\n\tversion: 1,\n\tscope: \"task\",\n\tinitial: () => ({}),\n\t// The document retires with its task.\n\tcheckpointWhen: () => false,\n});\n\ntype JournalEntry = {\n\t/** The VM's call ID. Its result is the entry's position + 1 (`seq`). */\n\tid: number;\n\t/** The VM clock while it processes this result. */\n\tat: number;\n\t/** Calls the VM had issued after processing this result; absent until acknowledged. */\n\tissuedAfter?: number;\n\t/** A global's call and outcome; a tool's result is its nested call's. */\n\tglobal?: { name: string; args?: JsonValue; outcome: JsonObject };\n};\n\ntype JournalState = {\n\tentries: JournalEntry[];\n\t/** Calls the VM had issued after the script's first run, before any result; absent until acknowledged. */\n\tfirstIssued?: number;\n};\n\nexport const CodemodeJournalDoc = defineDoc<JournalState>({\n\tkind: \"pi.codemode.journal\",\n\tversion: 1,\n\tscope: \"task\",\n\tinitial: () => ({ entries: [] }),\n\t// The document retires with its task.\n\tcheckpointWhen: () => false,\n});\n\n/**\n * What scripts keep with `store()` and read with `load()`, per conversation. Rewindable and copied as of the fork\n * point, so a fork sees the values as they were when its entry was committed.\n */\nexport const CodemodeStoreDoc = defineDoc<{ values: Record<string, JsonValue> }>({\n\tkind: \"pi.codemode.store\",\n\tversion: 1,\n\tscope: \"conversation\",\n\thistory: \"rewindable\",\n\tfork: \"asOf\",\n\tinitial: () => ({ values: {} }),\n\tcheckpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,\n});\n\n/** One tool call a script made, as the code mode call's details show it. */\nexport type CodemodeNestedCall = {\n\t/** The VM's number for the call; its nested call ID is `<callId>/c<id>`. */\n\tid: number;\n\tname: string;\n\t/** Compact JSON of the arguments, cut for display. */\n\targs: string;\n\tstatus: \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\tdurationMs?: number;\n\t/** Error text, cut for display. */\n\terror?: string;\n};\n\n/**\n * The code mode call's details, in its result: its tool calls in the order it made them, with their status. Calls to\n * globals are not listed. While the script runs, UIs show its nested calls from `pi.live.nestedTools`, so the list is\n * written once, with the result.\n */\nexport type CodemodeToolDetails = {\n\tcalls: CodemodeNestedCall[];\n\t/** Temp file with the complete text output, when the output was cut to its token budget. */\n\tfullOutputPath?: string;\n};\n\nconst ARGS_PREVIEW_CHARS = 200;\nconst ERROR_PREVIEW_CHARS = 500;\n\nfunction cut(text: string, max: number): string {\n\t// A copy: the row outlives the arguments or error text it previews.\n\treturn text.length > max ? `${ownedSlice(text, 0, max - 3)}...` : text;\n}\n\n/** A function scripts call as a top-level global; its result is journaled. */\nexport type CodemodeGlobal = {\n\treadonly name: string;\n\treadonly spread?: boolean;\n\texecute(args: unknown, api: ToolExecutionApi, context: Context): Promise<JsonValue | undefined>;\n};\n\nconst codemodeSchema = obj({ code: str({ description: \"Raw JavaScript source.\" }) }, { open: true });\n\nexport type CodemodeToolInput = Static<typeof codemodeSchema>;\n\nexport type CodemodeToolOptions = {\n\t/** Runs the scripts: `CodemodeSandbox` on Node, `RemoteCodemodeSandbox` on Cloudflare. */\n\treadonly sandbox: CodemodeSandboxBase;\n\t/** Groups of tools by name prefix, such as MCP servers, for the `codemode` section and tool search. */\n\treadonly namespaces?: readonly CodemodeNamespace[];\n\t/** Estimated tokens the tool declarations in the `codemode` section may use. Default 3000. */\n\treadonly inlineBudget?: number;\n\t/** Give scripts `models.*`: the model catalog, classifiers, and image generation. Default true. */\n\treadonly models?: boolean;\n\t/** @internal Host functions scripts call as globals. */\n\treadonly globals?: readonly CodemodeGlobal[];\n};\n\n/** Outputs bounded by the script's own token budget; the Harness's limits only stop a runaway. */\nconst OUTPUT_LIMITS = { maxBytes: 4 * 1024 * 1024, maxLines: 100_000 } as const;\n\n/** Globals for finding tools, answered from the start data, so a replay sees what the first run saw. */\nconst DISCOVERY_GLOBALS = [\"searchTools\", \"describeTool\", \"describeNamespace\"] as const;\nconst DEFAULT_SEARCH_LIMIT = 8;\n\n/** The code mode tool. Scripts call the conversation's callable tools as `tools.<name>(args)`. */\nexport function createCodemodeTool(options: CodemodeToolOptions): ToolRegistration<typeof codemodeSchema> {\n\treturn defineTool({\n\t\tname: CODEMODE_TOOL_NAME,\n\t\tdescription: codemodeDescription(options.models !== false),\n\t\tparameters: codemodeSchema,\n\t\toutputLimits: OUTPUT_LIMITS,\n\t\t// Capable models write the script as raw text instead of a JSON-escaped string; pi-ai applies it only for them.\n\t\tconstrainedSampling: { type: \"grammar\", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },\n\t\tcallers: [\"model\"],\n\t\treplay: \"safe\",\n\t\texecute: (args, api, context) => new CodemodeCall(options, api, context).execute(args.code),\n\t});\n}\n\n/**\n * The `codemode` extension: the code mode tool, and the `codemode` prompt section listing the tools scripts can call.\n */\nexport function createCodemodeExtension(options: CodemodeToolOptions): Extension {\n\treturn defineExtension({\n\t\tname: \"codemode\",\n\t\ttools: [createCodemodeTool(options), ...(options.models === false ? [] : createModelTools())],\n\t\tsections: [\n\t\t\tsection(\"codemode\", (input) =>\n\t\t\t\tcodemodeSection(\n\t\t\t\t\t// Deferred tools are found with `searchTools()`, as the coding agent leaves them out too.\n\t\t\t\t\tinput.agent.callable.filter(\n\t\t\t\t\t\t(tool) => !tool.name.startsWith(CODEMODE_INTERNAL_PREFIX) && tool.deferred !== true,\n\t\t\t\t\t),\n\t\t\t\t\toptions.namespaces ?? [],\n\t\t\t\t\toptions.inlineBudget ?? DEFAULT_CODEMODE_INLINE_BUDGET,\n\t\t\t\t),\n\t\t\t),\n\t\t],\n\t});\n}\n\n/**\n * What a script gets for a nested call, as in the coding agent. A tool with a schema resolves with its value, also on\n * an error result that carries one (`bash`'s `{ output, exitCode }` for a nonzero exit); a schema-less tool\n * resolves with its text output, images left out, as its declaration says. Any other error rejects, with its text: a\n * schema-less tool's output, else its error diagnostics.\n */\nfunction outcomeOf(name: string, structured: boolean, result: NestedToolExecutionResult): CodemodeOutcome {\n\tconst value = structured ? result.structuredOutput : textOf(result.structuredOutput);\n\tif (!result.isError || (structured && value !== undefined)) return { ok: true, value };\n\tconst message = structured ? \"\" : (value as string);\n\tconst diagnostics = result.diagnostics\n\t\t.filter((diagnostic) => diagnostic.severity === \"error\")\n\t\t.map((diagnostic) => diagnostic.message)\n\t\t.join(\"\\n\");\n\treturn {\n\t\tok: false,\n\t\tmessage: message || diagnostics || `Tool ${name} failed`,\n\t\t...(value === undefined ? {} : { properties: { structuredOutput: value } }),\n\t};\n}\n\n/** The text of a schema-less tool's collapsed output: a string, one image, or an array of text and image blocks. */\nfunction textOf(value: JsonValue | undefined): string {\n\tif (typeof value === \"string\") return value;\n\tif (!Array.isArray(value)) return \"\";\n\treturn value.flatMap((item) => (isText(item) ? [item.text] : [])).join(\"\\n\");\n}\n\nfunction isText(item: unknown): item is TextContent {\n\treturn typeof item === \"object\" && item !== null && (item as TextContent).type === \"text\";\n}\n\nfunction errorResult(message: string): ToolExecutionResult {\n\treturn { output: [{ type: \"text\", text: message }], isError: true };\n}\n\n/** One execution of the code mode tool: a first run, or a rerun after a restart that replays the journal. */\nclass CodemodeCall {\n\tprivate readonly options: CodemodeToolOptions;\n\tprivate readonly api: ToolExecutionApi;\n\tprivate readonly context: Context;\n\tprivate readonly controller = new AbortController();\n\tprivate run!: CodemodeRun;\n\tprivate start!: Start;\n\t/** The journal as this attempt found it; replay delivers exactly these. */\n\tprivate replayed: JournalEntry[] = [];\n\t/** Entries in the journal, replayed and live; the next delivery is `length + 1`. */\n\tprivate journalLength = 0;\n\t/** Replayed entries delivered so far. */\n\tprivate nextReplayed = 0;\n\tprivate replaying = false;\n\t/** Whether an earlier attempt ran this call: its nested call keys may already exist. */\n\tprivate rerun = false;\n\t/** Whether live calls may launch; before, they are held (see `release()`). */\n\tprivate released = false;\n\t/** The count an earlier attempt recorded after the script's first run. */\n\tprivate firstIssued: number | undefined;\n\t/** The highest issued count known to be committed: calls up to it may launch. */\n\tprivate durableIssued = 0;\n\t/** Live calls waiting for their issued count to be committed. */\n\tprivate waiting: CodemodeHostCall[] = [];\n\t/** Journal index of each replayed call ID. */\n\tprivate replayIndex = new Map<number, number>();\n\t/** Calls the VM issued so far; its call IDs are 1, 2, ... */\n\tprivate issued = 0;\n\t/** Replay: results of journaled calls, ready to deliver in journal order. */\n\tprivate readonly ready = new Map<number, CodemodeOutcome>();\n\t/** Replay: calls the journal does not have, admitted once replay is done. */\n\tprivate held: CodemodeHostCall[] = [];\n\t/** Live: finished calls waiting for their journal commit. */\n\tprivate queue: { id: number; at: number; outcome: CodemodeOutcome; global?: JournalEntry[\"global\"] }[] = [];\n\t/** Acknowledged counts to record, by result number (0: the script's first run). */\n\tprivate readonly acks = new Map<number, number>();\n\tprivate committing = false;\n\t/** Set once the call decided an outcome other than the script's own (divergence, mismatch) or failed. */\n\tprivate ended: ToolExecutionResult | undefined;\n\tprivate failure: unknown;\n\t/** `models.classify()`/`generateImages()` calls in flight, and those waiting for a slot. */\n\tprivate modelCalls = 0;\n\tprivate readonly modelWaiters: (() => void)[] = [];\n\t/** Images `models.generateImages()` returned, to notice a script that never shows them. */\n\tprivate generatedImages = 0;\n\t/** The script's tool calls for `details`, by VM call ID. */\n\tprivate readonly rows = new Map<number, CodemodeNestedCall>();\n\t/** Resolves once the VM's fingerprint is checked or recorded; nothing is delivered or admitted before. */\n\tprivate gate!: Promise<void>;\n\tprivate openGate!: () => void;\n\n\tconstructor(options: CodemodeToolOptions, api: ToolExecutionApi, context: Context) {\n\t\tthis.options = options;\n\t\tthis.api = api;\n\t\tthis.context = context;\n\t\tthis.gate = new Promise((resolve) => {\n\t\t\tthis.openGate = resolve;\n\t\t});\n\t}\n\n\tasync execute(source: string): Promise<ToolExecutionResult> {\n\t\tconst { code, options: sourceOptions } = parseCodemodeSource(source);\n\t\tconst { api, context } = this;\n\t\tconst agent = await api.agent(context);\n\t\tconst tools: DeclaredTool[] = agent.callable.map((tool) => ({\n\t\t\tname: tool.name,\n\t\t\tjsName: toCodemodeIdentifier(tool.name),\n\t\t\tdescription: sampleOf(tool),\n\t\t\t...(tool.structuredOutputSchema === undefined ? {} : { structured: true as const }),\n\t\t\t...(tool.name.startsWith(CODEMODE_INTERNAL_PREFIX) ? { hidden: true as const } : {}),\n\t\t}));\n\t\tconst callable = agent.callable.filter((tool) => !tool.name.startsWith(CODEMODE_INTERNAL_PREFIX));\n\t\tconst models = this.options.models === false ? [] : [...CATALOG_GLOBALS, ...Object.keys(MODEL_CALLS)];\n\t\tconst globals = [\n\t\t\t...DISCOVERY_GLOBALS.map((name) => ({ name, spread: true })),\n\t\t\t...models.map((name) => ({ name, spread: true })),\n\t\t\t...(this.options.globals ?? []).map((global) => ({ name: global.name, spread: global.spread === true })),\n\t\t];\n\t\tconst namespaces: Start[\"namespaces\"] = [];\n\t\tfor (const tool of callable) {\n\t\t\tconst namespace = namespaceOf(tool.name, this.options.namespaces ?? []);\n\t\t\tif (namespace === undefined) continue;\n\t\t\tlet entry = namespaces.find((candidate) => candidate.name === namespace.name);\n\t\t\tif (entry === undefined) {\n\t\t\t\tentry = {\n\t\t\t\t\tname: namespace.name,\n\t\t\t\t\t...(namespace.description === undefined ? {} : { description: namespace.description }),\n\t\t\t\t\t...(namespace.instructions === undefined ? {} : { instructions: namespace.instructions }),\n\t\t\t\t\ttools: [],\n\t\t\t\t};\n\t\t\t\tnamespaces.push(entry);\n\t\t\t}\n\t\t\tentry.tools.push(tool.name);\n\t\t}\n\t\tconst now = api.now();\n\t\tconst seed = crypto.getRandomValues(new Uint32Array(1))[0]!;\n\t\ttype Found =\n\t\t\t| { done: ToolExecutionResult }\n\t\t\t| { start: Start; journal: JournalEntry[]; firstIssued: number | undefined; rerun: boolean };\n\t\tconst found = await api.commit(async (tx): Promise<Found> => {\n\t\t\tconst run = await tx.doc(CodemodeRunDoc, api.taskId);\n\t\t\tif (run.result !== undefined) return { done: copyJson(run.result as JsonValue) as ToolExecutionResult };\n\t\t\tconst rerun = run.start !== undefined;\n\t\t\tif (run.start === undefined) {\n\t\t\t\tconst store = await tx.doc(CodemodeStoreDoc, api.conversationId);\n\t\t\t\tconst timeout = sourceOptions.timeoutMs;\n\t\t\t\trun.start = {\n\t\t\t\t\tversion: CODEMODE_MODULE_VERSION,\n\t\t\t\t\tstartedAt: now,\n\t\t\t\t\tseed,\n\t\t\t\t\t...(timeout === undefined ? {} : { deadline: now + timeout }),\n\t\t\t\t\ttools,\n\t\t\t\t\tnamespaces,\n\t\t\t\t\tglobals,\n\t\t\t\t\tmaxOutputTokens: sourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,\n\t\t\t\t\tstore: copyJson(store.values as JsonValue) as Record<string, JsonValue>,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst journal = await tx.doc(CodemodeJournalDoc, api.taskId);\n\t\t\treturn {\n\t\t\t\tstart: copyJson(run.start as unknown as JsonValue) as unknown as Start,\n\t\t\t\tjournal: copyJson(journal.entries as unknown as JsonValue) as unknown as JournalEntry[],\n\t\t\t\tfirstIssued: journal.firstIssued,\n\t\t\t\trerun,\n\t\t\t};\n\t\t}, context);\n\t\tif (\"done\" in found) return found.done;\n\t\tthis.start = found.start;\n\t\tthis.replayed = found.journal;\n\t\tthis.replayIndex = new Map(found.journal.map((entry, index) => [entry.id, index]));\n\t\tthis.journalLength = found.journal.length;\n\t\tthis.replaying = found.journal.length > 0;\n\t\tthis.rerun = found.rerun;\n\t\tthis.firstIssued = found.firstIssued;\n\t\t// A loop, not spread arguments: a journal can hold more entries than a call takes arguments.\n\t\tthis.durableIssued = found.journal.reduce(\n\t\t\t(max, entry) => Math.max(max, entry.issuedAfter ?? 0),\n\t\t\tfound.firstIssued ?? 0,\n\t\t);\n\n\t\tif (this.start.version !== CODEMODE_MODULE_VERSION) {\n\t\t\treturn this.decide(\n\t\t\t\terrorResult(\n\t\t\t\t\t`The script cannot resume: it started under code mode version ${this.start.version}, this is ${CODEMODE_MODULE_VERSION}.`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tconst remaining = this.start.deadline === undefined ? undefined : this.start.deadline - this.api.now();\n\t\tif (remaining !== undefined && remaining <= 0) {\n\t\t\treturn this.decide(errorResult(`Script timed out: its deadline passed while it was interrupted.`));\n\t\t}\n\n\t\tconst onAbort = () => this.controller.abort(context.abortSignal?.reason);\n\t\tcontext.abortSignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tif (context.abortSignal?.aborted) onAbort();\n\t\ttry {\n\t\t\tthis.run = this.options.sandbox.start(code, {\n\t\t\t\tstartedAt: this.start.startedAt,\n\t\t\t\tseed: this.start.seed,\n\t\t\t\ttools: this.start.tools.filter((tool) => tool.hidden !== true),\n\t\t\t\tglobals: this.start.globals,\n\t\t\t\tstore: this.start.store,\n\t\t\t\tsignal: this.controller.signal,\n\t\t\t\t...(remaining === undefined ? {} : { timeoutMs: remaining }),\n\t\t\t\tonStarted: (fingerprint) => void this.checkFingerprint(fingerprint),\n\t\t\t\tonCall: (call) => this.onCall(call),\n\t\t\t\tonIdle: (seq, issued) => this.onIdle(seq, issued),\n\t\t\t});\n\t\t\tconst result = await this.run.result;\n\t\t\tif (this.failure !== undefined) throw this.failure;\n\t\t\tif (this.ended !== undefined) return this.ended;\n\t\t\tcontext.abortSignal?.throwIfAborted();\n\t\t\t// Aborted, but not by this call: the host closed the sandbox, for example while shutting down before closing the\n\t\t\t// Harness. That decides nothing about the script: store nothing and end with this invocation, so a later attempt\n\t\t\t// replays it.\n\t\t\tif (!result.ok && result.error.kind === \"aborted\" && !this.controller.signal.aborted) {\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tif (context.abortSignal === undefined || context.abortSignal.aborted) resolve();\n\t\t\t\t\telse context.abortSignal.addEventListener(\"abort\", () => resolve(), { once: true });\n\t\t\t\t});\n\t\t\t\tcontext.abortSignal?.throwIfAborted();\n\t\t\t\tthrow new Error(\"The code mode sandbox was closed while the script ran\");\n\t\t\t}\n\t\t\t// A replay that ends where the live run went on is a divergence (design §4.3).\n\t\t\tconst during = result.during;\n\t\t\t// Within the replayed part, the first run included: a rerun without journal entries replays that much too.\n\t\t\tif (this.rerun && during !== undefined && during.seq <= this.replayed.length) {\n\t\t\t\t// The live run went on: it acknowledged that result, or it made a call that later results answer, which the\n\t\t\t\t// replay never made.\n\t\t\t\tconst continued =\n\t\t\t\t\t(during.seq === 0\n\t\t\t\t\t\t? this.replayed.length > 0 || this.firstIssued !== undefined\n\t\t\t\t\t\t: this.replayed[during.seq - 1]?.issuedAfter !== undefined) ||\n\t\t\t\t\tthis.replayed.slice(during.seq).some((entry) => entry.id > during.issued);\n\t\t\t\tif (continued) {\n\t\t\t\t\treturn this.decide(\n\t\t\t\t\t\terrorResult(\n\t\t\t\t\t\t\t`The script took a different path when resumed after a restart: it ended after result ${during.seq}, where it went on before.`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this.complete(result);\n\t\t} finally {\n\t\t\tcontext.abortSignal?.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t}\n\n\t/** Store an outcome the call decided, and end the VM if it runs; returns the outcome. */\n\tprivate async decide(decided: ToolExecutionResult): Promise<ToolExecutionResult> {\n\t\tconst result = { ...decided, details: this.details() as unknown as JsonValue };\n\t\tawait this.api.commit(async (tx) => {\n\t\t\tconst run = await tx.doc(CodemodeRunDoc, this.api.taskId);\n\t\t\trun.result ??= copyJson(result as unknown as JsonValue, { omitUndefinedProperties: true }) as JsonObject;\n\t\t}, this.context);\n\t\treturn result;\n\t}\n\n\t/** End the call with `message`: store it as the outcome, then stop the VM with an error the script cannot catch. */\n\tprivate diverge(message: string): void {\n\t\tif (this.ended !== undefined || this.failure !== undefined) return;\n\t\tconst result = errorResult(`The script took a different path when resumed after a restart: ${message}`);\n\t\tthis.ended = result;\n\t\tthis.decide(result).then(\n\t\t\t() => this.controller.abort(new Error(message)),\n\t\t\t(error: unknown) => this.fail(error),\n\t\t);\n\t}\n\n\t/** Whether nothing more may happen: the run has its outcome, or the call decided or failed. */\n\tprivate get stopped(): boolean {\n\t\treturn this.ended !== undefined || this.failure !== undefined || this.run?.finished === true;\n\t}\n\n\tprivate fail(error: unknown): void {\n\t\tif (this.failure !== undefined) return;\n\t\tthis.failure = error;\n\t\tthis.controller.abort(error);\n\t}\n\n\t/** The script's own outcome, stored with its store writes in one transaction. */\n\tprivate async complete(result: CodemodeResult): Promise<ToolExecutionResult> {\n\t\tconst details = this.details();\n\t\tconst formatted = await formatResult(result, {\n\t\t\tgeneratedImages: this.generatedImages,\n\t\t\twallMs: this.api.now() - this.start.startedAt,\n\t\t\tmaxOutputTokens: this.start.maxOutputTokens,\n\t\t\tcalls: details.calls,\n\t\t\tlimits: OUTPUT_LIMITS,\n\t\t\twrite: this.outputFiles(),\n\t\t});\n\t\tconst tool: ToolExecutionResult = {\n\t\t\toutput: formatted.content,\n\t\t\tisError: !result.ok,\n\t\t\tdetails: {\n\t\t\t\t...details,\n\t\t\t\t...(formatted.fullOutputPath === undefined ? {} : { fullOutputPath: formatted.fullOutputPath }),\n\t\t\t} as unknown as JsonValue,\n\t\t};\n\t\tconst writes = result.ok ? result.storeWrites : undefined;\n\t\treturn this.api.commit(async (tx) => {\n\t\t\tconst run = await tx.doc(CodemodeRunDoc, this.api.taskId);\n\t\t\tif (run.result !== undefined) return run.result as ToolExecutionResult;\n\t\t\trun.result = copyJson(tool as unknown as JsonValue, { omitUndefinedProperties: true }) as JsonObject;\n\t\t\tif (writes !== undefined && (Object.keys(writes.set).length > 0 || writes.delete.length > 0)) {\n\t\t\t\tconst store = await tx.doc(CodemodeStoreDoc, this.api.conversationId);\n\t\t\t\tfor (const key of writes.delete) delete store.values[key];\n\t\t\t\tfor (const [key, value] of Object.entries(writes.set)) store.values[key] = value as JsonValue;\n\t\t\t}\n\t\t\treturn tool;\n\t\t}, this.context);\n\t}\n\n\t/** Writes the result's files under fixed names into the run's output directory, so a rerun overwrites them. */\n\tprivate outputFiles(): OutputFile {\n\t\tconst env = this.api.env;\n\t\tlet directory: Promise<string> | undefined;\n\t\treturn async (name, data) => {\n\t\t\tif (env === undefined) return { error: \"no execution environment\" };\n\t\t\ttry {\n\t\t\t\tdirectory ??= this.outputDir(env);\n\t\t\t\tconst path = `${await directory}/${name}`;\n\t\t\t\tconst written = await env.writeFile(path, data, this.context);\n\t\t\t\treturn written.ok ? { path } : { error: written.error.message };\n\t\t\t} catch (error) {\n\t\t\t\treturn { error: errorMessage(error) };\n\t\t\t}\n\t\t};\n\t}\n\n\t/** The run's output directory: the recorded one, else a new temp directory, recorded before any file is written. */\n\tprivate async outputDir(env: ExecutionEnv): Promise<string> {\n\t\tconst recorded = await this.api.commit(\n\t\t\tasync (tx) => (await tx.doc(CodemodeRunDoc, this.api.taskId)).outputDir,\n\t\t\tthis.context,\n\t\t);\n\t\tif (recorded !== undefined) return recorded;\n\t\tconst created = await env.createTempDir(\"pi-codemode-\", this.context);\n\t\tif (!created.ok) throw new Error(created.error.message);\n\t\treturn this.api.commit(async (tx) => {\n\t\t\tconst run = await tx.doc(CodemodeRunDoc, this.api.taskId);\n\t\t\trun.outputDir ??= created.value;\n\t\t\treturn run.outputDir!;\n\t\t}, this.context);\n\t}\n\n\tprivate async checkFingerprint(fingerprint: string): Promise<void> {\n\t\tconst recorded = this.start.fingerprint;\n\t\tif (recorded !== undefined) {\n\t\t\tif (recorded !== fingerprint) {\n\t\t\t\tthis.ended = errorResult(\n\t\t\t\t\t`The script cannot resume: the sandbox changed since it started (${recorded} -> ${fingerprint}).`,\n\t\t\t\t);\n\t\t\t\tawait this.decide(this.ended).catch((error: unknown) => this.fail(error));\n\t\t\t\tthis.controller.abort(new Error(\"Sandbox fingerprint changed\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tawait this.api.commit(async (tx) => {\n\t\t\t\t\tconst run = await tx.doc(CodemodeRunDoc, this.api.taskId);\n\t\t\t\t\tif (run.start !== undefined) run.start.fingerprint = fingerprint;\n\t\t\t\t}, this.context);\n\t\t\t} catch (error) {\n\t\t\t\tthis.fail(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tthis.openGate();\n\t\t// Nothing was delivered before the gate: start now. A rerun without a journal releases its calls at the\n\t\t// script's first acknowledgment instead.\n\t\tif (this.replaying) this.deliverReplayed();\n\t\telse if (!this.rerun) void this.release();\n\t}\n\n\tprivate onCall(made: CodemodeHostCall): void {\n\t\tif (this.stopped) return;\n\t\tconst call = asToolCall(made);\n\t\tif (call.target === \"tool\") this.started(call);\n\t\tthis.issued = Math.max(this.issued, call.id);\n\t\tconst index = this.replaying ? (this.replayIndex.get(call.id) ?? -1) : -1;\n\t\tif (index === -1) {\n\t\t\tif (this.released) {\n\t\t\t\tthis.waiting.push(call);\n\t\t\t\tthis.launchCovered();\n\t\t\t} else this.held.push(call);\n\t\t\treturn;\n\t\t}\n\t\tconst entry = this.replayed[index]!;\n\t\tif (entry.global !== undefined) {\n\t\t\tif (call.target !== \"global\" || call.name !== entry.global.name || !sameJson(call.args, entry.global.args)) {\n\t\t\t\tthis.diverge(`call ${call.id} is ${describe(call)}, but was a call to ${entry.global.name}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.ready.set(call.id, entry.global.outcome as CodemodeOutcome);\n\t\t\tvoid this.gate.then(() => this.deliverReplayed());\n\t\t\treturn;\n\t\t}\n\t\tif (call.target !== \"tool\") {\n\t\t\tthis.diverge(`call ${call.id} is ${describe(call)}, but was a tool call`);\n\t\t\treturn;\n\t\t}\n\t\tvoid this.gate\n\t\t\t.then(() => this.callTool(call))\n\t\t\t.then(\n\t\t\t\t(outcome) => {\n\t\t\t\t\tthis.ready.set(call.id, outcome);\n\t\t\t\t\tthis.deliverReplayed();\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tif (this.stopped) return;\n\t\t\t\t\tif (this.context.abortSignal?.aborted) this.fail(error);\n\t\t\t\t\t// The key names another tool or other arguments.\n\t\t\t\t\telse this.diverge(`call ${call.id} is ${describe(call)}: ${errorMessage(error)}`);\n\t\t\t\t},\n\t\t\t);\n\t}\n\n\t/** Replay: deliver journaled results in journal order, each once the VM has issued its call. */\n\tprivate deliverReplayed(): void {\n\t\twhile (this.nextReplayed < this.replayed.length && !this.stopped) {\n\t\t\tconst entry = this.replayed[this.nextReplayed]!;\n\t\t\tconst outcome = this.ready.get(entry.id);\n\t\t\tif (entry.id > this.issued || outcome === undefined) return;\n\t\t\tthis.ready.delete(entry.id);\n\t\t\tthis.nextReplayed++;\n\t\t\tthis.run.deliver(this.nextReplayed, entry.at, entry.id, outcome);\n\t\t}\n\t}\n\n\tprivate onIdle(seq: number, issued: number): void {\n\t\tif (this.stopped) return;\n\t\t// A count an earlier attempt recorded must match; a missing one is recorded now.\n\t\tif (this.rerun && seq <= this.replayed.length) {\n\t\t\tconst recorded = seq === 0 ? this.firstIssued : this.replayed[seq - 1]!.issuedAfter;\n\t\t\tif (recorded !== undefined && recorded !== issued) {\n\t\t\t\tthis.diverge(\n\t\t\t\t\tseq === 0\n\t\t\t\t\t\t? `its first run made ${issued} calls, where it had made ${recorded}`\n\t\t\t\t\t\t: `after result ${seq} it had made ${issued} calls, where it had made ${recorded}`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tthis.acks.set(seq, issued);\n\t\tif (!this.replaying) {\n\t\t\t// A rerun without a journal: every call an earlier attempt could have admitted is made by now.\n\t\t\tif (seq === 0 && this.rerun) void this.release();\n\t\t\t// Committed at once when the script has processed everything delivered: calls it made wait for it, and a script\n\t\t\t// waiting on a long call is where a restart usually finds it. Otherwise with the next commit; the VM catches up\n\t\t\t// without waiting on anything.\n\t\t\tif (seq === this.journalLength) void this.pump();\n\t\t\treturn;\n\t\t}\n\t\t// Caught up: the VM processed everything delivered and waits.\n\t\tif (seq !== this.nextReplayed) return;\n\t\tconst next = this.replayed[seq];\n\t\tif (next !== undefined) {\n\t\t\tif (next.id > issued) this.diverge(`it waits without making call ${next.id}, which it made before`);\n\t\t\treturn;\n\t\t}\n\t\t// The last replayed result is acknowledged: continue live, admitting the calls the journal did not have once their\n\t\t// count is committed.\n\t\tthis.replaying = false;\n\t\tvoid this.pump();\n\t\tvoid this.release();\n\t}\n\n\t/**\n\t * Let the held calls launch, and later live calls, each once its issued count is committed. On a rerun, an earlier\n\t * attempt may have admitted some of them under their keys, as other calls: when the replay releases (idle after the\n\t * last journaled result, or after its first run without a journal) its counts matched every recorded one, so it has\n\t * made every call an earlier attempt could have admitted. All held calls are checked first, whatever their target,\n\t * and a divergence launches none. Calls made after this are new.\n\t */\n\tprivate async release(): Promise<void> {\n\t\tawait this.gate;\n\t\tif (this.stopped || this.released) return;\n\t\tconst calls = this.held.splice(0);\n\t\tif (this.rerun) {\n\t\t\tfor (const call of calls) {\n\t\t\t\tlet other: string | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tother = await this.earlier(call);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.fail(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (this.stopped) return;\n\t\t\t\tif (other !== undefined) {\n\t\t\t\t\tthis.diverge(`call ${call.id} is ${describe(call)}, but was ${other}`);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.released = true;\n\t\tthis.waiting.push(...calls, ...this.held.splice(0));\n\t\tthis.launchCovered();\n\t}\n\n\t/** Launch the waiting calls whose issued count is committed. */\n\tprivate launchCovered(): void {\n\t\tif (!this.released || this.stopped) return;\n\t\tconst covered = this.waiting.filter((call) => call.id <= this.durableIssued);\n\t\tif (covered.length === 0) return;\n\t\tthis.waiting = this.waiting.filter((call) => call.id > this.durableIssued);\n\t\tfor (const call of covered) this.launch(call);\n\t}\n\n\t/** The call an earlier attempt made under this call's key, when it is another one: another target, tool, or arguments. */\n\tprivate async earlier(call: CodemodeHostCall): Promise<string | undefined> {\n\t\tconst { api, context } = this;\n\t\tconst taskId = (await api.snapshot(NestedCallDoc, api.taskId, `c${call.id}`, context))?.taskId;\n\t\tif (taskId === undefined) return undefined;\n\t\tconst input = (await api.getTask(taskId, context))?.input as ToolTaskInput | undefined;\n\t\tif (input?.kind !== \"nested\") return undefined;\n\t\tconst made = input.call;\n\t\tif (call.target === \"tool\" && made.name === call.name && sameJson(made.arguments, call.args ?? {}))\n\t\t\treturn undefined;\n\t\treturn `tools.${made.name}(${JSON.stringify(made.arguments)})`;\n\t}\n\n\t/** Run one live call and journal its result. */\n\tprivate launch(call: CodemodeHostCall): void {\n\t\tif (this.stopped) return;\n\t\tconst running: Promise<{ outcome: CodemodeOutcome; global?: JournalEntry[\"global\"] }> =\n\t\t\tcall.target === \"tool\"\n\t\t\t\t? this.callTool(call).then((outcome) => ({ outcome }))\n\t\t\t\t: this.callGlobal(call).then((outcome) => ({\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\tglobal: {\n\t\t\t\t\t\t\tname: call.name,\n\t\t\t\t\t\t\t...(call.args === undefined ? {} : { args: call.args as JsonValue }),\n\t\t\t\t\t\t\toutcome: outcome as JsonObject,\n\t\t\t\t\t\t},\n\t\t\t\t\t}));\n\t\trunning.then(\n\t\t\t(done) => {\n\t\t\t\t// A result after the outcome is decided has nowhere to go, and the call's API has ended.\n\t\t\t\tif (this.stopped) return;\n\t\t\t\tthis.queue.push({ id: call.id, at: this.api.now(), ...done });\n\t\t\t\tvoid this.pump();\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\t// Stopped meanwhile: the outcome is decided, or a waiting model call gave up.\n\t\t\t\tif (this.stopped) return;\n\t\t\t\tif (this.context.abortSignal?.aborted) this.fail(error);\n\t\t\t\t// A key an earlier attempt admitted with another tool or other arguments: this attempt took another path.\n\t\t\t\telse this.diverge(`call ${call.id} is ${describe(call)}: ${errorMessage(error)}`);\n\t\t\t},\n\t\t);\n\t}\n\n\tprivate async callTool(call: CodemodeHostCall): Promise<CodemodeOutcome> {\n\t\t// Passed as the script gave them; validation reports arguments that are not an object.\n\t\tconst args = (call.args ?? {}) as JsonObject;\n\t\tconst model = call.name.startsWith(CODEMODE_INTERNAL_PREFIX);\n\t\tif (model) {\n\t\t\tawait this.modelSlot();\n\t\t\t// The call may have stopped while this one waited: a finished script admits no new paid call.\n\t\t\tif (this.stopped) {\n\t\t\t\tthis.releaseModelSlot();\n\t\t\t\tthrow new Error(\"The script has ended\");\n\t\t\t}\n\t\t}\n\t\tlet result: NestedToolExecutionResult;\n\t\ttry {\n\t\t\tresult = await this.api.executeTool(call.name, args, this.context, { key: `c${call.id}` });\n\t\t} finally {\n\t\t\tif (model) this.releaseModelSlot();\n\t\t}\n\t\tif (call.name === GENERATE_IMAGES_TOOL) this.generatedImages += countImages(result.structuredOutput);\n\t\tconst structured = this.start.tools.find((tool) => tool.name === call.name)?.structured === true;\n\t\tconst outcome = outcomeOf(call.name, structured, result);\n\t\tthis.finishRow(call.id, outcome, result);\n\t\treturn outcome;\n\t}\n\n\t/** The script made a tool call: its row appears, running, also while it waits to launch. */\n\tprivate started(call: CodemodeHostCall): void {\n\t\tif (this.rows.has(call.id)) return;\n\t\tconst args = call.args === undefined ? \"\" : (JSON.stringify(call.args) ?? \"\");\n\t\tconst name = call.name.startsWith(CODEMODE_INTERNAL_PREFIX)\n\t\t\t? call.name.slice(CODEMODE_INTERNAL_PREFIX.length)\n\t\t\t: call.name;\n\t\tthis.rows.set(call.id, { id: call.id, name, args: cut(args, ARGS_PREVIEW_CHARS), status: \"running\" });\n\t}\n\n\t/** A tool call ended: its row gets its status, duration, and error. */\n\t/** The call ended: an error result is an error row, also when the script got its value (bash's nonzero exit). */\n\tprivate finishRow(id: number, outcome: CodemodeOutcome, result: NestedToolExecutionResult): void {\n\t\tconst row = this.rows.get(id);\n\t\tif (row === undefined) return;\n\t\trow.status = result.isError ? \"error\" : \"ok\";\n\t\tif (result.durationMs !== undefined) row.durationMs = result.durationMs;\n\t\tconst errors = result.diagnostics.filter((diagnostic) => diagnostic.severity === \"error\");\n\t\tconst error = !outcome.ok ? outcome.message : errors.map((diagnostic) => diagnostic.message).join(\"\\n\");\n\t\tif (result.isError && error !== \"\") row.error = cut(error, ERROR_PREVIEW_CHARS);\n\t}\n\n\t/** The rows in call order; calls still running when the script ended were cancelled. */\n\tprivate details(): CodemodeToolDetails {\n\t\tconst calls = [...this.rows.values()]\n\t\t\t.sort((a, b) => a.id - b.id)\n\t\t\t.map((row) => (row.status === \"running\" ? { ...row, status: \"cancelled\" as const } : row));\n\t\treturn { calls };\n\t}\n\n\tprivate async callGlobal(call: CodemodeHostCall): Promise<CodemodeOutcome> {\n\t\tconst discovery = (DISCOVERY_GLOBALS as readonly string[]).includes(call.name);\n\t\tconst catalog = (CATALOG_GLOBALS as readonly string[]).includes(call.name);\n\t\tconst global =\n\t\t\tdiscovery || catalog ? undefined : this.options.globals?.find((candidate) => candidate.name === call.name);\n\t\tif (!discovery && !catalog && global === undefined) return { ok: false, message: `Unknown global ${call.name}` };\n\t\ttry {\n\t\t\t// `undefined` stays undefined: the journal omits the value, and a replay resolves with undefined again.\n\t\t\tconst value = discovery\n\t\t\t\t? this.discover(call)\n\t\t\t\t: catalog\n\t\t\t\t\t? await catalogCall(call.name, call.args, this.api.models, this.context)\n\t\t\t\t\t: await global!.execute(call.args, this.api, this.context);\n\t\t\treturn { ok: true, value };\n\t\t} catch (error) {\n\t\t\tif (this.context.abortSignal?.aborted) throw error;\n\t\t\treturn { ok: false, message: errorMessage(error) };\n\t\t}\n\t}\n\n\tprivate async modelSlot(): Promise<void> {\n\t\tif (this.modelCalls >= MAX_CONCURRENT_MODEL_CALLS) {\n\t\t\tawait new Promise<void>((resolve) => this.modelWaiters.push(resolve));\n\t\t}\n\t\tthis.modelCalls++;\n\t}\n\n\tprivate releaseModelSlot(): void {\n\t\tthis.modelCalls--;\n\t\tthis.modelWaiters.shift()?.();\n\t}\n\n\t/** `searchTools()`, `describeTool()`, `describeNamespace()`: answered from the start data. */\n\tprivate discover(call: CodemodeHostCall): JsonValue | undefined {\n\t\tconst args = Array.isArray(call.args) ? call.args : [];\n\t\tconst { namespaces } = this.start;\n\t\tconst tools = this.start.tools.filter((tool) => tool.hidden !== true);\n\t\tconst namespaceOfTool = (name: string) => namespaces.find((namespace) => namespace.tools.includes(name));\n\t\tconst matchesNamespace = (namespace: Start[\"namespaces\"][number], query: string) =>\n\t\t\tnamespace.name === query || toCodemodeIdentifier(namespace.name) === toCodemodeIdentifier(query);\n\t\tif (call.name === \"describeTool\") {\n\t\t\tconst [name] = args;\n\t\t\tif (typeof name !== \"string\") throw new Error(\"describeTool() expects a tool name\");\n\t\t\treturn tools.find((tool) => tool.name === name || tool.jsName === name)?.description;\n\t\t}\n\t\tif (call.name === \"describeNamespace\") {\n\t\t\tconst [name] = args;\n\t\t\tif (typeof name !== \"string\") throw new Error(\"describeNamespace() expects a namespace name\");\n\t\t\tconst namespace = namespaces.find((candidate) => matchesNamespace(candidate, name));\n\t\t\tif (namespace === undefined) return undefined;\n\t\t\treturn {\n\t\t\t\tname: namespace.name,\n\t\t\t\t...(namespace.description === undefined ? {} : { description: namespace.description }),\n\t\t\t\t...(namespace.instructions === undefined ? {} : { instructions: namespace.instructions }),\n\t\t\t\ttools: namespace.tools.map((tool) => toCodemodeIdentifier(tool)),\n\t\t\t};\n\t\t}\n\t\tconst [query, options] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];\n\t\tif (typeof query !== \"string\") throw new Error(\"searchTools() expects a query string\");\n\t\tconst limit = options?.limit ?? DEFAULT_SEARCH_LIMIT;\n\t\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit <= 0) {\n\t\t\tthrow new Error(\"searchTools() limit must be a positive integer\");\n\t\t}\n\t\tconst namespace = options?.namespace;\n\t\tif (namespace !== undefined && namespace !== null && typeof namespace !== \"string\") {\n\t\t\tthrow new Error(\"searchTools() namespace must be a string\");\n\t\t}\n\t\tconst documents = tools.flatMap((tool) => {\n\t\t\tconst own = namespaceOfTool(tool.name);\n\t\t\tif (typeof namespace === \"string\" && (own === undefined || !matchesNamespace(own, namespace))) return [];\n\t\t\tconst namespaceText =\n\t\t\t\town === undefined ? \"\" : [own.name, own.description ?? \"\", own.instructions ?? \"\"].join(\" \");\n\t\t\t// `description` is the tool's sample: its description and declaration, with the parameters' names and descriptions.\n\t\t\treturn [{ name: tool.name, text: tool.description, namespaceText }];\n\t\t});\n\t\treturn rankDocuments(query, documents, limit).map((name) => {\n\t\t\tconst tool = tools.find((candidate) => candidate.name === name)!;\n\t\t\treturn { name: tool.jsName, description: tool.description };\n\t\t});\n\t}\n\n\t/**\n\t * Journal finished calls and acknowledged counts in one commit, then deliver the calls and launch the calls the\n\t * counts cover; one commit in flight at a time, so what arrives meanwhile goes into the next.\n\t */\n\tprivate async pump(): Promise<void> {\n\t\tif (this.committing || this.stopped) return;\n\t\tif (this.queue.length === 0 && this.acks.size === 0) return;\n\t\tthis.committing = true;\n\t\tconst batch = this.queue.splice(0);\n\t\tconst acks = [...this.acks];\n\t\tthis.acks.clear();\n\t\ttry {\n\t\t\tawait this.api.commit(async (tx) => {\n\t\t\t\tconst journal = await tx.doc(CodemodeJournalDoc, this.api.taskId);\n\t\t\t\tfor (const [seq, issued] of acks) {\n\t\t\t\t\tif (seq === 0) journal.firstIssued ??= issued;\n\t\t\t\t\telse {\n\t\t\t\t\t\tconst entry = journal.entries[seq - 1];\n\t\t\t\t\t\tif (entry !== undefined && entry.issuedAfter === undefined) entry.issuedAfter = issued;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const item of batch) {\n\t\t\t\t\tconst entry = {\n\t\t\t\t\t\tid: item.id,\n\t\t\t\t\t\tat: item.at,\n\t\t\t\t\t\t...(item.global === undefined ? {} : { global: item.global }),\n\t\t\t\t\t};\n\t\t\t\t\tjournal.entries.push(\n\t\t\t\t\t\tcopyJson(entry as unknown as JsonValue, { omitUndefinedProperties: true }) as unknown as JournalEntry,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}, this.context);\n\t\t} catch (error) {\n\t\t\tthis.fail(error);\n\t\t\treturn;\n\t\t}\n\t\tfor (const [, issued] of acks) this.durableIssued = Math.max(this.durableIssued, issued);\n\t\tfor (const item of batch) {\n\t\t\tthis.journalLength++;\n\t\t\tif (!this.run.finished) this.run.deliver(this.journalLength, item.at, item.id, item.outcome);\n\t\t}\n\t\tthis.launchCovered();\n\t\tthis.committing = false;\n\t\tvoid this.pump();\n\t}\n}\n\n/** A script's call of `models.classify()` or `models.generateImages()` as the call of its internal tool. */\nfunction asToolCall(call: CodemodeHostCall): CodemodeHostCall {\n\tconst tool = call.target === \"global\" ? MODEL_CALLS[call.name] : undefined;\n\tif (tool === undefined) return call;\n\tconst [model, context] = Array.isArray(call.args) ? call.args : [];\n\treturn { id: call.id, target: \"tool\", name: tool, args: { model: model ?? null, context: context ?? null } };\n}\n\n/** Image blocks in a `models.generateImages()` result. */\nfunction countImages(value: unknown): number {\n\tconst output = typeof value === \"object\" && value !== null ? (value as { output?: unknown }).output : undefined;\n\treturn Array.isArray(output) ? output.filter((item) => (item as { type?: unknown })?.type === \"image\").length : 0;\n}\n\nfunction describe(call: CodemodeHostCall): string {\n\treturn `${call.target === \"tool\" ? \"tools.\" : \"\"}${call.name}(${JSON.stringify(call.args) ?? \"\"})`;\n}\n\n/** Structural JSON equality; key order does not matter. */\nfunction sameJson(a: unknown, b: unknown): 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) => sameJson(item, b[i]))\n\t\t);\n\t}\n\tconst keys = Object.keys(a);\n\treturn (\n\t\tkeys.length === Object.keys(b).length &&\n\t\tkeys.every(\n\t\t\t(key) =>\n\t\t\t\tObject.hasOwn(b, key) && sameJson((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n\t\t)\n\t);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { Type } from "typebox";
1
+ import { obj, unknown } from "@earendil-works/pi-schema";
2
2
  import { defineTool } from "../harness/define.js";
3
3
  /** Reserved names of code mode's internal tools; they are never listed to scripts or the model. */
4
4
  export const CODEMODE_INTERNAL_PREFIX = "pi.codemode.";
@@ -178,7 +178,7 @@ function resolveModel(name, type, model, models) {
178
178
  ? `"${provider}/${id}" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}`
179
179
  : `Unknown ${type} model "${provider}/${id}". ${listHint}`);
180
180
  }
181
- const ModelCallParameters = Type.Object({ model: Type.Unknown(), context: Type.Unknown() });
181
+ const ModelCallParameters = obj({ model: unknown(), context: unknown() }, { open: true });
182
182
  /** The result of a model call as the tool returns it: the whole result for the script, usage counted by the Harness. */
183
183
  function modelResult(label, result, value) {
184
184
  const ok = result.stopReason === "stop";
@@ -200,7 +200,7 @@ export function createModelTools() {
200
200
  name: CLASSIFY_TOOL,
201
201
  description: "models.classify() of code mode scripts.",
202
202
  parameters: ModelCallParameters,
203
- structuredOutputSchema: Type.Unknown(),
203
+ structuredOutputSchema: unknown(),
204
204
  callers: ["tools"],
205
205
  execute: async (args, api, context) => {
206
206
  const model = resolveModel("models.classify", "classifier", args.model, api.models);
@@ -216,7 +216,7 @@ export function createModelTools() {
216
216
  name: GENERATE_IMAGES_TOOL,
217
217
  description: "models.generateImages() of code mode scripts.",
218
218
  parameters: ModelCallParameters,
219
- structuredOutputSchema: Type.Unknown(),
219
+ structuredOutputSchema: unknown(),
220
220
  callers: ["tools"],
221
221
  execute: async (args, api, context) => {
222
222
  const model = resolveModel("models.generateImages", "image", args.model, api.models);