@earendil-works/pi-durable 1.5.0 → 1.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +17 -4
- package/dist/codemode/codemode.d.ts +2 -1
- package/dist/codemode/codemode.d.ts.map +1 -1
- package/dist/codemode/codemode.js +1 -37
- package/dist/codemode/codemode.js.map +1 -1
- package/dist/codemode/models.d.ts +2 -1
- package/dist/codemode/models.d.ts.map +1 -1
- package/dist/codemode/models.js.map +1 -1
- package/dist/documents.d.ts +1 -1
- package/dist/documents.d.ts.map +1 -1
- package/dist/documents.js +1 -1
- package/dist/documents.js.map +1 -1
- package/dist/entries.d.ts +1 -1
- package/dist/entries.d.ts.map +1 -1
- package/dist/entries.js.map +1 -1
- package/dist/env/index.d.ts +1 -1
- package/dist/env/index.d.ts.map +1 -1
- package/dist/env/index.js.map +1 -1
- package/dist/env/node-watch.d.ts +1 -1
- package/dist/env/node-watch.d.ts.map +1 -1
- package/dist/env/node-watch.js.map +1 -1
- package/dist/env/node.d.ts +1 -1
- package/dist/env/node.d.ts.map +1 -1
- package/dist/env/node.js.map +1 -1
- package/dist/harness/agent.d.ts.map +1 -1
- package/dist/harness/agent.js +27 -1
- package/dist/harness/agent.js.map +1 -1
- package/dist/harness/compaction.d.ts +8 -3
- package/dist/harness/compaction.d.ts.map +1 -1
- package/dist/harness/compaction.js +21 -9
- package/dist/harness/compaction.js.map +1 -1
- package/dist/harness/context.d.ts +1 -1
- package/dist/harness/context.d.ts.map +1 -1
- package/dist/harness/context.js.map +1 -1
- package/dist/harness/define.d.ts +1 -1
- package/dist/harness/define.d.ts.map +1 -1
- package/dist/harness/define.js.map +1 -1
- package/dist/harness/generation.d.ts +1 -1
- package/dist/harness/generation.d.ts.map +1 -1
- package/dist/harness/generation.js +6 -4
- package/dist/harness/generation.js.map +1 -1
- package/dist/harness/harness.d.ts +1 -1
- package/dist/harness/harness.d.ts.map +1 -1
- package/dist/harness/harness.js.map +1 -1
- package/dist/harness/inbox.d.ts +2 -1
- package/dist/harness/inbox.d.ts.map +1 -1
- package/dist/harness/inbox.js +1 -1
- package/dist/harness/inbox.js.map +1 -1
- package/dist/harness/json.d.ts +1 -1
- package/dist/harness/json.d.ts.map +1 -1
- package/dist/harness/json.js.map +1 -1
- package/dist/harness/live.d.ts +2 -1
- package/dist/harness/live.d.ts.map +1 -1
- package/dist/harness/live.js.map +1 -1
- package/dist/harness/partial-changes.d.ts +1 -1
- package/dist/harness/partial-changes.d.ts.map +1 -1
- package/dist/harness/partial-changes.js +1 -0
- package/dist/harness/partial-changes.js.map +1 -1
- package/dist/harness/prompt.d.ts +1 -1
- package/dist/harness/prompt.d.ts.map +1 -1
- package/dist/harness/prompt.js.map +1 -1
- package/dist/harness/provider.d.ts +1 -1
- package/dist/harness/provider.d.ts.map +1 -1
- package/dist/harness/provider.js.map +1 -1
- package/dist/harness/registry-reader.d.ts +1 -1
- package/dist/harness/registry-reader.d.ts.map +1 -1
- package/dist/harness/registry-reader.js.map +1 -1
- package/dist/harness/scheduler.d.ts +2 -1
- package/dist/harness/scheduler.d.ts.map +1 -1
- package/dist/harness/scheduler.js +42 -13
- package/dist/harness/scheduler.js.map +1 -1
- package/dist/harness/submissions.d.ts +1 -1
- package/dist/harness/submissions.d.ts.map +1 -1
- package/dist/harness/submissions.js +1 -1
- package/dist/harness/submissions.js.map +1 -1
- package/dist/harness/task-graph.d.ts +3 -1
- package/dist/harness/task-graph.d.ts.map +1 -1
- package/dist/harness/task-graph.js +1 -1
- package/dist/harness/task-graph.js.map +1 -1
- package/dist/harness/tool.d.ts +1 -1
- package/dist/harness/tool.d.ts.map +1 -1
- package/dist/harness/tool.js +1 -1
- package/dist/harness/tool.js.map +1 -1
- package/dist/harness/transcript.d.ts +1 -1
- package/dist/harness/transcript.d.ts.map +1 -1
- package/dist/harness/transcript.js.map +1 -1
- package/dist/harness/types.d.ts +21 -4
- package/dist/harness/types.d.ts.map +1 -1
- package/dist/harness/types.js.map +1 -1
- package/dist/harness/usage.d.ts +2 -1
- package/dist/harness/usage.d.ts.map +1 -1
- package/dist/harness/usage.js +1 -1
- package/dist/harness/usage.js.map +1 -1
- package/dist/harness/util.d.ts +1 -1
- package/dist/harness/util.d.ts.map +1 -1
- package/dist/harness/util.js.map +1 -1
- package/dist/harness/view.d.ts +2 -1
- package/dist/harness/view.d.ts.map +1 -1
- package/dist/harness/view.js +1 -1
- package/dist/harness/view.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/session/cached-storage.d.ts +2 -1
- package/dist/session/cached-storage.d.ts.map +1 -1
- package/dist/session/cached-storage.js.map +1 -1
- package/dist/session/forks.d.ts +1 -1
- package/dist/session/forks.d.ts.map +1 -1
- package/dist/session/forks.js.map +1 -1
- package/dist/session/keys.d.ts +2 -1
- package/dist/session/keys.d.ts.map +1 -1
- package/dist/session/keys.js.map +1 -1
- package/dist/session/session.d.ts +3 -1
- package/dist/session/session.d.ts.map +1 -1
- package/dist/session/session.js +1 -1
- package/dist/session/session.js.map +1 -1
- package/dist/session/transaction.d.ts +4 -3
- package/dist/session/transaction.d.ts.map +1 -1
- package/dist/session/transaction.js +3 -3
- package/dist/session/transaction.js.map +1 -1
- package/dist/session/writer.d.ts +1 -1
- package/dist/session/writer.d.ts.map +1 -1
- package/dist/session/writer.js.map +1 -1
- package/dist/storage/indexeddb.d.ts +2 -1
- package/dist/storage/indexeddb.d.ts.map +1 -1
- package/dist/storage/indexeddb.js.map +1 -1
- package/dist/storage/jsonl/index.d.ts +1 -1
- package/dist/storage/jsonl/index.d.ts.map +1 -1
- package/dist/storage/jsonl/index.js +1 -1
- package/dist/storage/jsonl/index.js.map +1 -1
- package/dist/storage/jsonl/node.d.ts +3 -3
- package/dist/storage/jsonl/node.d.ts.map +1 -1
- package/dist/storage/jsonl/node.js +2 -2
- package/dist/storage/jsonl/node.js.map +1 -1
- package/dist/storage/jsonl/storage.d.ts +32 -3
- package/dist/storage/jsonl/storage.d.ts.map +1 -1
- package/dist/storage/jsonl/storage.js +70 -19
- package/dist/storage/jsonl/storage.js.map +1 -1
- package/dist/storage/memory.d.ts +2 -1
- package/dist/storage/memory.d.ts.map +1 -1
- package/dist/storage/memory.js.map +1 -1
- package/dist/storage/sqlite/commit.d.ts +52 -0
- package/dist/storage/sqlite/commit.d.ts.map +1 -0
- package/dist/storage/sqlite/commit.js +371 -0
- package/dist/storage/sqlite/commit.js.map +1 -0
- package/dist/storage/sqlite/rows.d.ts +33 -0
- package/dist/storage/sqlite/rows.d.ts.map +1 -0
- package/dist/storage/sqlite/rows.js +53 -0
- package/dist/storage/sqlite/rows.js.map +1 -0
- package/dist/storage/sqlite/statements.d.ts +13 -0
- package/dist/storage/sqlite/statements.d.ts.map +1 -0
- package/dist/storage/sqlite/statements.js +88 -0
- package/dist/storage/sqlite/statements.js.map +1 -0
- package/dist/storage/sqlite/storage.d.ts +12 -11
- package/dist/storage/sqlite/storage.d.ts.map +1 -1
- package/dist/storage/sqlite/storage.js +44 -259
- package/dist/storage/sqlite/storage.js.map +1 -1
- package/dist/storage/store/commit.d.ts +2 -2
- package/dist/storage/store/commit.d.ts.map +1 -1
- package/dist/storage/store/commit.js +1 -1
- package/dist/storage/store/commit.js.map +1 -1
- package/dist/storage/store/documents.d.ts +1 -1
- package/dist/storage/store/documents.d.ts.map +1 -1
- package/dist/storage/store/documents.js +1 -1
- package/dist/storage/store/documents.js.map +1 -1
- package/dist/storage/store/queries.d.ts +2 -2
- package/dist/storage/store/queries.d.ts.map +1 -1
- package/dist/storage/store/queries.js.map +1 -1
- package/dist/storage/store/storage.d.ts +3 -2
- package/dist/storage/store/storage.d.ts.map +1 -1
- package/dist/storage/store/storage.js +1 -1
- package/dist/storage/store/storage.js.map +1 -1
- package/dist/storage/store/tables.d.ts +31 -31
- package/dist/storage/store/tables.d.ts.map +1 -1
- package/dist/storage/store/tables.js +1 -1
- package/dist/storage/store/tables.js.map +1 -1
- package/dist/testing/commit-writes.d.ts +1 -1
- package/dist/testing/commit-writes.d.ts.map +1 -1
- package/dist/testing/commit-writes.js.map +1 -1
- package/dist/testing/env-conformance.js.map +1 -1
- package/dist/testing/storage-benchmark.js.map +1 -1
- package/dist/testing/storage-conformance.js.map +1 -1
- package/dist/tool-search/tool-search.d.ts +2 -2
- package/dist/tool-search/tool-search.d.ts.map +1 -1
- package/dist/tool-search/tool-search.js +18 -6
- package/dist/tool-search/tool-search.js.map +1 -1
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.d.ts.map +1 -1
- package/dist/tools/bash.js.map +1 -1
- package/dist/tools/file-mutation-queue.d.ts +1 -1
- package/dist/tools/file-mutation-queue.d.ts.map +1 -1
- package/dist/tools/file-mutation-queue.js.map +1 -1
- package/dist/tools/path-utils.d.ts +1 -1
- package/dist/tools/path-utils.d.ts.map +1 -1
- package/dist/tools/path-utils.js.map +1 -1
- package/dist/tools/read.js.map +1 -1
- package/dist/types.d.ts +6 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [1.5.1] - 2026-11-09
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- `Tx.submission(id)` reads a committed submission record by ID, so a tool can find the entries of its run's inputs (`pi.live.run.inputs`) without scanning the transcript.
|
|
8
|
+
- Per-conversation compaction settings: `configure({ compaction })` stores a `CompactionSettings` (the shape of `HarnessSettings.compaction`, `modelOverrides` included) in `pi.agent`, inherited by children and forks. Each field resolves from the conversation's model override, then the harness's, then the conversation's own fields, then the harness-wide policy; a conversation's `enabled: false` also beats the harness's model overrides, so it turns off threshold, background and overflow compaction before a compaction task is created ([#11771](https://github.com/earendil-works/pi/issues/11771))
|
|
9
|
+
- JSONL storage opens read-only with `{ readOnly: true }` (`JsonlStorage.open()`, `openNodeJsonlStorage()`), for a viewer of a directory another process writes. A writable open repairs files on recovery: it truncates torn lines and unconfirmed sidecar records and reclaims sidecars, which can cut records a running writer just appended. The read-only open creates and writes nothing, skips those records in memory, holds the state committed at open, and `commit()` rejects with `JsonlStorageReadOnlyError`. A recovery that fails because it raced a writer's commit is retried. The README's read-only viewer guidance now says to open JSONL storage this way, since `HarnessOptions.readOnly` does not reach the storage open ([#11939](https://github.com/earendil-works/pi/issues/11939))
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- `SqliteStorage.commit()` costs a few SQL statements per call instead of about eight per batch: it reads the check state of all batches up front, checks them in memory, and writes the accepted batches per table in multi-row statements (rows as one JSON array parameter; rows with much text bound column by column), so a group commit over a remote SQLite takes a few round trips, not hundreds. A stored document record that cannot be parsed now rejects the call as a storage failure instead of refusing the batch.
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- Fixed `tool_search` not finding a deferred tool by property names and descriptions behind a local `$ref` in its parameters, as in MCP input schemas that put their models in `$defs`. Referenced definitions are read once, so recursive schemas do not loop, and definitions nothing references stay out of the search text ([#11803](https://github.com/earendil-works/pi/issues/11803))
|
|
18
|
+
- Fixed a task staying `waiting`, or `completing` with idle waits never resolving, when the last task it waited for or held ended while a scheduler pass was planning, as with a generation waiting on parallel tool calls: the pass's cleanup erased the new notification. A pass now takes its candidates and finalize checks out of the pending sets before it plans, so notifications that arrive meanwhile stay for the next pass ([#11892](https://github.com/earendil-works/pi/issues/11892))
|
|
19
|
+
- Fixed every code mode run failing with `URI malformed` when any callable tool had a `$ref` with a malformed percent escape (`#/$defs/%E0`) in its schema, even scripts that do not call that tool. The parameter now renders as `unknown` in the tool's declaration ([#11803](https://github.com/earendil-works/pi/issues/11803))
|
|
20
|
+
|
|
3
21
|
## [1.5.0] - 2026-11-02
|
|
4
22
|
|
|
5
23
|
### Breaking Changes
|
package/README.md
CHANGED
|
@@ -124,7 +124,7 @@ const root = await harness.root(context); // the same root as last time
|
|
|
124
124
|
harness.resume(); // continue any run the last process left unfinished
|
|
125
125
|
```
|
|
126
126
|
|
|
127
|
-
Work interrupted by a crash or close stays pending. `resume()` starts the task scheduler; submitting or waiting starts it too. A process that only shows a session another one drives opens it with `readOnly: true`: open recovers nothing, and every write, `resume()`, and every call that would run tasks rejects with `ReadOnlySession`. Each conversation has its own persisted UUIDv7 in `pi.provider`, forwarded to pi-ai as `sessionId` for provider prompt-cache and session affinity. It survives reopen, retries, reset, compaction, and model changes; a child or fork receives a fresh identity. A legacy conversation receives and persists one before its first generation or compaction request.
|
|
127
|
+
Work interrupted by a crash or close stays pending. `resume()` starts the task scheduler; submitting or waiting starts it too. A process that only shows a session another one drives opens it with `readOnly: true`: open recovers nothing, and every write, `resume()`, and every call that would run tasks rejects with `ReadOnlySession`. That option covers the Harness, not the storage open before it: open JSONL storage with `openNodeJsonlStorage(directory, context, { readOnly: true })` too, since a writable JSONL open repairs files the writer may be appending to (see [Storage](#storage)). SQLite storage opens as usual: SQLite's file locks keep it safe beside the writer. Each conversation has its own persisted UUIDv7 in `pi.provider`, forwarded to pi-ai as `sessionId` for provider prompt-cache and session affinity. It survives reopen, retries, reset, compaction, and model changes; a child or fork receives a fresh identity. A legacy conversation receives and persists one before its first generation or compaction request.
|
|
128
128
|
|
|
129
129
|
A retried submission with the same `requestId` returns the existing submission instead of submitting twice:
|
|
130
130
|
|
|
@@ -518,7 +518,7 @@ const resumed = await root.watch(context, transcript.resume);
|
|
|
518
518
|
|
|
519
519
|
Entries never change once committed, so a merge only adds; one that adds nothing returns the same `items` array. See `test/examples/31-transcript.ts`.
|
|
520
520
|
|
|
521
|
-
Watches are Chord's `WatchHandle` (exported by `@earendil-works/chord`; Durable re-exports it). The listener gets one `WatchCall` per call, tagged by `kind`, and the newest commit's context: `{ kind: "value", value, ops, retired }`. Chord's watches also have `{ kind: "failed", error }` calls for failures a source recovers from; Durable's failures are final, so a Durable watch never sends one and ends instead. A watch ends once, and `closed` (or `stop()`) gives a `WatchEnd` tagged by `kind`: `stopped`, `aborted` (its acquisition context was aborted), `ended` (the Harness closed, or a task document's task ended), `listener_error`, or `failed` (the Harness failed). An ended watch keeps its last value and no longer references the Harness.
|
|
521
|
+
Watches are Chord's `WatchHandle` (exported by `@earendil-works/chord/watch`; Durable re-exports it). The listener gets one `WatchCall` per call, tagged by `kind`, and the newest commit's context: `{ kind: "value", value, ops, retired }`. Chord's watches also have `{ kind: "failed", error }` calls for failures a source recovers from; Durable's failures are final, so a Durable watch never sends one and ends instead. A watch ends once, and `closed` (or `stop()`) gives a `WatchEnd` tagged by `kind`: `stopped`, `aborted` (its acquisition context was aborted), `ended` (the Harness closed, or a task document's task ended), `listener_error`, or `failed` (the Harness failed). An ended watch keeps its last value and no longer references the Harness.
|
|
522
522
|
|
|
523
523
|
Adapters that must change in the same step as Durable's memory, such as a Chord source over a view, attach a synchronous observer instead of a watch: `harness.observeConversation(id, observer, context)`, `harness.observeTaskGraph(observer, context)`, and `harness.observeDoc(token, ...scope, observer, context)` return the current `value` and `detach()`, and call `observer.advance(call, context)` with every later change as a `WatchCall` (always a `value` call), unfolded, as memory adopts it: inside the storage's commit for a stored commit, at once for a deferred one (before it is stored). A document observer gets one call per change at its address, so a commit that retires and recreates the document gives two; the task graph also advances without a commit when a registry change alters a task's `blocked` reason. A change can arrive before the `observeXXX()` promise resolves; its ops apply from the observation's `value`. `observer.end(end)` comes once with a `WatchEnd`: `ended` when the Harness closes or, for a task document, right after the retirement of the commit that ends its task, `failed` when the Harness fails. `advance` only records the change: no awaits, no Harness calls, no throws, and quick, since every commit waits for it. One that throws (or returns a rejected promise) is reported, detached, and ended `listener_error`. Watches are built on these observers.
|
|
524
524
|
|
|
@@ -637,6 +637,19 @@ settings: {
|
|
|
637
637
|
|
|
638
638
|
The fixed token counts rarely suit a 32k and a 1M context window alike; `modelOverrides` lets one harness serve both. The conversation's current model picks the entry, at the threshold check, after a context overflow, and when a compaction selects what to summarize.
|
|
639
639
|
|
|
640
|
+
One conversation can have its own compaction settings, of the same shape, stored in its agent like `maxTurns`:
|
|
641
|
+
|
|
642
|
+
```typescript
|
|
643
|
+
await root.configure({ compaction: { enabled: false } }, context); // no automatic compaction here, on any model
|
|
644
|
+
await research.configure(
|
|
645
|
+
{ compaction: { keepRecentTokens: 60000, modelOverrides: { "local/small-32k": { keepRecentTokens: 12000 } } } },
|
|
646
|
+
context,
|
|
647
|
+
);
|
|
648
|
+
await root.configure({ compaction: null }, context); // back to the settings
|
|
649
|
+
```
|
|
650
|
+
|
|
651
|
+
Each field comes from the first layer that sets it: the conversation's `modelOverrides` entry, the settings' `modelOverrides` entry, the conversation's own fields, then the settings. So a model-specific value beats a general one, and the conversation beats the harness at the same level: above, `research` keeps 60000 tokens on a model without an override anywhere and 12000 on `local/small-32k`; without its own entry it would get the settings' 8000 there. The exception is `enabled: false` on the conversation, which also beats the settings' model overrides. A change replaces the stored settings as a whole; `configure()` throws a `RangeError` for a token count that is not an integer 0 or more. Children and forks inherit it like the rest of the agent.
|
|
652
|
+
|
|
640
653
|
When a provider rejects a request because the context is too long, generation compacts and retries once. A summary that would cut before the start of the current context settles as `stale` when it is placed, so when several are in flight, the furthest cut stays in effect. Summarization spend counts in `pi.usage`. A `beforeCompact` hook on `CompactionTask` can decline or supply its own summary.
|
|
641
654
|
|
|
642
655
|
When a compaction that a generation waits for at the blocking threshold fails, the generation fails too, without sending a request: its inputs settle `unanswered` with `model_error` and detail `Compaction failed: <error>`. One that finds nothing to compact or is declined lets the request go ahead.
|
|
@@ -854,7 +867,7 @@ const usage = await harness.usage(context); // { models: { "openai/gpt-6-sol": U
|
|
|
854
867
|
| Memory | `MemoryStorage` from the package root | Nothing is persisted. |
|
|
855
868
|
| IndexedDB | `IndexedDbStorage.open(name)` from `@earendil-works/pi-durable/storage/indexeddb` | Browser-only storage in one IndexedDB database. |
|
|
856
869
|
| SQLite | `openNodeSqliteStorage(file)` from `@earendil-works/pi-durable/storage/sqlite/node` | One database file. WAL mode with `synchronous = NORMAL`: commits survive process crashes; the newest may be lost on power or host failure. |
|
|
857
|
-
| JSONL | `openNodeJsonlStorage(directory, context)` from `@earendil-works/pi-durable/storage/jsonl/node` | Append-only files in one directory. Pass `{ fsync: true }` to flush before each commit marker. Keeps the whole history in memory too, so memory grows with it; use SQLite for long-running agents. |
|
|
870
|
+
| JSONL | `openNodeJsonlStorage(directory, context)` from `@earendil-works/pi-durable/storage/jsonl/node` | Append-only files in one directory. Pass `{ fsync: true }` to flush before each commit marker, `{ readOnly: true }` to view a directory another process writes. Keeps the whole history in memory too, so memory grows with it; use SQLite for long-running agents. |
|
|
858
871
|
| Cloudflare Durable Object | `openDurableObjectSqliteStorage(ctx.storage)` from `@earendil-works/pi-durable/storage/sqlite/cloudflare` | The SQLite storage of one SQLite-backed Durable Object; commits are its storage transactions. |
|
|
859
872
|
|
|
860
873
|
In a browser, open IndexedDB storage with `await IndexedDbStorage.open(name)`. One owner must hold the database at a
|
|
@@ -878,7 +891,7 @@ await database.exec("CREATE TABLE IF NOT EXISTS host_notes (text TEXT)");
|
|
|
878
891
|
await database.run("INSERT INTO host_notes (text) VALUES (?)", text);
|
|
879
892
|
```
|
|
880
893
|
|
|
881
|
-
One process
|
|
894
|
+
One process writes a storage at a time; there is no cross-process locking. Opening JSONL storage writes too: it truncates torn lines and unconfirmed sidecar records, and removes sidecar records later commits made unnecessary. A viewer of a directory another process writes therefore opens it with `{ readOnly: true }`: that open writes nothing, skips the same records in memory, holds the state committed at open, and its `commit()` rejects with `JsonlStorageReadOnlyError`. A read-only open that races a commit is retried. The portable SQLite and JSONL cores (`/storage/sqlite`, `/storage/jsonl`) run without Node APIs, for example on Bun or in Cloudflare Durable Objects, given an asynchronous `SqliteDatabase` facade or a `FileSystem` from `@earendil-works/pi-durable/env`.
|
|
882
895
|
|
|
883
896
|
SQLite adapters implement promise-based `exec`, `run`, `get`, `all`, `transaction`, and `close`. `run`, `get`, and `all` take SQL text plus positional bindings; adapters may cache prepared statements by SQL text. A transaction callback receives a transaction handle; all work in the transaction must use it, and the handle expires when the callback settles. Adapters must queue unrelated operations and other transactions until the transaction finishes, so calling `database` itself inside the callback never settles:
|
|
884
897
|
|
|
@@ -34,7 +34,8 @@
|
|
|
34
34
|
* or when the script diverges: it makes another call, or calls in another order, than the journal says. Each ends the
|
|
35
35
|
* call with an error result.
|
|
36
36
|
*/
|
|
37
|
-
import {
|
|
37
|
+
import type { Context } from "@earendil-works/chord/context";
|
|
38
|
+
import { type JsonValue } from "@earendil-works/chord/json";
|
|
38
39
|
import type { CodemodeSandboxBase } from "@earendil-works/pi-codemode/portable";
|
|
39
40
|
import { type Static } from "@earendil-works/pi-schema";
|
|
40
41
|
import type { Extension, ToolExecutionApi, ToolRegistration } from "../harness/types.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codemode.d.ts","sourceRoot":"","sources":["../../src/codemode/codemode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"codemode.d.ts","sourceRoot":"","sources":["../../src/codemode/codemode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAE7D,OAAO,EAAY,KAAK,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAGtE,OAAO,KAAK,EAKX,mBAAmB,EACnB,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EAAO,KAAK,MAAM,EAAO,MAAM,2BAA2B,CAAC;AAMlE,OAAO,KAAK,EACX,SAAS,EAET,gBAAgB,EAEhB,gBAAgB,EAChB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EACN,KAAK,iBAAiB,EAMtB,MAAM,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G,EAAE,gBAAgB,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,CAAC;CAChG,CAAC;AAEF,QAAA,MAAM,cAAc;;EAAgF,CAAC;AAErG,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE9D,MAAM,MAAM,mBAAmB,GAAG;IACjC,0FAA0F;IAC1F,QAAQ,CAAC,OAAO,EAAE,mBAAmB,CAAC;IACtC,uGAAuG;IACvG,QAAQ,CAAC,UAAU,CAAC,EAAE,SAAS,iBAAiB,EAAE,CAAC;IACnD,8FAA8F;IAC9F,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,mGAAmG;IACnG,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B,wDAAwD;IACxD,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,cAAc,EAAE,CAAC;CAC7C,CAAC;AASF,kGAAkG;AAClG,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,mBAAmB,GAAG,gBAAgB,CAAC,OAAO,cAAc,CAAC,CAYxG;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,mBAAmB,GAAG,SAAS,CAiB/E"}
|
|
@@ -1,41 +1,5 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Durable code mode: a tool that runs model-written JavaScript in a QuickJS sandbox, whose script survives a restart.
|
|
3
|
-
*
|
|
4
|
-
* Problem: a script is in-memory VM state. A restart while
|
|
5
|
-
*
|
|
6
|
-
* const results = await Promise.all(paths.map((path) => tools.read({ path })));
|
|
7
|
-
*
|
|
8
|
-
* waits for the last of 200 reads would lose the script and every read it made.
|
|
9
|
-
*
|
|
10
|
-
* Solution: deterministic replay (`CodemodeSandboxBase.start()` in pi-codemode). The VM only runs when the host hands
|
|
11
|
-
* it a result; given the same start data, clock, seed, and results in the same order, it makes the same calls with
|
|
12
|
-
* the same arguments. The tool is replay-safe: after a restart, `execute()` runs again, starts the script again from
|
|
13
|
-
* the stored start data, and hands it the results it got before, in the order it got them, from a journal written
|
|
14
|
-
* before each delivery. Nested tool calls reattach to their tasks by key (`c<VM call id>`), so they never run twice
|
|
15
|
-
* unless their own replay policy reruns them; their results come from `NestedCallDoc`. Then the script continues live.
|
|
16
|
-
*
|
|
17
|
-
* Documents, scoped to the code mode call's task and gone when it settles:
|
|
18
|
-
* - `pi.codemode.run`: the start data, written once before the VM starts, and the outcome, written once when the call
|
|
19
|
-
* decides it (with the store writes, in one transaction), so a rerun after that returns it without a VM.
|
|
20
|
-
* - `pi.codemode.journal`: one entry per delivered result, in delivery order: the VM call ID, the clock value, the
|
|
21
|
-
* calls the VM had issued after processing it (once acknowledged), and a global's outcome, which nothing else stores.
|
|
22
|
-
*
|
|
23
|
-
* Each result's acknowledged call count is recorded with the next journal commit, or at once when the VM has processed
|
|
24
|
-
* everything delivered: a script waiting on a long call is where a restart usually finds it. A sequential script
|
|
25
|
-
* therefore costs one journal commit and one count commit per result, on top of its nested calls' own; that is the
|
|
26
|
-
* price of checking the most common crash point.
|
|
27
|
-
*
|
|
28
|
-
* A call is launched only once the count of calls issued in the drain that made it is committed. So every key an earlier
|
|
29
|
-
* attempt admitted is at most its last recorded count; a replay checks every recorded count, so when it releases its
|
|
30
|
-
* calls it has made every call an earlier attempt could have admitted, and later calls are new.
|
|
31
|
-
*
|
|
32
|
-
* A rerun refuses to replay (no new nested calls; nested calls admitted earlier may still resume on their own and are
|
|
33
|
-
* aborted by the call's cleanup) when this module's version or the VM's fingerprint changed, when the deadline passed,
|
|
34
|
-
* or when the script diverges: it makes another call, or calls in another order, than the journal says. Each ends the
|
|
35
|
-
* call with an error result.
|
|
36
|
-
*/
|
|
37
|
-
import { copyJson } from "@earendil-works/chord";
|
|
38
1
|
import { ownedSlice } from "@earendil-works/chord/delta";
|
|
2
|
+
import { copyJson } from "@earendil-works/chord/json";
|
|
39
3
|
import { toCodemodeIdentifier } from "@earendil-works/pi-codemode/declarations";
|
|
40
4
|
import { CODEMODE_SOURCE_GRAMMAR, parseCodemodeSource } from "@earendil-works/pi-codemode/source";
|
|
41
5
|
import { obj, str } from "@earendil-works/pi-schema";
|
|
@@ -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;AAC/E,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAEzD,OAAO,EAAE,oBAAoB,EAAE,MAAM,0CAA0C,CAAC;AAQhF,OAAO,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAClG,OAAO,EAAE,GAAG,EAAe,GAAG,EAAE,MAAM,2BAA2B,CAAC;AAClE,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;AACvB,OAAO,EACN,eAAe,EACf,wBAAwB,EACxB,WAAW,EACX,gBAAgB,EAChB,oBAAoB,EACpB,0BAA0B,EAC1B,WAAW,GACX,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,yBAAyB,EAAE,YAAY,EAAmB,MAAM,aAAa,CAAC;AAEvF;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AAEzC,MAAM,CAAC,M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,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 { 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
|
+
{"version":3,"file":"codemode.js","sourceRoot":"","sources":["../../src/codemode/codemode.ts"],"names":[],"mappings":"AAqCA,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,EAAE,QAAQ,EAAkB,MAAM,4BAA4B,CAAC;AAEtE,OAAO,EAA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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 } from \"@earendil-works/chord/context\";\nimport { ownedSlice } from \"@earendil-works/chord/delta\";\nimport { copyJson, type JsonValue } from \"@earendil-works/chord/json\";\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"]}
|
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
* tool listings): a nested durable call with its own task, live row, abort, usage accounting, and replay policy. The
|
|
8
8
|
* code mode tool turns a script's call of the global into a call of that tool.
|
|
9
9
|
*/
|
|
10
|
-
import type { Context
|
|
10
|
+
import type { Context } from "@earendil-works/chord/context";
|
|
11
|
+
import type { JsonValue } from "@earendil-works/chord/json";
|
|
11
12
|
import type { Models } from "@earendil-works/pi-ai";
|
|
12
13
|
import type { ToolRegistration } from "../harness/types.ts";
|
|
13
14
|
/** Reserved names of code mode's internal tools; they are never listed to scripts or the model. */
|