@ny4n/durable 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +41 -5
  3. package/dist/codemode/codemode.d.ts +132 -0
  4. package/dist/codemode/codemode.d.ts.map +1 -0
  5. package/dist/codemode/codemode.js +791 -0
  6. package/dist/codemode/codemode.js.map +1 -0
  7. package/dist/codemode/describe.d.ts +38 -0
  8. package/dist/codemode/describe.d.ts.map +1 -0
  9. package/dist/codemode/describe.js +117 -0
  10. package/dist/codemode/describe.js.map +1 -0
  11. package/dist/codemode/index.d.ts +3 -0
  12. package/dist/codemode/index.d.ts.map +1 -0
  13. package/dist/codemode/index.js +3 -0
  14. package/dist/codemode/index.js.map +1 -0
  15. package/dist/codemode/output.d.ts +39 -0
  16. package/dist/codemode/output.d.ts.map +1 -0
  17. package/dist/codemode/output.js +160 -0
  18. package/dist/codemode/output.js.map +1 -0
  19. package/dist/harness/agent.d.ts +4 -2
  20. package/dist/harness/agent.d.ts.map +1 -1
  21. package/dist/harness/agent.js +56 -26
  22. package/dist/harness/agent.js.map +1 -1
  23. package/dist/harness/compaction.d.ts +6 -1
  24. package/dist/harness/compaction.d.ts.map +1 -1
  25. package/dist/harness/compaction.js +10 -7
  26. package/dist/harness/compaction.js.map +1 -1
  27. package/dist/harness/events.d.ts +8 -2
  28. package/dist/harness/events.d.ts.map +1 -1
  29. package/dist/harness/events.js +4 -1
  30. package/dist/harness/events.js.map +1 -1
  31. package/dist/harness/generation.d.ts +2 -0
  32. package/dist/harness/generation.d.ts.map +1 -1
  33. package/dist/harness/generation.js +25 -4
  34. package/dist/harness/generation.js.map +1 -1
  35. package/dist/harness/inbox.d.ts +16 -4
  36. package/dist/harness/inbox.d.ts.map +1 -1
  37. package/dist/harness/inbox.js +26 -3
  38. package/dist/harness/inbox.js.map +1 -1
  39. package/dist/harness/live.d.ts +15 -1
  40. package/dist/harness/live.d.ts.map +1 -1
  41. package/dist/harness/live.js +10 -2
  42. package/dist/harness/live.js.map +1 -1
  43. package/dist/harness/scheduler.d.ts.map +1 -1
  44. package/dist/harness/scheduler.js +72 -10
  45. package/dist/harness/scheduler.js.map +1 -1
  46. package/dist/harness/submissions.d.ts +7 -4
  47. package/dist/harness/submissions.d.ts.map +1 -1
  48. package/dist/harness/submissions.js +29 -10
  49. package/dist/harness/submissions.js.map +1 -1
  50. package/dist/harness/tool.d.ts.map +1 -1
  51. package/dist/harness/tool.js +13 -1
  52. package/dist/harness/tool.js.map +1 -1
  53. package/dist/harness/types.d.ts +38 -11
  54. package/dist/harness/types.d.ts.map +1 -1
  55. package/dist/harness/types.js.map +1 -1
  56. package/dist/index.d.ts +2 -2
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/tool-search/index.d.ts +2 -0
  60. package/dist/tool-search/index.d.ts.map +1 -0
  61. package/dist/tool-search/index.js +2 -0
  62. package/dist/tool-search/index.js.map +1 -0
  63. package/dist/tool-search/tool-search.d.ts +18 -0
  64. package/dist/tool-search/tool-search.d.ts.map +1 -0
  65. package/dist/tool-search/tool-search.js +62 -0
  66. package/dist/tool-search/tool-search.js.map +1 -0
  67. package/package.json +16 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codemode.js","sourceRoot":"","sources":["../../src/codemode/codemode.ts"],"names":[],"mappings":"AAqCA,OAAO,EAAgB,QAAQ,EAAkB,MAAM,aAAa,CAAC;AACrE,OAAO,EAMN,oBAAoB,GACpB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACrF,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EAAE,YAAY,EA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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 `@ny4n/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 * - `nyan.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 * - `nyan.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 { TextContent } from \"@ny4n/ai/contracts\";\nimport { type Context, copyJson, type JsonValue } from \"@ny4n/chord\";\nimport {\n\ttype CodemodeHostCall,\n\ttype CodemodeOutcome,\n\ttype CodemodeResult,\n\ttype CodemodeRun,\n\ttype CodemodeSandboxBase,\n\ttoCodemodeIdentifier,\n} from \"@ny4n/codemode/portable\";\nimport { Bm25Ranker } from \"@ny4n/codemode/search\";\nimport { CODEMODE_SOURCE_GRAMMAR, parseCodemodeSource } from \"@ny4n/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 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 { 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 = 1;\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\n\n/**\n * One tool as the script sees it: `tools.<jsName>`. `structured`: the tool declares `structuredOutputSchema`, so an\n * error result with a value resolves with it.\n */\ntype DeclaredTool = { name: string; jsName: string; description: string; structured?: 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: \"nyan.codemode.run\",\n\tversion: 1,\n\tscope: \"task\",\n\tinitial: () => ({}),\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: \"nyan.codemode.journal\",\n\tversion: 1,\n\tscope: \"task\",\n\tinitial: () => ({ entries: [] }),\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: \"nyan.codemode.store\",\n\tversion: 1,\n\tscope: \"conversation\",\n\thistory: \"rewindable\",\n\tfork: \"asOf\",\n\tinitial: () => ({ values: {} }),\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 `nyan.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/** @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(),\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; nyan-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)],\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((tool) => tool.deferred !== true),\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/** 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}));\n\t\tconst callable = agent.callable;\n\t\tconst globals = [\n\t\t\t...DISCOVERY_GLOBALS.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 = Date.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 - Date.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,\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\twallMs: Date.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(\"nyan-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 = 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\tthis.queue.push({ id: call.id, at: Date.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 result = await this.api.executeTool(call.name, args, this.context, { key: `c${call.id}` });\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\tthis.rows.set(call.id, { id: call.id, name: call.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 global = discovery ? undefined : this.options.globals?.find((candidate) => candidate.name === call.name);\n\t\tif (!discovery && 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 ? this.discover(call) : 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\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;\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 new Bm25Ranker().rank(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\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"]}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * What the model reads about code mode, copied from the coding agent's code mode: the tool's fixed description (the
3
+ * script environment and its globals), and the `codemode` prompt section, which lists the tools scripts can call as
4
+ * TypeScript declarations, grouped by namespace and limited to a token budget. Tools that do not fit are found with
5
+ * `searchTools()`. The section renders from the conversation's callable tools, so it changes with them; the tool's
6
+ * description never does.
7
+ */
8
+ import type { CodemodeJsonSchema } from "@ny4n/codemode";
9
+ import type { ToolRegistration } from "../harness/types.ts";
10
+ /** A group of tools named by a common prefix, such as an MCP server's `mcp__github__`. */
11
+ export type CodemodeNamespace = {
12
+ readonly name: string;
13
+ readonly description?: string;
14
+ readonly instructions?: string;
15
+ /** Tool names starting with it belong to the namespace; the longest matching prefix wins. */
16
+ readonly prefix: string;
17
+ };
18
+ /** Default token budget of the tool declarations in the `codemode` section, as in the coding agent. */
19
+ export declare const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;
20
+ /** The code mode tool's description: the script environment and its globals, the same for every conversation. */
21
+ export declare function codemodeDescription(): string;
22
+ /** What a script sees of a tool: its declaration. Tools without an output schema resolve to their text output. */
23
+ export declare function declarationOf(tool: ToolRegistration): {
24
+ name: string;
25
+ description: string;
26
+ inputSchema: CodemodeJsonSchema;
27
+ outputSchema: CodemodeJsonSchema;
28
+ };
29
+ /** `toolSample` of a tool: its description and TypeScript declaration. */
30
+ export declare function sampleOf(tool: ToolRegistration): string;
31
+ /** The namespace of a tool: the one with the longest prefix its name starts with. */
32
+ export declare function namespaceOf(name: string, namespaces: readonly CodemodeNamespace[]): CodemodeNamespace | undefined;
33
+ /**
34
+ * The `codemode` section: the tools scripts can call, grouped by namespace, with their declarations as far as the
35
+ * budget allows. `undefined` without callable tools.
36
+ */
37
+ export declare function codemodeSection(tools: readonly ToolRegistration[], namespaces: readonly CodemodeNamespace[], budget: number): string | undefined;
38
+ //# sourceMappingURL=describ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ample, toCodemodeIdentifier } from "@ny4n/codemode/declarations";
2
+ /** Default token budget of the tool declarations in the `codemode` section, as in the coding agent. */
3
+ export const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;
4
+ /** Characters per token when estimating the cost of a tool section. */
5
+ const CHARS_PER_TOKEN = 4;
6
+ const TEXT_OUTPUT_SCHEMA = { type: "string" };
7
+ const DESCRIPTION_INTRO = `Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level \`await\` and \`return\` work. No Node, file system, network, or timers.
8
+ - \`await tools.<name>({ ...args })\` resolves to a string, or an object if the tool's declaration says so, and rejects with an Error on failure. A tool whose declaration returns an object resolves on failure too when it returned that object; check its fields. Calls still running when the script ends are cancelled.
9
+ - The script survives a restart: it resumes where it was, without running finished calls again.
10
+ - Optional first line: \`// @options: {"max_output_tokens": 10000, "timeout_ms": 60000}\``;
11
+ /** The code mode tool's description: the script environment and its globals, the same for every conversation. */
12
+ export function codemodeDescription() {
13
+ const globals = [
14
+ "Globals:",
15
+ "- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the other output in one `<console_output>` block. `image()` also saves the image to a temp file and the result names its path.",
16
+ "- `store(key, value)` and `load(key)` keep JSON values across codemode calls.",
17
+ "- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await describeNamespace(name)`: find tools the `codemode` section does not list.",
18
+ ];
19
+ return [
20
+ DESCRIPTION_INTRO,
21
+ globals.join("\n"),
22
+ "The `codemode` section of the system prompt lists the tools scripts can call, by namespace, as far as space allows.",
23
+ ].join("\n\n");
24
+ }
25
+ /** What a script sees of a tool: its declaration. Tools without an output schema resolve to their text output. */
26
+ export function declarationOf(tool) {
27
+ return {
28
+ name: tool.name,
29
+ description: tool.description,
30
+ inputSchema: tool.parameters,
31
+ outputSchema: tool.structuredOutputSchema ?? TEXT_OUTPUT_SCHEMA,
32
+ };
33
+ }
34
+ /** `toolSample` of a tool: its description and TypeScript declaration. */
35
+ export function sampleOf(tool) {
36
+ return renderToolSample(declarationOf(tool));
37
+ }
38
+ /** The namespace of a tool: the one with the longest prefix its name starts with. */
39
+ export function namespaceOf(name, namespaces) {
40
+ let found;
41
+ for (const namespace of namespaces) {
42
+ if (name.startsWith(namespace.prefix) && (found === undefined || namespace.prefix.length > found.prefix.length)) {
43
+ found = namespace;
44
+ }
45
+ }
46
+ return found;
47
+ }
48
+ /** `### \`id\` (\`raw name\`)` followed by the tool's description and declaration. */
49
+ function renderToolSection(tool) {
50
+ const id = toCodemodeIdentifier(tool.name);
51
+ const heading = id === tool.name ? `### \`${id}\`` : `### \`${id}\` (\`${tool.name}\`)`;
52
+ return `${heading}\n${sampleOf(tool).trim()}`;
53
+ }
54
+ /**
55
+ * Pick the tool sections that fit the budget: in each round every group (tools without a namespace first, then
56
+ * namespaces by name) places its cheapest remaining tool; a group whose next tool does not fit drops out while the
57
+ * others continue. Every namespace is represented before any namespace is complete.
58
+ */
59
+ function selectCatalog(groups, budget) {
60
+ const queues = groups.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost));
61
+ const shown = new Set();
62
+ let remaining = budget;
63
+ let active = queues.filter((queue) => queue.length > 0);
64
+ while (active.length > 0) {
65
+ active = active.filter((queue) => {
66
+ const next = queue[0];
67
+ if (next.cost > remaining)
68
+ return false;
69
+ remaining -= next.cost;
70
+ shown.add(next.name);
71
+ queue.shift();
72
+ return queue.length > 0;
73
+ });
74
+ }
75
+ return shown;
76
+ }
77
+ /**
78
+ * The `codemode` section: the tools scripts can call, grouped by namespace, with their declarations as far as the
79
+ * budget allows. `undefined` without callable tools.
80
+ */
81
+ export function codemodeSection(tools, namespaces, budget) {
82
+ if (tools.length === 0)
83
+ return undefined;
84
+ const groups = new Map([["", { namespace: undefined, entries: [] }]]);
85
+ for (const tool of tools) {
86
+ const namespace = namespaceOf(tool.name, namespaces);
87
+ const key = namespace ? `ns:${namespace.name}` : "";
88
+ const group = groups.get(key) ?? { namespace, entries: [] };
89
+ groups.set(key, group);
90
+ const section = renderToolSection(tool);
91
+ group.entries.push({ name: tool.name, section, cost: Math.ceil(section.length / CHARS_PER_TOKEN) });
92
+ }
93
+ const ordered = [...groups.values()].sort((a, b) => a.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name));
94
+ const shown = selectCatalog(ordered, budget);
95
+ const toolSections = ["Tools scripts can call (`await tools.<name>(args)`):"];
96
+ for (const { namespace, entries } of ordered) {
97
+ if (entries.length === 0)
98
+ continue;
99
+ const visible = entries.filter((entry) => shown.has(entry.name));
100
+ if (namespace) {
101
+ const listing = visible.length === entries.length
102
+ ? ""
103
+ : visible.length === 0
104
+ ? " (tools not listed)"
105
+ : " (some tools not listed)";
106
+ const description = namespace.description?.trim();
107
+ toolSections.push(`## ${namespace.name}${listing}${description ? `\n${description}` : ""}`);
108
+ }
109
+ else if (visible.length < entries.length) {
110
+ toolSections.push("Some tools are not listed: find them with `searchTools()`.");
111
+ }
112
+ for (const entry of visible)
113
+ toolSections.push(entry.section);
114
+ }
115
+ return toolSections.join("\n\n");
116
+ }
117
+ //# sourceMappingURL=describe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"describe.js","sourceRoot":"","sources":["../../src/codemode/describe.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AAYrF,uGAAuG;AACvG,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,CAAC;AACnD,uEAAuE;AACvE,MAAM,eAAe,GAAG,CAAC,CAAC;AAE1B,MAAM,kBAAkB,GAAuB,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;AAElE,MAAM,iBAAiB,GAAG;;;0FAGgE,CAAC;AAE3F,iHAAiH;AACjH,MAAM,UAAU,mBAAmB;IAClC,MAAM,OAAO,GAAG;QACf,UA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,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAE7C,MAAM,YAAY,GAAG,CAAC,sDAAsD,CAAC,CAAC;IAC9E,KAAK,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,OAAO,EAAE,CAAC;QAC9C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QACnC,MAAM,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;QACjE,IAAI,SAAS,EAAE,CAAC;YACf,MAAM,OAAO,GACZ,OAAO,CAAC,MAAM,KAAK,OAAO,CAAC,MAAM;gBAChC,CAAC,CAAC,EAAE;gBACJ,CAAC,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC;oBACrB,CAAC,CAAC,qBAAqB;oBACvB,CAAC,CAAC,0BAA0B,CAAC;YAChC,MAAM,WAAW,GAAG,SAAS,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC;YAClD,YAAY,CAAC,IAAI,CAAC,MAAM,SAAS,CAAC,IAAI,GAAG,OAAO,GAAG,WAAW,CAAC,CAAC,CAAC,KAAK,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QAC7F,CAAC;aAAM,IAAI,OAAO,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;YAC5C,YAAY,CAAC,IAAI,CAAC,4DAA4D,CAAC,CAAC;QACjF,CAAC;QACD,KAAK,MAAM,KAAK,IAAI,OAAO;YAAE,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAClC,CAAC","sourcesContent":["/**\n * What the model reads about code mode, copied from the coding agent's code mode: the tool's fixed description (the\n * script environment and its globals), and the `codemode` prompt section, which lists the tools scripts can call as\n * TypeScript declarations, grouped by namespace and limited to a token budget. Tools that do not fit are found with\n * `searchTools()`. The section renders from the conversation's callable tools, so it changes with them; the tool's\n * description never does.\n */\nimport type { CodemodeJsonSchema } from \"@ny4n/codemode\";\nimport { renderToolSample, toCodemodeIdentifier } from \"@ny4n/codemode/declarations\";\nimport type { ToolRegistration } from \"../harness/types.ts\";\n\n/** A group of tools named by a common prefix, such as an MCP server's `mcp__github__`. */\nexport type CodemodeNamespace = {\n\treadonly name: string;\n\treadonly description?: string;\n\treadonly instructions?: string;\n\t/** Tool names starting with it belong to the namespace; the longest matching prefix wins. */\n\treadonly prefix: string;\n};\n\n/** Default token budget of the tool declarations in the `codemode` section, as in the coding agent. */\nexport const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;\n/** Characters per token when estimating the cost of a tool section. */\nconst CHARS_PER_TOKEN = 4;\n\nconst TEXT_OUTPUT_SCHEMA: CodemodeJsonSchema = { type: \"string\" };\n\nconst DESCRIPTION_INTRO = `Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level \\`await\\` and \\`return\\` work. No Node, file system, network, or timers.\n- \\`await tools.<name>({ ...args })\\` resolves to a string, or an object if the tool's declaration says so, and rejects with an Error on failure. A tool whose declaration returns an object resolves on failure too when it returned that object; check its fields. Calls still running when the script ends are cancelled.\n- The script survives a restart: it resumes where it was, without running finished calls again.\n- Optional first line: \\`// @options: {\"max_output_tokens\": 10000, \"timeout_ms\": 60000}\\``;\n\n/** The code mode tool's description: the script environment and its globals, the same for every conversation. */\nexport function codemodeDescription(): string {\n\tconst globals = [\n\t\t\"Globals:\",\n\t\t\"- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the other output in one `<console_output>` block. `image()` also saves the image to a temp file and the result names its path.\",\n\t\t\"- `store(key, value)` and `load(key)` keep JSON values across codemode calls.\",\n\t\t\"- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await describeNamespace(name)`: find tools the `codemode` section does not list.\",\n\t];\n\treturn [\n\t\tDESCRIPTION_INTRO,\n\t\tglobals.join(\"\\n\"),\n\t\t\"The `codemode` section of the system prompt lists the tools scripts can call, by namespace, as far as space allows.\",\n\t].join(\"\\n\\n\");\n}\n\n/** What a script sees of a tool: its declaration. Tools without an output schema resolve to their text output. */\nexport function declarationOf(tool: ToolRegistration): {\n\tname: string;\n\tdescription: string;\n\tinputSchema: CodemodeJsonSchema;\n\toutputSchema: CodemodeJsonSchema;\n} {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tinputSchema: tool.parameters as CodemodeJsonSchema,\n\t\toutputSchema: (tool.structuredOutputSchema as CodemodeJsonSchema | undefined) ?? TEXT_OUTPUT_SCHEMA,\n\t};\n}\n\n/** `toolSample` of a tool: its description and TypeScript declaration. */\nexport function sampleOf(tool: ToolRegistration): string {\n\treturn renderToolSample(declarationOf(tool));\n}\n\n/** The namespace of a tool: the one with the longest prefix its name starts with. */\nexport function namespaceOf(name: string, namespaces: readonly CodemodeNamespace[]): CodemodeNamespace | undefined {\n\tlet found: CodemodeNamespace | undefined;\n\tfor (const namespace of namespaces) {\n\t\tif (name.startsWith(namespace.prefix) && (found === undefined || namespace.prefix.length > found.prefix.length)) {\n\t\t\tfound = namespace;\n\t\t}\n\t}\n\treturn found;\n}\n\n/** `### \\`id\\` (\\`raw name\\`)` followed by the tool's description and declaration. */\nfunction renderToolSection(tool: ToolRegistration): string {\n\tconst id = toCodemodeIdentifier(tool.name);\n\tconst heading = id === tool.name ? `### \\`${id}\\`` : `### \\`${id}\\` (\\`${tool.name}\\`)`;\n\treturn `${heading}\\n${sampleOf(tool).trim()}`;\n}\n\ntype CatalogEntry = { name: string; section: string; cost: number };\ntype CatalogGroup = { namespace: CodemodeNamespace | undefined; entries: CatalogEntry[] };\n\n/**\n * Pick the tool sections that fit the budget: in each round every group (tools without a namespace first, then\n * namespaces by name) places its cheapest remaining tool; a group whose next tool does not fit drops out while the\n * others continue. Every namespace is represented before any namespace is complete.\n */\nfunction selectCatalog(groups: readonly CatalogGroup[], budget: number): Set<string> {\n\tconst queues = groups.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost));\n\tconst shown = new Set<string>();\n\tlet remaining = budget;\n\tlet active = queues.filter((queue) => queue.length > 0);\n\twhile (active.length > 0) {\n\t\tactive = active.filter((queue) => {\n\t\t\tconst next = queue[0]!;\n\t\t\tif (next.cost > remaining) return false;\n\t\t\tremaining -= next.cost;\n\t\t\tshown.add(next.name);\n\t\t\tqueue.shift();\n\t\t\treturn queue.length > 0;\n\t\t});\n\t}\n\treturn shown;\n}\n\n/**\n * The `codemode` section: the tools scripts can call, grouped by namespace, with their declarations as far as the\n * budget allows. `undefined` without callable tools.\n */\nexport function codemodeSection(\n\ttools: readonly ToolRegistration[],\n\tnamespaces: readonly CodemodeNamespace[],\n\tbudget: number,\n): string | undefined {\n\tif (tools.length === 0) return undefined;\n\tconst groups = new Map<string, CatalogGroup>([[\"\", { namespace: undefined, entries: [] }]]);\n\tfor (const tool of tools) {\n\t\tconst namespace = namespaceOf(tool.name, namespaces);\n\t\tconst key = namespace ? `ns:${namespace.name}` : \"\";\n\t\tconst group = groups.get(key) ?? { namespace, entries: [] };\n\t\tgroups.set(key, group);\n\t\tconst section = renderToolSection(tool);\n\t\tgroup.entries.push({ name: tool.name, section, cost: Math.ceil(section.length / CHARS_PER_TOKEN) });\n\t}\n\tconst ordered = [...groups.values()].sort((a, b) =>\n\t\ta.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name),\n\t);\n\tconst shown = selectCatalog(ordered, budget);\n\n\tconst toolSections = [\"Tools scripts can call (`await tools.<name>(args)`):\"];\n\tfor (const { namespace, entries } of ordered) {\n\t\tif (entries.length === 0) continue;\n\t\tconst visible = entries.filter((entry) => shown.has(entry.name));\n\t\tif (namespace) {\n\t\t\tconst listing =\n\t\t\t\tvisible.length === entries.length\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: visible.length === 0\n\t\t\t\t\t\t? \" (tools not listed)\"\n\t\t\t\t\t\t: \" (some tools not listed)\";\n\t\t\tconst description = namespace.description?.trim();\n\t\t\ttoolSections.push(`## ${namespace.name}${listing}${description ? `\\n${description}` : \"\"}`);\n\t\t} else if (visible.length < entries.length) {\n\t\t\ttoolSections.push(\"Some tools are not listed: find them with `searchTools()`.\");\n\t\t}\n\t\tfor (const entry of visible) toolSections.push(entry.section);\n\t}\n\treturn toolSections.join(\"\\n\\n\");\n}\n"]}
@@ -0,0 +1,3 @@
1
+ export { CODEMODE_MODULE_VERSION, CODEMODE_TOOL_NAME, type CodemodeGlobal, type CodemodeNestedCall, CodemodeStoreDoc, type CodemodeToolDetails, type CodemodeToolInput, type CodemodeToolOptions, createCodemodeExtension, createCodemodeTool, } from "./codemode.ts";
2
+ export { type CodemodeNamespace, DEFAULT_CODEMODE_INLINE_BUDGET } from "./describe.ts";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/codemode/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,uBAAuB,EACvB,kBAAkB,EAClB,KAAK,cAAc,EACnB,KAAK,kBAAkB,EACvB,gBAAgB,EAChB,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EACxB,uBAAuB,EACvB,kBAAkB,GAClB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,KAAK,iBAAiB,EAAE,8BAA8B,EAAE,MAAM,eAAe,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { CODEMODE_MODULE_VERSION, CODEMODE_TOOL_NAME, CodemodeStoreDoc, createCodemodeExtension, createCodemodeTool, } from "./codemode.js";
2
+ export { DEFAULT_CODEMODE_INLINE_BUDGET } from "./describe.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/codemode/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,uBAAuB,EACvB,kBAAkB,EAGlB,gBAAgB,EAIhB,uBAAuB,EACvB,kBAAkB,GAClB,MAAM,eAAe,CAAC;AACvB,OAAO,EAA0B,8BAA8B,EAAE,MAAM,eAAe,CAAC","sourcesContent":["export {\n\tCODEMODE_MODULE_VERSION,\n\tCODEMODE_TOOL_NAME,\n\ttype CodemodeGlobal,\n\ttype CodemodeNestedCall,\n\tCodemodeStoreDoc,\n\ttype CodemodeToolDetails,\n\ttype CodemodeToolInput,\n\ttype CodemodeToolOptions,\n\tcreateCodemodeExtension,\n\tcreateCodemodeTool,\n} from \"./codemode.ts\";\nexport { type CodemodeNamespace, DEFAULT_CODEMODE_INLINE_BUDGET } from \"./describe.ts\";\n"]}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * A script's result as the model reads it, copied from the coding agent's code mode: a "Script completed/failed"
3
+ * header with the wall time, the script's text items (`==> text N/M <==` when there are several), its `console` lines
4
+ * in one `<console_output>` block, the returned value, and on failure the error with the calls already made. Text past
5
+ * the token budget is cut to its start and end, with the complete text in a temp file; images are saved to temp files
6
+ * too, with their path next to them, because a script has no other way to hand their bytes on.
7
+ */
8
+ import type { ImageContent, TextContent } from "@ny4n/ai/contracts";
9
+ import type { CodemodeResult } from "@ny4n/codemode/portable";
10
+ type Item = TextContent | ImageContent;
11
+ /** Writes a file of the result under a fixed name; its path, or why it could not be written. */
12
+ export type OutputFile = (name: string, data: string | Uint8Array) => Promise<{
13
+ path: string;
14
+ } | {
15
+ error: string;
16
+ }>;
17
+ /** The tool's output limits, which the Harness enforces by cutting without a spill file: results stay inside them. */
18
+ type Limits = {
19
+ readonly maxBytes: number;
20
+ readonly maxLines: number;
21
+ };
22
+ /** Default token budget for script output. */
23
+ export declare const DEFAULT_MAX_OUTPUT_TOKENS = 10000;
24
+ /** The tool result's content for a script's result, and the path of the complete text when it was cut. */
25
+ export declare function formatResult(result: CodemodeResult, options: {
26
+ readonly wallMs: number;
27
+ readonly maxOutputTokens: number;
28
+ readonly calls: readonly {
29
+ name: string;
30
+ status: string;
31
+ }[];
32
+ readonly limits: Limits;
33
+ readonly write: OutputFile;
34
+ }): Promise<{
35
+ content: Item[];
36
+ fullOutputPath?: string;
37
+ }>;
38
+ export {};
39
+ //# sourceMappingURL=output.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"output.d.ts","sourceRoot":"","sources":["../../src/codemode/output.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,KAAK,EAAsB,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAElF,KAAK,IAAI,GAAG,WAAW,GAAG,YAAY,CAAC;AAEvC,gGAAgG;AAChG,MAAM,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,KAAK,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAEpH,sHAAsH;AACtH,KAAK,MAAM,GAAG;IAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC;AAIvE,8CAA8C;AAC9C,eAAO,MAAM,yBAAyB,QAAS,CAAC;AAwJhD,0GAA0G;AAC1G,wBAAsB,YAAY,CACjC,MAAM,EAAE,cAAc,EACtB,OAAO,EAAE;IACR,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,KAAK,EAAE,SAAS;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC5D,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;CAC3B,GACC,OAAO,CAAC;IAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAavD"}
@@ -0,0 +1,160 @@
1
+ /** Lines of the result besides the script's text: the header, markers, notes. */
2
+ const LINE_MARGIN = 100;
3
+ /** Default token budget for script output. */
4
+ export const DEFAULT_MAX_OUTPUT_TOKENS = 10_000;
5
+ /** Characters per token when estimating. */
6
+ const CHARS_PER_TOKEN = 4;
7
+ /** File extensions of the image types `image()` accepts. */
8
+ const IMAGE_EXTENSIONS = {
9
+ "image/png": ".png",
10
+ "image/jpeg": ".jpg",
11
+ "image/gif": ".gif",
12
+ "image/webp": ".webp",
13
+ };
14
+ /** Like the script's `text()`: strings as is, other values as compact JSON. */
15
+ function valueText(value) {
16
+ if (typeof value === "string")
17
+ return value;
18
+ return JSON.stringify(value) ?? String(value);
19
+ }
20
+ /**
21
+ * Lay out the script's output so the model can tell items apart: with more than one text item, each starts with a
22
+ * `==> text N/M <==` line; `console` lines follow all other output in one `<console_output>` block.
23
+ */
24
+ function formatItems(output) {
25
+ const total = output.filter((item) => item.type === "text" && !item.console).length;
26
+ const items = [];
27
+ const consoleLines = [];
28
+ let index = 0;
29
+ for (const item of output) {
30
+ if (item.type === "image")
31
+ items.push(item);
32
+ else if (item.console)
33
+ consoleLines.push(item.text);
34
+ else {
35
+ index++;
36
+ items.push({ type: "text", text: total > 1 ? `==> text ${index}/${total} <==\n${item.text}` : item.text });
37
+ }
38
+ }
39
+ if (consoleLines.length > 0) {
40
+ items.push({ type: "text", text: `<console_output>\n${consoleLines.join("\n")}\n</console_output>` });
41
+ }
42
+ return items;
43
+ }
44
+ /**
45
+ * Join adjacent text items into one, each part starting on its own line. The separator check looks at the last
46
+ * non-empty part, not the joined text: reading the end of a growing concatenation makes V8 copy it on every item, which
47
+ * is quadratic.
48
+ */
49
+ function joinAdjacentText(items) {
50
+ const joined = [];
51
+ let parts = [];
52
+ let lastPart = "";
53
+ const flush = () => {
54
+ if (parts.length > 0)
55
+ joined.push({ type: "text", text: parts.join("") });
56
+ parts = [];
57
+ lastPart = "";
58
+ };
59
+ for (const item of items) {
60
+ if (item.type !== "text") {
61
+ flush();
62
+ joined.push(item);
63
+ continue;
64
+ }
65
+ if (lastPart !== "" && !lastPart.endsWith("\n")) {
66
+ parts.push("\n");
67
+ lastPart = "\n";
68
+ }
69
+ parts.push(item.text);
70
+ if (item.text !== "")
71
+ lastPart = item.text;
72
+ }
73
+ flush();
74
+ return joined;
75
+ }
76
+ /**
77
+ * Apply the token budget: when the combined text exceeds it, the text items become one item that keeps the start and
78
+ * end of the text, and images follow it. The complete text is written to a temp file.
79
+ */
80
+ async function truncate(items, maxTokens, limits, write) {
81
+ const texts = items.filter((item) => item.type === "text").map((item) => item.text);
82
+ const combined = texts.join("\n");
83
+ // Within the limits too: a UTF-16 unit is at most 3 UTF-8 bytes, and the rest of the result is a few short lines.
84
+ const budget = Math.min(maxTokens * CHARS_PER_TOKEN, Math.floor(limits.maxBytes / 4));
85
+ const lineBudget = Math.floor((limits.maxLines - LINE_MARGIN) / 2);
86
+ const lines = combined.split("\n").length;
87
+ if (texts.length === 0 || (combined.length <= budget && lines <= 2 * lineBudget))
88
+ return { items: [...items] };
89
+ const headChars = Math.floor(budget / 2);
90
+ const tailChars = budget - headChars;
91
+ const head = combined.slice(0, headChars).split("\n").slice(0, lineBudget).join("\n");
92
+ const tail = tailChars > 0 ? combined.slice(-tailChars).split("\n").slice(-lineBudget).join("\n") : "";
93
+ const removed = combined.length - head.length - tail.length;
94
+ let text = `Warning: truncated output (original token count: ${Math.ceil(combined.length / CHARS_PER_TOKEN)})\nTotal output lines: ${combined.split("\n").length}\n\n${head}…${Math.ceil(removed / CHARS_PER_TOKEN)} tokens truncated…${tail}`;
95
+ const spilled = await write("output.txt", combined);
96
+ text +=
97
+ "path" in spilled
98
+ ? `\n\n[Full output: ${spilled.path} (read with offset/limit)]`
99
+ : `\n\n[Could not save the full output: ${spilled.error}]`;
100
+ return {
101
+ items: [{ type: "text", text }, ...items.filter((item) => item.type === "image")],
102
+ ...("path" in spilled ? { fullOutputPath: spilled.path } : {}),
103
+ };
104
+ }
105
+ /** Save each image to a file and put a text item with its path before it; an image shown twice is saved once. */
106
+ async function saveImages(items, write) {
107
+ const labels = new Map();
108
+ const label = async ({ data, mimeType }, index) => {
109
+ const bytes = Uint8Array.from(atob(data), (char) => char.charCodeAt(0));
110
+ const kind = `${mimeType}, ${bytes.length} bytes`;
111
+ // A failed write must not discard the result of a script whose calls already ran: it becomes part of the label.
112
+ const saved = await write(`image-${index}${IMAGE_EXTENSIONS[mimeType] ?? ".bin"}`, bytes);
113
+ return "path" in saved
114
+ ? `[Image saved to ${saved.path} (${kind})]`
115
+ : `[Image (${kind}) could not be saved: ${saved.error}]`;
116
+ };
117
+ const result = await Promise.all(items.map(async (item) => {
118
+ if (item.type !== "image")
119
+ return [item];
120
+ let pending = labels.get(item.data);
121
+ if (pending === undefined) {
122
+ pending = label(item, labels.size + 1);
123
+ labels.set(item.data, pending);
124
+ }
125
+ return [{ type: "text", text: await pending }, item];
126
+ }));
127
+ return result.flat();
128
+ }
129
+ function formatError(result, calls) {
130
+ const { error } = result;
131
+ const head = error.kind === "script"
132
+ ? (error.stack ?? `${error.name ?? "Error"}: ${error.message}`)
133
+ : error.kind === "timeout"
134
+ ? `Script timed out: ${error.message}`
135
+ : error.kind === "aborted"
136
+ ? `Script aborted: ${error.message}`
137
+ : `Script sandbox failed: ${error.message}`;
138
+ const summary = calls.length === 0
139
+ ? "No tool calls were made."
140
+ : `Tool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(", ")}`;
141
+ return `${head}\n\n${summary}`;
142
+ }
143
+ /** The tool result's content for a script's result, and the path of the complete text when it was cut. */
144
+ export async function formatResult(result, options) {
145
+ const output = [...result.output];
146
+ if (result.ok && result.value !== undefined)
147
+ output.push({ type: "text", text: valueText(result.value) });
148
+ const items = formatItems(output);
149
+ if (!result.ok)
150
+ items.push({ type: "text", text: `Script error:\n${formatError(result, options.calls)}` });
151
+ const truncated = await truncate(joinAdjacentText(items), options.maxOutputTokens, options.limits, options.write);
152
+ // After truncation, which joins the text items and moves images after them, so each path stays next to its image.
153
+ const content = joinAdjacentText(await saveImages(truncated.items, options.write));
154
+ const header = `${result.ok ? "Script completed" : "Script failed"}\nWall time ${(options.wallMs / 1000).toFixed(1)} seconds\nOutput:\n`;
155
+ return {
156
+ content: [{ type: "text", text: header }, ...content],
157
+ ...(truncated.fullOutputPath === undefined ? {} : { fullOutputPath: truncated.fullOutputPath }),
158
+ };
159
+ }
160
+ //# sourceMappingURL=output.js.map