@knpkv/relay 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE-THIRD-PARTY.md +29 -0
- package/README.md +90 -2
- package/dist/backends.d.ts +26 -0
- package/dist/backends.d.ts.map +1 -0
- package/dist/harness.d.ts +128 -0
- package/dist/harness.d.ts.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +12099 -0
- package/dist/index.js.map +7 -0
- package/dist/model.d.ts +188 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/registry.d.ts +47 -0
- package/dist/registry.d.ts.map +1 -0
- package/dist/turn.d.ts +68 -0
- package/dist/turn.d.ts.map +1 -0
- package/package.json +69 -3
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/backends.ts", "../../../node_modules/.pnpm/@earendil-works+chord@1.0.4/node_modules/@earendil-works/chord/src/context/index.ts", "../../../node_modules/.pnpm/@earendil-works+chord@1.0.4/node_modules/@earendil-works/chord/src/json.ts", "../../../node_modules/.pnpm/@earendil-works+chord@1.0.4/node_modules/@earendil-works/chord/src/delta/apply-immutable-trusted.ts", "../../../node_modules/.pnpm/@earendil-works+chord@1.0.4/node_modules/@earendil-works/chord/src/delta/tracker.ts", "../../../node_modules/.pnpm/@earendil-works+chord@1.0.4/node_modules/@earendil-works/chord/src/delta/index.ts", "../../../node_modules/.pnpm/@earendil-works+chord@1.0.4/node_modules/@earendil-works/chord/src/services/state-internals.ts", "../../../node_modules/.pnpm/@earendil-works+chord@1.0.4/node_modules/@earendil-works/chord/src/services/state.ts", "../../../node_modules/.pnpm/@earendil-works+chord@1.0.4/node_modules/@earendil-works/chord/src/api.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/ids.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/documents.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/entries.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/errors.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/agent.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/utils/text.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/utils/estimate.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/utils/retry.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/tasks.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/context.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/utils/overflow.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/utils/transcript.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/inbox.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/json.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/prompt.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/utils/uuid.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/provider.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/utils/validation.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/truncate.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/output.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/usage.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/tool.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/generation.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/live.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/util.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/submissions.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/compaction.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/define.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/session/observation.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/view.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/events.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/types.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/session/forks.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/session/transaction.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/session/session.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/registry.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/scheduler.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/task-graph.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/harness/harness.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/storage/sqlite/migrations.ts", "../../../node_modules/.pnpm/@earendil-works+pi-durable@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+sig_b474b6d1ab9f01c266a856b4658ce3c3/node_modules/@earendil-works/pi-durable/src/storage/sqlite/storage.ts", "../src/harness.ts", "../src/libsqlDatabase.ts", "../src/model.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/index.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/utils/event-stream.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/api/lazy.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/auth/context.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/utils/abort.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/auth/credential-store.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/utils/diagnostics.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/utils/models-error.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/auth/resolve.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/models-store.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/utils/model-operations.ts", "../../../node_modules/.pnpm/@earendil-works+pi-ai@1.0.4_@aws-sdk+credential-provider-node@3.972.84_@smithy+signatur_ac5ad4d70d70722967598787c63e0434/node_modules/@earendil-works/pi-ai/src/models.ts", "../src/piProvider.ts", "../src/piTools.ts", "../src/turn.ts", "../src/registry.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * The two backends Relay supports, each a model turn through the user's own CLI login: Claude Code\n * (Claude Pro/Max or whatever the CLI is signed in with) and Codex (ChatGPT login). Relay never holds a\n * provider credential; the CLI does.\n *\n * Both run with every CLI tool withheld (`prompt-only` / `promptOnly`): the harness runs Relay's tools\n * behind its gate, so the CLI is only ever asked for one structured answer.\n *\n * Each backend's `probe` runs `<cli> --version` with only `PATH`, so the dock can say \"installed, not yet\n * verified\" without spending a model call.\n *\n * @module\n */\nimport * as ClaudeCli from \"@knpkv/ai-claude\"\nimport * as CodexCli from \"@knpkv/ai-codex\"\nimport { readLocalCliRuntimeMetadata } from \"@knpkv/ai-runtime\"\nimport { Effect, FileSystem, Layer } from \"effect\"\nimport { ChildProcessSpawner } from \"effect/process\"\nimport { RelayBackendUnavailable } from \"./harness.js\"\nimport type { RelayBackend } from \"./harness.js\"\n\nexport interface CliBackendOptions {\n /** Working directory the CLI starts in. It reads no files there: every tool is withheld. */\n readonly cwd: string\n /** Model override; omitted means the CLI's configured default. */\n readonly model?: string | undefined\n}\n\ninterface CliProbe {\n readonly executable: string\n readonly implementation: string\n readonly install: string\n readonly cwd: string\n}\n\nconst notInstalled = (cli: CliProbe) => new RelayBackendUnavailable({ cause: \"NotInstalled\", fix: cli.install })\n\nconst misconfigured = (cli: CliProbe) =>\n new RelayBackendUnavailable({\n cause: \"Misconfigured\",\n fix: `${cli.executable} --version printed no version; reinstall it.`\n })\n\nconst probe = (\n spawner: ChildProcessSpawner.ChildProcessSpawner[\"Service\"],\n cli: CliProbe\n) =>\n readLocalCliRuntimeMetadata({ executable: cli.executable, implementation: cli.implementation, cwd: cli.cwd }).pipe(\n Effect.mapError((failure) => failure.reason === \"unavailable\" ? notInstalled(cli) : misconfigured(cli)),\n // A local CLI always reports its version; only a remote API may not.\n Effect.flatMap((metadata) =>\n metadata.version === null ? Effect.fail(misconfigured(cli)) : Effect.succeed(metadata.version)\n ),\n Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)\n )\n\n/** Claude Code on the user's own login. */\nexport const claudeCodeBackend = Effect.fn(\"Relay.claudeCodeBackend\")(function*(options: CliBackendOptions) {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner\n return {\n id: \"claude-code\",\n name: \"Claude Code\",\n model: ClaudeCli.model({ cwd: options.cwd, access: \"prompt-only\", model: options.model }).pipe(\n Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner))\n ),\n probe: probe(spawner, {\n executable: \"claude\",\n implementation: \"claude\",\n install: \"Install Claude Code: npm install -g @anthropic-ai/claude-code\",\n cwd: options.cwd\n }),\n signInFix: \"Run claude and sign in with /login.\"\n } satisfies RelayBackend\n})\n\n/** Codex on the user's own ChatGPT login. */\nexport const codexCliBackend = Effect.fn(\"Relay.codexCliBackend\")(function*(options: CliBackendOptions) {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner\n const fileSystem = yield* FileSystem.FileSystem\n return {\n id: \"codex-cli\",\n name: \"Codex\",\n model: CodexCli.model({ cwd: options.cwd, access: \"read-only\", promptOnly: true, model: options.model }).pipe(\n Layer.provide(Layer.mergeAll(\n Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),\n Layer.succeed(FileSystem.FileSystem, fileSystem)\n ))\n ),\n probe: probe(spawner, {\n executable: \"codex\",\n implementation: \"codex-cli\",\n install: \"Install Codex: npm install -g @openai/codex\",\n cwd: options.cwd\n }),\n signInFix: \"Run codex login.\"\n } satisfies RelayBackend\n})\n", "import type { Context, ContextKey } from \"../types.ts\";\n\nconst ABORT_SIGNAL_CONTEXT_KEY: ContextKey<AbortSignal | undefined> = Object.freeze({\n\ttoken: Symbol(\"chord.abortSignal\"),\n});\n\nabstract class BaseContext implements Context {\n\tabstract value<T>(key: ContextKey<T>): T | undefined;\n\tabstract toString(): string;\n\n\tget abortSignal(): AbortSignal | undefined {\n\t\treturn this.value(ABORT_SIGNAL_CONTEXT_KEY);\n\t}\n}\n\nclass EmptyContext extends BaseContext {\n\treadonly #name: string;\n\n\tconstructor(name: string) {\n\t\tsuper();\n\t\tthis.#name = name;\n\t}\n\n\tvalue<T>(_key: ContextKey<T>): T | undefined {\n\t\treturn undefined;\n\t}\n\n\ttoString(): string {\n\t\treturn this.#name;\n\t}\n}\n\nclass ContextValue<T> extends BaseContext {\n\treadonly #parent: Context;\n\treadonly #key: ContextKey<T>;\n\treadonly #value: T;\n\n\tconstructor(parent: Context, key: ContextKey<T>, value: T) {\n\t\tsuper();\n\t\tthis.#parent = parent;\n\t\tthis.#key = key;\n\t\tthis.#value = value;\n\t}\n\n\tvalue<Value>(key: ContextKey<Value>): Value | undefined {\n\t\tif (key.token === this.#key.token) return this.#value as unknown as Value;\n\t\treturn this.#parent.value(key);\n\t}\n\n\ttoString(): string {\n\t\treturn `${this.#parent}.WithValue(${this.#key.token.description ?? \"anonymous\"})`;\n\t}\n}\n\nexport const BACKGROUND_CONTEXT: Context = new EmptyContext(\"[Context BACKGROUND_CONTEXT]\");\nexport const TODO_CONTEXT: Context = new EmptyContext(\"[Context TODO_CONTEXT]\");\n\nexport function createContextKey<T>(description: string): ContextKey<T> {\n\treturn Object.freeze({ token: Symbol(description) });\n}\n\n/** Derive a context containing one additional or replaced value. */\nexport function withContextValue<T>(key: ContextKey<T>, value: T, parent: Context): Context {\n\treturn new ContextValue(parent, key, value);\n}\n\n/**\n * Derive a context cancelled by either the parent signal or the supplied signal.\n * The parent context remains unchanged.\n */\nexport function withAbortSignal(signal: AbortSignal, context: Context): Context {\n\tconst parentSignal = context.abortSignal;\n\tconst combined = parentSignal === undefined ? signal : AbortSignal.any([parentSignal, signal]);\n\treturn withContextValue(ABORT_SIGNAL_CONTEXT_KEY, combined, context);\n}\n\n/** Derive a context retaining all values except caller cancellation. Intended for mandatory cleanup only. */\nexport function withoutAbortSignal(context: Context): Context {\n\treturn withContextValue(ABORT_SIGNAL_CONTEXT_KEY, undefined, context);\n}\n\n/** Derive an independently cancellable child context. */\nexport function withCancel(context: Context): {\n\treadonly context: Context;\n\treadonly cancel: (reason?: unknown) => void;\n} {\n\tconst controller = new AbortController();\n\treturn {\n\t\tcontext: withAbortSignal(controller.signal, context),\n\t\tcancel: (reason?: unknown) => controller.abort(reason),\n\t};\n}\n\n/**\n * Observe a promise until it settles or the invocation is cancelled.\n * Cancellation rejects only this waiter; it does not cancel the underlying promise.\n */\nexport function awaitWithContext<T>(promise: Promise<T>, context: Context): Promise<T> {\n\tconst signal = context.abortSignal;\n\tif (signal === undefined) return promise;\n\tif (signal.aborted) return Promise.reject(abortError(signal));\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst onAbort = (): void => reject(abortError(signal));\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid promise.then(\n\t\t\t(value) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction abortError(signal: AbortSignal): Error {\n\tconst reason: unknown = signal.reason;\n\treturn reason instanceof Error ? reason : new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n", "import type { JsonValue } from \"./types.ts\";\n\nconst DATA_DESCRIPTOR: PropertyDescriptor = {\n\tvalue: undefined,\n\twritable: true,\n\tenumerable: true,\n\tconfigurable: true,\n};\n\nexport type CopyJsonOptions = {\n\t/** Omit undefined object properties while preserving strict array semantics. */\n\treadonly omitUndefinedProperties?: boolean;\n};\n\n/** Copy a value into an alias-free strict-JSON tree owned by the caller. */\nexport function copyJson(value: unknown, options?: CopyJsonOptions): JsonValue {\n\treturn copy(value, undefined, options?.omitUndefinedProperties === true);\n}\n\nfunction copy(value: unknown, ancestors: Set<object> | undefined, omitUndefinedProperties: boolean): JsonValue {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") {\n\t\tif (Number.isFinite(value)) return value;\n\t\tthrow new TypeError(\"Value contains a non-finite number and is not strict JSON\");\n\t}\n\tif (typeof value !== \"object\")\n\t\tthrow new TypeError(`Value contains a non-JSON ${typeof value}; expected strict JSON`);\n\tconst active = ancestors ?? new Set<object>();\n\tif (active.has(value)) throw new TypeError(\"Value contains cycles and is not strict JSON\");\n\tactive.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\t// Indices plus `length` only: extra, symbol, and missing keys all change the count.\n\t\t\tif (Object.getPrototypeOf(value) !== Array.prototype || Reflect.ownKeys(value).length !== value.length + 1) {\n\t\t\t\tthrow new TypeError(\"Value must contain strict JSON dense plain arrays\");\n\t\t\t}\n\t\t\tconst result = new Array<JsonValue>(value.length);\n\t\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, index);\n\t\t\t\tif (descriptor === undefined || !descriptor.enumerable || !(\"value\" in descriptor)) {\n\t\t\t\t\tthrow new TypeError(\"Value must contain strict JSON enumerable indexed data properties\");\n\t\t\t\t}\n\t\t\t\tdefineData(result, String(index), copy(descriptor.value, active, omitUndefinedProperties));\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\tif (prototype !== Object.prototype && prototype !== null) {\n\t\t\tthrow new TypeError(\"Value must contain strict JSON plain objects or arrays\");\n\t\t}\n\t\tconst result = Object.create(prototype) as Record<string, JsonValue>;\n\t\tfor (const key of Reflect.ownKeys(value)) {\n\t\t\tif (typeof key === \"symbol\") throw new TypeError(\"Value contains a symbol key and is not strict JSON\");\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n\t\t\tif (!descriptor.enumerable || !(\"value\" in descriptor)) {\n\t\t\t\tthrow new TypeError(\"Value must contain strict JSON enumerable data properties\");\n\t\t\t}\n\t\t\tif (descriptor.value === undefined && omitUndefinedProperties) continue;\n\t\t\tdefineData(result, key, copy(descriptor.value, active, omitUndefinedProperties));\n\t\t}\n\t\treturn result;\n\t} finally {\n\t\tactive.delete(value);\n\t}\n}\n\nfunction defineData(target: object, key: PropertyKey, value: JsonValue): void {\n\tDATA_DESCRIPTOR.value = value;\n\tObject.defineProperty(target, key, DATA_DESCRIPTOR);\n\tDATA_DESCRIPTOR.value = undefined;\n}\n\n/** Return whether a value is finite strict JSON with plain objects and no cycles. */\nexport function isJsonValue(value: unknown): value is JsonValue {\n\treturn check(value, new Set<object>());\n}\n\nfunction check(value: unknown, ancestors: Set<object>): boolean {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n\tif (typeof value === \"number\") return Number.isFinite(value);\n\tif (Array.isArray(value)) {\n\t\tif (Object.getPrototypeOf(value) !== Array.prototype) return false;\n\t\tconst keys = Reflect.ownKeys(value);\n\t\tif (keys.length !== value.length + 1 || keys.some((key) => typeof key !== \"string\")) return false;\n\t\tif (ancestors.has(value)) return false;\n\t\tancestors.add(value);\n\t\ttry {\n\t\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n\t\t\t\tif (\n\t\t\t\t\tdescriptor === undefined ||\n\t\t\t\t\t!descriptor.enumerable ||\n\t\t\t\t\t!(\"value\" in descriptor) ||\n\t\t\t\t\t!check(descriptor.value, ancestors)\n\t\t\t\t) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} finally {\n\t\t\tancestors.delete(value);\n\t\t}\n\t}\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) return false;\n\tif (Reflect.ownKeys(value).some((key) => typeof key !== \"string\")) return false;\n\tif (ancestors.has(value)) return false;\n\tancestors.add(value);\n\ttry {\n\t\tfor (const descriptor of Object.values(Object.getOwnPropertyDescriptors(value))) {\n\t\t\tif (!descriptor.enumerable || !(\"value\" in descriptor) || !check(descriptor.value, ancestors)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t} finally {\n\t\tancestors.delete(value);\n\t}\n}\n", "import type { JsonValue } from \"../types.ts\";\nimport type { Op, Path, Seg } from \"./index.ts\";\n\ntype JsonContainer = JsonValue[] | Record<string, JsonValue>;\ntype CopiedPath = { root: JsonValue; target: JsonContainer };\n\nconst DATA_DESCRIPTOR: PropertyDescriptor = {\n\tvalue: undefined,\n\twritable: true,\n\tenumerable: true,\n\tconfigurable: true,\n};\n\n/** Apply self-produced trusted operations while copying each touched container once. */\nexport function applyImmutableTrusted<T>(target: T, operations: readonly Op[]): T {\n\tlet root = target as unknown as JsonValue;\n\tconst owned = new WeakSet<object>();\n\tfor (const operation of operations) {\n\t\tif (operation[0] === \"r\") {\n\t\t\troot = operation[1];\n\t\t\tcontinue;\n\t\t}\n\t\tif (operation[0] === \"p\" || operation[0] === \"m\") {\n\t\t\tconst copied = copyPath(root, operation[1], operation[1].length, owned);\n\t\t\troot = copied.root;\n\t\t\tif (!Array.isArray(copied.target)) throw new TypeError(\"Trusted array operation target is not an array\");\n\t\t\tif (operation[0] === \"p\") spliceTrusted(copied.target, operation[2], operation[3], operation[4]);\n\t\t\telse permuteTrusted(copied.target, operation[2]);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst path = operation[1];\n\t\tconst copied = copyPath(root, path, path.length - 1, owned);\n\t\troot = copied.root;\n\t\tconst key = path[path.length - 1]!;\n\t\tswitch (operation[0]) {\n\t\t\tcase \"s\":\n\t\t\t\tdefineData(copied.target, key, operation[2]);\n\t\t\t\tbreak;\n\t\t\tcase \"d\":\n\t\t\t\tif (Array.isArray(copied.target)) {\n\t\t\t\t\tif (typeof key !== \"number\") throw new TypeError(\"Trusted array deletion key is not numeric\");\n\t\t\t\t\tspliceTrusted(copied.target, key, 1, []);\n\t\t\t\t} else Reflect.deleteProperty(copied.target, key);\n\t\t\t\tbreak;\n\t\t\tcase \"a\": {\n\t\t\t\tconst current = read(copied.target, key);\n\t\t\t\tif (typeof current !== \"string\") throw new TypeError(\"Trusted append target is not a string\");\n\t\t\t\tdefineData(copied.target, key, `${current}${operation[2]}`);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"t\": {\n\t\t\t\tconst current = read(copied.target, key);\n\t\t\t\tif (typeof current !== \"string\") throw new TypeError(\"Trusted truncate target is not a string\");\n\t\t\t\tdefineData(copied.target, key, current.slice(operation[2]));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn root as unknown as T;\n}\n\nfunction copyPath(root: JsonValue, path: Path, length: number, owned: WeakSet<object>): CopiedPath {\n\tif (!isContainer(root)) throw new TypeError(\"Trusted operation root is not a container\");\n\tlet copiedRoot = root;\n\tif (!owned.has(root)) {\n\t\tcopiedRoot = shallowCopy(root);\n\t\towned.add(copiedRoot);\n\t}\n\tlet destination = copiedRoot as JsonContainer;\n\tfor (let index = 0; index < length; index++) {\n\t\tconst segment = path[index]!;\n\t\tconst child = read(destination, segment);\n\t\tif (!isContainer(child)) throw new TypeError(\"Trusted operation path is not a container\");\n\t\tif (owned.has(child)) {\n\t\t\tdestination = child;\n\t\t\tcontinue;\n\t\t}\n\t\tconst copy = shallowCopy(child);\n\t\tdefineData(destination, segment, copy);\n\t\towned.add(copy);\n\t\tdestination = copy;\n\t}\n\treturn { root: copiedRoot, target: destination };\n}\n\nfunction shallowCopy(value: JsonContainer): JsonContainer {\n\tif (Array.isArray(value)) return Array.from(value);\n\tconst result = Object.create(Object.getPrototypeOf(value) === null ? null : Object.prototype) as Record<\n\t\tstring,\n\t\tJsonValue\n\t>;\n\tfor (const key of Object.keys(value)) defineData(result, key, value[key]!);\n\treturn result;\n}\n\nfunction read(target: JsonContainer, key: Seg): JsonValue {\n\treturn (target as Record<Seg, JsonValue>)[key]!;\n}\n\nfunction defineData(target: JsonContainer, key: Seg, value: JsonValue): void {\n\tDATA_DESCRIPTOR.value = value;\n\tObject.defineProperty(target, key, DATA_DESCRIPTOR);\n\tDATA_DESCRIPTOR.value = undefined;\n}\n\nfunction spliceTrusted(target: JsonValue[], start: number, remove: number, items: readonly JsonValue[]): void {\n\tconst oldLength = target.length;\n\tconst delta = items.length - remove;\n\tif (delta > 0) {\n\t\ttarget.length = oldLength + delta;\n\t\ttarget.copyWithin(start + items.length, start + remove, oldLength);\n\t} else if (delta < 0) {\n\t\ttarget.copyWithin(start + items.length, start + remove, oldLength);\n\t\ttarget.length = oldLength + delta;\n\t}\n\tfor (let index = 0; index < items.length; index++) defineData(target, start + index, items[index]!);\n}\n\nfunction permuteTrusted(target: JsonValue[], permutation: readonly number[]): void {\n\tif (target.length !== permutation.length) throw new TypeError(\"Trusted permutation length mismatch\");\n\tconst previous = target.slice();\n\tfor (let index = 0; index < permutation.length; index++) target[index] = previous[permutation[index]!]!;\n}\n\nfunction isContainer(value: unknown): value is JsonContainer {\n\treturn value !== null && typeof value === \"object\";\n}\n", "import { copyJson } from \"../json.ts\";\nimport type { JsonValue } from \"../types.ts\";\nimport { applyImmutableTrusted } from \"./apply-immutable-trusted.ts\";\nimport type { Draft } from \"./draft.ts\";\nimport { applyImmutable, type NonEmptyPath, type Op, overlap, type Path, RESERVED_SEGMENTS } from \"./index.ts\";\n\nexport type { Draft, JsonValue, Op };\n\ntype Primitive = null | boolean | number | string;\ntype Container = JsonValue[] | Record<string, JsonValue>;\ntype Stored = JsonValue;\ntype StoredRef = Primitive | { index: number };\ntype Status = \"open\" | \"prepared\" | \"consumed\" | \"aborted\" | \"stale\";\ntype StatusCell = { value: Status };\n\ntype InsertSource = { refs: StoredRef[] };\ntype ParentKind = 0 | 1 | 2; // object, base-array entry, inserted-array entry\n\ntype BasePiece = { kind: \"base\"; start: number; length: number; step: 1 | -1 };\ntype InsertPiece = { kind: \"insert\"; source: InsertSource; start: number; length: number; step: 1 | -1 };\ntype Piece = BasePiece | InsertPiece;\n\ntype PieceNode = {\n\tpiece: Piece;\n\tleft: PieceNode | undefined;\n\tright: PieceNode | undefined;\n\tpriority: number;\n\telements: number;\n};\n\ntype PieceLocation = { piece: Piece; logicalStart: number; minimum: number; maximum: number };\n\ntype DenseRegion = { start: number; length: number };\ntype DenseCandidates = { indices: number[]; bits: Uint8Array | undefined; length: number };\n\ntype ArrayPlan = {\n\tremoveRuns: number[];\n\tpermutation: number[] | undefined;\n\tinsertRuns: number[];\n};\n\ntype ArrayOverlay = {\n\troot: PieceNode | undefined;\n\tpieces: Piece[] | undefined;\n\tbaseOverrides: Map<number, StoredRef> | undefined;\n\tinsertOverrides: Map<InsertSource, Map<number, StoredRef>> | undefined;\n\tstructural: boolean;\n\tgeneration: number;\n\tplan: ArrayPlan | undefined;\n\tseed: number;\n\tlocatedOffset: number;\n\tbaseLocations: PieceLocation[] | undefined;\n\tinsertLocations: Map<InsertSource, PieceLocation[]> | undefined;\n};\n\ntype OverlayNode = {\n\tcontext: OverlayContext;\n\tbaseIndex: number;\n\tparentIndex: number;\n\tparentKind: ParentKind;\n\tparentKey: string | number;\n\tparentSource?: InsertSource;\n\tparentPlacement: boolean;\n\ttarget: object;\n\tproxy: object;\n\twriteKey?: string;\n\twriteValue?: StoredRef;\n\twrites?: Map<string, StoredRef>;\n\tdeleteKey?: string;\n\tdeletes?: Set<string>;\n\treadded?: Set<string>;\n\tarray?: ArrayOverlay;\n\tdirty?: boolean;\n\tsubtreeDirty?: boolean;\n\tpreparedPath?: Path;\n};\n\ntype OverlayContext = {\n\towner: object;\n\ttracker: WeakRef<TrackerImpl<object>>;\n\tbaseRevision: number;\n\tstatus: StatusCell;\n\troot: OverlayNode | undefined;\n\tbases: Container[] | undefined;\n\tstored: Container[] | undefined;\n\tdirty: OverlayNode[];\n\tnodes: OverlayNode[];\n\trawNodes: WeakMap<object, OverlayNode> | undefined;\n\tops: Op[] | undefined;\n\treplacement: boolean;\n\treplacementNoop: boolean;\n\tbaseValue: object | undefined;\n\toverlayReleased: boolean;\n\tsimpleObjectMaterialization: boolean;\n\tregistryRef: WeakRef<OverlayContext> | undefined;\n};\n\nconst NODE = Symbol(\"chord.delta.overlay.node\");\nconst PREPARED = new WeakMap<object, OverlayContext>();\nconst RELEASED: Record<string, JsonValue> = {};\nconst ARRAY_MUTATORS = new Set<PropertyKey>([\n\t\"push\",\n\t\"pop\",\n\t\"shift\",\n\t\"unshift\",\n\t\"splice\",\n\t\"reverse\",\n\t\"sort\",\n\t\"fill\",\n\t\"copyWithin\",\n]);\nconst MAX_DELTA_OPERATIONS = 4_096;\nconst MAX_SIMPLE_OBJECT_NODES = 128;\nconst DATA_DESCRIPTOR: PropertyDescriptor = {\n\tvalue: undefined,\n\twritable: true,\n\tenumerable: true,\n\tconfigurable: true,\n};\n\nexport interface Prepared<T extends object> {\n\treadonly base: T;\n\treadonly value: T;\n\treadonly ops: readonly Op[];\n\treadonly baseRevision: number;\n\tabort(): void;\n}\n\nexport interface Change<T extends object> {\n\treadonly state: Draft<T>;\n\tprepare(): Prepared<T>;\n\tabort(): void;\n}\n\nexport interface Tracker<T extends object> {\n\treadonly value: T;\n\treadonly revision: number;\n\tbeginChange(): Change<T>;\n\tprepareReplace(value: T): Prepared<T>;\n\tadopt(prepared: Prepared<T>): void;\n}\n\nclass PreparedImpl<T extends object> implements Prepared<T> {\n\treadonly #context: OverlayContext;\n\treadonly value: T;\n\treadonly base: T;\n\treadonly ops: readonly Op[];\n\n\tconstructor(context: OverlayContext, value: T, operations: readonly Op[]) {\n\t\tthis.#context = context;\n\t\tthis.value = value;\n\t\tthis.base = context.baseValue as T;\n\t\tthis.ops = operations;\n\t\tPREPARED.set(this, context);\n\t}\n\n\tget baseRevision(): number {\n\t\treturn this.#context.baseRevision;\n\t}\n\n\tabort(): void {\n\t\tabortContext(this.#context);\n\t}\n}\n\nclass ChangeImpl<T extends object> implements Change<T> {\n\t#context: OverlayContext | undefined;\n\t#preparedStatus: StatusCell | undefined;\n\t#settled = false;\n\n\tconstructor(context: OverlayContext) {\n\t\tthis.#context = context;\n\t}\n\n\tget state(): Draft<T> {\n\t\tconst state = this.#context?.root?.proxy;\n\t\tif (state === undefined) throw new TypeError(\"Cannot use a settled overlay\");\n\t\treturn state as Draft<T>;\n\t}\n\n\tprepare(): Prepared<T> {\n\t\tif (this.#settled) throw new Error(\"Change has already been settled\");\n\t\tconst context = this.#context!;\n\t\tassertWritable(context);\n\t\tcontext.status.value = \"prepared\";\n\t\ttry {\n\t\t\tif (!context.replacement) context.ops = context.dirty.length === 0 ? [] : emitOperations(context);\n\t\t\tconst prepared = materializePrepared<T>(context);\n\t\t\tthis.#preparedStatus = context.status;\n\t\t\tthis.#settled = true;\n\t\t\treturn prepared;\n\t\t} catch (error) {\n\t\t\tcontext.status.value = \"aborted\";\n\t\t\tclearContext(context);\n\t\t\tthis.#settled = true;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tthis.#context = undefined;\n\t\t}\n\t}\n\n\tabort(): void {\n\t\tif (this.#settled) {\n\t\t\tif (this.#preparedStatus?.value === \"prepared\") this.#preparedStatus.value = \"aborted\";\n\t\t\tthis.#preparedStatus = undefined;\n\t\t\treturn;\n\t\t}\n\t\tthis.#settled = true;\n\t\tabortContext(this.#context!);\n\t\tthis.#context = undefined;\n\t}\n}\n\nclass TrackerImpl<T extends object> implements Tracker<T> {\n\treadonly #owner = {};\n\treadonly #contexts = new Set<WeakRef<OverlayContext>>();\n\treadonly #selfRef: WeakRef<TrackerImpl<object>>;\n\t#value: T;\n\t#revision = 0;\n\t#pruneBudget = 256;\n\n\tconstructor(initial: T) {\n\t\tthis.#value = initial;\n\t\tthis.#selfRef = new WeakRef(this as unknown as TrackerImpl<object>);\n\t}\n\n\tget value(): T {\n\t\treturn this.#value;\n\t}\n\n\tget revision(): number {\n\t\treturn this.#revision;\n\t}\n\n\tbeginChange(): Change<T> {\n\t\tconst context = createContext(this.#selfRef, this.#owner, this.#revision, this.#value, false, this.#value);\n\t\tthis.#register(context);\n\t\treturn new ChangeImpl(context);\n\t}\n\n\tprepareReplace(value: T): Prepared<T> {\n\t\tconst context = createContext(this.#selfRef, this.#owner, this.#revision, value, true, this.#value);\n\t\tcontext.status.value = \"prepared\";\n\t\tthis.#register(context);\n\t\ttry {\n\t\t\treturn materializePrepared<T>(context);\n\t\t} catch (error) {\n\t\t\tcontext.status.value = \"aborted\";\n\t\t\tclearContext(context);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tadopt(prepared: Prepared<T>): void {\n\t\tconst context = PREPARED.get(prepared as object);\n\t\tif (context?.owner !== this.#owner) throw new Error(\"Prepared change belongs to a different tracker\");\n\t\tif (context.status.value === \"consumed\") throw new Error(\"Prepared change has already been used\");\n\t\tif (context.status.value === \"aborted\") throw new Error(\"Prepared change has been aborted\");\n\t\tif (context.status.value === \"stale\") throw new Error(\"Prepared change is stale\");\n\t\tif (context.status.value !== \"prepared\") throw new Error(\"Prepared change is not ready\");\n\t\tif (context.baseRevision !== this.#revision) {\n\t\t\tcontext.status.value = \"stale\";\n\t\t\tclearContext(context);\n\t\t\tthrow new Error(\"Prepared change is stale\");\n\t\t}\n\n\t\tif (this.#value !== prepared.base) {\n\t\t\tcontext.status.value = \"stale\";\n\t\t\tthrow new Error(\"Prepared change is stale\");\n\t\t}\n\t\t// Materialization happened during prepare. Adoption is an infallible pointer\n\t\t// swap so storage failure can discard the candidate without touching authority.\n\t\tthis.#value = prepared.value;\n\t\tcontext.status.value = \"consumed\";\n\t\tthis.#revision += 1;\n\t\tthis.#invalidate(context);\n\t}\n\n\treleaseContext(context: OverlayContext): void {\n\t\tif (context.registryRef !== undefined) this.#contexts.delete(context.registryRef);\n\t\tcontext.registryRef = undefined;\n\t}\n\n\t#register(context: OverlayContext): void {\n\t\tconst reference = new WeakRef(context);\n\t\tcontext.registryRef = reference;\n\t\tthis.#contexts.add(reference);\n\t\tthis.#pruneBudget -= 1;\n\t\tif (this.#pruneBudget === 0) {\n\t\t\tthis.#prune();\n\t\t\tthis.#pruneBudget = Math.max(256, this.#contexts.size);\n\t\t}\n\t}\n\n\t#prune(): void {\n\t\tfor (const reference of this.#contexts) {\n\t\t\tif (reference.deref() === undefined) this.#contexts.delete(reference);\n\t\t}\n\t}\n\n\t#invalidate(winner: OverlayContext): void {\n\t\tfor (const reference of this.#contexts) {\n\t\t\tconst context = reference.deref();\n\t\t\tif (context === undefined || context === winner) continue;\n\t\t\tif (context.status.value === \"open\" || context.status.value === \"prepared\") context.status.value = \"stale\";\n\t\t\t// Adoption must not walk every node touched by a competing draft. Drop the\n\t\t\t// context's strong overlay references in O(1); externally retained proxies\n\t\t\t// still see the stale status and are reclaimed with their holders.\n\t\t\treleaseOverlayReferences(context);\n\t\t}\n\t\tthis.#contexts.clear();\n\t\tthis.#pruneBudget = 256;\n\t}\n\n\treplacementBase(context: OverlayContext): T | undefined {\n\t\treturn context.baseRevision === this.#revision ? this.#value : undefined;\n\t}\n}\n\n/** Take immutable ownership of an alias-free strict-JSON root in O(1). */\nexport function track<T extends object>(initial: T): Tracker<T> {\n\treturn new TrackerImpl(initial);\n}\n\nfunction materializePrepared<T extends object>(context: OverlayContext): PreparedImpl<T> {\n\tconst operations = ensureOperations(context);\n\tconst base = context.baseValue as T;\n\t// Operation payloads are already detached from the mutable overlay. The\n\t// resulting revision and public batch intentionally share those payloads under\n\t// the trusted immutable-transfer contract.\n\tconst value =\n\t\toperations.length === 0\n\t\t\t? base\n\t\t\t: context.simpleObjectMaterialization\n\t\t\t\t? (cloneNode(context.root!) as T)\n\t\t\t\t: materializeOperations(base, operations);\n\tconst prepared = new PreparedImpl(context, value, operations);\n\tif (context.nodes.length > 4_096) releaseOverlayReferences(context);\n\telse clearContext(context);\n\treturn prepared;\n}\n\nfunction materializeOperations<T extends object>(base: T, operations: readonly Op[]): T {\n\tfor (const operation of operations) {\n\t\t// Native splice/permutation remains faster for large structural batches.\n\t\tif (operation[0] === \"p\" || operation[0] === \"m\") return applyImmutable(base, operations);\n\t}\n\treturn applyImmutableTrusted(base, operations);\n}\n\nfunction createContext<T extends object>(\n\ttracker: WeakRef<TrackerImpl<object>>,\n\towner: object,\n\tbaseRevision: number,\n\troot: T,\n\treplacement: boolean,\n\tbase: T,\n): OverlayContext {\n\tconst context: OverlayContext = {\n\t\towner,\n\t\ttracker,\n\t\tbaseRevision,\n\t\tstatus: { value: \"open\" },\n\t\troot: undefined,\n\t\tbases: [],\n\t\tstored: [],\n\t\tdirty: [],\n\t\tnodes: [],\n\t\trawNodes: new WeakMap(),\n\t\tops: undefined,\n\t\treplacement,\n\t\treplacementNoop: false,\n\t\tbaseValue: base,\n\t\toverlayReleased: false,\n\t\tsimpleObjectMaterialization: false,\n\t\tregistryRef: undefined,\n\t};\n\tcontext.root = createNode(context, root as Container, undefined);\n\treturn context;\n}\n\nconst sharedObjectHandler: ProxyHandler<object> = {\n\tdeleteProperty(target, property) {\n\t\treturn deleteProperty(nodeForTarget(target), property);\n\t},\n\tdefineProperty(target) {\n\t\tassertWritable(nodeForTarget(target).context);\n\t\tthrow new TypeError(\"Defining overlay properties is not supported\");\n\t},\n\tget(target, property) {\n\t\tif (property === \"then\") {\n\t\t\tconst node = (target as Record<PropertyKey, unknown>)[NODE] as OverlayNode | undefined;\n\t\t\tif (node === undefined || isSettledContext(node.context)) return undefined;\n\t\t}\n\t\tconst node = nodeForTarget(target);\n\t\tif (property === NODE) return node;\n\t\treturn getProperty(node, property);\n\t},\n\tgetOwnPropertyDescriptor(target, property) {\n\t\treturn getDescriptor(nodeForTarget(target), property);\n\t},\n\tgetPrototypeOf(target) {\n\t\tconst node = nodeForTarget(target);\n\t\tassertReadable(node.context);\n\t\treturn Object.getPrototypeOf(nodeBase(node));\n\t},\n\thas(target, property) {\n\t\treturn hasProperty(nodeForTarget(target), property);\n\t},\n\tisExtensible(target) {\n\t\tassertReadable(nodeForTarget(target).context);\n\t\treturn true;\n\t},\n\townKeys(target) {\n\t\treturn ownKeys(nodeForTarget(target));\n\t},\n\tpreventExtensions(target) {\n\t\tassertWritable(nodeForTarget(target).context);\n\t\tthrow new TypeError(\"Overlays cannot be made non-extensible\");\n\t},\n\tset(target, property, value) {\n\t\treturn setProperty(nodeForTarget(target), property, value);\n\t},\n\tsetPrototypeOf(target) {\n\t\tassertWritable(nodeForTarget(target).context);\n\t\tthrow new TypeError(\"Changing an overlay prototype is not supported\");\n\t},\n};\n\nconst sharedArrayHandler: ProxyHandler<object> = sharedObjectHandler;\n\nfunction createNode(\n\tcontext: OverlayContext,\n\tbase: Container,\n\tparent: OverlayNode | undefined,\n\tparentKind: ParentKind = 0,\n\tparentKey: string | number = \"\",\n\tparentSource: InsertSource | undefined = undefined,\n\tparentPlacement = false,\n): OverlayNode {\n\tconst existing = context.rawNodes!.get(base);\n\tif (existing !== undefined) return existing;\n\tconst target: object = Array.isArray(base) ? [] : {};\n\tconst baseIndex = context.bases!.length;\n\tconst parentIndex = parent?.baseIndex ?? -1;\n\tcontext.bases!.push(base);\n\tconst node: OverlayNode = {\n\t\tcontext,\n\t\tbaseIndex,\n\t\tparentIndex,\n\t\tparentKind,\n\t\tparentKey,\n\t\tparentPlacement,\n\t\ttarget,\n\t\tproxy: target,\n\t};\n\tif (parentSource !== undefined) node.parentSource = parentSource;\n\t(target as Record<PropertyKey, unknown>)[NODE] = node;\n\tnode.proxy = new Proxy(target, Array.isArray(base) ? sharedArrayHandler : sharedObjectHandler);\n\tcontext.rawNodes!.set(base, node);\n\tcontext.nodes.push(node);\n\treturn node;\n}\n\nfunction nodeBase(node: OverlayNode): Container {\n\treturn node.context.bases![node.baseIndex]!;\n}\n\nfunction nodeParent(node: OverlayNode): OverlayNode | undefined {\n\treturn node.parentIndex < 0 ? undefined : node.context.nodes[node.parentIndex];\n}\n\nfunction storeValue(context: OverlayContext, value: Stored): StoredRef {\n\tif (!isContainer(value)) return value;\n\tconst index = context.stored!.length;\n\tcontext.stored!.push(value);\n\treturn { index };\n}\n\nfunction storedValue(context: OverlayContext, reference: StoredRef): Stored {\n\treturn typeof reference === \"object\" && reference !== null ? context.stored![reference.index]! : reference;\n}\n\nfunction replaceStoredValue(context: OverlayContext, reference: StoredRef, value: Stored): StoredRef {\n\tif (isContainer(value)) {\n\t\tif (typeof reference === \"object\" && reference !== null) {\n\t\t\tcontext.stored![reference.index] = value;\n\t\t\treturn reference;\n\t\t}\n\t\treturn storeValue(context, value);\n\t}\n\tif (typeof reference === \"object\" && reference !== null) context.stored![reference.index] = RELEASED;\n\treturn value;\n}\n\nfunction releaseStoredValue(context: OverlayContext, reference: StoredRef): void {\n\tif (typeof reference === \"object\" && reference !== null) context.stored![reference.index] = RELEASED;\n}\n\nfunction nodeForTarget(target: object): OverlayNode {\n\tconst node = (target as Record<PropertyKey, unknown>)[NODE] as OverlayNode | undefined;\n\tif (node === undefined) throw new TypeError(\"Cannot use a settled overlay\");\n\treturn node;\n}\n\nfunction isSettledContext(context: OverlayContext): boolean {\n\treturn (\n\t\tcontext.overlayReleased ||\n\t\tcontext.status.value === \"consumed\" ||\n\t\tcontext.status.value === \"aborted\" ||\n\t\tcontext.status.value === \"stale\"\n\t);\n}\n\nfunction assertReadable(context: OverlayContext): void {\n\tif (isSettledContext(context)) throw new TypeError(\"Cannot use a settled overlay\");\n}\n\nfunction assertWritable(context: OverlayContext): void {\n\tassertReadable(context);\n\tif (context.status.value !== \"open\") throw new TypeError(\"Prepared overlays are read-only\");\n}\n\nfunction getProperty(node: OverlayNode, property: PropertyKey): unknown {\n\tassertReadable(node.context);\n\tif (Array.isArray(nodeBase(node))) {\n\t\tconst overlay = arrayOverlay(node);\n\t\tif (property === \"length\") return arrayLength(overlay);\n\t\tif (ARRAY_MUTATORS.has(property)) return arrayMutators[property as keyof typeof arrayMutators];\n\t\tconst index = arrayIndex(property);\n\t\tif (index !== undefined) return getArrayIndex(node, index);\n\t\treturn Reflect.get(Array.prototype, property, node.proxy);\n\t}\n\tif (typeof property === \"symbol\") return Reflect.get(nodeBase(node), property, node.proxy);\n\tconst key = String(property);\n\tif (!objectHas(node, key)) {\n\t\tif (isObjectDeleted(node, key) || Object.hasOwn(nodeBase(node), key)) return undefined;\n\t\treturn Reflect.get(nodeBase(node), property, node.proxy);\n\t}\n\tconst value = objectValue(node, key);\n\tif (!isContainer(value)) return value;\n\treturn createNode(node.context, value, node, 0, key, undefined, hasObjectWrite(node, key)).proxy;\n}\n\nfunction getArrayIndex(node: OverlayNode, index: number): unknown {\n\tconst overlay = arrayOverlay(node);\n\tif (index >= arrayLength(overlay)) return undefined;\n\tconst piece = locatePiece(overlay, index);\n\tconst sourceIndex = piece.start + piece.step * overlay.locatedOffset;\n\tconst value = entryValueAt(node, piece, sourceIndex);\n\tif (!isContainer(value)) return value;\n\treturn createNode(\n\t\tnode.context,\n\t\tvalue,\n\t\tnode,\n\t\tpiece.kind === \"base\" ? 1 : 2,\n\t\tsourceIndex,\n\t\tpiece.kind === \"insert\" ? piece.source : undefined,\n\t\tpiece.kind === \"insert\" || hasEntryOverrideAt(overlay, piece, sourceIndex),\n\t).proxy;\n}\n\nfunction setProperty(node: OverlayNode, property: PropertyKey, supplied: unknown): boolean {\n\tassertWritable(node.context);\n\tif (typeof property === \"symbol\") throw new TypeError(\"Symbol writes are not supported\");\n\tif (Array.isArray(nodeBase(node))) {\n\t\tif (property === \"length\") {\n\t\t\tsetArrayLength(node, toArrayLength(supplied));\n\t\t\treturn true;\n\t\t}\n\t\tconst index = arrayIndex(property);\n\t\tif (index === undefined) throw new TypeError(\"Only array indices and length can be written\");\n\t\tif (index > arrayLength(arrayOverlay(node))) throw new TypeError(\"Overlay arrays cannot contain holes\");\n\t\tsetArrayIndex(node, index, clonePlacement(supplied));\n\t\treturn true;\n\t}\n\tconst key = String(property);\n\tif (supplied === undefined) return deleteProperty(node, key);\n\tconst stored = clonePlacement(supplied);\n\tconst current = objectValue(node, key);\n\tconst wasDeleted = isObjectDeleted(node, key);\n\tif (!wasDeleted && !isContainer(stored) && current === stored) return true;\n\tsetObjectWrite(node, key, stored);\n\tif (wasDeleted && Object.hasOwn(nodeBase(node), key)) {\n\t\tif (node.readded === undefined) node.readded = new Set();\n\t\tnode.readded.add(key);\n\t}\n\tdeleteObjectDeletion(node, key);\n\tmarkDirty(node);\n\treturn true;\n}\n\nfunction deleteProperty(node: OverlayNode, property: PropertyKey): boolean {\n\tassertWritable(node.context);\n\tif (typeof property === \"symbol\") throw new TypeError(\"Symbol writes are not supported\");\n\tif (Array.isArray(nodeBase(node))) throw new TypeError(\"Overlay arrays cannot contain holes\");\n\tconst key = String(property);\n\tif (!objectHas(node, key)) return true;\n\tdeleteObjectWrite(node, key);\n\tnode.readded?.delete(key);\n\tsetObjectDeletion(node, key);\n\tmarkDirty(node);\n\treturn true;\n}\n\nfunction hasProperty(node: OverlayNode, property: PropertyKey): boolean {\n\tassertReadable(node.context);\n\tif (Array.isArray(nodeBase(node))) {\n\t\tif (property === \"length\") return true;\n\t\tconst index = arrayIndex(property);\n\t\tif (index !== undefined) return index < arrayLength(arrayOverlay(node));\n\t\treturn property in Array.prototype;\n\t}\n\treturn typeof property === \"symbol\" ? property in nodeBase(node) : objectHas(node, String(property));\n}\n\nfunction ownKeys(node: OverlayNode): ArrayLike<string | symbol> {\n\tassertReadable(node.context);\n\tif (Array.isArray(nodeBase(node))) {\n\t\tconst length = arrayLength(arrayOverlay(node));\n\t\tconst keys = new Array<string>(length + 1);\n\t\tfor (let index = 0; index < length; index++) keys[index] = String(index);\n\t\tkeys[length] = \"length\";\n\t\treturn keys;\n\t}\n\tlet existingKeysOnly =\n\t\tnode.deleteKey === undefined &&\n\t\tnode.deletes === undefined &&\n\t\tnode.readded === undefined &&\n\t\t(node.writeKey === undefined || Object.hasOwn(nodeBase(node), node.writeKey));\n\tif (existingKeysOnly && node.writes !== undefined) {\n\t\tfor (const key of node.writes.keys()) {\n\t\t\tif (!Object.hasOwn(nodeBase(node), key)) {\n\t\t\t\texistingKeysOnly = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (existingKeysOnly) return Object.keys(nodeBase(node));\n\tconst keys = Object.keys(nodeBase(node)).filter((key) => !isObjectDeleted(node, key) && !node.readded?.has(key));\n\tconst seen = new Set(keys);\n\tif (node.writeKey !== undefined && !seen.has(node.writeKey)) {\n\t\tkeys.push(node.writeKey);\n\t\tseen.add(node.writeKey);\n\t}\n\tif (node.writes !== undefined) {\n\t\tfor (const key of node.writes.keys()) {\n\t\t\tif (seen.has(key)) continue;\n\t\t\tkeys.push(key);\n\t\t\tseen.add(key);\n\t\t}\n\t}\n\tconst indices: number[] = [];\n\tconst strings: string[] = [];\n\tfor (const key of keys) {\n\t\tconst index = arrayIndex(key);\n\t\tif (index === undefined) strings.push(key);\n\t\telse indices.push(index);\n\t}\n\tindices.sort((left, right) => left - right);\n\treturn [...indices.map(String), ...strings];\n}\n\nfunction getDescriptor(node: OverlayNode, property: PropertyKey): PropertyDescriptor | undefined {\n\tassertReadable(node.context);\n\tif (Array.isArray(nodeBase(node))) {\n\t\tif (property === \"length\") {\n\t\t\tconst length = arrayLength(arrayOverlay(node));\n\t\t\t(node.target as unknown[]).length = length;\n\t\t\treturn Reflect.getOwnPropertyDescriptor(node.target, \"length\");\n\t\t}\n\t\tconst index = arrayIndex(property);\n\t\tif (index === undefined || index >= arrayLength(arrayOverlay(node))) return undefined;\n\t} else {\n\t\tif (typeof property === \"symbol\" || !objectHas(node, String(property))) return undefined;\n\t}\n\treturn {\n\t\tconfigurable: true,\n\t\tenumerable: true,\n\t\twritable: node.context.status.value === \"open\",\n\t\tvalue: getProperty(node, property),\n\t};\n}\n\nfunction hasObjectWrite(node: OverlayNode, key: string): boolean {\n\treturn node.writeKey === key || (node.writes?.has(key) ?? false);\n}\n\nfunction setObjectWrite(node: OverlayNode, key: string, value: Stored): void {\n\tif (node.writes !== undefined) {\n\t\tconst reference = node.writes.get(key);\n\t\tnode.writes.set(\n\t\t\tkey,\n\t\t\treference === undefined ? storeValue(node.context, value) : replaceStoredValue(node.context, reference, value),\n\t\t);\n\t\treturn;\n\t}\n\tif (node.writeKey === undefined || node.writeKey === key) {\n\t\tnode.writeKey = key;\n\t\tnode.writeValue =\n\t\t\tnode.writeValue === undefined\n\t\t\t\t? storeValue(node.context, value)\n\t\t\t\t: replaceStoredValue(node.context, node.writeValue, value);\n\t\treturn;\n\t}\n\tnode.writes = new Map();\n\tnode.writes.set(node.writeKey, node.writeValue!);\n\tnode.writes.set(key, storeValue(node.context, value));\n\tnode.writeKey = undefined;\n\tnode.writeValue = undefined;\n}\n\nfunction deleteObjectWrite(node: OverlayNode, key: string): void {\n\tif (node.writeKey === key) {\n\t\tnode.writeKey = undefined;\n\t\treleaseStoredValue(node.context, node.writeValue!);\n\t\tnode.writeValue = undefined;\n\t} else {\n\t\tconst reference = node.writes?.get(key);\n\t\tif (reference !== undefined) releaseStoredValue(node.context, reference);\n\t\tnode.writes?.delete(key);\n\t}\n}\n\nfunction isObjectDeleted(node: OverlayNode, key: string): boolean {\n\treturn node.deleteKey === key || (node.deletes?.has(key) ?? false);\n}\n\nfunction setObjectDeletion(node: OverlayNode, key: string): void {\n\tif (node.deletes !== undefined) {\n\t\tnode.deletes.add(key);\n\t\treturn;\n\t}\n\tif (node.deleteKey === undefined || node.deleteKey === key) {\n\t\tnode.deleteKey = key;\n\t\treturn;\n\t}\n\tnode.deletes = new Set();\n\tnode.deletes.add(node.deleteKey);\n\tnode.deletes.add(key);\n\tnode.deleteKey = undefined;\n}\n\nfunction deleteObjectDeletion(node: OverlayNode, key: string): void {\n\tif (node.deleteKey === key) node.deleteKey = undefined;\n\telse node.deletes?.delete(key);\n}\n\nfunction objectHas(node: OverlayNode, key: string): boolean {\n\tif (isObjectDeleted(node, key)) return false;\n\treturn hasObjectWrite(node, key) || Object.hasOwn(nodeBase(node), key);\n}\n\nfunction objectValue(node: OverlayNode, key: string): Stored {\n\tif (node.writeKey === key) return storedValue(node.context, node.writeValue!);\n\tconst reference = node.writes?.get(key);\n\tif (reference !== undefined) return storedValue(node.context, reference);\n\treturn (nodeBase(node) as Record<string, JsonValue>)[key]!;\n}\n\nfunction markDirty(node: OverlayNode): void {\n\tif (node.dirty) return;\n\tnode.dirty = true;\n\tnode.context.dirty.push(node);\n\tfor (let parent = nodeParent(node); parent !== undefined; parent = nodeParent(parent)) parent.subtreeDirty = true;\n}\n\nfunction arrayOverlay(node: OverlayNode): ArrayOverlay {\n\tif (node.array !== undefined) return node.array;\n\tconst base = nodeBase(node) as JsonValue[];\n\tconst overlay: ArrayOverlay = {\n\t\troot: undefined,\n\t\tpieces: undefined,\n\t\tbaseOverrides: undefined,\n\t\tinsertOverrides: undefined,\n\t\tstructural: false,\n\t\tgeneration: 0,\n\t\tplan: undefined,\n\t\tseed: 0x9e3779b9,\n\t\tlocatedOffset: 0,\n\t\tbaseLocations: undefined,\n\t\tinsertLocations: undefined,\n\t};\n\tif (base.length > 0)\n\t\toverlay.root = createPieceNode(overlay, { kind: \"base\", start: 0, length: base.length, step: 1 });\n\tnode.array = overlay;\n\treturn overlay;\n}\n\nfunction baseOverridesForWrite(overlay: ArrayOverlay): Map<number, StoredRef> {\n\tif (overlay.baseOverrides === undefined) overlay.baseOverrides = new Map();\n\treturn overlay.baseOverrides;\n}\n\nfunction insertOverridesForWrite(overlay: ArrayOverlay): Map<InsertSource, Map<number, StoredRef>> {\n\tif (overlay.insertOverrides === undefined) overlay.insertOverrides = new Map();\n\treturn overlay.insertOverrides;\n}\n\nfunction nextPiecePriority(overlay: ArrayOverlay): number {\n\tlet value = overlay.seed;\n\tvalue ^= value << 13;\n\tvalue ^= value >>> 17;\n\tvalue ^= value << 5;\n\toverlay.seed = value >>> 0;\n\treturn overlay.seed;\n}\n\nfunction treeElements(node: PieceNode | undefined): number {\n\treturn node?.elements ?? 0;\n}\n\nfunction updatePieceNode(node: PieceNode): void {\n\tnode.elements = treeElements(node.left) + node.piece.length + treeElements(node.right);\n}\n\nfunction createPieceNode(overlay: ArrayOverlay, piece: Piece): PieceNode {\n\treturn { piece, left: undefined, right: undefined, priority: nextPiecePriority(overlay), elements: piece.length };\n}\n\nfunction mergePieceTrees(left: PieceNode | undefined, right: PieceNode | undefined): PieceNode | undefined {\n\tif (left === undefined) return right;\n\tif (right === undefined) return left;\n\tif (left.priority >= right.priority) {\n\t\tleft.right = mergePieceTrees(left.right, right);\n\t\tupdatePieceNode(left);\n\t\treturn left;\n\t}\n\tright.left = mergePieceTrees(left, right.left);\n\tupdatePieceNode(right);\n\treturn right;\n}\n\nfunction splitPieceTree(\n\toverlay: ArrayOverlay,\n\troot: PieceNode | undefined,\n\tindex: number,\n): [PieceNode | undefined, PieceNode | undefined] {\n\tif (root === undefined) return [undefined, undefined];\n\tconst leftLength = treeElements(root.left);\n\tif (index < leftLength) {\n\t\tconst [left, right] = splitPieceTree(overlay, root.left, index);\n\t\troot.left = right;\n\t\tupdatePieceNode(root);\n\t\treturn [left, root];\n\t}\n\tconst pieceEnd = leftLength + root.piece.length;\n\tif (index > pieceEnd) {\n\t\tconst [left, right] = splitPieceTree(overlay, root.right, index - pieceEnd);\n\t\troot.right = left;\n\t\tupdatePieceNode(root);\n\t\treturn [root, right];\n\t}\n\tif (index === leftLength) {\n\t\tconst left = root.left;\n\t\troot.left = undefined;\n\t\tupdatePieceNode(root);\n\t\treturn [left, root];\n\t}\n\tif (index === pieceEnd) {\n\t\tconst right = root.right;\n\t\troot.right = undefined;\n\t\tupdatePieceNode(root);\n\t\treturn [root, right];\n\t}\n\tconst offset = index - leftLength;\n\tconst first = { ...root.piece, length: offset };\n\tconst second = {\n\t\t...root.piece,\n\t\tstart: root.piece.start + root.piece.step * offset,\n\t\tlength: root.piece.length - offset,\n\t};\n\treturn [\n\t\tmergePieceTrees(root.left, createPieceNode(overlay, first)),\n\t\tmergePieceTrees(createPieceNode(overlay, second), root.right),\n\t];\n}\n\nfunction leftmostPieceNode(node: PieceNode): PieceNode {\n\twhile (node.left !== undefined) node = node.left;\n\treturn node;\n}\n\nfunction rightmostPieceNode(node: PieceNode): PieceNode {\n\twhile (node.right !== undefined) node = node.right;\n\treturn node;\n}\n\nfunction mergeablePieces(left: Piece, right: Piece): boolean {\n\tif (left.kind !== right.kind) return false;\n\tif (left.kind === \"insert\" && left.source !== (right as InsertPiece).source) return false;\n\tif (left.length === 1 && right.length === 1) return Math.abs(right.start - left.start) === 1;\n\treturn left.step === right.step && left.start + left.step * left.length === right.start;\n}\n\nfunction joinNormalized(\n\toverlay: ArrayOverlay,\n\tleft: PieceNode | undefined,\n\tright: PieceNode | undefined,\n): PieceNode | undefined {\n\tif (left === undefined) return right;\n\tif (right === undefined) return left;\n\tconst leftPiece = rightmostPieceNode(left).piece;\n\tconst rightPiece = leftmostPieceNode(right).piece;\n\tif (!mergeablePieces(leftPiece, rightPiece)) return mergePieceTrees(left, right);\n\tconst [leftRest] = splitPieceTree(overlay, left, treeElements(left) - leftPiece.length);\n\tconst [, rightRest] = splitPieceTree(overlay, right, rightPiece.length);\n\tconst step = leftPiece.length === 1 ? ((rightPiece.start - leftPiece.start) as 1 | -1) : leftPiece.step;\n\tconst combined: Piece =\n\t\tleftPiece.kind === \"base\"\n\t\t\t? { kind: \"base\", start: leftPiece.start, length: leftPiece.length + rightPiece.length, step }\n\t\t\t: {\n\t\t\t\t\tkind: \"insert\",\n\t\t\t\t\tsource: leftPiece.source,\n\t\t\t\t\tstart: leftPiece.start,\n\t\t\t\t\tlength: leftPiece.length + rightPiece.length,\n\t\t\t\t\tstep,\n\t\t\t\t};\n\treturn joinNormalized(overlay, joinNormalized(overlay, leftRest, createPieceNode(overlay, combined)), rightRest);\n}\n\nfunction flattenPieceTree(node: PieceNode | undefined, output: Piece[]): void {\n\tif (node === undefined) return;\n\tflattenPieceTree(node.left, output);\n\toutput.push(node.piece);\n\tflattenPieceTree(node.right, output);\n}\n\nfunction piecesOf(overlay: ArrayOverlay): readonly Piece[] {\n\tif (overlay.pieces === undefined) {\n\t\toverlay.pieces = [];\n\t\tflattenPieceTree(overlay.root, overlay.pieces);\n\t}\n\treturn overlay.pieces;\n}\n\nfunction treeFromPieces(overlay: ArrayOverlay, pieces: Piece[]): PieceNode | undefined {\n\tmergePieces(pieces);\n\tlet root: PieceNode | undefined;\n\tfor (const piece of pieces) root = mergePieceTrees(root, createPieceNode(overlay, piece));\n\treturn root;\n}\n\nfunction replaceAllPieces(overlay: ArrayOverlay, pieces: Piece[]): void {\n\toverlay.root = treeFromPieces(overlay, pieces);\n\toverlay.pieces = undefined;\n\toverlay.baseLocations = undefined;\n\toverlay.insertLocations = undefined;\n}\n\nfunction arrayLength(overlay: ArrayOverlay): number {\n\treturn treeElements(overlay.root);\n}\n\nfunction locatePiece(overlay: ArrayOverlay, index: number): Piece {\n\tlet node = overlay.root;\n\twhile (node !== undefined) {\n\t\tconst leftLength = treeElements(node.left);\n\t\tif (index < leftLength) node = node.left;\n\t\telse if (index >= leftLength + node.piece.length) {\n\t\t\tindex -= leftLength + node.piece.length;\n\t\t\tnode = node.right;\n\t\t} else {\n\t\t\toverlay.locatedOffset = index - leftLength;\n\t\t\treturn node.piece;\n\t\t}\n\t}\n\tthrow new RangeError(\"Array overlay index is out of range\");\n}\n\nfunction arrayIndex(property: PropertyKey): number | undefined {\n\tif (typeof property !== \"string\" || property.length === 0 || property.length > 10) return undefined;\n\tif (property === \"0\") return 0;\n\tconst first = property.charCodeAt(0);\n\tif (first < 49 || first > 57) return undefined;\n\tlet index = first - 48;\n\tfor (let offset = 1; offset < property.length; offset++) {\n\t\tconst digit = property.charCodeAt(offset) - 48;\n\t\tif (digit < 0 || digit > 9) return undefined;\n\t\tindex = index * 10 + digit;\n\t\tif (index >= 4_294_967_295) return undefined;\n\t}\n\treturn index;\n}\n\nfunction entryValueAt(node: OverlayNode, piece: Piece, sourceIndex: number): Stored {\n\tconst overlay = arrayOverlay(node);\n\tif (piece.kind === \"base\") {\n\t\tconst valueIndex = overlay.baseOverrides?.get(sourceIndex);\n\t\treturn valueIndex === undefined\n\t\t\t? (nodeBase(node) as JsonValue[])[sourceIndex]!\n\t\t\t: storedValue(node.context, valueIndex);\n\t}\n\tconst overrides = overlay.insertOverrides?.get(piece.source);\n\tconst reference = overrides?.has(sourceIndex) ? overrides.get(sourceIndex)! : piece.source.refs[sourceIndex]!;\n\treturn storedValue(node.context, reference);\n}\n\nfunction hasEntryOverrideAt(overlay: ArrayOverlay, piece: Piece, sourceIndex: number): boolean {\n\treturn piece.kind === \"base\"\n\t\t? (overlay.baseOverrides?.has(sourceIndex) ?? false)\n\t\t: (overlay.insertOverrides?.get(piece.source)?.has(sourceIndex) ?? false);\n}\n\nfunction extendRightmostPiece(node: PieceNode, amount: number): void {\n\tif (node.right !== undefined) extendRightmostPiece(node.right, amount);\n\telse node.piece.length += amount;\n\tupdatePieceNode(node);\n}\n\nfunction invalidatePieceCaches(overlay: ArrayOverlay): void {\n\toverlay.pieces = undefined;\n\toverlay.baseLocations = undefined;\n\toverlay.insertLocations = undefined;\n\toverlay.plan = undefined;\n}\n\nfunction replacePieceRange(node: OverlayNode, index: number, remove: number, inserted: Piece[]): void {\n\tif (remove === 0 && inserted.length === 0) return;\n\tconst overlay = arrayOverlay(node);\n\tif (remove === 0 && index === arrayLength(overlay) && inserted.length === 1 && overlay.root !== undefined) {\n\t\tconst addition = inserted[0]!;\n\t\tconst tail = rightmostPieceNode(overlay.root).piece;\n\t\tif (\n\t\t\taddition.kind === \"insert\" &&\n\t\t\ttail.kind === \"insert\" &&\n\t\t\ttail.step === 1 &&\n\t\t\ttail.start + tail.length === tail.source.refs.length\n\t\t) {\n\t\t\tfor (let offset = 0; offset < addition.length; offset++) {\n\t\t\t\ttail.source.refs.push(addition.source.refs[addition.start + offset]!);\n\t\t\t}\n\t\t\textendRightmostPiece(overlay.root, addition.length);\n\t\t\tinvalidatePieceCaches(overlay);\n\t\t\toverlay.structural = true;\n\t\t\toverlay.generation += 1;\n\t\t\tmarkDirty(node);\n\t\t\treturn;\n\t\t}\n\t}\n\tconst [left, rest] = splitPieceTree(overlay, overlay.root, index);\n\tconst [, right] = splitPieceTree(overlay, rest, remove);\n\tconst middle = treeFromPieces(overlay, inserted);\n\toverlay.root = joinNormalized(overlay, joinNormalized(overlay, left, middle), right);\n\tinvalidatePieceCaches(overlay);\n\toverlay.structural = true;\n\toverlay.generation += 1;\n\tmarkDirty(node);\n}\n\nfunction mergePieces(pieces: Piece[]): void {\n\tfor (let index = 1; index < pieces.length; ) {\n\t\tconst left = pieces[index - 1]!;\n\t\tconst right = pieces[index]!;\n\t\tconst sameSource =\n\t\t\tleft.kind === right.kind && (left.kind === \"base\" || left.source === (right as InsertPiece).source);\n\t\tif (sameSource && left.length === 1 && right.length === 1 && Math.abs(right.start - left.start) === 1) {\n\t\t\tleft.step = (right.start - left.start) as 1 | -1;\n\t\t\tleft.length = 2;\n\t\t\tpieces.splice(index, 1);\n\t\t} else if (sameSource && left.step === right.step && left.start + left.step * left.length === right.start) {\n\t\t\tleft.length += right.length;\n\t\t\tpieces.splice(index, 1);\n\t\t} else index += 1;\n\t}\n}\n\nfunction insertPiece(node: OverlayNode, items: Stored[], start = 0): InsertPiece[] {\n\tif (items.length === start) return [];\n\tconst refs: StoredRef[] = [];\n\tfor (let index = start; index < items.length; index++) refs.push(storeValue(node.context, items[index]!));\n\treturn [{ kind: \"insert\", source: { refs }, start: 0, length: refs.length, step: 1 }];\n}\n\nfunction insertPlacementPiece(node: OverlayNode, values: unknown[], start = 0): InsertPiece[] {\n\tif (values.length === start) return [];\n\tconst storedLength = node.context.stored!.length;\n\ttry {\n\t\tfor (let index = start; index < values.length; index++)\n\t\t\tvalues[index] = storeValue(node.context, clonePlacement(values[index]));\n\t} catch (error) {\n\t\tnode.context.stored!.length = storedLength;\n\t\tthrow error;\n\t}\n\treturn [\n\t\t{\n\t\t\tkind: \"insert\",\n\t\t\tsource: { refs: values as StoredRef[] },\n\t\t\tstart,\n\t\t\tlength: values.length - start,\n\t\t\tstep: 1,\n\t\t},\n\t];\n}\n\nfunction setArrayIndex(node: OverlayNode, index: number, stored: Stored): void {\n\tconst overlay = arrayOverlay(node);\n\tconst length = arrayLength(overlay);\n\tif (index === length) {\n\t\treplacePieceRange(node, length, 0, insertPiece(node, [stored]));\n\t\treturn;\n\t}\n\tconst piece = locatePiece(overlay, index);\n\tconst sourceIndex = piece.start + piece.step * overlay.locatedOffset;\n\tconst current = entryValueAt(node, piece, sourceIndex);\n\tif (!isContainer(stored) && current === stored) return;\n\tif (piece.kind === \"base\") {\n\t\tconst existingIndex = overlay.baseOverrides?.get(sourceIndex);\n\t\tif (!isContainer(stored) && stored === (nodeBase(node) as JsonValue[])[sourceIndex]) {\n\t\t\tif (existingIndex !== undefined) releaseStoredValue(node.context, existingIndex);\n\t\t\toverlay.baseOverrides?.delete(sourceIndex);\n\t\t} else if (existingIndex === undefined) {\n\t\t\tbaseOverridesForWrite(overlay).set(sourceIndex, storeValue(node.context, stored));\n\t\t} else overlay.baseOverrides!.set(sourceIndex, replaceStoredValue(node.context, existingIndex, stored));\n\t} else {\n\t\tlet overrides = overlay.insertOverrides?.get(piece.source);\n\t\tconst existingIndex = overrides?.get(sourceIndex);\n\t\tif (!isContainer(stored) && stored === storedValue(node.context, piece.source.refs[sourceIndex]!)) {\n\t\t\tif (existingIndex !== undefined) releaseStoredValue(node.context, existingIndex);\n\t\t\toverrides?.delete(sourceIndex);\n\t\t\tif (overrides?.size === 0) overlay.insertOverrides?.delete(piece.source);\n\t\t} else {\n\t\t\tif (overrides === undefined) {\n\t\t\t\toverrides = new Map();\n\t\t\t\tinsertOverridesForWrite(overlay).set(piece.source, overrides);\n\t\t\t}\n\t\t\tif (existingIndex === undefined) overrides.set(sourceIndex, storeValue(node.context, stored));\n\t\t\telse overrides.set(sourceIndex, replaceStoredValue(node.context, existingIndex, stored));\n\t\t}\n\t}\n\tmarkDirty(node);\n}\n\nfunction setArrayLength(node: OverlayNode, next: number): void {\n\tconst current = arrayLength(arrayOverlay(node));\n\tif (next === current) return;\n\tif (next < current) replacePieceRange(node, next, current - next, []);\n\telse\n\t\treplacePieceRange(\n\t\t\tnode,\n\t\t\tcurrent,\n\t\t\t0,\n\t\t\tinsertPiece(\n\t\t\t\tnode,\n\t\t\t\tArray.from({ length: next - current }, () => null),\n\t\t\t),\n\t\t);\n}\n\nfunction toArrayLength(value: unknown): number {\n\tconst number = Number(value);\n\tif (!Number.isInteger(number) || number < 0 || number >= 4_294_967_296) throw new RangeError(\"Invalid array length\");\n\treturn number;\n}\n\nfunction toIntegerOrInfinity(value: unknown): number {\n\tconst number = Number(value);\n\tif (Number.isNaN(number) || number === 0) return 0;\n\treturn Number.isFinite(number) ? Math.trunc(number) : number;\n}\n\nfunction clampIndex(value: number, length: number): number {\n\tif (value === Number.NEGATIVE_INFINITY) return 0;\n\tif (value < 0) return Math.max(length + value, 0);\n\treturn Math.min(value, length);\n}\n\nfunction mutatorNode(receiver: unknown): OverlayNode | undefined {\n\tif (!isContainer(receiver)) return undefined;\n\tconst node = Reflect.get(receiver, NODE) as OverlayNode | undefined;\n\tif (node === undefined) return undefined;\n\tif (!Array.isArray(nodeBase(node))) throw new TypeError(\"Array mutator called on incompatible receiver\");\n\tassertWritable(node.context);\n\treturn node;\n}\n\nconst arrayMutators = {\n\tpush(this: unknown, ...items: unknown[]): number {\n\t\tconst node = mutatorNode(this);\n\t\tif (node === undefined) return Reflect.apply(Array.prototype.push, this, items) as number;\n\t\tconst length = arrayLength(arrayOverlay(node));\n\t\treplacePieceRange(node, length, 0, insertPlacementPiece(node, items));\n\t\treturn length + items.length;\n\t},\n\tpop(this: unknown): unknown {\n\t\tconst node = mutatorNode(this);\n\t\tif (node === undefined) return Reflect.apply(Array.prototype.pop, this, []);\n\t\tconst length = arrayLength(arrayOverlay(node));\n\t\tif (length === 0) return undefined;\n\t\tconst value = getArrayIndex(node, length - 1);\n\t\treplacePieceRange(node, length - 1, 1, []);\n\t\treturn value;\n\t},\n\tshift(this: unknown): unknown {\n\t\tconst node = mutatorNode(this);\n\t\tif (node === undefined) return Reflect.apply(Array.prototype.shift, this, []);\n\t\tconst length = arrayLength(arrayOverlay(node));\n\t\tif (length === 0) return undefined;\n\t\tconst value = getArrayIndex(node, 0);\n\t\treplacePieceRange(node, 0, 1, []);\n\t\treturn value;\n\t},\n\tunshift(this: unknown, ...items: unknown[]): number {\n\t\tconst node = mutatorNode(this);\n\t\tif (node === undefined) return Reflect.apply(Array.prototype.unshift, this, items) as number;\n\t\treplacePieceRange(node, 0, 0, insertPlacementPiece(node, items));\n\t\treturn arrayLength(arrayOverlay(node));\n\t},\n\tsplice(this: unknown, ...args: unknown[]): unknown[] {\n\t\tconst node = mutatorNode(this);\n\t\tif (node === undefined) return Reflect.apply(Array.prototype.splice, this, args) as unknown[];\n\t\tconst length = arrayLength(arrayOverlay(node));\n\t\tconst start = args.length === 0 ? 0 : clampIndex(toIntegerOrInfinity(args[0]), length);\n\t\tconst remove =\n\t\t\targs.length === 0\n\t\t\t\t? 0\n\t\t\t\t: args.length === 1\n\t\t\t\t\t? length - start\n\t\t\t\t\t: Math.min(Math.max(toIntegerOrInfinity(args[1]), 0), length - start);\n\t\tconst removed = Array.from({ length: remove }, (_, offset) => getArrayIndex(node, start + offset));\n\t\tconst itemStart = Math.min(2, args.length);\n\t\tconst itemCount = Math.max(args.length - 2, 0);\n\t\treplacePieceRange(node, start, remove, insertPlacementPiece(node, args, itemStart));\n\t\tsetArrayLength(node, length - remove + itemCount);\n\t\treturn removed;\n\t},\n\treverse(this: unknown): unknown {\n\t\tconst node = mutatorNode(this);\n\t\tif (node === undefined) return Reflect.apply(Array.prototype.reverse, this, []);\n\t\tconst overlay = arrayOverlay(node);\n\t\tif (arrayLength(overlay) < 2) return node.proxy;\n\t\tconst pieces = [...piecesOf(overlay)].reverse();\n\t\tfor (const piece of pieces) {\n\t\t\tpiece.start += piece.step * (piece.length - 1);\n\t\t\tpiece.step = piece.step === 1 ? -1 : 1;\n\t\t}\n\t\treplaceAllPieces(overlay, pieces);\n\t\toverlay.structural = true;\n\t\toverlay.generation += 1;\n\t\toverlay.plan = undefined;\n\t\tmarkDirty(node);\n\t\treturn node.proxy;\n\t},\n\tsort(this: unknown, comparator?: unknown): unknown {\n\t\tconst node = mutatorNode(this);\n\t\tif (node === undefined) return Reflect.apply(Array.prototype.sort, this, [comparator]);\n\t\tif (comparator !== undefined && typeof comparator !== \"function\")\n\t\t\tthrow new TypeError(\"Comparator must be a function\");\n\t\tconst overlay = arrayOverlay(node);\n\t\tconst insertedSources: InsertSource[] = [];\n\t\tconst insertedIndices: number[] = [];\n\t\tconst insertedValues: unknown[] = [];\n\t\tconst baseValues: unknown[] = new Array((nodeBase(node) as JsonValue[]).length);\n\t\tconst order: number[] = [];\n\t\tfor (const piece of piecesOf(overlay)) {\n\t\t\tfor (let offset = 0; offset < piece.length; offset++) {\n\t\t\t\tconst sourceIndex = piece.start + piece.step * offset;\n\t\t\t\tif (piece.kind === \"base\") {\n\t\t\t\t\torder.push(sourceIndex);\n\t\t\t\t\tbaseValues[sourceIndex] = publicSortValue(node, sourceIndex, insertedSources, insertedIndices);\n\t\t\t\t} else {\n\t\t\t\t\tinsertedSources.push(piece.source);\n\t\t\t\t\tinsertedIndices.push(sourceIndex);\n\t\t\t\t\tconst token = -insertedSources.length;\n\t\t\t\t\torder.push(token);\n\t\t\t\t\tinsertedValues.push(publicSortValue(node, token, insertedSources, insertedIndices));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst baseSnapshot = new Map<number, Stored>();\n\t\tfor (const [index, valueIndex] of overlay.baseOverrides ?? [])\n\t\t\tbaseSnapshot.set(index, storedValue(node.context, valueIndex));\n\t\tconst insertSnapshots = new Map<InsertSource, Map<number, Stored>>();\n\t\tfor (const [source, overrides] of overlay.insertOverrides ?? []) {\n\t\t\tconst snapshot = new Map<number, Stored>();\n\t\t\tfor (const [index, valueIndex] of overrides) snapshot.set(index, storedValue(node.context, valueIndex));\n\t\t\tinsertSnapshots.set(source, snapshot);\n\t\t}\n\t\tconst generation = overlay.generation;\n\t\torder.sort((left, right) => {\n\t\t\tconst leftValue = left < 0 ? insertedValues[-left - 1] : baseValues[left];\n\t\t\tconst rightValue = right < 0 ? insertedValues[-right - 1] : baseValues[right];\n\t\t\tif (typeof comparator === \"function\") return Number(comparator(leftValue, rightValue));\n\t\t\tconst a = String(leftValue);\n\t\t\tconst b = String(rightValue);\n\t\t\treturn a < b ? -1 : a > b ? 1 : 0;\n\t\t});\n\t\tif (\n\t\t\tbaseSnapshot.size > 0 ||\n\t\t\tinsertSnapshots.size > 0 ||\n\t\t\t(overlay.baseOverrides?.size ?? 0) > 0 ||\n\t\t\t(overlay.insertOverrides?.size ?? 0) > 0\n\t\t) {\n\t\t\tfor (const token of order) {\n\t\t\t\trestoreSortOverride(node, token, insertedSources, insertedIndices, baseSnapshot, insertSnapshots);\n\t\t\t}\n\t\t}\n\t\tconst comparatorWasStructural = overlay.generation !== generation;\n\t\tconst currentLength = arrayLength(overlay);\n\t\tconst samePrefix =\n\t\t\tcurrentLength >= order.length &&\n\t\t\torder.every((token, index) => sameSortTokenAt(overlay, index, token, insertedSources, insertedIndices));\n\t\tif (!samePrefix) {\n\t\t\treplacePieceRange(\n\t\t\t\tnode,\n\t\t\t\t0,\n\t\t\t\tMath.min(order.length, currentLength),\n\t\t\t\tpiecesFromSortOrder(order, insertedSources, insertedIndices),\n\t\t\t);\n\t\t}\n\t\tif (comparatorWasStructural) deduplicateArrayEntries(node);\n\t\treturn node.proxy;\n\t},\n\tfill(this: unknown, supplied: unknown, startArg?: unknown, endArg?: unknown): unknown {\n\t\tconst node = mutatorNode(this);\n\t\tif (node === undefined) return Reflect.apply(Array.prototype.fill, this, [supplied, startArg, endArg]);\n\t\tconst length = arrayLength(arrayOverlay(node));\n\t\tconst start = startArg === undefined ? 0 : clampIndex(toIntegerOrInfinity(startArg), length);\n\t\tconst end = endArg === undefined ? length : clampIndex(toIntegerOrInfinity(endArg), length);\n\t\tif (end <= start) return node.proxy;\n\t\tconst items = Array.from({ length: end - start }, () => clonePlacement(supplied));\n\t\treplacePieceRange(node, start, end - start, insertPiece(node, items));\n\t\treturn node.proxy;\n\t},\n\tcopyWithin(this: unknown, targetArg: unknown, startArg: unknown, endArg?: unknown): unknown {\n\t\tconst node = mutatorNode(this);\n\t\tif (node === undefined) return Reflect.apply(Array.prototype.copyWithin, this, [targetArg, startArg, endArg]);\n\t\tconst length = arrayLength(arrayOverlay(node));\n\t\tconst target = clampIndex(toIntegerOrInfinity(targetArg), length);\n\t\tconst start = clampIndex(toIntegerOrInfinity(startArg), length);\n\t\tconst end = endArg === undefined ? length : clampIndex(toIntegerOrInfinity(endArg), length);\n\t\tconst count = Math.min(Math.max(end - start, 0), length - target);\n\t\tconst values = Array.from({ length: count }, (_, offset) => clonePlacement(getArrayIndex(node, start + offset)));\n\t\treplacePieceRange(node, target, count, insertPiece(node, values));\n\t\treturn node.proxy;\n\t},\n};\n\nfunction sortTokenSource(token: number, sources: readonly InsertSource[]): InsertSource | undefined {\n\treturn token < 0 ? sources[-token - 1] : undefined;\n}\n\nfunction sortTokenIndex(token: number, indices: readonly number[]): number {\n\treturn token < 0 ? indices[-token - 1]! : token;\n}\n\nfunction publicSortValue(\n\tnode: OverlayNode,\n\ttoken: number,\n\tsources: readonly InsertSource[],\n\tindices: readonly number[],\n): unknown {\n\tconst overlay = arrayOverlay(node);\n\tconst source = sortTokenSource(token, sources);\n\tconst sourceIndex = sortTokenIndex(token, indices);\n\tconst overrideIndex =\n\t\tsource === undefined\n\t\t\t? overlay.baseOverrides?.get(sourceIndex)\n\t\t\t: overlay.insertOverrides?.get(source)?.get(sourceIndex);\n\tconst value =\n\t\toverrideIndex !== undefined\n\t\t\t? storedValue(node.context, overrideIndex)\n\t\t\t: source === undefined\n\t\t\t\t? (nodeBase(node) as JsonValue[])[sourceIndex]!\n\t\t\t\t: storedValue(node.context, source.refs[sourceIndex]!);\n\tif (!isContainer(value)) return value;\n\treturn createNode(\n\t\tnode.context,\n\t\tvalue,\n\t\tnode,\n\t\tsource === undefined ? 1 : 2,\n\t\tsourceIndex,\n\t\tsource,\n\t\tsource !== undefined || (overlay.baseOverrides?.has(sourceIndex) ?? false),\n\t).proxy;\n}\n\nfunction restoreSortOverride(\n\tnode: OverlayNode,\n\ttoken: number,\n\tsources: readonly InsertSource[],\n\tindices: readonly number[],\n\tbaseSnapshot: ReadonlyMap<number, Stored>,\n\tinsertSnapshots: ReadonlyMap<InsertSource, ReadonlyMap<number, Stored>>,\n): void {\n\tconst overlay = arrayOverlay(node);\n\tconst source = sortTokenSource(token, sources);\n\tconst sourceIndex = sortTokenIndex(token, indices);\n\tif (source === undefined) {\n\t\tconst existingIndex = overlay.baseOverrides?.get(sourceIndex);\n\t\tconst snapshotValue = baseSnapshot.get(sourceIndex);\n\t\tif (snapshotValue !== undefined) {\n\t\t\tif (existingIndex === undefined)\n\t\t\t\tbaseOverridesForWrite(overlay).set(sourceIndex, storeValue(node.context, snapshotValue));\n\t\t\telse overlay.baseOverrides!.set(sourceIndex, replaceStoredValue(node.context, existingIndex, snapshotValue));\n\t\t} else {\n\t\t\tif (existingIndex !== undefined) releaseStoredValue(node.context, existingIndex);\n\t\t\toverlay.baseOverrides?.delete(sourceIndex);\n\t\t}\n\t\treturn;\n\t}\n\tlet overrides = overlay.insertOverrides?.get(source);\n\tconst existingIndex = overrides?.get(sourceIndex);\n\tconst snapshotValue = insertSnapshots.get(source)?.get(sourceIndex);\n\tif (snapshotValue !== undefined) {\n\t\tif (overrides === undefined) {\n\t\t\toverrides = new Map();\n\t\t\tinsertOverridesForWrite(overlay).set(source, overrides);\n\t\t}\n\t\tif (existingIndex === undefined) overrides.set(sourceIndex, storeValue(node.context, snapshotValue));\n\t\telse overrides.set(sourceIndex, replaceStoredValue(node.context, existingIndex, snapshotValue));\n\t} else {\n\t\tif (existingIndex !== undefined) releaseStoredValue(node.context, existingIndex);\n\t\toverrides?.delete(sourceIndex);\n\t\tif (overrides?.size === 0) overlay.insertOverrides?.delete(source);\n\t}\n}\n\nfunction sameSortTokenAt(\n\toverlay: ArrayOverlay,\n\tlogicalIndex: number,\n\ttoken: number,\n\tsources: readonly InsertSource[],\n\tindices: readonly number[],\n): boolean {\n\tconst piece = locatePiece(overlay, logicalIndex);\n\tconst sourceIndex = piece.start + piece.step * overlay.locatedOffset;\n\tconst tokenSource = sortTokenSource(token, sources);\n\treturn (\n\t\tsourceIndex === sortTokenIndex(token, indices) &&\n\t\t((piece.kind === \"base\" && tokenSource === undefined) ||\n\t\t\t(piece.kind === \"insert\" && piece.source === tokenSource))\n\t);\n}\n\nfunction deduplicateArrayEntries(node: OverlayNode): void {\n\tconst overlay = arrayOverlay(node);\n\tconst seenBase = new Set<number>();\n\tconst seenInsert = new Map<InsertSource, Set<number>>();\n\tconst next: Piece[] = [];\n\tlet duplicated = false;\n\tfor (const piece of piecesOf(overlay)) {\n\t\tfor (let offset = 0; offset < piece.length; offset++) {\n\t\t\tconst sourceIndex = piece.start + piece.step * offset;\n\t\t\tlet seen: boolean;\n\t\t\tif (piece.kind === \"base\") {\n\t\t\t\tseen = seenBase.has(sourceIndex);\n\t\t\t\tseenBase.add(sourceIndex);\n\t\t\t} else {\n\t\t\t\tlet indices = seenInsert.get(piece.source);\n\t\t\t\tif (indices === undefined) {\n\t\t\t\t\tindices = new Set();\n\t\t\t\t\tseenInsert.set(piece.source, indices);\n\t\t\t\t}\n\t\t\t\tseen = indices.has(sourceIndex);\n\t\t\t\tindices.add(sourceIndex);\n\t\t\t}\n\t\t\tif (seen) {\n\t\t\t\tduplicated = true;\n\t\t\t\tappendMergedPiece(\n\t\t\t\t\tnext,\n\t\t\t\t\tinsertPiece(node, [clonePlacementStored(entryValueAt(node, piece, sourceIndex), node.context)])[0]!,\n\t\t\t\t);\n\t\t\t} else appendMergedPiece(next, singletonPiece(piece, sourceIndex));\n\t\t}\n\t}\n\tif (!duplicated) return;\n\treplaceAllPieces(overlay, next);\n\toverlay.structural = true;\n\toverlay.generation += 1;\n\toverlay.plan = undefined;\n\tmarkDirty(node);\n}\n\nfunction piecesFromSortOrder(\n\torder: readonly number[],\n\tsources: readonly InsertSource[],\n\tindices: readonly number[],\n): Piece[] {\n\tconst pieces: Piece[] = [];\n\tfor (const token of order) {\n\t\tconst source = token < 0 ? sources[-token - 1] : undefined;\n\t\tconst sourceIndex = token < 0 ? indices[-token - 1]! : token;\n\t\tconst previous = pieces.at(-1);\n\t\tconst sameSource =\n\t\t\tprevious !== undefined &&\n\t\t\t((source === undefined && previous.kind === \"base\") ||\n\t\t\t\t(source !== undefined && previous.kind === \"insert\" && previous.source === source));\n\t\tif (previous !== undefined && sameSource) {\n\t\t\tif (previous.length === 1) {\n\t\t\t\tconst step = sourceIndex - previous.start;\n\t\t\t\tif (step === 1 || step === -1) {\n\t\t\t\t\tprevious.step = step;\n\t\t\t\t\tprevious.length = 2;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else if (previous.start + previous.step * previous.length === sourceIndex) {\n\t\t\t\tprevious.length += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tpieces.push(\n\t\t\tsource === undefined\n\t\t\t\t? { kind: \"base\", start: sourceIndex, length: 1, step: 1 }\n\t\t\t\t: { kind: \"insert\", source, start: sourceIndex, length: 1, step: 1 },\n\t\t);\n\t}\n\treturn pieces;\n}\n\nfunction appendMergedPiece(pieces: Piece[], piece: Piece): void {\n\tconst previous = pieces.at(-1);\n\tconst sameSource =\n\t\tprevious !== undefined &&\n\t\tprevious.kind === piece.kind &&\n\t\t(previous.kind === \"base\" || previous.source === (piece as InsertPiece).source);\n\tif (previous !== undefined && sameSource && previous.length === 1 && piece.length === 1) {\n\t\tconst step = piece.start - previous.start;\n\t\tif (step === 1 || step === -1) {\n\t\t\tprevious.step = step;\n\t\t\tprevious.length = 2;\n\t\t\treturn;\n\t\t}\n\t}\n\tif (\n\t\tprevious !== undefined &&\n\t\tsameSource &&\n\t\tprevious.step === piece.step &&\n\t\tprevious.start + previous.step * previous.length === piece.start\n\t) {\n\t\tprevious.length += piece.length;\n\t} else pieces.push(piece);\n}\n\nfunction singletonPiece(piece: Piece, sourceIndex: number): Piece {\n\treturn piece.kind === \"base\"\n\t\t? { kind: \"base\", start: sourceIndex, length: 1, step: 1 }\n\t\t: { kind: \"insert\", source: piece.source, start: sourceIndex, length: 1, step: 1 };\n}\n\nfunction clonePlacement(value: unknown): Stored {\n\tconst proxyNode = isContainer(value) ? (Reflect.get(value, NODE) as OverlayNode | undefined) : undefined;\n\treturn proxyNode === undefined ? copyJson(value) : clonePlacementNode(proxyNode);\n}\n\nfunction cloneNode(node: OverlayNode): Container {\n\tassertReadable(node.context);\n\tif (Array.isArray(nodeBase(node))) {\n\t\tconst overlay = arrayOverlay(node);\n\t\tconst result: JsonValue[] = [];\n\t\tfor (const piece of piecesOf(overlay)) {\n\t\t\tfor (let offset = 0; offset < piece.length; offset++) {\n\t\t\t\tconst sourceIndex = piece.start + piece.step * offset;\n\t\t\t\tresult.push(cloneStored(entryValueAt(node, piece, sourceIndex), node.context));\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tconst result = Object.create(Object.getPrototypeOf(nodeBase(node))) as Record<string, JsonValue>;\n\tfor (const key of ownKeys(node) as string[])\n\t\tdefineData(result, key, cloneStored(objectValue(node, key), node.context));\n\treturn result;\n}\n\nfunction cloneStored(value: Stored, context: OverlayContext): Stored {\n\tif (!isContainer(value)) return value;\n\tconst node = context.rawNodes!.get(value);\n\treturn node === undefined || (!node.dirty && !node.subtreeDirty) ? value : cloneNode(node);\n}\n\nfunction clonePlacementNode(node: OverlayNode): Container {\n\tassertReadable(node.context);\n\tif (Array.isArray(nodeBase(node))) {\n\t\tconst overlay = arrayOverlay(node);\n\t\tconst result: JsonValue[] = [];\n\t\tfor (const piece of piecesOf(overlay)) {\n\t\t\tfor (let offset = 0; offset < piece.length; offset++) {\n\t\t\t\tconst sourceIndex = piece.start + piece.step * offset;\n\t\t\t\tresult.push(clonePlacementStored(entryValueAt(node, piece, sourceIndex), node.context));\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tconst result = Object.create(Object.getPrototypeOf(nodeBase(node))) as Record<string, JsonValue>;\n\tfor (const key of ownKeys(node) as string[])\n\t\tdefineData(result, key, clonePlacementStored(objectValue(node, key), node.context));\n\treturn result;\n}\n\nfunction clonePlacementStored(value: Stored, context: OverlayContext): Stored {\n\tif (!isContainer(value)) return copyJson(value);\n\tconst node = context.rawNodes!.get(value);\n\treturn node === undefined ? copyJson(value) : clonePlacementNode(node);\n}\n\nfunction defineData(target: object, key: PropertyKey, value: JsonValue): void {\n\tDATA_DESCRIPTOR.value = value;\n\tObject.defineProperty(target, key, DATA_DESCRIPTOR);\n\tDATA_DESCRIPTOR.value = undefined;\n}\n\nfunction emitOperations(context: OverlayContext): Op[] {\n\tconst simple = emitSimpleObjectOperations(context);\n\tif (simple !== undefined) return simple;\n\tconst operations: Op[] = [];\n\tconst forcedFolds = new Map<OverlayNode, Path>();\n\tconst emissionPaths = new Map<OverlayNode, Path>();\n\tconst denseIndices = new Map<OverlayNode, DenseCandidates>();\n\tfor (const node of context.dirty) {\n\t\trecordDenseArrayPosition(node, denseIndices);\n\t\tif (Array.isArray(nodeBase(node))) {\n\t\t\tconst overlay = arrayOverlay(node);\n\t\t\tif (!overlay.structural && (overlay.baseOverrides?.size ?? 0) > 0) {\n\t\t\t\tlet candidates = denseIndices.get(node);\n\t\t\t\tif (candidates === undefined) {\n\t\t\t\t\tcandidates = { indices: [], bits: undefined, length: (nodeBase(node) as JsonValue[]).length };\n\t\t\t\t\tdenseIndices.set(node, candidates);\n\t\t\t\t}\n\t\t\t\tfor (const index of overlay.baseOverrides!.keys()) addDenseCandidate(candidates, index);\n\t\t\t}\n\t\t}\n\t}\n\tconst denseRegions = new Map<OverlayNode, DenseRegion[]>();\n\tfor (const [array, candidates] of denseIndices) {\n\t\tconst path = resolvePath(array);\n\t\tif (path === undefined || path.some((segment) => typeof segment === \"string\" && RESERVED_SEGMENTS.has(segment))) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst regions = buildDenseRegions(candidates);\n\t\tif (regions.length > 0) denseRegions.set(array, regions);\n\t}\n\tfor (const node of context.dirty) {\n\t\tconst path = resolvePath(node);\n\t\tif (path === undefined) continue;\n\t\tif (hasCoveringDenseRegion(node, path, denseRegions)) continue;\n\t\temissionPaths.set(node, path);\n\t\tif (!Array.isArray(nodeBase(node)) && hasReservedMutation(node)) forcedFolds.set(node, path);\n\t\tconst reservedAt = path.findIndex((segment) => typeof segment === \"string\" && RESERVED_SEGMENTS.has(segment));\n\t\tif (reservedAt >= 0) {\n\t\t\tlet ancestor = node;\n\t\t\tfor (let depth = path.length; depth > reservedAt; depth--) ancestor = nodeParent(ancestor)!;\n\t\t\tforcedFolds.set(ancestor, path.slice(0, reservedAt));\n\t\t}\n\t}\n\tfor (const [node, path] of forcedFolds) emissionPaths.set(node, path);\n\tfor (const node of denseRegions.keys()) {\n\t\tconst path = resolvePath(node);\n\t\tif (path !== undefined && !hasCoveringDenseRegion(node, path, denseRegions)) emissionPaths.set(node, path);\n\t}\n\tlet maxDepth = 0;\n\tfor (const path of emissionPaths.values()) maxDepth = Math.max(maxDepth, path.length);\n\tconst buckets: OverlayNode[][] = Array.from({ length: maxDepth + 1 }, () => []);\n\tfor (const [node, path] of emissionPaths) buckets[path.length]!.push(node);\n\tconst folded = new Set<OverlayNode>();\n\tfor (const bucket of buckets) {\n\t\tfor (const node of bucket) {\n\t\t\tconst path = emissionPaths.get(node)!;\n\t\t\tif (hasPlacementAncestor(node) || hasFoldedAncestor(node, folded)) continue;\n\t\t\tif (forcedFolds.has(node)) {\n\t\t\t\temitSet(operations, path, cloneNode(node));\n\t\t\t\tfolded.add(node);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (Array.isArray(nodeBase(node))) emitArrayOperations(node, path, operations, denseRegions.get(node));\n\t\t\telse emitObjectOperations(node, path, operations);\n\t\t\tif (operations.length > MAX_DELTA_OPERATIONS) {\n\t\t\t\tlocatedDenseArray = undefined;\n\t\t\t\treturn [[\"r\", cloneNode(context.root!)]];\n\t\t\t}\n\t\t}\n\t}\n\tlocatedDenseArray = undefined;\n\treturn operations;\n}\n\nfunction emitSimpleObjectOperations(context: OverlayContext): Op[] | undefined {\n\tconst nodes: OverlayNode[] = [];\n\tfor (const node of context.dirty) {\n\t\tif (Array.isArray(nodeBase(node)) || hasReservedMutation(node) || hasPlacementAncestor(node)) return undefined;\n\t\tfor (let parent = nodeParent(node); parent !== undefined; parent = nodeParent(parent)) {\n\t\t\tif (Array.isArray(nodeBase(parent))) return undefined;\n\t\t}\n\t\tconst path = resolvePath(node);\n\t\tif (path === undefined) continue;\n\t\tfor (const segment of path) {\n\t\t\tif (typeof segment === \"string\" && RESERVED_SEGMENTS.has(segment)) return undefined;\n\t\t}\n\t\tnodes.push(node);\n\t\tif (nodes.length > MAX_SIMPLE_OBJECT_NODES) return undefined;\n\t}\n\t// Stable insertion sort avoids comparator/bucket allocations for the usual\n\t// handful of dirty object nodes.\n\tfor (let index = 1; index < nodes.length; index++) {\n\t\tconst node = nodes[index]!;\n\t\tconst depth = node.preparedPath!.length;\n\t\tlet at = index;\n\t\twhile (at > 0 && nodes[at - 1]!.preparedPath!.length > depth) {\n\t\t\tnodes[at] = nodes[at - 1]!;\n\t\t\tat -= 1;\n\t\t}\n\t\tnodes[at] = node;\n\t}\n\tconst operations: Op[] = [];\n\tlet canMaterializeDirectly = true;\n\tfor (const node of nodes) {\n\t\tif (emitObjectOperations(node, node.preparedPath!, operations)) canMaterializeDirectly = false;\n\t\tif (operations.length > MAX_DELTA_OPERATIONS) return [[\"r\", cloneNode(context.root!)]];\n\t}\n\tcontext.simpleObjectMaterialization = canMaterializeDirectly;\n\treturn operations;\n}\n\nlet locatedDenseArray: OverlayNode | undefined;\nlet locatedDenseIndex = 0;\n\nfunction locateDenseArrayPosition(node: OverlayNode): boolean {\n\tlet child = node;\n\tfor (let parent = nodeParent(child); parent !== undefined; parent = nodeParent(child)) {\n\t\tif (Array.isArray(nodeBase(parent))) {\n\t\t\tconst overlay = arrayOverlay(parent);\n\t\t\tif (child.parentKind !== 1 || overlay.structural) return false;\n\t\t\tconst sourceIndex = child.parentKey as number;\n\t\t\tconst valueIndex = overlay.baseOverrides?.get(sourceIndex);\n\t\t\tconst current =\n\t\t\t\tvalueIndex === undefined\n\t\t\t\t\t? (nodeBase(parent) as JsonValue[])[sourceIndex]\n\t\t\t\t\t: storedValue(parent.context, valueIndex);\n\t\t\tif (current !== nodeBase(child)) return false;\n\t\t\tlocatedDenseArray = parent;\n\t\t\tlocatedDenseIndex = sourceIndex;\n\t\t\treturn true;\n\t\t}\n\t\tchild = parent;\n\t}\n\treturn false;\n}\n\nfunction hasCoveringDenseRegion(\n\tnode: OverlayNode,\n\tpath: Path,\n\tdenseRegions: ReadonlyMap<OverlayNode, readonly DenseRegion[]>,\n): boolean {\n\tfor (let parent = nodeParent(node); parent !== undefined; parent = nodeParent(parent)) {\n\t\tconst regions = denseRegions.get(parent);\n\t\tif (regions === undefined) continue;\n\t\tconst parentPath = resolvePath(parent);\n\t\tif (parentPath === undefined || path.length <= parentPath.length) continue;\n\t\tlet matches = true;\n\t\tfor (let index = 0; index < parentPath.length; index++) {\n\t\t\tif (path[index] !== parentPath[index]) {\n\t\t\t\tmatches = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!matches) continue;\n\t\tconst index = path[parentPath.length];\n\t\tif (typeof index === \"number\" && regionContaining(regions, index)) return true;\n\t}\n\treturn false;\n}\n\nfunction addDenseCandidate(candidates: DenseCandidates, index: number): void {\n\tif (candidates.bits !== undefined) {\n\t\tcandidates.bits[index] = 1;\n\t\treturn;\n\t}\n\tcandidates.indices.push(index);\n\tif (candidates.indices.length < 256) return;\n\tcandidates.bits = new Uint8Array(candidates.length);\n\tfor (const existing of candidates.indices) candidates.bits[existing] = 1;\n\tcandidates.indices.length = 0;\n}\n\nfunction recordDenseArrayPosition(node: OverlayNode, groups: Map<OverlayNode, DenseCandidates>): void {\n\tif (!locateDenseArrayPosition(node)) return;\n\tlet candidates = groups.get(locatedDenseArray!);\n\tif (candidates === undefined) {\n\t\tcandidates = { indices: [], bits: undefined, length: (nodeBase(locatedDenseArray!) as JsonValue[]).length };\n\t\tgroups.set(locatedDenseArray!, candidates);\n\t}\n\taddDenseCandidate(candidates, locatedDenseIndex);\n}\n\nfunction buildDenseRegions(candidates: DenseCandidates): DenseRegion[] {\n\tif (candidates.bits === undefined) return [];\n\tconst regions: DenseRegion[] = [];\n\tconst bits = candidates.bits;\n\tfor (let at = 0; at < bits.length; ) {\n\t\twhile (at < bits.length && bits[at] === 0) at += 1;\n\t\tif (at === bits.length) break;\n\t\tconst start = at;\n\t\tlet end = at;\n\t\tlet count = 0;\n\t\tlet gap = 0;\n\t\twhile (at < bits.length) {\n\t\t\tif (bits[at] !== 0) {\n\t\t\t\tcount += 1;\n\t\t\t\tend = at;\n\t\t\t\tgap = 0;\n\t\t\t} else if (++gap > 1) break;\n\t\t\tat += 1;\n\t\t}\n\t\tconst length = end - start + 1;\n\t\tif (count >= 256 && count * 2 >= length) regions.push({ start, length });\n\t}\n\treturn regions;\n}\n\nfunction regionContaining(regions: readonly DenseRegion[], index: number): boolean {\n\tfor (const region of regions) if (index >= region.start && index < region.start + region.length) return true;\n\treturn false;\n}\n\nfunction hasReservedMutation(node: OverlayNode): boolean {\n\tif (node.writeKey !== undefined && RESERVED_SEGMENTS.has(node.writeKey)) return true;\n\tif (node.deleteKey !== undefined && RESERVED_SEGMENTS.has(node.deleteKey)) return true;\n\tif (node.writes !== undefined) {\n\t\tfor (const key of node.writes.keys()) if (RESERVED_SEGMENTS.has(key)) return true;\n\t}\n\tif (node.deletes !== undefined) {\n\t\tfor (const key of node.deletes) if (RESERVED_SEGMENTS.has(key)) return true;\n\t}\n\treturn false;\n}\n\nfunction hasFoldedAncestor(node: OverlayNode, folded: ReadonlySet<OverlayNode>): boolean {\n\tfor (let parent = nodeParent(node); parent !== undefined; parent = nodeParent(parent))\n\t\tif (folded.has(parent)) return true;\n\treturn false;\n}\n\nfunction hasPlacementAncestor(node: OverlayNode): boolean {\n\tfor (let current: OverlayNode | undefined = node; current !== undefined; current = nodeParent(current)) {\n\t\tif (nodeParent(current) !== undefined && current.parentPlacement) return true;\n\t}\n\treturn false;\n}\n\nfunction emitObjectWrite(node: OverlayNode, path: Path, operations: Op[], key: string, value: Stored): boolean {\n\tconst nextPath = [...path, key] as unknown as NonEmptyPath;\n\tconst before =\n\t\tnode.readded?.has(key) || !Object.hasOwn(nodeBase(node), key)\n\t\t\t? undefined\n\t\t\t: (nodeBase(node) as Record<string, JsonValue>)[key];\n\tconst after = cloneStored(value, node.context);\n\tconst emitted = emitChangedValue(operations, nextPath, before, after);\n\treturn isContainer(before) && isContainer(after) && !emitted;\n}\n\nfunction emitObjectOperations(node: OverlayNode, path: Path, operations: Op[]): boolean {\n\t// Immutable replay must encode delete-and-readd explicitly so string-key\n\t// insertion order matches the draft.\n\tif (node.readded !== undefined) {\n\t\tfor (const key of node.readded) {\n\t\t\tif (Object.hasOwn(nodeBase(node), key)) operations.push([\"d\", [...path, key] as unknown as NonEmptyPath]);\n\t\t}\n\t}\n\tlet normalizedContainerWrite = false;\n\tif (node.writeKey !== undefined)\n\t\tnormalizedContainerWrite = emitObjectWrite(\n\t\t\tnode,\n\t\t\tpath,\n\t\t\toperations,\n\t\t\tnode.writeKey,\n\t\t\tobjectValue(node, node.writeKey),\n\t\t);\n\tif (node.writes !== undefined) {\n\t\tfor (const [key, valueIndex] of node.writes) {\n\t\t\tif (operations.length > MAX_DELTA_OPERATIONS) return normalizedContainerWrite;\n\t\t\tif (emitObjectWrite(node, path, operations, key, storedValue(node.context, valueIndex)))\n\t\t\t\tnormalizedContainerWrite = true;\n\t\t}\n\t}\n\tif (node.deleteKey !== undefined && Object.hasOwn(nodeBase(node), node.deleteKey)) {\n\t\toperations.push([\"d\", [...path, node.deleteKey] as unknown as NonEmptyPath]);\n\t}\n\tif (node.deletes !== undefined) {\n\t\tfor (const key of node.deletes) {\n\t\t\tif (operations.length > MAX_DELTA_OPERATIONS) return normalizedContainerWrite;\n\t\t\tif (Object.hasOwn(nodeBase(node), key)) operations.push([\"d\", [...path, key] as unknown as NonEmptyPath]);\n\t\t}\n\t}\n\treturn normalizedContainerWrite;\n}\n\nfunction buildArrayPlan(node: OverlayNode): ArrayPlan {\n\tconst overlay = arrayOverlay(node);\n\tif (overlay.plan !== undefined) return overlay.plan;\n\tconst base = nodeBase(node) as JsonValue[];\n\tconst pieces = piecesOf(overlay);\n\tconst retained = new Uint8Array(base.length);\n\tconst targetBase: number[] = [];\n\tfor (const piece of pieces) {\n\t\tif (piece.kind !== \"base\") continue;\n\t\tfor (let offset = 0; offset < piece.length; offset++) {\n\t\t\tconst index = piece.start + piece.step * offset;\n\t\t\tretained[index] = 1;\n\t\t\ttargetBase.push(index);\n\t\t}\n\t}\n\tconst removeRuns: number[] = [];\n\tfor (let end = base.length; end > 0; ) {\n\t\tif (retained[end - 1] !== 0) {\n\t\t\tend -= 1;\n\t\t\tcontinue;\n\t\t}\n\t\tlet start = end - 1;\n\t\twhile (start > 0 && retained[start - 1] === 0) start -= 1;\n\t\tremoveRuns.push(start, end - start);\n\t\tend = start;\n\t}\n\tconst retainedBase: number[] = [];\n\tfor (let index = 0; index < retained.length; index++) if (retained[index] !== 0) retainedBase.push(index);\n\tlet permutation: number[] | undefined;\n\tif (targetBase.some((value, index) => value !== retainedBase[index])) {\n\t\tconst positions = new Map(retainedBase.map((value, index) => [value, index]));\n\t\tpermutation = targetBase.map((value) => positions.get(value)!);\n\t}\n\tconst insertRuns: number[] = [];\n\tlet logicalIndex = 0;\n\tfor (let pieceIndex = 0; pieceIndex < pieces.length; ) {\n\t\tconst piece = pieces[pieceIndex]!;\n\t\tif (piece.kind === \"base\") {\n\t\t\tlogicalIndex += piece.length;\n\t\t\tpieceIndex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst startPiece = pieceIndex;\n\t\twhile (pieceIndex < pieces.length && pieces[pieceIndex]!.kind === \"insert\") {\n\t\t\tlogicalIndex += pieces[pieceIndex]!.length;\n\t\t\tpieceIndex += 1;\n\t\t}\n\t\tinsertRuns.push(logicalIndex - rangeLength(pieces, startPiece, pieceIndex), startPiece, pieceIndex);\n\t}\n\toverlay.plan = { removeRuns, permutation, insertRuns };\n\treturn overlay.plan;\n}\n\nfunction rangeLength(pieces: readonly Piece[], start: number, end: number): number {\n\tlet length = 0;\n\tfor (let index = start; index < end; index++) length += pieces[index]!.length;\n\treturn length;\n}\n\nfunction emitArrayOperations(\n\tnode: OverlayNode,\n\tpath: Path,\n\toperations: Op[],\n\tdenseRegions: readonly DenseRegion[] | undefined,\n): void {\n\tconst overlay = arrayOverlay(node);\n\tconst base = nodeBase(node) as JsonValue[];\n\tif (denseRegions !== undefined) {\n\t\tfor (const region of denseRegions) {\n\t\t\tif (operations.length > MAX_DELTA_OPERATIONS) return;\n\t\t\toperations.push([\"p\", path, region.start, region.length, cloneArrayRegion(node, region)]);\n\t\t}\n\t}\n\tif (overlay.structural) {\n\t\tconst plan = buildArrayPlan(node);\n\t\tfor (let index = 0; index < plan.removeRuns.length; index += 2) {\n\t\t\tif (operations.length > MAX_DELTA_OPERATIONS) return;\n\t\t\toperations.push([\"p\", path, plan.removeRuns[index]!, plan.removeRuns[index + 1]!, []]);\n\t\t}\n\t\tif (plan.permutation !== undefined) operations.push([\"m\", path, plan.permutation]);\n\t\tconst pieces = piecesOf(overlay);\n\t\tfor (let run = 0; run < plan.insertRuns.length; run += 3) {\n\t\t\tif (operations.length > MAX_DELTA_OPERATIONS) return;\n\t\t\tconst logicalIndex = plan.insertRuns[run]!;\n\t\t\tconst items: JsonValue[] = [];\n\t\t\tfor (let pieceIndex = plan.insertRuns[run + 1]!; pieceIndex < plan.insertRuns[run + 2]!; pieceIndex++) {\n\t\t\t\tconst piece = pieces[pieceIndex]! as InsertPiece;\n\t\t\t\tfor (let offset = 0; offset < piece.length; offset++) {\n\t\t\t\t\tconst sourceIndex = piece.start + piece.step * offset;\n\t\t\t\t\titems.push(cloneStored(entryValueAt(node, piece, sourceIndex), node.context));\n\t\t\t\t}\n\t\t\t}\n\t\t\toperations.push([\"p\", path, logicalIndex, 0, items]);\n\t\t}\n\t}\n\tfor (const [baseIndex, valueIndex] of overlay.baseOverrides ?? []) {\n\t\tif (operations.length > MAX_DELTA_OPERATIONS) return;\n\t\tconst index = findEntryIndex(overlay, 1, baseIndex, undefined);\n\t\tif (index === undefined || (denseRegions !== undefined && regionContaining(denseRegions, index))) continue;\n\t\temitChangedValue(\n\t\t\toperations,\n\t\t\t[...path, index] as unknown as NonEmptyPath,\n\t\t\tbase[baseIndex],\n\t\t\tcloneStored(storedValue(node.context, valueIndex), node.context),\n\t\t);\n\t}\n}\n\nfunction cloneArrayRegion(node: OverlayNode, region: DenseRegion): JsonValue[] {\n\tconst overlay = arrayOverlay(node);\n\tconst result: JsonValue[] = [];\n\tfor (let index = region.start; index < region.start + region.length; index++) {\n\t\tconst piece = locatePiece(overlay, index);\n\t\tconst sourceIndex = piece.start + piece.step * overlay.locatedOffset;\n\t\tresult.push(cloneStored(entryValueAt(node, piece, sourceIndex), node.context));\n\t}\n\treturn result;\n}\n\nfunction emitChangedValue(\n\toperations: Op[],\n\tpath: NonEmptyPath,\n\tbefore: JsonValue | undefined,\n\tafter: JsonValue,\n): boolean {\n\tif (!isContainer(after) && before === after) return false;\n\tif (isContainer(before) && isContainer(after) && equalTrustedJson(before, after)) return false;\n\tif (typeof before === \"string\" && typeof after === \"string\") {\n\t\t// Slice/equality stays on V8's rope fast path; startsWith scans the entire\n\t\t// accumulated prefix on every append.\n\t\tif (after.length > before.length && after.slice(0, before.length) === before) {\n\t\t\toperations.push([\"a\", path, after.slice(before.length)]);\n\t\t\treturn true;\n\t\t}\n\t\tconst shared = overlap(before, after, 65_536);\n\t\tif (shared > 0) {\n\t\t\toperations.push([\"t\", path, before.length - shared]);\n\t\t\tif (after.length > shared) operations.push([\"a\", path, after.slice(shared)]);\n\t\t\treturn true;\n\t\t}\n\t}\n\toperations.push([\"s\", path, after]);\n\treturn true;\n}\n\nfunction emitSet(operations: Op[], path: Path, value: JsonValue): void {\n\tif (path.length === 0) operations.push([\"r\", value]);\n\telse operations.push([\"s\", path as NonEmptyPath, value]);\n}\n\nfunction resolvePath(node: OverlayNode): Path | undefined {\n\tif (node.preparedPath !== undefined) return node.preparedPath;\n\tconst parent = nodeParent(node);\n\tif (parent === undefined) {\n\t\tnode.preparedPath = [];\n\t\treturn node.preparedPath;\n\t}\n\tconst parentPath = resolvePath(parent);\n\tif (parentPath === undefined) return undefined;\n\tif (node.parentKind === 0) {\n\t\tconst key = node.parentKey as string;\n\t\tif (!objectHas(parent, key) || objectValue(parent, key) !== nodeBase(node)) return undefined;\n\t\tnode.preparedPath = [...parentPath, key];\n\t\treturn node.preparedPath;\n\t}\n\tconst overlay = arrayOverlay(parent);\n\tconst index = findEntryIndex(overlay, node.parentKind, node.parentKey as number, node.parentSource);\n\tif (index === undefined) return undefined;\n\tconst piece = locatePiece(overlay, index);\n\tif (entryValueAt(parent, piece, node.parentKey as number) !== nodeBase(node)) return undefined;\n\tnode.preparedPath = [...parentPath, index];\n\treturn node.preparedPath;\n}\n\nfunction ensurePieceLocations(overlay: ArrayOverlay): void {\n\tif (overlay.baseLocations !== undefined) return;\n\toverlay.baseLocations = [];\n\toverlay.insertLocations = new Map();\n\tlet logicalStart = 0;\n\tfor (const piece of piecesOf(overlay)) {\n\t\tconst last = piece.start + piece.step * (piece.length - 1);\n\t\tconst location = {\n\t\t\tpiece,\n\t\t\tlogicalStart,\n\t\t\tminimum: Math.min(piece.start, last),\n\t\t\tmaximum: Math.max(piece.start, last),\n\t\t};\n\t\tif (piece.kind === \"base\") overlay.baseLocations.push(location);\n\t\telse {\n\t\t\tlet locations = overlay.insertLocations.get(piece.source);\n\t\t\tif (locations === undefined) {\n\t\t\t\tlocations = [];\n\t\t\t\toverlay.insertLocations.set(piece.source, locations);\n\t\t\t}\n\t\t\tlocations.push(location);\n\t\t}\n\t\tlogicalStart += piece.length;\n\t}\n\tconst byMinimum = (left: PieceLocation, right: PieceLocation): number => left.minimum - right.minimum;\n\toverlay.baseLocations.sort(byMinimum);\n\tfor (const locations of overlay.insertLocations.values()) locations.sort(byMinimum);\n}\n\nfunction findEntryIndex(\n\toverlay: ArrayOverlay,\n\tkind: ParentKind,\n\tsourceIndex: number,\n\tsource: InsertSource | undefined,\n): number | undefined {\n\tif (kind === 1 && !overlay.structural) return sourceIndex;\n\tensurePieceLocations(overlay);\n\tconst locations = kind === 1 ? overlay.baseLocations! : overlay.insertLocations!.get(source!);\n\tif (locations === undefined) return undefined;\n\tlet low = 0;\n\tlet high = locations.length;\n\twhile (low < high) {\n\t\tconst middle = (low + high) >>> 1;\n\t\tif (locations[middle]!.minimum <= sourceIndex) low = middle + 1;\n\t\telse high = middle;\n\t}\n\tconst location = locations[low - 1];\n\tif (location === undefined || sourceIndex > location.maximum) return undefined;\n\tconst offset = (sourceIndex - location.piece.start) / location.piece.step;\n\treturn offset >= 0 && offset < location.piece.length ? location.logicalStart + offset : undefined;\n}\n\nfunction ensureOperations(context: OverlayContext): Op[] {\n\tif (context.ops !== undefined) return context.ops;\n\tassertReadable(context);\n\tif (context.replacement) {\n\t\tconst base = context.tracker.deref()?.replacementBase(context);\n\t\tcontext.replacementNoop =\n\t\t\tbase !== undefined && equalTrustedJson(base as unknown as JsonValue, nodeBase(context.root!) as JsonValue);\n\t\tcontext.ops = context.replacementNoop ? [] : [[\"r\", nodeBase(context.root!)]];\n\t} else context.ops = emitOperations(context);\n\treturn context.ops;\n}\n\nfunction equalTrustedJson(left: JsonValue, right: JsonValue): boolean {\n\tif (left === right) return true;\n\tif (!isContainer(left) || !isContainer(right) || Array.isArray(left) !== Array.isArray(right)) return false;\n\tif (Array.isArray(left)) {\n\t\tconst other = right as JsonValue[];\n\t\tif (left.length !== other.length) return false;\n\t\tfor (let index = 0; index < left.length; index++)\n\t\t\tif (!equalTrustedJson(left[index]!, other[index]!)) return false;\n\t\treturn true;\n\t}\n\tconst other = right as Record<string, JsonValue>;\n\tconst keys = Object.keys(left);\n\tif (keys.length !== Object.keys(other).length) return false;\n\tfor (const key of keys) if (!Object.hasOwn(other, key) || !equalTrustedJson(left[key]!, other[key]!)) return false;\n\treturn true;\n}\n\nfunction abortContext(context: OverlayContext): void {\n\tif (context.status.value === \"aborted\" || context.status.value === \"consumed\" || context.status.value === \"stale\")\n\t\treturn;\n\tcontext.status.value = \"aborted\";\n\tclearContext(context);\n}\n\nfunction releaseOverlayReferences(context: OverlayContext): void {\n\tcontext.tracker.deref()?.releaseContext(context);\n\tif (locatedDenseArray?.context === context) locatedDenseArray = undefined;\n\tcontext.overlayReleased = true;\n\tcontext.dirty.length = 0;\n\tcontext.nodes.length = 0;\n\tcontext.rawNodes = undefined;\n\tcontext.ops = undefined;\n\tcontext.root = undefined;\n\tcontext.bases = undefined;\n\tcontext.stored = undefined;\n\tcontext.baseValue = undefined;\n}\n\nfunction clearContext(context: OverlayContext): void {\n\tcontext.tracker.deref()?.releaseContext(context);\n\tif (locatedDenseArray?.context === context) locatedDenseArray = undefined;\n\tfor (const node of context.nodes) {\n\t\tif (Array.isArray(node.target)) node.target.length = 0;\n\t\tReflect.deleteProperty(node.target, NODE);\n\t\tnode.writes?.clear();\n\t\tnode.deletes?.clear();\n\t\tnode.readded?.clear();\n\t\tif (node.array?.pieces !== undefined) node.array.pieces.length = 0;\n\t\tif (node.array !== undefined) {\n\t\t\tnode.array.root = undefined;\n\t\t\tnode.array.baseLocations = undefined;\n\t\t\tnode.array.insertLocations = undefined;\n\t\t}\n\t\tnode.array?.baseOverrides?.clear();\n\t\tnode.array?.insertOverrides?.clear();\n\t\tnode.parentSource = undefined;\n\t\tnode.target = RELEASED;\n\t\tnode.proxy = RELEASED;\n\t\tnode.writeKey = undefined;\n\t\tnode.writeValue = undefined;\n\t\tnode.writes = undefined;\n\t\tnode.deleteKey = undefined;\n\t\tnode.deletes = undefined;\n\t\tnode.readded = undefined;\n\t\tnode.array = undefined;\n\t\tnode.subtreeDirty = undefined;\n\t\tnode.preparedPath = undefined;\n\t}\n\tcontext.dirty.length = 0;\n\tcontext.nodes.length = 0;\n\tcontext.rawNodes = undefined;\n\tcontext.ops = undefined;\n\tcontext.root = undefined;\n\tcontext.bases = undefined;\n\tcontext.stored = undefined;\n\tcontext.baseValue = undefined;\n\tcontext.overlayReleased = true;\n}\n\nfunction isContainer(value: unknown): value is Container {\n\treturn value !== null && typeof value === \"object\";\n}\n", "import type { JsonValue } from \"../types.ts\";\n\nexport type { JsonValue } from \"../types.ts\";\n\nconst isObj = (value: unknown): value is object => value !== null && typeof value === \"object\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// chord/delta — immutable revision tracking and operations over plain JSON.\n//\n// Depends on nothing else in the harness. Session storage, the runtime and the\n// facet host consume it; keep the arrows pointing that way.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type Seg = string | number;\nexport type Path = readonly Seg[];\nexport type NonEmptyPath = readonly [Seg, ...Seg[]];\n\n/** A path inline, or an id assigned by the encoder on second use. */\nexport type PathRef<P extends Path = Path> = P | number;\n\n/**\n * Tuples are the form — in memory, on the wire, on disk.\n *\n * `r` is the ONLY op that replaces a whole value. `s`/`d`/`a`/`t` cannot target\n * the root: the type forbids it. `p` and `m` may, because a tracked value can\n * itself be an array. Operation shape is not canonical: an array may be emptied by either\n * a replacement or a root splice.\n *\n * `Op` knows nothing about the path dictionary. Interning, id references and\n * omitted paths live in `WireOp` and exist only between `encode` and `decode`.\n */\nexport type Op =\n\t| readonly [\"r\", JsonValue]\n\t| readonly [\"s\", NonEmptyPath, JsonValue]\n\t| readonly [\"d\", NonEmptyPath]\n\t| readonly [\"a\", NonEmptyPath, string]\n\t| readonly [\"t\", NonEmptyPath, number]\n\t| readonly [\"p\", Path, number, number, JsonValue[]]\n\t/** Reorder an array in place: `new[i] = old[permutation[i]]`. */\n\t| readonly [\"m\", Path, number[]];\n\n/**\n * What crosses a boundary. Adds two compressions and nothing else:\n *\n * [\"#\", id, path] defines an id, emitted on a path's SECOND use\n * a numeric PathRef references a previously defined id\n * a shortened tuple reuses the previous op's path; arity disambiguates\n *\n * [\"r\", value] carries no path, so it encodes to itself — which is why isBase\n * works unchanged on either vocabulary.\n */\nexport type WireOp =\n\t| readonly [\"r\", JsonValue]\n\t| readonly [\"s\", PathRef<NonEmptyPath>, JsonValue]\n\t| readonly [\"s\", JsonValue]\n\t| readonly [\"d\", PathRef<NonEmptyPath>]\n\t| readonly [\"d\"]\n\t| readonly [\"a\", PathRef<NonEmptyPath>, string]\n\t| readonly [\"a\", string]\n\t| readonly [\"t\", PathRef<NonEmptyPath>, number]\n\t| readonly [\"t\", number]\n\t| readonly [\"p\", PathRef, number, number, JsonValue[]]\n\t| readonly [\"p\", number, number, JsonValue[]]\n\t| readonly [\"m\", PathRef, number[]]\n\t| readonly [\"m\", number[]]\n\t| readonly [\"#\", number, Path];\n\n// ─── Classification ──────────────────────────────────────────────────────────\n\nexport const isReplace = (op: Op | WireOp): boolean => op[0] === \"r\";\n\n/**\n * A batch begins with a replacement. Flush guarantees `r` is at index 0 or absent,\n * so this is exact rather than a heuristic.\n */\nexport const isBase = (ops: readonly (Op | WireOp)[]): boolean => ops.length > 0 && ops[0]![0] === \"r\";\n\n// ─── Overlap ─────────────────────────────────────────────────────────────────\n\n/**\n * Longest suffix of `a` that is a prefix of `b`. Probes with indexOf and verifies\n * exact substring equality, so the hot loops are native. A hand-written KMP is\n * asymptotically equivalent and much slower in practice.\n *\n * Always correct: the returned n satisfies a.slice(a.length - n) === b.slice(0, n).\n */\nexport function overlap(a: string, b: string, scan: number, probe = 64, maxCandidates = 8): number {\n\tif (a.length === 0 || b.length === 0 || scan === 0) return 0;\n\tconst tail = a.length > scan ? a.slice(a.length - scan) : a;\n\n\t// A probe of length h can only find overlaps of at least h — the head must\n\t// actually occur in `a`. So try a long head first (few candidates, and it\n\t// catches the large overlaps a rolling window produces), then fall back to one\n\t// character, which finds any overlap at the cost of more candidates.\n\t//\n\t// Candidates are bounded because repetitive output — a build log, or any run of\n\t// one character — makes a long head match at thousands of positions. Giving up\n\t// returns 0, which emits a set: larger, never wrong.\n\tfor (const h of [Math.min(probe, b.length), 1]) {\n\t\tconst head = b.slice(0, h);\n\t\tlet tried = 0;\n\t\tfor (let k = tail.indexOf(head); k !== -1; k = tail.indexOf(head, k + 1)) {\n\t\t\tif (++tried > maxCandidates) break;\n\t\t\tconst n = tail.length - k;\n\t\t\tif (n <= b.length && tail.slice(k) === b.slice(0, n)) return n;\n\t\t}\n\t\tif (h === 1) break;\n\t}\n\treturn 0;\n}\n\n// ─── Immutable revision tracking ─────────────────────────────────────────────\n\nexport { diffRevisions } from \"./diff.ts\";\nexport type { Draft } from \"./draft.ts\";\nexport { type Change, type Prepared, type Tracker, track } from \"./tracker.ts\";\n\n// ─── Path safety ─────────────────────────────────────────────────────────────\n\n/**\n * Segments that reach the prototype chain.\n *\n * `JSON.parse` is safe on its own — it makes `__proto__` an own property. What is\n * not safe is `parent[key] = value`, which is exactly what an applier does, and\n * paths are data: `[\"s\", [\"__proto__\", \"isAdmin\"], true]` pollutes\n * `Object.prototype` for the whole process.\n *\n * Ops arrive from a facet, a plugin compartment, or a tool whose details may echo\n * model output, so none of it is trusted input.\n */\nexport const RESERVED_SEGMENTS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nexport class UnsafePathError extends Error {\n\t// Not a parameter property: Node's --experimental-strip-types rejects those,\n\t// and these files are meant to run under it directly.\n\treadonly segment: Seg;\n\tconstructor(segment: Seg) {\n\t\tsuper(`unsafe path segment: ${String(segment)}`);\n\t\tthis.segment = segment;\n\t\tthis.name = \"UnsafePathError\";\n\t}\n}\n\n/**\n * Verb, arity and payload shape for a **decoded** op: paths inline, no `#`, no\n * short forms. `apply` uses this.\n *\n * Validating `Op` against the wire grammar would be laxer than the type: a\n * two-element `[\"s\", value]` would pass, and `apply` would then read the value as\n * a path. Each vocabulary gets the validator that matches it.\n */\nexport function assertValidOp(op: unknown): asserts op is Op {\n\tif (!Array.isArray(op) || op.length === 0) throw new TypeError(\"op is not a tuple\");\n\tswitch (op[0]) {\n\t\tcase \"r\":\n\t\t\tif (op.length !== 2) throw new TypeError(\"r arity\");\n\t\t\treturn;\n\t\tcase \"s\":\n\t\t\tif (op.length !== 3) throw new TypeError(\"s arity\");\n\t\t\tassertPathArg(op[1], true);\n\t\t\treturn;\n\t\tcase \"d\":\n\t\t\tif (op.length !== 2) throw new TypeError(\"d arity\");\n\t\t\tassertPathArg(op[1], true);\n\t\t\treturn;\n\t\tcase \"a\":\n\t\t\tif (op.length !== 3 || typeof op[2] !== \"string\") throw new TypeError(\"a shape\");\n\t\t\tassertPathArg(op[1], true);\n\t\t\treturn;\n\t\tcase \"t\":\n\t\t\tif (op.length !== 3 || !Number.isInteger(op[2]) || op[2] < 0) throw new TypeError(\"t shape\");\n\t\t\tassertPathArg(op[1], true);\n\t\t\treturn;\n\t\tcase \"p\": {\n\t\t\tif (op.length !== 5) throw new TypeError(\"p arity\");\n\t\t\tassertPathArg(op[1]);\n\t\t\tif (!Number.isInteger(op[2]) || op[2] < 0) throw new TypeError(\"p index\");\n\t\t\tif (!Number.isInteger(op[3]) || op[3] < 0) throw new TypeError(\"p remove\");\n\t\t\tif (!Array.isArray(op[4])) throw new TypeError(\"p items\");\n\t\t\treturn;\n\t\t}\n\t\tcase \"m\":\n\t\t\tif (op.length !== 3) throw new TypeError(\"m arity\");\n\t\t\tassertPathArg(op[1]);\n\t\t\tassertPermutation(op[2]);\n\t\t\treturn;\n\t\t// Silently skipping an unknown verb is how a newer producer's op vanishes.\n\t\tdefault:\n\t\t\tthrow new TypeError(`unknown op verb: ${String(op[0])}`);\n\t}\n}\n\nfunction assertPathArg(p: unknown, nonEmpty = false): void {\n\tif (!Array.isArray(p)) throw new TypeError(\"path is not an array\");\n\tif (nonEmpty && p.length === 0) throw new TypeError(\"path is empty\");\n\tassertSafePath(p as Path);\n}\n\nfunction assertPermutation(value: unknown): asserts value is number[] {\n\tif (!Array.isArray(value)) throw new TypeError(\"m permutation is not an array\");\n\tconst seen = new Uint8Array(value.length);\n\tfor (const index of value) {\n\t\tif (!Number.isInteger(index) || index < 0 || index >= value.length || seen[index] !== 0) {\n\t\t\tthrow new TypeError(\"m permutation is not a bijection\");\n\t\t}\n\t\tseen[index] = 1;\n\t}\n}\n\n/** The same, for the wire grammar: ids and short forms are legal here. */\nexport function assertValidWireOp(op: unknown): asserts op is WireOp {\n\tif (!Array.isArray(op) || op.length === 0) throw new TypeError(\"op is not a tuple\");\n\tconst [verb] = op as unknown[];\n\tconst okRef = (r: unknown): void => {\n\t\tif (typeof r === \"number\") {\n\t\t\tif (!Number.isInteger(r) || r < 0) throw new TypeError(\"bad path id\");\n\t\t\treturn;\n\t\t}\n\t\t// A string is not a path. Unchecked, `\"a\".slice(0, -1)` is `\"\"`, so it\n\t\t// resolves to the ROOT and writes there — a path that is not a path, accepted.\n\t\tif (!Array.isArray(r)) throw new TypeError(\"path is not an array\");\n\t\tassertSafePath(r as Path);\n\t};\n\tswitch (verb) {\n\t\tcase \"r\":\n\t\t\tif (op.length !== 2) throw new TypeError(\"r arity\");\n\t\t\treturn;\n\t\tcase \"s\":\n\t\t\tif (op.length === 3) okRef(op[1]);\n\t\t\telse if (op.length !== 2) throw new TypeError(\"s arity\");\n\t\t\treturn;\n\t\tcase \"d\":\n\t\t\tif (op.length === 2) okRef(op[1]);\n\t\t\telse if (op.length !== 1) throw new TypeError(\"d arity\");\n\t\t\treturn;\n\t\tcase \"a\":\n\t\t\tif (op.length === 3) {\n\t\t\t\tokRef(op[1]);\n\t\t\t\tif (typeof op[2] !== \"string\") throw new TypeError(\"a value\");\n\t\t\t} else if (op.length === 2) {\n\t\t\t\tif (typeof op[1] !== \"string\") throw new TypeError(\"a value\");\n\t\t\t} else throw new TypeError(\"a arity\");\n\t\t\treturn;\n\t\tcase \"t\":\n\t\t\tif (op.length === 3) {\n\t\t\t\tokRef(op[1]);\n\t\t\t\tif (!Number.isInteger(op[2]) || (op[2] as number) < 0) throw new TypeError(\"t count\");\n\t\t\t} else if (op.length === 2) {\n\t\t\t\tif (!Number.isInteger(op[1]) || (op[1] as number) < 0) throw new TypeError(\"t count\");\n\t\t\t} else throw new TypeError(\"t arity\");\n\t\t\treturn;\n\t\tcase \"p\": {\n\t\t\tconst [i, r, items] = op.length === 5 ? [op[2], op[3], op[4]] : op.length === 4 ? [op[1], op[2], op[3]] : [];\n\t\t\tif (items === undefined) throw new TypeError(\"p arity\");\n\t\t\tif (op.length === 5) okRef(op[1]);\n\t\t\tif (!Number.isInteger(i) || (i as number) < 0) throw new TypeError(\"p index\");\n\t\t\tif (!Number.isInteger(r) || (r as number) < 0) throw new TypeError(\"p remove\");\n\t\t\tif (!Array.isArray(items)) throw new TypeError(\"p items\");\n\t\t\treturn;\n\t\t}\n\t\tcase \"m\":\n\t\t\tif (op.length === 3) okRef(op[1]);\n\t\t\telse if (op.length !== 2) throw new TypeError(\"m arity\");\n\t\t\tassertPermutation(op[op.length - 1]);\n\t\t\treturn;\n\t\tcase \"#\": {\n\t\t\tif (op.length !== 3 || !Number.isInteger(op[1]) || (op[1] as number) < 0 || !Array.isArray(op[2])) {\n\t\t\t\tthrow new TypeError(\"# shape\");\n\t\t\t}\n\t\t\tassertSafePath(op[2] as Path);\n\t\t\treturn;\n\t\t}\n\t\t// Silently skipping an unknown verb is how a newer producer's op vanishes.\n\t\tdefault:\n\t\t\tthrow new TypeError(`unknown op verb: ${String(verb)}`);\n\t}\n}\n\nexport function assertSafePath(path: Path): void {\n\tfor (const seg of path) {\n\t\tif (typeof seg === \"string\") {\n\t\t\tif (RESERVED_SEGMENTS.has(seg)) throw new UnsafePathError(seg);\n\t\t} else if (!Number.isInteger(seg) || seg < 0) {\n\t\t\tthrow new UnsafePathError(seg);\n\t\t}\n\t}\n}\n\n/**\n * An index may address an existing element or append exactly one past the end.\n *\n * This is not an arbitrary cap — it is what keeps the value a `JsonValue`. A\n * sparse array does not survive a JSON round trip: holes serialise to `null` and\n * return as real properties, so `arr[7] = x` on a length-3 array already produces\n * state a replica cannot match. Rejecting the write is more honest than silently\n * diverging.\n *\n * It also removes the denial of service it would otherwise permit:\n * `[\"s\", [\"xs\", 4294967290], 1]` allocates a 4.29-billion-entry array from one op.\n * Growth stays possible and stays proportional — the tracker already emits\n * `arr.length = n` as a splice of explicit nulls, whose op size grows with the\n * gap, so a large growth costs a large op rather than a small one.\n */\nfunction assertIndexInRange(parent: readonly unknown[], index: number): void {\n\tif (index > parent.length) throw new UnsafePathError(index);\n}\n\n// ─── Applier ─────────────────────────────────────────────────────────────────\n\nexport class PathError extends Error {\n\treadonly path: Path | number;\n\tconstructor(path: Path | number) {\n\t\tsuper(`unresolvable path: ${JSON.stringify(path)}`);\n\t\tthis.path = path;\n\t\tthis.name = \"PathError\";\n\t}\n}\n\n/**\n * Apply ops to a plain mutable value. Returns the value, because `r` replaces it\n * outright and cannot be done in place.\n *\n * Takes decoded ops. Path ids and omitted paths are a wire concern — run\n * `decode` first if the ops came from a boundary.\n */\nexport function apply<T>(target: T | undefined, ops: readonly Op[]): T {\n\treturn applyOps(target, ops);\n}\n\nfunction applyOps<T>(target: T | undefined, ops: readonly Op[]): T {\n\tlet root = target as unknown as JsonValue;\n\n\tfor (const op of ops) {\n\t\tassertValidOp(op);\n\t\tif (op[0] === \"r\") {\n\t\t\t// Adopted, not copied. The consumer owns the batch it was handed.\n\t\t\t//\n\t\t\t// Fanning one batch out to several consumers in-process therefore makes\n\t\t\t// their replicas alias each other. That is an ownership rule, not a\n\t\t\t// defect: copy the batch at the fan-out point, or let each consumer\n\t\t\t// decode its own. A batch that crosses a real boundary is already\n\t\t\t// distinct, because serialisation produces fresh objects.\n\t\t\troot = op[1];\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst path = op[1];\n\t\tassertSafePath(path);\n\n\t\tif (op[0] === \"p\") {\n\t\t\tconst target_ = path.length === 0 ? root : resolve(root, path);\n\t\t\tif (!Array.isArray(target_)) throw new PathError(path);\n\t\t\ttarget_.splice(op[2], op[3]);\n\t\t\tconst chunkSize = 10_000;\n\t\t\tfor (let offset = 0; offset < op[4].length; offset += chunkSize) {\n\t\t\t\ttarget_.splice(op[2] + offset, 0, ...op[4].slice(offset, offset + chunkSize));\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (op[0] === \"m\") {\n\t\t\tconst target_ = path.length === 0 ? root : resolve(root, path);\n\t\t\tif (!Array.isArray(target_) || target_.length !== op[2].length) throw new PathError(path);\n\t\t\tconst previous = target_.slice();\n\t\t\tfor (let index = 0; index < op[2].length; index++) target_[index] = previous[op[2][index]!]!;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// s/d/a/t can never target the root — the type forbids it.\n\t\tconst parent = resolve(root, path.slice(0, -1)) as Record<Seg, JsonValue>;\n\t\tconst key = path[path.length - 1]!;\n\t\tif (Array.isArray(parent)) {\n\t\t\tif (typeof key !== \"number\") throw new UnsafePathError(key);\n\t\t\tassertIndexInRange(parent, key);\n\t\t}\n\t\t// defineProperty rather than assignment: a setter inherited from the prototype\n\t\t// chain would otherwise run on write.\n\t\tconst write = (value: JsonValue) => {\n\t\t\tObject.defineProperty(parent, key, { value, writable: true, enumerable: true, configurable: true });\n\t\t};\n\t\tconst read = (): unknown => (Object.hasOwn(parent, key) ? parent[key] : undefined);\n\t\tswitch (op[0]) {\n\t\t\tcase \"s\":\n\t\t\t\twrite(op[2]);\n\t\t\t\tbreak;\n\t\t\tcase \"d\":\n\t\t\t\tif (Array.isArray(parent)) {\n\t\t\t\t\tif (typeof key !== \"number\" || key >= parent.length) throw new PathError(path);\n\t\t\t\t\t(parent as unknown as JsonValue[]).splice(key, 1);\n\t\t\t\t} else delete parent[key];\n\t\t\t\tbreak;\n\t\t\tcase \"a\": {\n\t\t\t\tconst current = read();\n\t\t\t\tif (typeof current !== \"string\") throw new PathError(path);\n\t\t\t\twrite(`${current}${op[2]}`);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"t\": {\n\t\t\t\tconst current = read();\n\t\t\t\tif (typeof current !== \"string\") throw new PathError(path);\n\t\t\t\twrite(current.slice(op[2]));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn root as unknown as T;\n}\n\n/** Apply one decoded operation batch without mutating the previous immutable value. */\nexport function applyImmutable<T>(target: T | undefined, ops: readonly Op[]): T {\n\treturn applyImmutableBatches(target, [ops]);\n}\n\n/**\n * Apply decoded operation batches as one final-result-only replay.\n *\n * Containers copied for an earlier batch may be mutated while applying a later\n * batch, so this deliberately exposes no intermediate revisions.\n */\nexport function applyImmutableBatches<T>(target: T | undefined, batches: Iterable<readonly Op[]>): T {\n\tlet root = target as unknown as JsonValue;\n\tconst owned = new WeakSet<object>();\n\tfor (const ops of batches) {\n\t\tfor (const op of ops) {\n\t\t\tassertValidOp(op);\n\t\t\tif (op[0] === \"r\") {\n\t\t\t\troot = op[1];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\troot = copyContainers(root, op[0] === \"p\" || op[0] === \"m\" ? op[1] : op[1].slice(0, -1), owned);\n\t\t\troot = applyOps(root, [op]);\n\t\t}\n\t}\n\treturn root as unknown as T;\n}\n\nfunction copyContainers(root: JsonValue, path: Path, owned: WeakSet<object>): JsonValue {\n\tconst copy = (value: JsonValue): JsonValue[] | Record<string, JsonValue> => {\n\t\tif (Array.isArray(value)) return value.slice();\n\t\tif (!isObj(value)) throw new PathError(path);\n\t\tconst result = Object.create(Object.getPrototypeOf(value) === null ? null : Object.prototype) as Record<\n\t\t\tstring,\n\t\t\tJsonValue\n\t\t>;\n\t\tfor (const key of Object.keys(value)) {\n\t\t\tObject.defineProperty(result, key, {\n\t\t\t\tvalue: (value as Record<string, JsonValue>)[key],\n\t\t\t\twritable: true,\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t};\n\tif (!isObj(root)) throw new PathError(path);\n\tlet copiedRoot: JsonValue[] | Record<string, JsonValue>;\n\tif (owned.has(root)) copiedRoot = root as JsonValue[] | Record<string, JsonValue>;\n\telse {\n\t\tcopiedRoot = copy(root);\n\t\towned.add(copiedRoot);\n\t}\n\tlet destination = copiedRoot;\n\tfor (const segment of path) {\n\t\tif (!Object.hasOwn(destination, segment)) throw new PathError(path);\n\t\tif (Array.isArray(destination) && typeof segment !== \"number\") throw new UnsafePathError(segment);\n\t\tconst child = (destination as Record<Seg, JsonValue>)[segment]!;\n\t\tif (!isObj(child)) throw new PathError(path);\n\t\tif (owned.has(child)) {\n\t\t\tdestination = child as JsonValue[] | Record<string, JsonValue>;\n\t\t\tcontinue;\n\t\t}\n\t\tconst copiedChild = copy(child);\n\t\tObject.defineProperty(destination, segment, {\n\t\t\tvalue: copiedChild,\n\t\t\twritable: true,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t\towned.add(copiedChild);\n\t\tdestination = copiedChild;\n\t}\n\treturn copiedRoot;\n}\n\nfunction resolveValue(root: JsonValue, path: Path): JsonValue {\n\tlet node: JsonValue = root;\n\tfor (const seg of path) {\n\t\tif (!isObj(node)) throw new PathError(path);\n\t\tif (Array.isArray(node) && typeof seg !== \"number\") throw new UnsafePathError(seg);\n\t\t// Own properties only: an inherited getter must not run, and a walk must not\n\t\t// escape the value into the prototype chain.\n\t\tif (!Object.hasOwn(node, seg as PropertyKey)) throw new PathError(path);\n\t\tnode = (node as Record<Seg, JsonValue>)[seg]!;\n\t}\n\treturn node;\n}\n\nfunction resolve(root: JsonValue, path: Path): JsonValue {\n\tconst node = resolveValue(root, path);\n\tif (!isObj(node)) throw new PathError(path);\n\treturn node;\n}\n\n// ─── Codec ───────────────────────────────────────────────────────────────────\n//\n// Path interning and arity omission live between the tracker and a boundary;\n// `Op` and `apply` know nothing about them.\n//\n// ONE PAIR PER INDEPENDENT STATE STREAM. Every decoder must observe exactly the\n// batches encoded by its matching encoder, beginning with that state's base.\n// Sharing a transport connection does not make separately hydrated states one\n// stream.\n\nconst pathKey = (path: Path): string => JSON.stringify(path);\n\nexport interface Encoder {\n\tencode(ops: readonly Op[]): WireOp[];\n}\n\n/**\n * Intern on SECOND use. A definition costs more than the path it replaces, so\n * interning on first use loses on the many paths written exactly once.\n */\nexport function encoder(): Encoder {\n\tconst seen = new Set<string>();\n\tconst ids = new Map<string, number>();\n\tlet nextId = 0;\n\tlet previous: string | undefined; // last path in THIS batch\n\n\treturn {\n\t\tencode(ops) {\n\t\t\t// Arity omission is scoped to a batch. Letting it span batches would make\n\t\t\t// a batch's first op depend on the previous batch's last one, so a reader\n\t\t\t// that skips or reorders a batch decodes into the wrong path. Ids are the\n\t\t\t// only cross-batch state, and the dictionary makes those explicit.\n\t\t\tprevious = undefined;\n\t\t\tconst out: WireOp[] = [];\n\t\t\tfor (const op of ops) {\n\t\t\t\tif (op[0] === \"r\") {\n\t\t\t\t\tout.push(op);\n\t\t\t\t\t// A base batch is a RECOVERY POINT: a reader replays from the last one\n\t\t\t\t\t// with a fresh decoder. So everything after it must be self-contained.\n\t\t\t\t\t// Keeping ids across a replacement emits references to definitions the\n\t\t\t\t\t// reader never saw — recovery fails with an unresolvable path id.\n\t\t\t\t\tseen.clear();\n\t\t\t\t\tids.clear();\n\t\t\t\t\tnextId = 0;\n\t\t\t\t\tprevious = undefined;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst path = op[1];\n\t\t\t\tconst key = pathKey(path);\n\n\t\t\t\t// Same path as the previous op: drop the ref entirely.\n\t\t\t\tif (key === previous) {\n\t\t\t\t\tswitch (op[0]) {\n\t\t\t\t\t\tcase \"s\":\n\t\t\t\t\t\t\tout.push([\"s\", op[2]]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"d\":\n\t\t\t\t\t\t\tout.push([\"d\"]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"a\":\n\t\t\t\t\t\t\tout.push([\"a\", op[2]]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"t\":\n\t\t\t\t\t\t\tout.push([\"t\", op[2]]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"p\":\n\t\t\t\t\t\t\tout.push([\"p\", op[2], op[3], op[4]]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"m\":\n\t\t\t\t\t\t\tout.push([\"m\", op[2]]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tlet ref: PathRef = path;\n\t\t\t\tconst existing = ids.get(key);\n\t\t\t\tif (existing !== undefined) {\n\t\t\t\t\tref = existing;\n\t\t\t\t} else if (seen.has(key)) {\n\t\t\t\t\tconst id = nextId++;\n\t\t\t\t\tids.set(key, id);\n\t\t\t\t\tout.push([\"#\", id, path]); // second use: define, then reference\n\t\t\t\t\tref = id;\n\t\t\t\t} else {\n\t\t\t\t\tseen.add(key); // first use: inline\n\t\t\t\t}\n\n\t\t\t\tswitch (op[0]) {\n\t\t\t\t\tcase \"s\":\n\t\t\t\t\t\tout.push([\"s\", ref as PathRef<NonEmptyPath>, op[2]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"d\":\n\t\t\t\t\t\tout.push([\"d\", ref as PathRef<NonEmptyPath>]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"a\":\n\t\t\t\t\t\tout.push([\"a\", ref as PathRef<NonEmptyPath>, op[2]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"t\":\n\t\t\t\t\t\tout.push([\"t\", ref as PathRef<NonEmptyPath>, op[2]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"p\":\n\t\t\t\t\t\tout.push([\"p\", ref, op[2], op[3], op[4]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"m\":\n\t\t\t\t\t\tout.push([\"m\", ref, op[2]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tprevious = key;\n\t\t\t}\n\t\t\treturn out;\n\t\t},\n\t};\n}\n\nexport interface Decoder {\n\tdecode(wire: readonly WireOp[]): Op[];\n}\n\nexport function decoder(): Decoder {\n\tconst paths = new Map<number, Path>();\n\n\treturn {\n\t\tdecode(wire) {\n\t\t\tlet previous: Path | undefined; // scoped to the batch, as in encode\n\t\t\tconst out: Op[] = [];\n\t\t\tfor (const op of wire) {\n\t\t\t\tassertValidWireOp(op);\n\t\t\t\tif (op[0] === \"#\") {\n\t\t\t\t\tassertSafePath(op[2]);\n\t\t\t\t\tpaths.set(op[1], op[2]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (op[0] === \"r\") {\n\t\t\t\t\tout.push(op);\n\t\t\t\t\tpaths.clear();\n\t\t\t\t\tprevious = undefined;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Arity tells us whether a ref is present: the short forms omit it.\n\t\t\t\tconst short =\n\t\t\t\t\t(op[0] === \"d\" && op.length === 1) ||\n\t\t\t\t\t(op[0] !== \"d\" && op[0] !== \"p\" && op.length === 2) ||\n\t\t\t\t\t(op[0] === \"p\" && op.length === 4);\n\n\t\t\t\tlet path: Path;\n\t\t\t\tif (short) {\n\t\t\t\t\tif (previous === undefined) throw new PathError([]);\n\t\t\t\t\tpath = previous;\n\t\t\t\t} else {\n\t\t\t\t\tconst ref = op[1] as PathRef;\n\t\t\t\t\tif (typeof ref === \"number\") {\n\t\t\t\t\t\tconst resolved = paths.get(ref);\n\t\t\t\t\t\tif (resolved === undefined) throw new PathError(ref);\n\t\t\t\t\t\tpath = resolved;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpath = ref;\n\t\t\t\t\t}\n\t\t\t\t\tprevious = path;\n\t\t\t\t}\n\n\t\t\t\tif (op[0] !== \"p\" && op[0] !== \"m\" && path.length === 0) throw new PathError(path);\n\t\t\t\tswitch (op[0]) {\n\t\t\t\t\tcase \"s\":\n\t\t\t\t\t\tout.push([\"s\", path as NonEmptyPath, (short ? op[1] : op[2]) as JsonValue]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"d\":\n\t\t\t\t\t\tout.push([\"d\", path as NonEmptyPath]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"a\":\n\t\t\t\t\t\tout.push([\"a\", path as NonEmptyPath, (short ? op[1] : op[2]) as string]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"t\":\n\t\t\t\t\t\tout.push([\"t\", path as NonEmptyPath, (short ? op[1] : op[2]) as number]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"p\": {\n\t\t\t\t\t\tconst [i, r, items] = short\n\t\t\t\t\t\t\t? [op[1] as number, op[2] as number, op[3] as JsonValue[]]\n\t\t\t\t\t\t\t: [op[2] as number, op[3] as number, op[4] as JsonValue[]];\n\t\t\t\t\t\tout.push([\"p\", path, i, r, items]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"m\":\n\t\t\t\t\t\tout.push([\"m\", path, (short ? op[1] : op[2]) as number[]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn out;\n\t\t},\n\t};\n}\n", "import type { Op } from \"../delta/index.ts\";\nimport type { Context } from \"../types.ts\";\n\nexport interface ReplicatedStateInternals {\n\t/** Atomically capture the immutable value and its matching publication sequence. */\n\tsnapshot(): { readonly value: unknown; readonly sequence: number };\n\tsubscribe(listener: (ops: readonly Op[], sequence: number, context: Context) => void): () => void;\n}\n\nconst sources = new WeakMap<object, ReplicatedStateInternals>();\n\nexport function registerReplicatedStateInternals(value: object, internals: ReplicatedStateInternals): void {\n\tsources.set(value, internals);\n}\n\nexport function getReplicatedStateInternals(value: unknown): ReplicatedStateInternals | undefined {\n\tif (typeof value !== \"object\" || value === null) return undefined;\n\treturn sources.get(value);\n}\n", "import { BACKGROUND_CONTEXT } from \"../context/index.ts\";\nimport { applyImmutable, isBase, type Op, type Prepared, type Tracker, track } from \"../delta/index.ts\";\nimport { JsonRevisionValidator } from \"../delta/revision-validator.ts\";\nimport type {\n\tAttachedReplicatedState,\n\tContext,\n\tJsonValue,\n\tMutableReplicatedState,\n\tReplicatedState,\n\tReplicatedStateDelivery,\n\tReplicatedStateSource,\n\tReplicatedStateSourceAttachment,\n\tReplicatedStateSourceFrame,\n\tReplicatedStateSourceOptions,\n} from \"../types.ts\";\nimport { registerReplicatedStateInternals } from \"./state-internals.ts\";\n\n/** The void signature also accepts synchronous callbacks that return an ignored value. */\ntype StateListener<T> = (value: T, context: Context, delivery: ReplicatedStateDelivery) => void;\n\ntype StateDelivery<T> = {\n\treadonly value: T;\n\treadonly context: Context;\n\treadonly delivery: ReplicatedStateDelivery;\n};\n\n/** One public subscription, independent of producer and other subscriber progress. */\nclass StateSubscriber<T> {\n\treadonly #listener: StateListener<T>;\n\treadonly #reportError: (error: Error) => void;\n\treadonly #pending: StateDelivery<T>[] = [];\n\t#running = false;\n\t#started = false;\n\t#closed = false;\n\n\tconstructor(listener: StateListener<T>, reportError: (error: Error) => void) {\n\t\tthis.#listener = listener;\n\t\tthis.#reportError = reportError;\n\t}\n\n\tpush(frame: StateDelivery<T>): void {\n\t\tif (this.#closed) return;\n\t\tif (this.#pending.length === 100) {\n\t\t\t// A cold replica can queue updates reentrantly before this subscriber's first hydration starts.\n\t\t\tconst hydration = this.#started ? undefined : this.#pending[0];\n\t\t\tthis.#pending.length = 0;\n\t\t\tif (hydration !== undefined) this.#pending.push(hydration);\n\t\t}\n\t\tthis.#pending.push(frame);\n\t}\n\n\tdrain(): void {\n\t\tif (this.#running || this.#closed) return;\n\t\tthis.#running = true;\n\t\tfor (let frame = this.#pending.shift(); frame !== undefined; frame = this.#pending.shift()) {\n\t\t\tthis.#started = true;\n\t\t\ttry {\n\t\t\t\tconst result: unknown = this.#listener(frame.value, frame.context, frame.delivery);\n\t\t\t\tif (isPromiseLike(result)) {\n\t\t\t\t\tvoid Promise.resolve(result).then(\n\t\t\t\t\t\t() => this.#resume(),\n\t\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\t\tthis.#report(error);\n\t\t\t\t\t\t\tthis.#resume();\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis.#report(error);\n\t\t\t}\n\t\t}\n\t\tthis.#running = false;\n\t}\n\n\tclear(): void {\n\t\tthis.#pending.length = 0;\n\t}\n\n\tclose(): void {\n\t\tthis.#closed = true;\n\t\tthis.clear();\n\t}\n\n\t#resume(): void {\n\t\tthis.#running = false;\n\t\tthis.drain();\n\t}\n\n\t#report(error: unknown): void {\n\t\ttry {\n\t\t\tthis.#reportError(toError(error));\n\t\t} catch (reportError) {\n\t\t\treportErrorAsync(toError(reportError));\n\t\t}\n\t}\n}\n\ntype SourceListener = (ops: readonly Op[], sequence: number, context: Context) => void;\n\ntype Publication<T> = {\n\treadonly value: T;\n\treadonly ops: readonly Op[];\n\treadonly sequence: number;\n\treadonly context: Context;\n};\n\n/** Maintains local publication order independently of how revisions are produced. */\nclass ReplicatedStatePublisher<T> {\n\treadonly #listeners = new Map<StateSubscriber<T>, number>();\n\treadonly #reportError: (error: Error) => void;\n\treadonly #sourceListeners = new Set<SourceListener>();\n\treadonly #publications: Publication<T>[] = [];\n\t#value: T;\n\t#sequence = 0;\n\t#delivering = false;\n\n\tconstructor(initial: T, reportError: (error: Error) => void = reportErrorAsync) {\n\t\tthis.#value = initial;\n\t\tthis.#reportError = reportError;\n\t}\n\n\tget value(): T {\n\t\treturn this.#value;\n\t}\n\n\tsnapshot(): { readonly value: T; readonly sequence: number } {\n\t\treturn { value: this.#value, sequence: this.#sequence };\n\t}\n\n\tsubscribe(listener: StateListener<T>): () => void {\n\t\tconst { value, sequence } = this.snapshot();\n\t\tconst subscriber = new StateSubscriber(listener, this.#reportError);\n\t\tthis.#listeners.set(subscriber, sequence);\n\t\tsubscriber.push({ value, context: serviceDeliveryContext(), delivery: { kind: \"hydrate\", sequence } });\n\t\tsubscriber.drain();\n\t\treturn () => {\n\t\t\tsubscriber.close();\n\t\t\tthis.#listeners.delete(subscriber);\n\t\t};\n\t}\n\n\tsubscribeSource(listener: SourceListener): () => void {\n\t\tthis.#sourceListeners.add(listener);\n\t\treturn () => this.#sourceListeners.delete(listener);\n\t}\n\n\t/** Publish an already-prepared immutable revision and return isolated listener failures. */\n\tpublish(value: T, ops: readonly Op[], context: Context): unknown[] {\n\t\tthis.#value = value;\n\t\tthis.#sequence += 1;\n\t\tthis.#publications.push({ value, ops, sequence: this.#sequence, context });\n\t\tif (this.#delivering) return [];\n\n\t\tthis.#delivering = true;\n\t\tconst errors: unknown[] = [];\n\t\ttry {\n\t\t\tfor (\n\t\t\t\tlet publication = this.#publications.shift();\n\t\t\t\tpublication !== undefined;\n\t\t\t\tpublication = this.#publications.shift()\n\t\t\t) {\n\t\t\t\tfor (const listener of [...this.#sourceListeners]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlistener(publication.ops, publication.sequence, publication.context);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\terrors.push(error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst delivery = { kind: \"update\", sequence: publication.sequence } as const;\n\t\t\t\tfor (const [subscriber, hydratedSequence] of [...this.#listeners]) {\n\t\t\t\t\tif (publication.sequence <= hydratedSequence) continue;\n\t\t\t\t\tsubscriber.push({ value: publication.value, context: publication.context, delivery });\n\t\t\t\t\tsubscriber.drain();\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.#delivering = false;\n\t\t}\n\t\treturn errors;\n\t}\n}\n\nexport class MutableReplicatedStateImpl<T extends object> implements MutableReplicatedState<T> {\n\treadonly #tracker: Tracker<T>;\n\treadonly #publisher: ReplicatedStatePublisher<T>;\n\t#changing = false;\n\n\tconstructor(initial: T) {\n\t\tthis.#tracker = track(initial);\n\t\tthis.#publisher = new ReplicatedStatePublisher(this.#tracker.value);\n\t\tregisterReplicatedStateInternals(this, {\n\t\t\tsnapshot: () => this.#publisher.snapshot(),\n\t\t\tsubscribe: (listener) => this.#publisher.subscribeSource(listener),\n\t\t});\n\t}\n\n\tget value(): T {\n\t\treturn this.#tracker.value;\n\t}\n\n\tchange(context: Context, mutate: Parameters<MutableReplicatedState<T>[\"change\"]>[1]): void {\n\t\tif (this.#changing) throw new Error(\"Replicated state cannot be changed reentrantly from a change callback\");\n\t\tthis.#changing = true;\n\t\tlet prepared: Prepared<T>;\n\t\ttry {\n\t\t\tconst change = this.#tracker.beginChange();\n\t\t\ttry {\n\t\t\t\tconst outcome = (mutate as (draft: typeof change.state) => unknown)(change.state);\n\t\t\t\tif (isPromiseLike(outcome)) {\n\t\t\t\t\tvoid Promise.resolve(outcome).catch(() => undefined);\n\t\t\t\t\tthrow new TypeError(\"Replicated state change callbacks must be synchronous\");\n\t\t\t\t}\n\t\t\t\tprepared = change.prepare();\n\t\t\t} catch (error) {\n\t\t\t\tchange.abort();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.#changing = false;\n\t\t}\n\n\t\tthis.#tracker.adopt(prepared);\n\t\tif (prepared.ops.length === 0) return;\n\t\tthrowCollectedErrors(\n\t\t\tthis.#publisher.publish(prepared.value, prepared.ops, context),\n\t\t\t\"Replicated state listeners failed\",\n\t\t);\n\t}\n\n\treplace(context: Context, value: T): void {\n\t\tif (this.#changing) throw new Error(\"Replicated state cannot be replaced from a change callback\");\n\t\tconst prepared = this.#tracker.prepareReplace(value);\n\t\tthis.#tracker.adopt(prepared);\n\t\tif (prepared.ops.length === 0) return;\n\t\tthrowCollectedErrors(\n\t\t\tthis.#publisher.publish(prepared.value, prepared.ops, context),\n\t\t\t\"Replicated state listeners failed\",\n\t\t);\n\t}\n\n\tsubscribe(listener: StateListener<T>): () => void {\n\t\treturn this.#publisher.subscribe(listener);\n\t}\n}\n\nclass AttachedReplicatedStateImpl<T> implements AttachedReplicatedState<T> {\n\treadonly #publisher: ReplicatedStatePublisher<T>;\n\treadonly #attachment: ReplicatedStateSourceAttachment<T>;\n\treadonly #reportError: (error: Error) => void;\n\t#cursor: number;\n\t#disposed = false;\n\n\tconstructor(attachment: ReplicatedStateSourceAttachment<T>, options: ReplicatedStateSourceOptions) {\n\t\tconst { snapshot } = attachment;\n\t\tassertCursor(snapshot.cursor, \"snapshot\");\n\t\tthis.#attachment = attachment;\n\t\tthis.#cursor = snapshot.cursor;\n\t\tthis.#reportError = options.onError ?? reportErrorAsync;\n\t\tthis.#publisher = new ReplicatedStatePublisher(snapshot.value, (error) => this.#report(error));\n\t\tregisterReplicatedStateInternals(this, {\n\t\t\tsnapshot: () => this.#publisher.snapshot(),\n\t\t\tsubscribe: (listener) => this.#publisher.subscribeSource(listener),\n\t\t});\n\t}\n\n\tget value(): T {\n\t\treturn this.#publisher.value;\n\t}\n\n\tsubscribe(listener: StateListener<T>): () => void {\n\t\treturn this.#publisher.subscribe(listener);\n\t}\n\n\tactivate(): void {\n\t\tthis.#attachment.activate((frame) => this.#receive(frame));\n\t}\n\n\tdispose(): void {\n\t\tif (this.#disposed) return;\n\t\tthis.#disposed = true;\n\t\tthis.#attachment.dispose();\n\t}\n\n\t#receive(frame: ReplicatedStateSourceFrame<T>): void {\n\t\tif (this.#disposed) return;\n\t\ttry {\n\t\t\tassertCursor(frame.cursor, \"frame\");\n\t\t\tconst expected = this.#cursor + 1;\n\t\t\tif (frame.cursor !== expected) {\n\t\t\t\tthrow new Error(`Replicated state source cursor has a gap: expected ${expected}, received ${frame.cursor}`);\n\t\t\t}\n\t\t\tthis.#cursor = frame.cursor;\n\t\t\tconst errors = this.#publisher.publish(frame.value, frame.ops, frame.context);\n\t\t\tif (errors.length === 1) this.#report(errors[0]);\n\t\t\telse if (errors.length > 1) this.#report(new AggregateError(errors, \"Replicated state listeners failed\"));\n\t\t} catch (error) {\n\t\t\tthis.#fail(toError(error));\n\t\t}\n\t}\n\n\t#fail(error: Error): void {\n\t\tif (this.#disposed) return;\n\t\tthis.#disposed = true;\n\t\ttry {\n\t\t\tthis.#attachment.dispose();\n\t\t} catch (disposeError) {\n\t\t\tthis.#report(new AggregateError([error, disposeError], \"Replicated state source contract failed\"));\n\t\t\treturn;\n\t\t}\n\t\tthis.#report(error);\n\t}\n\n\t#report(error: unknown): void {\n\t\ttry {\n\t\t\tthis.#reportError(toError(error));\n\t\t} catch (reportError) {\n\t\t\treportErrorAsync(toError(reportError));\n\t\t}\n\t}\n}\n\n/** Attach a publication-only replicated state to one authoritative immutable source stream. */\nexport function attachReplicatedStateSource<T>(\n\tsource: ReplicatedStateSource<T>,\n\toptions: ReplicatedStateSourceOptions = {},\n): AttachedReplicatedState<T> {\n\tconst attachment = source.attach();\n\ttry {\n\t\tconst state = new AttachedReplicatedStateImpl(attachment, options);\n\t\tstate.activate();\n\t\treturn state;\n\t} catch (error) {\n\t\ttry {\n\t\t\tattachment.dispose();\n\t\t} catch (disposeError) {\n\t\t\tthrow new AggregateError([error, disposeError], \"Failed to attach replicated state source\");\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/** A cold read-only state used by service consumers until a complete snapshot arrives. */\nexport class ReplicatedStateReplica<T extends JsonValue = JsonValue> implements ReplicatedState<T> {\n\treadonly #listeners = new Set<StateSubscriber<T>>();\n\treadonly #reportError: (error: Error) => void;\n\treadonly #validator = new JsonRevisionValidator();\n\t#value: T | undefined;\n\t#sequence: number | undefined;\n\n\tconstructor(reportError: (error: Error) => void) {\n\t\tthis.#reportError = reportError;\n\t}\n\n\tget value(): T | undefined {\n\t\treturn this.#value;\n\t}\n\n\tsubscribe(listener: StateListener<T>): () => void {\n\t\tconst subscriber = new StateSubscriber(listener, this.#reportError);\n\t\tthis.#listeners.add(subscriber);\n\t\tif (this.#value !== undefined) {\n\t\t\tsubscriber.push({\n\t\t\t\tvalue: this.#value,\n\t\t\t\tcontext: serviceDeliveryContext(),\n\t\t\t\tdelivery: { kind: \"hydrate\", sequence: this.#sequence! },\n\t\t\t});\n\t\t\tsubscriber.drain();\n\t\t}\n\t\treturn () => {\n\t\t\tsubscriber.close();\n\t\t\tthis.#listeners.delete(subscriber);\n\t\t};\n\t}\n\n\thydrate(sequence: number, ops: readonly Op[], context: Context): void {\n\t\tlet next: T;\n\t\ttry {\n\t\t\tif (!isBase(ops)) throw new Error(\"Replicated state snapshot is not a base operation batch\");\n\t\t\tnext = this.#validator.validate(applyImmutable<T>(undefined, ops));\n\t\t} catch (error) {\n\t\t\tthis.clear();\n\t\t\tthrow error;\n\t\t}\n\t\tthis.#sequence = sequence;\n\t\tthis.#value = next;\n\t\tthis.#deliverAll(context, { kind: \"hydrate\", sequence });\n\t}\n\n\tupdate(sequence: number, ops: readonly Op[], context: Context): void {\n\t\tif (this.#sequence === undefined || this.#value === undefined) {\n\t\t\tthrow new Error(\"Replicated state received an update before hydration\");\n\t\t}\n\t\tif (sequence !== this.#sequence + 1) {\n\t\t\tthis.clear();\n\t\t\tthrow new Error(\"Replicated state update sequence has a gap\");\n\t\t}\n\t\tlet next: T;\n\t\ttry {\n\t\t\tnext = this.#validator.validate(applyImmutable(this.#value, ops));\n\t\t} catch (error) {\n\t\t\tthis.clear();\n\t\t\tthrow error;\n\t\t}\n\t\tthis.#sequence = sequence;\n\t\tthis.#value = next;\n\t\tthis.#deliverAll(context, { kind: \"update\", sequence });\n\t}\n\n\tclear(): void {\n\t\tthis.#value = undefined;\n\t\tthis.#sequence = undefined;\n\t\tfor (const subscriber of this.#listeners) subscriber.clear();\n\t}\n\n\t#deliverAll(context: Context, delivery: ReplicatedStateDelivery): void {\n\t\tif (this.#value === undefined) return;\n\t\tconst frame = { value: this.#value, context, delivery };\n\t\tconst subscribers = [...this.#listeners];\n\t\t// Enqueue for everyone before user code can publish another revision reentrantly.\n\t\tfor (const subscriber of subscribers) subscriber.push(frame);\n\t\tfor (const subscriber of subscribers) subscriber.drain();\n\t}\n}\n\n/** @internal Context for synthetic service deliveries without a caller. */\nexport function serviceDeliveryContext(): Context {\n\t// TODO: Add delivery-scoped cancellation or metadata if deliveries gain an owned lifecycle.\n\treturn BACKGROUND_CONTEXT;\n}\n\nfunction assertCursor(cursor: number, kind: \"snapshot\" | \"frame\"): void {\n\tif (!Number.isSafeInteger(cursor))\n\t\tthrow new TypeError(`Replicated state source ${kind} cursor must be a safe integer`);\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n\treturn (\n\t\t((typeof value === \"object\" && value !== null) || typeof value === \"function\") &&\n\t\ttypeof (value as { then?: unknown }).then === \"function\"\n\t);\n}\n\nfunction throwCollectedErrors(errors: readonly unknown[], message: string): void {\n\tif (errors.length === 1) throw errors[0];\n\tif (errors.length > 1) throw new AggregateError(errors, message);\n}\n\nfunction reportErrorAsync(error: Error): void {\n\tqueueMicrotask(() => {\n\t\tthrow error;\n\t});\n}\n\nfunction toError(error: unknown): Error {\n\treturn error instanceof Error ? error : new Error(String(error));\n}\n", "import { FacetKernel } from \"./facets/host.ts\";\nimport { disposeLoadedFacets } from \"./facets/loader.ts\";\nimport { RemoteServiceBindingImpl } from \"./services/consumer.ts\";\nimport { attachReplicatedStateSource, MutableReplicatedStateImpl } from \"./services/state.ts\";\nimport type {\n\tAttachedReplicatedState,\n\tFacet,\n\tFacetHost,\n\tFacetLoader,\n\tFacetOptions,\n\tLoadedFacets,\n\tMutableReplicatedState,\n\tRemoteServiceBinding,\n\tRemoteServiceBindingOptions,\n\tRemoteServiceContract,\n\tReplicatedStateSource,\n\tReplicatedStateSourceOptions,\n\tService,\n} from \"./types.ts\";\n\n/** Create an active host for one complete set of facets. */\nexport async function createFacetHost(options: FacetOptions): Promise<FacetHost> {\n\tconst kernel = new FacetKernel(options);\n\tawait kernel.activate();\n\treturn Object.freeze({\n\t\tservices: kernel.provider,\n\t\treload: (facets: readonly Facet[]) => kernel.reload(facets),\n\t\tdispose: () => kernel.dispose(),\n\t});\n}\n\nexport function createStaticFacetLoader(facets: readonly Facet[]): FacetLoader {\n\tconst loadedFacets = Object.freeze([...facets]);\n\treturn {\n\t\tasync load() {\n\t\t\treturn { facets: loadedFacets, async dispose() {} };\n\t\t},\n\t};\n}\n\nexport function combineFacetLoaders(loaders: readonly FacetLoader[]): FacetLoader {\n\treturn {\n\t\tasync load() {\n\t\t\tconst loaded: LoadedFacets[] = [];\n\t\t\ttry {\n\t\t\t\tfor (const loader of loaders) loaded.push(await loader.load());\n\t\t\t} catch (error) {\n\t\t\t\tconst cleanupErrors = await disposeLoadedFacets(loaded.reverse());\n\t\t\t\tif (cleanupErrors.length > 0) {\n\t\t\t\t\tthrow new AggregateError([error, ...cleanupErrors], \"Facet loading and cleanup failed\");\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tlet disposed = false;\n\t\t\treturn {\n\t\t\t\tfacets: Object.freeze(loaded.flatMap(({ facets }) => facets)),\n\t\t\t\tasync dispose() {\n\t\t\t\t\tif (disposed) return;\n\t\t\t\t\tdisposed = true;\n\t\t\t\t\tconst errors = await disposeLoadedFacets([...loaded].reverse());\n\t\t\t\t\tif (errors.length === 1) throw errors[0];\n\t\t\t\t\tif (errors.length > 1) throw new AggregateError(errors, \"Failed to dispose loaded facets\");\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport function defineFacet(facet: Facet): Facet {\n\treturn facet;\n}\n\nexport function defineService<T>(id: string, options: { readonly local: true }): Service<T>;\nexport function defineService<T>(\n\tid: string,\n\t...options: [RemoteServiceContract<T>] extends [never]\n\t\t? readonly [options: never]\n\t\t: readonly [options?: { readonly local?: false }]\n): Service<T>;\nexport function defineService(id: string, options?: { readonly local?: boolean }): Service<unknown> {\n\tif (id.length === 0) throw new TypeError(\"Service ID must not be empty\");\n\t// TODO: check if the reserved namespace should be part of Chord.\n\tif (id.startsWith(\"$chord.\")) throw new TypeError(\"Service IDs beginning with $chord. are reserved\");\n\treturn Object.freeze({ id, local: options?.local ?? false });\n}\n\nexport function createRemoteServiceBinding(options: RemoteServiceBindingOptions): RemoteServiceBinding {\n\treturn new RemoteServiceBindingImpl(options);\n}\n\nexport function replicatedState<T>(\n\tsource: ReplicatedStateSource<T>,\n\toptions?: ReplicatedStateSourceOptions,\n): AttachedReplicatedState<T>;\n/**\n * Create authoritative state by taking immutable ownership of an alias-free strict-JSON root.\n * The caller must not mutate `initial` after this call.\n */\nexport function replicatedState<T extends object>(initial: T): MutableReplicatedState<T>;\nexport function replicatedState(\n\tinitialOrSource: object | ReplicatedStateSource<unknown>,\n\toptions?: ReplicatedStateSourceOptions,\n): MutableReplicatedState<object> | AttachedReplicatedState<unknown> {\n\tif (isReplicatedStateSource(initialOrSource)) return attachReplicatedStateSource(initialOrSource, options);\n\treturn new MutableReplicatedStateImpl(initialOrSource);\n}\n\nfunction isReplicatedStateSource(value: object): value is ReplicatedStateSource<unknown> {\n\treturn typeof (value as { readonly attach?: unknown }).attach === \"function\";\n}\n", "import type { Id, Seq } from \"./types.ts\";\n\n/** Apply an erased ID brand at a trusted numeric allocation or decoding boundary. */\nexport function idFromNumber<I extends Id<string>>(value: number): I {\n\treturn value as I;\n}\n\n/** Apply the erased commit-sequence brand at a trusted storage boundary. */\nexport function seqFromNumber(value: number): Seq {\n\treturn value as Seq;\n}\n", "import { copyJson, type JsonValue } from \"@earendil-works/chord\";\nimport type { Op } from \"@earendil-works/chord/delta\";\nimport { idFromNumber } from \"./ids.ts\";\nimport type {\n\tCheckpointInfo,\n\tCommonDocDefinition,\n\tConversationDocFamilyToken,\n\tConversationDocToken,\n\tConversationId,\n\tDocDefinition,\n\tDocFamilyDefinition,\n\tDocFamilyToken,\n\tDocToken,\n\tDocumentAddress,\n\tDocumentCreate,\n\tDocumentId,\n\tDocumentRecord,\n\tDocumentSemantics,\n\tId,\n\tJsonObject,\n\tLatestConversationSemantics,\n\tRewindableConversationDocFamilyToken,\n\tRewindableConversationDocToken,\n\tRewindableConversationSemantics,\n\tSessionDocFamilyToken,\n\tSessionDocToken,\n\tStoredDocument,\n\tTaskDocFamilyToken,\n\tTaskDocToken,\n\tTaskId,\n} from \"./types.ts\";\n\ntype FamilyInput<T extends JsonObject, I extends JsonValue> = Omit<CommonDocDefinition<T>, \"initial\"> & {\n\treadonly family: true;\n\tinitial(seed: I): T;\n};\n\n/** Define a Session-scoped singleton document. */\nexport function defineDoc<T extends JsonObject>(\n\tdefinition: CommonDocDefinition<T> & { readonly scope: \"session\" },\n): SessionDocToken<T>;\n/** Define a latest-only conversation singleton document. */\nexport function defineDoc<T extends JsonObject>(\n\tdefinition: CommonDocDefinition<T> & LatestConversationSemantics,\n): ConversationDocToken<T>;\n/** Define a rewindable conversation singleton document. */\nexport function defineDoc<T extends JsonObject>(\n\tdefinition: CommonDocDefinition<T> & RewindableConversationSemantics,\n): RewindableConversationDocToken<T>;\n/** Define a task-scoped singleton document. */\nexport function defineDoc<T extends JsonObject>(\n\tdefinition: CommonDocDefinition<T> & { readonly scope: \"task\" },\n): TaskDocToken<T>;\nexport function defineDoc<T extends JsonObject>(definition: DocDefinition<T>): DocToken<T, DocDefinition<T>> {\n\tvalidateDefinition(definition);\n\treturn { definition };\n}\n\n/** Define a Session-scoped document family. */\nexport function defineDocFamily<T extends JsonObject, I extends JsonValue>(\n\tdefinition: FamilyInput<T, I> & { readonly scope: \"session\" },\n): SessionDocFamilyToken<T, I>;\n/** Define a latest-only conversation document family. */\nexport function defineDocFamily<T extends JsonObject, I extends JsonValue>(\n\tdefinition: FamilyInput<T, I> & LatestConversationSemantics,\n): ConversationDocFamilyToken<T, I>;\n/** Define a rewindable conversation document family. */\nexport function defineDocFamily<T extends JsonObject, I extends JsonValue>(\n\tdefinition: FamilyInput<T, I> & RewindableConversationSemantics,\n): RewindableConversationDocFamilyToken<T, I>;\n/** Define a task-scoped document family. */\nexport function defineDocFamily<T extends JsonObject, I extends JsonValue>(\n\tdefinition: FamilyInput<T, I> & { readonly scope: \"task\" },\n): TaskDocFamilyToken<T, I>;\nexport function defineDocFamily<T extends JsonObject, I extends JsonValue>(\n\tdefinition: DocFamilyDefinition<T, I>,\n): DocFamilyToken<T, I, DocFamilyDefinition<T, I>> {\n\tvalidateDefinition(definition);\n\treturn { definition };\n}\n\n/** Erased definition shape used by the Session after overload resolution. */\nexport type AnyDocDefinition = DocumentSemantics & {\n\treadonly kind: string;\n\treadonly version: number;\n\treadonly family?: true;\n\tinitial(seed?: JsonValue): JsonObject;\n\tmigrate?(value: JsonObject, fromVersion: number): JsonObject;\n\tcheckpointWhen?(value: Readonly<JsonObject>, ops: readonly Op[], info: CheckpointInfo): boolean;\n};\n\n/** Erased singleton or family token. */\nexport type AnyDocToken = { readonly definition: AnyDocDefinition };\n\nfunction validateDefinition(definition: AnyDocDefinition): void {\n\tif (!Number.isSafeInteger(definition.version) || definition.version < 1) {\n\t\tthrow new TypeError(`Document ${definition.kind} version must be a positive integer`);\n\t}\n}\n\n/** Logical address plus its string identity for maps. */\nexport type ResolvedAddress = {\n\treadonly address: DocumentAddress;\n\treadonly id: string;\n\treadonly nextArgument: number;\n};\n\n/** Resolve an overloaded argument list and return the index after the owner and family key. */\nexport function resolveAddress(definition: AnyDocDefinition, args: readonly unknown[]): ResolvedAddress {\n\tlet index = 0;\n\tlet scope: DocumentAddress[\"scope\"];\n\tswitch (definition.scope) {\n\t\tcase \"session\":\n\t\t\tscope = { kind: \"session\" };\n\t\t\tbreak;\n\t\tcase \"conversation\":\n\t\t\tscope = { kind: \"conversation\", conversationId: ownerId<ConversationId>(args[index++], definition) };\n\t\t\tbreak;\n\t\tcase \"task\":\n\t\t\tscope = { kind: \"task\", taskId: ownerId<TaskId>(args[index++], definition) };\n\t\t\tbreak;\n\t}\n\tconst key = definition.family === true ? (args[index++] as string) : undefined;\n\tconst address: DocumentAddress =\n\t\tkey === undefined ? { kind: definition.kind, scope } : { kind: definition.kind, scope, key };\n\treturn { address, id: addressId(address), nextArgument: index };\n}\n\nfunction ownerId<I extends Id<string>>(value: unknown, definition: AnyDocDefinition): I {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value)) {\n\t\tthrow new TypeError(`Document ${definition.kind} requires a ${definition.scope} ID`);\n\t}\n\treturn idFromNumber<I>(value);\n}\n\n/** Stable string identity of one logical address. */\nexport function addressId(address: DocumentAddress): string {\n\tconst owner =\n\t\taddress.scope.kind === \"session\"\n\t\t\t? null\n\t\t\t: address.scope.kind === \"conversation\"\n\t\t\t\t? address.scope.conversationId\n\t\t\t\t: address.scope.taskId;\n\treturn JSON.stringify([address.kind, address.scope.kind, owner, address.key ?? null]);\n}\n\n/** Build the storage create record for a new incarnation at an address. */\nexport function documentCreate(definition: AnyDocDefinition, address: DocumentAddress, id: DocumentId): DocumentCreate {\n\tconst key = address.key === undefined ? {} : { key: address.key };\n\tswitch (address.scope.kind) {\n\t\tcase \"session\":\n\t\t\treturn { id, kind: address.kind, ...key, scope: address.scope };\n\t\tcase \"task\":\n\t\t\treturn { id, kind: address.kind, ...key, scope: address.scope };\n\t\tcase \"conversation\":\n\t\t\treturn {\n\t\t\t\tid,\n\t\t\t\tkind: address.kind,\n\t\t\t\t...key,\n\t\t\t\tscope: address.scope,\n\t\t\t\thistory: definition.history!,\n\t\t\t\tfork: definition.fork!,\n\t\t\t} as DocumentCreate;\n\t}\n}\n\n/** Reject typed access whose token disagrees with the persisted scope, history, or fork semantics. */\nexport function checkRecordScope(definition: AnyDocDefinition, record: DocumentCreate | DocumentRecord): void {\n\tif (\n\t\trecord.scope.kind !== definition.scope ||\n\t\t(record.scope.kind === \"conversation\" &&\n\t\t\t(record.history !== definition.history || record.fork !== definition.fork))\n\t) {\n\t\tthrow new TypeError(`Document ${record.id} (${record.kind}) does not match the supplied definition semantics`);\n\t}\n}\n\n/** Reject typed access to a stored version the supplied definition cannot use. */\nexport function checkRecordVersion(\n\tdefinition: AnyDocDefinition,\n\trecord: DocumentCreate | DocumentRecord,\n\tversion: number,\n): void {\n\tif (version > definition.version) {\n\t\tthrow new Error(`Document ${record.id} (${record.kind}) has newer version ${version} than ${definition.version}`);\n\t}\n\tif (version < definition.version && definition.migrate === undefined) {\n\t\tthrow new Error(`Document ${record.id} (${record.kind}) requires migration from version ${version}`);\n\t}\n}\n\n/** Validate and materialize a detached stored value for typed access. */\nexport function materializeDocument(definition: AnyDocDefinition, stored: StoredDocument): JsonObject {\n\treturn materializeDocumentValue(definition, stored.record, stored.version, stored.value);\n}\n\n/** Validate and materialize one detached value before its first persisted incarnation. */\nexport function materializeDocumentValue(\n\tdefinition: AnyDocDefinition,\n\trecord: DocumentCreate | DocumentRecord,\n\tversion: number,\n\tvalue: JsonObject,\n): JsonObject {\n\tcheckRecordScope(definition, record);\n\tcheckRecordVersion(definition, record, version);\n\tif (version === definition.version) return value;\n\treturn copyJson(definition.migrate!(value, version)) as JsonObject;\n}\n", "import type { JsonValue } from \"@earendil-works/chord\";\nimport type { CompactionReason, ToolDiagnostic } from \"./harness/types.ts\";\nimport type { Entry, EntryRecord, TypedEntry } from \"./types.ts\";\n\n/** Define a typed entry kind whose `is()` guard narrows by `EntryRecord.kind`. */\nexport function defineEntry<D extends JsonValue = never>(kind: string): Entry<D> {\n\tif (typeof kind !== \"string\" || kind.length === 0) throw new TypeError(\"Entry kind must be a non-empty string\");\n\treturn {\n\t\tkind,\n\t\tis: (entry: EntryRecord | undefined): entry is TypedEntry<D> => entry !== undefined && entry.kind === kind,\n\t};\n}\n\n/** User input: `model` is `[UserMessage]`. Written by submissions. */\nexport const UserEntry = defineEntry(\"pi.user\");\n/** Provider result with any stop reason: `model` is `[AssistantMessage]`. Written by generation. */\nexport const AssistantEntry = defineEntry(\"pi.assistant\");\n/** Positional prompt and tool change: `model` is `[SystemMessage]` with empty `content`. */\nexport const SystemEntry = defineEntry(\"pi.system\");\n/**\n * Tool result: `model` is `[ToolResultMessage]`, whose content ends with the rendered diagnostics block; `data` holds\n * the structured diagnostics, possibly none. Written by tool tasks, and by generation for calls it did not offer.\n */\nexport const ToolResultEntry = defineEntry<{ diagnostics: ToolDiagnostic[] }>(\"pi.tool-result\");\n/**\n * Start of a new context: always `head: \"self\"`, with `model` absent for a plain reset or `[UserMessage]` carrying the\n * handoff text. Written by `Conversation.reset()` and the `handoff` tool control.\n */\nexport const ResetEntry = defineEntry(\"pi.reset\");\n/**\n * Compaction summary: `model` is `[UserMessage]` with the wrapped summary, `head` the first kept entry. Written by\n * compaction tasks, directly or through a write submission.\n */\nexport const CompactionEntry = defineEntry<{ reason: CompactionReason }>(\"pi.compaction\");\n", "import type { ConversationId } from \"./types.ts\";\n\n/** A transaction read a table after its first table write. Read every required row before writing. */\nexport class ReadAfterWrite extends Error {\n\tconstructor(method: string) {\n\t\tsuper(`Tx.${method}() cannot read tables after the first table write`);\n\t\tthis.name = \"ReadAfterWrite\";\n\t}\n}\n\n/** Storage rejected a batch before any durable effect; the owning Session may continue safely. */\nexport class StorageRejected extends Error {\n\tconstructor(message: string, options?: ErrorOptions) {\n\t\tsuper(message, options);\n\t\tthis.name = \"StorageRejected\";\n\t}\n}\n\n/** A submission reached a busy conversation and was not admitted. */\nexport class ConversationBusy extends Error {\n\treadonly conversationId: ConversationId;\n\n\tconstructor(conversationId: ConversationId) {\n\t\tsuper(`Conversation ${conversationId} is busy`);\n\t\tthis.name = \"ConversationBusy\";\n\t\tthis.conversationId = conversationId;\n\t}\n}\n", "import { copyJson, type Draft } from \"@earendil-works/chord\";\nimport { defineDoc } from \"../documents.ts\";\nimport type { ConversationId, ConversationRecord, Tx } from \"../types.ts\";\nimport type {\n\tAgent,\n\tAgentChange,\n\tAgentState,\n\tCompactionPolicy,\n\tConversationRetryPolicy,\n\tExtension,\n\tHarnessSettings,\n\tProgressPolicy,\n\tPromptSection,\n\tRegistrySnapshot,\n\tSettings,\n\tToolRegistration,\n} from \"./types.ts\";\n\nexport const DEFAULT_RETRY_POLICY: ConversationRetryPolicy = {\n\tenabled: true,\n\tmaxRetries: 3,\n\tbaseDelayMs: 2000,\n\tmaxAgentDelayMs: 60000,\n};\n\nexport const DEFAULT_COMPACTION_POLICY: CompactionPolicy = {\n\tenabled: true,\n\treserveTokens: 16384,\n\tkeepRecentTokens: 20000,\n\tbackgroundTokens: 32768,\n};\n\nexport const DEFAULT_PROGRESS_POLICY: ProgressPolicy = {\n\tpartialIntervalMs: 100,\n\toutputIntervalMs: 100,\n};\n\n/** The reserved section key of the agent's `instructions`. */\nexport const INSTRUCTIONS_KEY = \"instructions\";\n\n/** Built-in agent document; rewindable so forks start from the agent at their fork entry. */\nexport const AgentDoc = defineDoc<AgentState>({\n\tkind: \"pi.agent\",\n\tversion: 1,\n\tscope: \"conversation\",\n\thistory: \"rewindable\",\n\tfork: \"asOf\",\n\tinitial: () => ({}),\n\tcheckpointWhen: () => true,\n});\n\n/** Resolve the host settings: every field over its built-in default, object fields merged. */\nexport function resolveSettings(settings: HarnessSettings | undefined): Settings {\n\tconst extensions = settings?.extensions;\n\treturn {\n\t\t...(extensions === undefined ? {} : { extensions }),\n\t\tstream: { ...settings?.stream },\n\t\tretry: { ...DEFAULT_RETRY_POLICY, ...settings?.retry },\n\t\tcompaction: { ...DEFAULT_COMPACTION_POLICY, ...settings?.compaction },\n\t\t// Field by field, so an explicitly undefined interval keeps its default.\n\t\tprogress: {\n\t\t\tpartialIntervalMs: settings?.progress?.partialIntervalMs ?? DEFAULT_PROGRESS_POLICY.partialIntervalMs,\n\t\t\toutputIntervalMs: settings?.progress?.outputIntervalMs ?? DEFAULT_PROGRESS_POLICY.outputIntervalMs,\n\t\t},\n\t\ttoolExecution: settings?.toolExecution ?? \"parallel\",\n\t\tsteeringMode: settings?.steeringMode ?? \"one-at-a-time\",\n\t\tfollowUpMode: settings?.followUpMode ?? \"one-at-a-time\",\n\t};\n}\n\n/** Apply one change to `pi.agent`: a given field replaces the stored one, `null` clears it, `undefined` changes nothing. */\nexport async function configure(tx: Tx, conversationId: ConversationId, change: AgentChange): Promise<void> {\n\tconst state = await tx.doc(AgentDoc, conversationId);\n\tapplyChange(state, change);\n}\n\n/**\n * `addTools` of a tool round: an array gets each name it lacks appended, `{ remove }` loses the names, and unset tools\n * already offer every tool, so nothing is written.\n */\nexport async function addTools(tx: Tx, conversationId: ConversationId, added: readonly string[]): Promise<void> {\n\tconst state = await tx.doc(AgentDoc, conversationId);\n\tconst tools = state.tools;\n\tif (tools === undefined) return;\n\tif (Array.isArray(tools)) {\n\t\tfor (const name of added) if (!tools.includes(name)) tools.push(name);\n\t} else {\n\t\tconst remove = (tools as { remove: string[] }).remove;\n\t\tif (remove.some((name) => added.includes(name))) {\n\t\t\tstate.tools = { remove: remove.filter((name) => !added.includes(name)) };\n\t\t}\n\t}\n}\n\nfunction applyChange(state: Draft<AgentState>, change: AgentChange): void {\n\tconst set = <K extends keyof AgentState>(key: K, value: AgentState[K] | null | undefined) => {\n\t\tif (value === undefined) return;\n\t\tif (value === null) delete state[key];\n\t\telse state[key] = value as Draft<AgentState>[K];\n\t};\n\tset(\"model\", change.model === undefined || change.model === null ? change.model : { ...change.model });\n\tset(\"thinkingLevel\", change.thinkingLevel);\n\tconst extensions = change.extensions;\n\tset(\n\t\t\"extensions\",\n\t\textensions === undefined || extensions === null\n\t\t\t? extensions\n\t\t\t: isList(extensions)\n\t\t\t\t? names(extensions)\n\t\t\t\t: {\n\t\t\t\t\t\t...(extensions.add === undefined ? {} : { add: names(extensions.add) }),\n\t\t\t\t\t\t...(extensions.remove === undefined ? {} : { remove: names(extensions.remove) }),\n\t\t\t\t\t},\n\t);\n\tconst tools = change.tools;\n\tset(\n\t\t\"tools\",\n\t\ttools === undefined || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) },\n\t);\n\tset(\"instructions\", change.instructions);\n\tset(\"cwd\", change.cwd);\n}\n\nfunction isList<T>(value: readonly T[] | object): value is readonly T[] {\n\treturn Array.isArray(value);\n}\n\nfunction names(items: readonly { readonly name: string }[]): string[] {\n\treturn items.map((item) => item.name);\n}\n\n/**\n * Built-in part of every Harness commit that creates or forks a conversation, for `pi.agent`: a fork keeps its `asOf`\n * copy; a new task-owned conversation copies the stored agent of its owner task's conversation; a new ownerless one\n * starts empty.\n */\nexport async function createAgent(tx: Tx, conversation: ConversationRecord): Promise<void> {\n\tif (conversation.parent !== undefined) return;\n\tconst agent = await tx.doc(AgentDoc, conversation.id);\n\tif (conversation.owner === undefined) return;\n\tconst owner = await tx.doc(AgentDoc, conversation.owner.conversationId);\n\tObject.assign(agent, copyJson(owner) as AgentState);\n}\n\n/** Handlers of the selected extensions' hooks for a task name, in extension order. */\nexport function agentHooks(agent: Agent, taskName: string): object[] {\n\tconst handlers: object[] = [];\n\tfor (const extension of agent.extensions) {\n\t\tfor (const hook of extension.hooks ?? []) if (hook.task === taskName) handlers.push(hook.handlers);\n\t}\n\treturn handlers;\n}\n\n/**\n * Resolve an agent from its stored state (absent: every field unset), a registry snapshot, and resolved settings. A\n * wrapper that throws or renames drops its target and is reported; a wrapper without a target does nothing.\n */\nexport function resolveAgent<Tool extends ToolRegistration>(\n\tstate: Readonly<AgentState> | undefined,\n\tsnapshot: RegistrySnapshot<Tool>,\n\tsettings: Settings,\n\treport: (error: unknown) => void,\n): Agent<Tool> {\n\tconst extensions = selectExtensions(state?.extensions, snapshot, settings);\n\n\tconst composed = new Map<string, Tool>();\n\tfor (const extension of extensions) for (const tool of extension.tools ?? []) composed.set(tool.name, tool);\n\tconst sections = new Map<string, PromptSection<Tool>>();\n\tfor (const extension of extensions) {\n\t\tfor (const section of extension.sections ?? []) sections.set(section.key, section);\n\t}\n\tfor (const extension of extensions) {\n\t\tfor (const wrap of extension.wraps ?? []) {\n\t\t\tif (\"tool\" in wrap)\n\t\t\t\tapplyWrap(\n\t\t\t\t\tcomposed,\n\t\t\t\t\twrap.tool,\n\t\t\t\t\t(tool) => wrap.wrap(tool),\n\t\t\t\t\t(tool) => tool.name,\n\t\t\t\t\treport,\n\t\t\t\t);\n\t\t\telse\n\t\t\t\tapplyWrap(\n\t\t\t\t\tsections,\n\t\t\t\t\twrap.section,\n\t\t\t\t\t(section) => wrap.wrap(section),\n\t\t\t\t\t(section) => section.key,\n\t\t\t\t\treport,\n\t\t\t\t);\n\t\t}\n\t}\n\n\tconst filter = state?.tools;\n\tlet tools: Tool[];\n\tif (filter === undefined) tools = [...composed.values()];\n\telse if (Array.isArray(filter)) {\n\t\ttools = [];\n\t\tfor (const name of new Set(filter)) {\n\t\t\tconst tool = composed.get(name);\n\t\t\tif (tool !== undefined) tools.push(tool);\n\t\t}\n\t} else {\n\t\tconst removed = new Set((filter as { remove: string[] }).remove);\n\t\ttools = [...composed.values()].filter((tool) => !removed.has(tool.name));\n\t}\n\n\tconst instructions = state?.instructions;\n\tconst agentSections = [...sections.values()];\n\tif (instructions !== undefined) agentSections.push({ key: INSTRUCTIONS_KEY, render: () => instructions });\n\n\tconst agent: Agent<Tool> = {\n\t\t...(state?.model === undefined ? {} : { model: state.model }),\n\t\tthinkingLevel: state?.thinkingLevel ?? \"off\",\n\t\textensions,\n\t\ttools,\n\t\tsections: agentSections,\n\t\t...(instructions === undefined ? {} : { instructions }),\n\t\t...(state?.cwd === undefined ? {} : { cwd: state.cwd }),\n\t};\n\treturn agent;\n}\n\n/** Selected installed extensions: the stored array, or the default selection edited by `{ add, remove }`. */\nfunction selectExtensions<Tool extends ToolRegistration>(\n\tstored: AgentState[\"extensions\"],\n\tsnapshot: RegistrySnapshot<Tool>,\n\tsettings: Settings,\n): Extension<Tool>[] {\n\tlet selected: string[];\n\tif (Array.isArray(stored)) selected = stored;\n\telse {\n\t\tconst base = settings.extensions?.map((extension) => extension.name) ?? snapshot.installed().map((e) => e.name);\n\t\tconst edit = stored as { add?: string[]; remove?: string[] } | undefined;\n\t\tconst removed = new Set(edit?.remove ?? []);\n\t\tselected = [...base, ...(edit?.add ?? [])].filter((name) => !removed.has(name));\n\t}\n\tconst extensions: Extension<Tool>[] = [];\n\tfor (const name of new Set(selected)) {\n\t\tconst extension = snapshot.extension(name);\n\t\tif (extension !== undefined) extensions.push(extension);\n\t}\n\treturn extensions;\n}\n\nfunction applyWrap<T>(\n\titems: Map<string, T>,\n\ttarget: string,\n\twrap: (item: T) => T,\n\tnameOf: (item: T) => string,\n\treport: (error: unknown) => void,\n): void {\n\tconst item = items.get(target);\n\tif (item === undefined) return;\n\ttry {\n\t\tconst wrapped = wrap(item);\n\t\tif (nameOf(wrapped) !== target) throw new Error(`Wrapper renamed ${target} to ${nameOf(wrapped)}`);\n\t\titems.set(target, wrapped);\n\t} catch (error) {\n\t\titems.delete(target);\n\t\treport(error);\n\t}\n}\n", "import type { ImageContent, SystemMessage, TextContent, ThinkingContent, ToolCall } from \"../types.ts\";\n\ntype Content = TextContent | ImageContent | ThinkingContent | ToolCall;\n\n/** Extract and join text from message content. */\nexport function contentText(content: string | readonly Content[], separator = \"\\n\"): string {\n\tif (typeof content === \"string\") return content;\n\treturn content\n\t\t.filter((block) => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(separator);\n}\n\n/** Render a system message as a complete prompt: its content followed by its sections. */\nexport function getSystemMessageText(message: SystemMessage): string {\n\tconst parts = [contentText(message.content)];\n\tfor (const text of Object.values(message.sections ?? {})) {\n\t\tif (text !== null) parts.push(text);\n\t}\n\treturn parts.filter((part) => part.length > 0).join(\"\\n\\n\");\n}\n\n/**\n * Render a later system message for APIs that accept system messages mid-conversation.\n * Section changes are framed by name so the model can relate them to the leading prompt.\n * This framing is request-time only and may change between versions.\n */\nexport function renderSystemMessageUpdate(message: SystemMessage): string {\n\tconst parts: string[] = [];\n\tconst text = contentText(message.content);\n\tif (text.length > 0) parts.push(text);\n\tfor (const [name, value] of Object.entries(message.sections ?? {})) {\n\t\tparts.push(\n\t\t\tvalue === null\n\t\t\t\t? `Removed system prompt section \"${name}\".`\n\t\t\t\t: `Updated system prompt section \"${name}\":\\n\\n${value}`,\n\t\t);\n\t}\n\treturn parts.join(\"\\n\\n\");\n}\n", "import type { AssistantMessage, ImageContent, Message, TextContent, TranscriptContext, Usage } from \"../types.ts\";\nimport { getSystemMessageText } from \"./text.ts\";\n\nexport interface ContextUsageEstimate {\n\t/** Estimated total context tokens. */\n\ttokens: number;\n\t/** Tokens reported by the most recent applicable assistant usage block. */\n\tusageTokens: number;\n\t/** Estimated tokens after the most recent applicable assistant usage block. */\n\ttrailingTokens: number;\n\t/** Index of the applicable message that provided usage, or null when none exists. */\n\tlastUsageIndex: number | null;\n}\n\nconst CHARS_PER_TOKEN = 4;\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\nfunction safeJsonStringify(value: unknown): string {\n\ttry {\n\t\treturn JSON.stringify(value) ?? \"undefined\";\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\n\nfunction estimateTextAndImageContentChars(content: string | Array<TextContent | ImageContent>): number {\n\tif (typeof content === \"string\") return content.length;\n\n\tlet chars = 0;\n\tfor (const block of content) chars += block.type === \"text\" ? block.text.length : ESTIMATED_IMAGE_CHARS;\n\treturn chars;\n}\n\nexport function estimateTextTokens(text: string): number {\n\treturn Math.ceil(text.length / CHARS_PER_TOKEN);\n}\n\nexport function estimateTextAndImageContentTokens(content: string | Array<TextContent | ImageContent>): number {\n\treturn Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN);\n}\n\nexport function estimateMessageTokens(message: Message): number {\n\tlet chars = 0;\n\n\tif (message.role === \"system\") {\n\t\treturn (\n\t\t\testimateTextTokens(getSystemMessageText(message)) +\n\t\t\testimateToolsTokens(message.toolsAdded) +\n\t\t\testimateToolsTokens(message.toolsRemoved)\n\t\t);\n\t}\n\tif (message.role === \"user\") return estimateTextAndImageContentTokens(message.content);\n\tif (message.role === \"toolResult\") return estimateTextAndImageContentTokens(message.content);\n\n\tfor (const block of message.content) {\n\t\tif (block.type === \"text\") {\n\t\t\tchars += block.text.length;\n\t\t} else if (block.type === \"thinking\") {\n\t\t\tchars += block.thinking.length;\n\t\t} else {\n\t\t\tchars += block.name.length + safeJsonStringify(block.arguments).length;\n\t\t}\n\t}\n\treturn Math.ceil(chars / CHARS_PER_TOKEN);\n}\n\nfunction getLastAssistantUsageInfo(messages: readonly Message[]): { usage: Usage; index: number } | undefined {\n\tlet latestPrefixTimestamp = Number.NEGATIVE_INFINITY;\n\tlet usageInfo: { usage: Usage; index: number } | undefined;\n\n\tfor (let i = 0; i < messages.length; i++) {\n\t\tconst message = messages[i];\n\t\tif (message.role === \"assistant\") {\n\t\t\tconst assistant = message as AssistantMessage;\n\t\t\t// A newer prefix message was inserted after this response (for example, a\n\t\t\t// compaction summary), so its usage cannot describe the current prefix.\n\t\t\tconst usageAppliesToPrefix = assistant.timestamp >= latestPrefixTimestamp;\n\t\t\tif (\n\t\t\t\tusageAppliesToPrefix &&\n\t\t\t\tassistant.stopReason !== \"aborted\" &&\n\t\t\t\tassistant.stopReason !== \"error\" &&\n\t\t\t\tcalculateContextTokens(assistant.usage) > 0\n\t\t\t) {\n\t\t\t\tusageInfo = { usage: assistant.usage, index: i };\n\t\t\t}\n\t\t}\n\t\tlatestPrefixTimestamp = Math.max(latestPrefixTimestamp, message.timestamp);\n\t}\n\n\treturn usageInfo;\n}\n\nexport function estimateContextTokens(context: TranscriptContext | readonly Message[]): ContextUsageEstimate {\n\tconst messages = \"messages\" in context ? context.messages : context;\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\tif (usageInfo) {\n\t\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\t\tlet trailingTokens = 0;\n\t\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\t\ttrailingTokens += estimateMessageTokens(messages[i]);\n\t\t}\n\t\treturn { tokens: usageTokens + trailingTokens, usageTokens, trailingTokens, lastUsageIndex: usageInfo.index };\n\t}\n\n\tlet tokens = 0;\n\tfor (const message of messages) tokens += estimateMessageTokens(message);\n\treturn { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };\n}\n\nfunction estimateToolsTokens(tools: readonly unknown[] | undefined): number {\n\tif (!tools || tools.length === 0) return 0;\n\treturn estimateTextTokens(safeJsonStringify(tools));\n}\n", "import type { AssistantMessage } from \"../types.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nconst NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n\n\t// Sign in with ChatGPT: the subscription's shared usage limit, which resets\n\t// after hours rather than seconds.\n\t\"subscription_sharing_usage_limit_exceeded\",\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"currently experiencing high demand\",\n\t\"model is at capacity\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t\"429\",\n\t\"500\",\n\t\"502\",\n\t\"503\",\n\t\"504\",\n\t\"520\",\n\t\"524\",\n\t\"service.?unavailable\",\n\t\"server.?error\",\n\t\"internal.?error\",\n\n\t// Wrapper/provider text for transient upstream failures, including OpenRouter\n\t// \"Provider returned error\" responses (#2264).\n\t\"provider.?returned.?error\",\n\t\"exceeded request buffer limit while retrying upstream\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"upstream.?connect\",\n\t\"reset before headers\",\n\t\"socket hang up\",\n\t\"socket connection was closed\",\n\t\"timed? out\",\n\t\"timeout\",\n\t\"terminated\",\n\n\t// WebSocket transports can report close/error text instead of HTTP/fetch text.\n\t\"websocket.?closed\",\n\t\"websocket.?error\",\n\n\t// Premature stream endings from SDKs and transports. Anthropic can throw\n\t// \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n\t// (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n\t\"ended without\",\n\t\"stream ended before message_stop\",\n\t\"stream ended before a terminal response event\",\n\t\"http2 request did not get a response\",\n\t// Node ERR_HTTP2_STREAM_CANCEL: the HTTP/2 session died before the request was\n\t// sent, e.g. after the Bedrock SDK's 5-minute session timeout (#10379).\n\t\"pending stream has been canceled\",\n\n\t// Provider-requested retry delay cap failures should flow through the outer\n\t// retry policy so callers can surface/abort the backoff (#1123).\n\t\"retry delay\",\n\n\t// Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n\t// stream exceptions (#6019).\n\t\"you can retry your request\",\n\t\"try your request again\",\n\t\"please retry your request\",\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n\n\t// Sign in with ChatGPT: usage or user data temporarily unavailable. Usage\n\t// failures can arrive mid-stream without an HTTP 503 in the message.\n\t\"subscription_sharing_usage_unavailable\",\n\t\"subscription_sharing_user_unavailable\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * `maxAgentDelayMs` caps each computed delay and defaults to 60 seconds.\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`, `maxAgentDelayMs`) in coding-agent; kept\n * here so the classifier and the policy-driven retry loop live together and stay reusable\n * by the SDK and other callers.\n */\nexport interface RetryPolicy {\n\tenabled: boolean;\n\t/** Max retry attempts (0 = no retries). The initial call never counts as a retry. */\n\tmaxRetries: number;\n\t/** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */\n\tbaseDelayMs: number;\n\t/** Optional cap for agent-level retry delays in ms. Defaults to 60 seconds. */\n\tmaxAgentDelayMs?: number;\n}\n\nexport const DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 60_000;\n\nexport function retryDelayMs(policy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\">, attempt: number): number {\n\tconst delay = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);\n\tconst safeDelay = Number.isSafeInteger(delay) ? delay : Number.MAX_SAFE_INTEGER;\n\treturn Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n}\n\n/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */\nexport interface RetryCallbacks {\n\t/** Emitted before the backoff sleep of each retry attempt (1-indexed). */\n\tonRetryScheduled?: (\n\t\tattempt: number,\n\t\tmaxAttempts: number,\n\t\tdelayMs: number,\n\t\terrorMessage: string,\n\t) => void | Promise<void>;\n\t/** Emitted after the backoff sleep, immediately before the retried call starts. */\n\tonRetryAttemptStart?: () => void | Promise<void>;\n\t/** Emitted once when the loop ends: success if a later call completed normally. */\n\tonRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;\n}\n\nclass RetrySleepAbortError extends Error {\n\tconstructor() {\n\t\tsuper(\"Aborted\");\n\t}\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new RetrySleepAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new RetrySleepAbortError());\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(\n\tproduce: () => Promise<AssistantMessage>,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\tconst response = await produce();\n\n\t\t// Abort: terminal but not successful. Never retry an aborted message.\n\t\tif (response.stopReason === \"aborted\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Success: non-error, non-abort responses return as-is.\n\t\tif (response.stopReason !== \"error\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Non-retryable, or budget exhausted: return the final error message.\n\t\tif (attempt >= maxAttempts || !isRetryableAssistantError(response)) {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n\t\t\treturn response;\n\t\t}\n\n\t\tattempt++;\n\t\tlastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n\t\tconst delayMs = retryDelayMs(policy!, attempt);\n\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t// Normalize aborts during retry backoff to the same AssistantMessage shape as\n\t\t// provider stream aborts, so callers do not need to care when cancellation happened.\n\t\ttry {\n\t\t\tawait sleep(delayMs, signal);\n\t\t} catch (error) {\n\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\tif (error instanceof RetrySleepAbortError) {\n\t\t\t\tconst { errorMessage: _errorMessage, ...rest } = response;\n\t\t\t\treturn { ...rest, stopReason: \"aborted\" };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tawait callbacks?.onRetryAttemptStart?.();\n\t}\n}\n\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\tconst errorMessage = message.errorMessage;\n\tif (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)) return false;\n\treturn RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);\n}\n", "import type { Task, TaskDefinition } from \"./types.ts\";\n\n/** Define an executable task. Register it in the registry so a Harness can run tasks of its kind. */\nexport function defineTask<I, S extends { phase: string }, R, H extends object = object>(\n\tdefinition: TaskDefinition<I, S, R, H>,\n): Task<I, S, R, H> {\n\treturn { definition };\n}\n", "import type { Context } from \"@earendil-works/chord\";\nimport type { AssistantMessage, Message, ToolCall, ToolResultMessage } from \"@earendil-works/pi-ai\";\nimport type { SessionImpl } from \"../session/session.ts\";\nimport type { ContextEdit, ConversationId, Cursor, EntryId, EntryRecord, Storage } from \"../types.ts\";\nimport type { ContextView } from \"./types.ts\";\n\nconst SCAN_PAGE_SIZE = 256;\nconst EXCLUDED_STOP_REASONS: ReadonlySet<AssistantMessage[\"stopReason\"]> = new Set([\"aborted\", \"error\", \"deferred\"]);\nconst MISSING_RESULT_TEXT = \"Tool result unavailable: history ends before this call completed.\";\n\n/** Head marker and newest visible entry that fix one committed context range. */\nexport type ContextBounds = {\n\treadonly head: (EntryRecord & { readonly head: EntryId }) | undefined;\n\treadonly tail: EntryId;\n};\n\n/**\n * Capture the bounds of the current context, or of the context cut off at the visible entry `at`, with two O(1)\n * reads. Run this on the Session line; entries at or below the tail are immutable, so `deriveContext()` can then scan\n * them off the line.\n */\nexport async function captureContextBounds(\n\tstorage: Storage,\n\tconversationId: ConversationId,\n\tcontext: Context,\n\tat?: EntryId,\n): Promise<ContextBounds | undefined> {\n\tlet tail: EntryId | undefined;\n\tif (at === undefined) {\n\t\ttail = (await storage.scanEntries({ conversationId }, 1, undefined, context)).items[0]?.id;\n\t\tif (tail === undefined) return undefined;\n\t} else {\n\t\tif ((await storage.entry(conversationId, at, context)) === undefined) {\n\t\t\tthrow new Error(`Entry ${at} is not visible from conversation ${conversationId}`);\n\t\t}\n\t\ttail = at;\n\t}\n\treturn { head: await storage.findLatestHeadMarker(conversationId, tail, context), tail };\n}\n\n/** Committed context of one conversation: bounds captured on the Session line, entries derived off it. */\nexport async function readContext(\n\tsession: SessionImpl,\n\tstorage: Storage,\n\tconversationId: ConversationId,\n\tcontext: Context,\n\tat?: EntryId,\n): Promise<ContextView> {\n\tconst bounds = await session.readOnLine(() => captureContextBounds(storage, conversationId, context, at));\n\treturn deriveContext(storage, conversationId, bounds, context);\n}\n\n/**\n * Derive the active transcript and model context of one conversation within captured bounds.\n *\n * H = newest visible head marker; the range runs from `H.head` (or transcript start) through the tail. Per target,\n * the newest edit in the range wins. Context entries are H followed by the range's non-head entries.\n */\nexport async function deriveContext(\n\tstorage: Storage,\n\tconversationId: ConversationId,\n\tbounds: ContextBounds | undefined,\n\tcontext: Context,\n): Promise<ContextView> {\n\tif (bounds === undefined) return { head: undefined, entries: [], contributions: [], messages: [] };\n\tconst head = bounds.head;\n\tconst range = await scanRange(storage, conversationId, bounds, context);\n\tconst edits = new Map<EntryId, ContextEdit>();\n\t// Edits of every entry in the range count, including older head markers that `selectActive()` drops.\n\tfor (const entry of range) for (const edit of entry.edits ?? []) edits.set(edit.target, edit);\n\n\tconst entries = selectActive(head, range);\n\tconst contributions = entries.map((entry): Message[] => {\n\t\tconst edit = edits.get(entry.id);\n\t\tif (edit?.action === \"omit\") return [];\n\t\tconst contributed = edit?.action === \"replace\" ? edit.messages : (entry.model ?? []);\n\t\treturn contributed.filter(\n\t\t\t(message) => message.role !== \"assistant\" || !EXCLUDED_STOP_REASONS.has(message.stopReason),\n\t\t);\n\t});\n\treturn { head, entries, contributions, messages: orderToolResults(contributions.flat()) };\n}\n\n/** The raw active entries within captured bounds, without deriving model context. */\nexport async function activeEntries(\n\tstorage: Storage,\n\tconversationId: ConversationId,\n\tbounds: ContextBounds | undefined,\n\tcontext: Context,\n): Promise<EntryRecord[]> {\n\tif (bounds === undefined) return [];\n\treturn selectActive(bounds.head, await scanRange(storage, conversationId, bounds, context));\n}\n\n/** Visible entries from the head marker's head, or transcript start, through the tail, oldest first. */\nasync function scanRange(\n\tstorage: Storage,\n\tconversationId: ConversationId,\n\tbounds: ContextBounds,\n\tcontext: Context,\n): Promise<EntryRecord[]> {\n\tconst head = bounds.head;\n\tconst range: EntryRecord[] = [];\n\tlet cursor: Cursor | undefined;\n\tdo {\n\t\tconst page = await storage.scanEntries(\n\t\t\thead === undefined\n\t\t\t\t? { conversationId, maxEntryId: bounds.tail }\n\t\t\t\t: { conversationId, minEntryId: head.head, maxEntryId: bounds.tail },\n\t\t\tSCAN_PAGE_SIZE,\n\t\t\tcursor,\n\t\t\tcontext,\n\t\t);\n\t\trange.push(...page.items);\n\t\tcursor = page.next;\n\t} while (cursor !== undefined);\n\treturn range.reverse();\n}\n\n/** The head marker followed by the range's non-head entries, or the whole range without a marker. */\nfunction selectActive(head: ContextBounds[\"head\"], range: EntryRecord[]): EntryRecord[] {\n\treturn head === undefined ? range : [head, ...range.filter((entry) => entry.head === undefined)];\n}\n\n/**\n * Place each assistant's tool results directly after it in call order. Results are taken from the messages before\n * the next assistant; a missing result is synthesized and unmatched results are dropped.\n */\nexport function orderToolResults(messages: readonly Message[]): Message[] {\n\tconst ordered: Message[] = [];\n\tfor (let index = 0; index < messages.length; index++) {\n\t\tconst message = messages[index]!;\n\t\tif (message.role === \"toolResult\") continue;\n\t\tordered.push(message);\n\t\tif (message.role !== \"assistant\") continue;\n\t\tconst calls = message.content.filter((content): content is ToolCall => content.type === \"toolCall\");\n\t\tif (calls.length === 0) continue;\n\t\tconst results = new Map<string, number>();\n\t\tfor (let next = index + 1; next < messages.length && messages[next]!.role !== \"assistant\"; next++) {\n\t\t\tconst candidate = messages[next]!;\n\t\t\tif (candidate.role === \"toolResult\" && !results.has(candidate.toolCallId)) {\n\t\t\t\tresults.set(candidate.toolCallId, next);\n\t\t\t}\n\t\t}\n\t\tfor (const call of calls) {\n\t\t\tconst resultIndex = results.get(call.id);\n\t\t\tordered.push(resultIndex === undefined ? missingResult(call, message.timestamp) : messages[resultIndex]!);\n\t\t}\n\t}\n\treturn ordered;\n}\n\nfunction missingResult(call: ToolCall, timestamp: number): ToolResultMessage {\n\treturn {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: call.id,\n\t\ttoolName: call.name,\n\t\tcontent: [{ type: \"text\", text: MISSING_RESULT_TEXT }],\n\t\tisError: true,\n\t\tdetails: { reason: \"missing_result\" },\n\t\ttimestamp,\n\t};\n}\n", "import type { AssistantMessage } from \"../types.ts\";\n\n/**\n * Regex patterns to detect context overflow errors from different providers.\n *\n * These patterns match error messages returned when the input exceeds\n * the model's context window.\n *\n * Provider-specific patterns (with example error messages):\n *\n * - Anthropic: \"prompt is too long: 213462 tokens > 200000 maximum\"\n * - Anthropic: \"413 {\\\"error\\\":{\\\"type\\\":\\\"request_too_large\\\",\\\"message\\\":\\\"Request exceeds the maximum size\\\"}}\"\n * - OpenAI: \"Your input exceeds the context window of this model\"\n * - OpenAI/LiteLLM: \"Requested token count exceeds the model's maximum context length of 131072 tokens\"\n * - OpenAI-compatible: \"Input length (265330) exceeds model's maximum context length (262144).\"\n * - Google: \"The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)\"\n * - xAI: \"This model's maximum prompt length is 131072 but the request contains 537812 tokens\"\n * - Groq: \"Please reduce the length of the messages or completion\"\n * - OpenRouter: \"This endpoint's maximum context length is X tokens. However, you requested about Y tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"the request exceeds the available context size, try increasing it\"\n * - LM Studio: \"tokens to keep from the initial prompt is greater than the context length\"\n * - GitHub Copilot: \"prompt token count of X exceeds the limit of Y\"\n * - MiniMax: \"invalid params, context window exceeds limit\"\n * - Kimi For Coding: \"Your request exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - Cerebras: \"400/413 status code (no body)\"\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - z.ai: `{\"code\":\"1261\",\"message\":\"Prompt too long\"}`, `{\"code\":\"1261\",\"message\":\"Prompt exceeds max length\"}` (CN endpoint), or silent overflow via usage.input > contextWindow\n * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason \"length\"\n * with output=0 (no room left to generate). Detected via stopReason \"length\" + zero output +\n * input filling the context window.\n * - DashScope/Qwen: \"Range of input length should be [1, X]\" (HTTP 400 invalid_parameter_error)\n * - Ollama: Some deployments truncate silently, others return errors like \"prompt too long; exceeded max context length by X tokens\"\n */\nconst OVERFLOW_PATTERNS = [\n\t/prompt (?:is )?too long/i, // Anthropic and z.ai token overflow\n\t/prompt exceeds max length/i, // z.ai CN endpoint token overflow\n\t/request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)\n\t/input is too long for requested model/i, // Amazon Bedrock\n\t/exceeds the context window/i, // OpenAI (Completions & Responses API)\n\t/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\\d,]+ tokens?|\\s*\\([\\d,]+\\))/i, // OpenAI-compatible proxies (LiteLLM)\n\t/input token count.*exceeds the maximum/i, // Google (Gemini)\n\t/maximum prompt length is \\d+/i, // xAI (Grok)\n\t/reduce the length of the messages/i, // Groq\n\t/maximum context length is \\d+ tokens/i, // OpenRouter (most backends)\n\t/exceeds (?:the )?maximum allowed input length of [\\d,]+ tokens?/i, // OpenRouter/Poolside\n\t/input \\(\\d+ tokens\\) is longer than the model'?s context length \\(\\d+ tokens\\)/i, // Together AI\n\t/exceeds the limit of \\d+/i, // GitHub Copilot\n\t/exceeds the available context size/i, // llama.cpp server\n\t/greater than the context length/i, // LM Studio\n\t/context window exceeds limit/i, // MiniMax\n\t/exceeded model token limit/i, // Kimi For Coding\n\t/too large for model with \\d+ maximum context length/i, // Mistral\n\t/prompt has [\\d,]+ tokens?, but the configured context size is [\\d,]+ tokens?/i, // DS4 server\n\t/model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text\n\t/prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error\n\t/range of input length should be/i, // DashScope / Qwen Token Plan\n\t/context[_ ]length[_ ]exceeded/i, // Generic fallback\n\t/too many tokens/i, // Generic fallback\n\t/token limit exceeded/i, // Generic fallback\n];\n\nconst CEREBRAS_BODYLESS_OVERFLOW_PATTERN = /^4(?:00|13)\\s*(?:status code)?\\s*\\(no body\\)/i;\n\n/**\n * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).\n * Error messages matching any of these are excluded from overflow detection\n * even if they also match an OVERFLOW_PATTERN.\n *\n * Example: Bedrock formats throttling errors as \"ThrottlingException: Too many tokens,\n * please wait before trying again.\" which would match the /too many tokens/i overflow\n * pattern without this exclusion.\n */\nconst NON_OVERFLOW_PATTERNS = [\n\t/^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)\n\t/rate limit/i, // Generic rate limiting\n\t/too many requests/i, // Generic HTTP 429 style\n];\n\n/**\n * Check if an assistant message represents a context overflow error.\n *\n * This handles three cases:\n * 1. Error-based overflow: Most providers return stopReason \"error\" with a\n * specific error message pattern.\n * 2. Silent overflow: Some providers accept overflow requests and return\n * successfully. For these, we check if usage.input exceeds the context window.\n * 3. Length-stop overflow: Xiaomi MiMo can return \"length\" with zero output when\n * the input fills the context window.\n *\n * ## Reliability by Provider\n *\n * **Reliable detection (returns error with detectable message):**\n * - Anthropic: \"prompt is too long: X tokens > Y maximum\" or \"request_too_large\"\n * - OpenAI (Completions & Responses): \"exceeds the context window\", \"exceeds the model's maximum context length of X tokens\", or \"exceeds model's maximum context length (X)\"\n * - Google Gemini: \"input token count exceeds the maximum\"\n * - xAI (Grok): \"maximum prompt length is X but request contains Y\"\n * - Groq: \"reduce the length of the messages\"\n * - Cerebras: 400/413 status code (no body)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - OpenRouter (most backends): \"maximum context length is X tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"exceeds the available context size\"\n * - LM Studio: \"greater than the context length\"\n * - Kimi For Coding: \"exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - DashScope/Qwen: \"Range of input length should be [1, X]\"\n * - z.ai: \"Prompt too long\"\n *\n * **Unreliable detection:**\n * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),\n * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.\n * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason \"length\" with\n * output=0. Pass contextWindow param to detect via the \"filled context + zero output\" signal.\n * - Ollama: May truncate input silently for some setups, but may also return explicit\n * overflow errors that match the patterns above. Silent truncation still cannot be\n * detected here because we do not know the expected token count.\n *\n * ## Custom Providers\n *\n * If you've added custom models via settings.json, this function may not detect\n * overflow errors from those providers. To add support:\n *\n * 1. Send a request that exceeds the model's context window\n * 2. Check the errorMessage in the response\n * 3. Create a regex pattern that matches the error\n * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or\n * check the errorMessage yourself before calling this function\n *\n * @param message - The assistant message to check\n * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)\n * @returns true if the message indicates a context overflow\n */\nexport function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean {\n\t// Case 1: Check error message patterns\n\tif (message.stopReason === \"error\" && message.errorMessage) {\n\t\t// Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)\n\t\tconst isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!));\n\t\tif (!isNonOverflow) {\n\t\t\tif (OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (message.provider === \"cerebras\" && CEREBRAS_BODYLESS_OVERFLOW_PATTERN.test(message.errorMessage)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Case 2: Silent overflow (z.ai style) - successful but usage exceeds context\n\tif (contextWindow && message.stopReason === \"stop\") {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens > contextWindow) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input\n\t// to fit the context window, leaving no room for output. Returns stopReason \"length\"\n\t// with output=0 and input+cacheRead filling the context window.\n\tif (contextWindow && message.stopReason === \"length\" && message.usage.output === 0) {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens >= contextWindow * 0.99) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * Check whether a length stop ended below the caller or model's intended output limit.\n * Such responses may be caused by context pressure or provider-side truncation, so callers\n * can make one bounded compact-and-retry attempt. `desiredMaxOutput` must be the original\n * limit before any context-based clamping.\n */\nexport function isRecoverableLength(message: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn message.stopReason === \"length\" && desiredMaxOutput > 0 && message.usage.output < desiredMaxOutput;\n}\n\n/**\n * Get the overflow patterns for testing purposes.\n */\nexport function getOverflowPatterns(): RegExp[] {\n\treturn [...OVERFLOW_PATTERNS];\n}\n", "import type { Context, Message, SystemMessage, Tool, ToolReference, TranscriptContext } from \"../types.ts\";\nimport { contentText, getSystemMessageText } from \"./text.ts\";\n\nexport type { TranscriptContext } from \"../types.ts\";\n\n/**\n * Build the leading system message for a prompt and tool set. Returns undefined when\n * both are empty, so an empty transcript stays empty.\n */\nexport function createInitialSystemMessage(\n\tsystemPrompt: string | undefined,\n\ttools: Tool[] | undefined,\n): SystemMessage | undefined {\n\tconst hasSystemPrompt = systemPrompt !== undefined && systemPrompt.length > 0;\n\tconst hasTools = tools !== undefined && tools.length > 0;\n\tif (!hasSystemPrompt && !hasTools) return undefined;\n\treturn {\n\t\trole: \"system\",\n\t\tcontent: systemPrompt ?? \"\",\n\t\t...(hasTools ? { toolsAdded: tools } : {}),\n\t\ttimestamp: 0,\n\t};\n}\n\n/**\n * Fold `Context.systemPrompt` and `Context.tools` into a leading system message.\n * This is the only entry point that produces a {@link TranscriptContext}; every\n * provider-facing function expects the result.\n */\nexport function normalizeContext(context: Context): TranscriptContext {\n\tconst initialMessage = createInitialSystemMessage(context.systemPrompt, context.tools);\n\tconst messages = initialMessage ? [initialMessage, ...context.messages] : context.messages;\n\treturn { messages } as TranscriptContext;\n}\n\n/**\n * Any message list. The replay helpers only read entries whose role is `\"system\"`, so\n * agent transcripts that carry custom message roles can be passed without filtering.\n */\nexport type TranscriptMessages = readonly { role: string }[];\n\nfunction isSystemMessage(message: { role: string }): message is SystemMessage {\n\treturn message.role === \"system\";\n}\n\n/** Return the leading system message, if the transcript starts with one. */\nexport function getInitialSystemMessage(messages: TranscriptMessages): SystemMessage | undefined {\n\tconst first = messages[0];\n\treturn first && isSystemMessage(first) ? first : undefined;\n}\n\n/** Drop the leading system message for APIs that carry the prompt outside the message list. */\nexport function withoutInitialSystemMessage(messages: Message[]): Message[] {\n\treturn getInitialSystemMessage(messages) ? messages.slice(1) : messages;\n}\n\n/** Resolve the tools available after applying every transcript delta in order. */\nexport function getCurrentTools(messages: TranscriptMessages): Tool[] {\n\tconst tools = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsRemoved ?? []) tools.delete(tool.name);\n\t\tfor (const tool of message.toolsAdded ?? []) tools.set(tool.name, tool);\n\t}\n\treturn [...tools.values()];\n}\n\n/**\n * Replay every system message into one leading system message holding the current\n * prompt and tools. Later `content` is appended to the base prompt, `sections` are\n * patched by name, and tools are resolved with {@link getCurrentTools}.\n */\nexport function getCurrentSystemMessage(messages: TranscriptMessages): SystemMessage | undefined {\n\tconst content: string[] = [];\n\tconst sections = new Map<string, string>();\n\tlet timestamp: number | undefined;\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\ttimestamp ??= message.timestamp;\n\t\tconst text = contentText(message.content);\n\t\tif (text.length > 0) content.push(text);\n\t\tfor (const [name, value] of Object.entries(message.sections ?? {})) {\n\t\t\tif (value === null) sections.delete(name);\n\t\t\telse sections.set(name, value);\n\t\t}\n\t}\n\tconst tools = getCurrentTools(messages);\n\tif (timestamp === undefined && tools.length === 0) return undefined;\n\treturn {\n\t\trole: \"system\",\n\t\tcontent: content.join(\"\\n\\n\"),\n\t\t...(sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}),\n\t\t...(tools.length > 0 ? { toolsAdded: tools } : {}),\n\t\ttimestamp: timestamp ?? 0,\n\t};\n}\n\n/** Render the current system prompt text after replaying every system message. */\nexport function getCurrentSystemPrompt(messages: TranscriptMessages): string {\n\tconst message = getCurrentSystemMessage(messages);\n\treturn message ? getSystemMessageText(message) : \"\";\n}\n\n/**\n * Rebuild the transcript for APIs without mid-conversation system messages: the replayed\n * system message leads, and every later system message is dropped.\n */\nexport function collapseSystemMessages(context: TranscriptContext): TranscriptContext {\n\tconst head = getCurrentSystemMessage(context.messages);\n\tconst messages = context.messages.filter((message) => message.role !== \"system\");\n\treturn { messages: head ? [head, ...messages] : messages } as TranscriptContext;\n}\n\n/** Keep later system messages in place when the model accepts them; otherwise collapse them. */\nexport function resolveTranscript(\n\tcontext: TranscriptContext,\n\tsupportsMidConvoSystemMessages: boolean | undefined,\n): TranscriptContext {\n\treturn supportsMidConvoSystemMessages ? context : collapseSystemMessages(context);\n}\n\n/** Strip executable and display-only fields from a tool before transcript comparison or persistence. */\nexport function toToolDeclaration(tool: Tool): Tool {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: JSON.parse(JSON.stringify(tool.parameters)) as Tool[\"parameters\"],\n\t\t...(tool.constrainedSampling === undefined ? {} : { constrainedSampling: tool.constrainedSampling }),\n\t};\n}\n\n/**\n * Whether two tools declare the same interface to the model.\n *\n * Both sides go through {@link toToolDeclaration} first: its JSON round-trip drops the\n * typebox symbol keys and `undefined` fields that a structural comparison would see, and\n * builds both objects with the same key order, so comparing the serialized declarations\n * is exact. This avoids a deep-equal dependency in a browser-safe package.\n */\nexport function declarationsEqual(left: Tool, right: Tool): boolean {\n\treturn JSON.stringify(toToolDeclaration(left)) === JSON.stringify(toToolDeclaration(right));\n}\n\nexport interface ToolStateChanges {\n\ttoolsAdded: Tool[];\n\ttoolsRemoved: ToolReference[];\n}\n\n/** Compare two complete tool states. A changed definition is a removal followed by an addition. */\nexport function getToolStateChanges(previous: readonly Tool[], current: readonly Tool[]): ToolStateChanges {\n\tconst previousTools = new Map(previous.map((tool) => [tool.name, tool]));\n\tconst currentTools = new Map(current.map((tool) => [tool.name, tool]));\n\treturn {\n\t\ttoolsAdded: current\n\t\t\t.filter((tool) => {\n\t\t\t\tconst previousTool = previousTools.get(tool.name);\n\t\t\t\treturn previousTool === undefined || !declarationsEqual(previousTool, tool);\n\t\t\t})\n\t\t\t.map(toToolDeclaration),\n\t\ttoolsRemoved: previous\n\t\t\t.filter((tool) => {\n\t\t\t\tconst currentTool = currentTools.get(tool.name);\n\t\t\t\treturn currentTool === undefined || !declarationsEqual(tool, currentTool);\n\t\t\t})\n\t\t\t.map((tool) => ({ name: tool.name })),\n\t};\n}\n\n/** Every definition referenced by transcript tool state, in first-declaration order. */\nexport function getDeclaredTools(messages: TranscriptMessages): Tool[] {\n\tconst definitions = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsAdded ?? []) definitions.set(tool.name, tool);\n\t}\n\treturn [...definitions.values()];\n}\n\n/**\n * Whether a tool name was declared twice with different definitions. A transport that can\n * only reference previously declared tools by name cannot replay such a history.\n *\n * @deprecated No built-in transport needs this anymore: Anthropic expresses redefinitions with\n * inline `tool_definition` blocks. Kept for API compatibility and will be removed in a future release.\n */\nexport function hasToolRedefinitions(messages: TranscriptMessages): boolean {\n\tconst declared = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsAdded ?? []) {\n\t\t\tconst previous = declared.get(tool.name);\n\t\t\tif (previous !== undefined && !declarationsEqual(previous, tool)) return true;\n\t\t\tdeclared.set(tool.name, tool);\n\t\t}\n\t}\n\treturn false;\n}\n\n/** Whether tool history contains a removal or same-name redeclaration that an addition-only transport cannot replay. */\nexport function hasNonAdditiveToolChanges(messages: TranscriptMessages): boolean {\n\tconst declared = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tif ((message.toolsRemoved?.length ?? 0) > 0) return true;\n\t\tfor (const tool of message.toolsAdded ?? []) {\n\t\t\tif (declared.has(tool.name)) return true;\n\t\t\tdeclared.add(tool.name);\n\t\t}\n\t}\n\treturn false;\n}\n\nexport interface TranscriptTools {\n\t/** Tools sent in the top-level request field. */\n\trequestTools: Tool[];\n\t/**\n\t * Whether later system messages carry their own `toolsAdded` as in-place additions.\n\t * When false, `requestTools` already holds the complete current tool set.\n\t */\n\tanchorsAdditions: boolean;\n}\n\n/**\n * Split tool declarations between the top-level request field and in-place additions.\n * Transports that can anchor additions at a system message keep the initial tools at the\n * top and load later ones where they appear; that only works when no tool was removed or\n * redeclared, so everything else sends the current tool list.\n */\nexport function resolveTranscriptTools(messages: TranscriptMessages, supportsToolAdditions: boolean): TranscriptTools {\n\tconst anchorsAdditions = supportsToolAdditions && !hasNonAdditiveToolChanges(messages);\n\treturn {\n\t\trequestTools: anchorsAdditions\n\t\t\t? (getInitialSystemMessage(messages)?.toolsAdded ?? [])\n\t\t\t: getCurrentTools(messages),\n\t\tanchorsAdditions,\n\t};\n}\n", "import type { Draft, JsonRepresentation } from \"@earendil-works/chord\";\nimport { defineDoc } from \"../documents.ts\";\nimport { UserEntry } from \"../entries.ts\";\nimport type { ConversationId, EntryDraft, EntryId, JsonObject, SubmissionId, Tx } from \"../types.ts\";\nimport type { QueueMode, Settings, UserInput } from \"./types.ts\";\n\n/** A queued submission: user input for a run, or a passive entry write. */\nexport type InboxItem =\n\t| { id: SubmissionId; mode: \"steer\" | \"followUp\"; content: JsonRepresentation<UserInput> }\n\t/** `entry` is an `EntryDraft`, stored as plain JSON. */\n\t| { id: SubmissionId; mode: \"write\"; entry: JsonObject };\n\n/** Built-in queue of one conversation's submissions waiting for a boundary, in ID order. */\nexport type InboxState = { items: InboxItem[] };\n\nexport const InboxDoc = defineDoc<InboxState>({\n\tkind: \"pi.inbox\",\n\tversion: 1,\n\tscope: \"conversation\",\n\thistory: \"latest\",\n\tfork: \"initial\",\n\tinitial: () => ({ items: [] }),\n\tcheckpointWhen: (value) => value.items.length === 0,\n});\n\n/** The settings a boundary reads, on the Session line. */\nexport type QueueModes = Pick<Settings, \"steeringMode\" | \"followUpMode\">;\n\n/** What a boundary reads before the commit's first table write, and the newest head it has seen so far. */\nexport type Boundary = {\n\treadonly conversationId: ConversationId;\n\treadonly inbox: Draft<InboxState>;\n\treadonly steeringMode: QueueMode;\n\treadonly followUpMode: QueueMode;\n\t/** Start of the active range, the newest head marker's `head`; advanced by heads written in this commit. */\n\thead: EntryId | undefined;\n};\n\n/** Selected user items, in ID order, and whether a `head: \"self\"` write (a reset) was placed. */\nexport type BoundaryResult = { readonly users: SubmissionId[]; readonly reset: boolean };\n\n/**\n * Read what a boundary needs. Table reads must precede the commit's first table write, so callers prepare the\n * boundary at the start of their commit.\n */\nexport async function prepareBoundary(tx: Tx, conversationId: ConversationId, modes: QueueModes): Promise<Boundary> {\n\tconst head = (await tx.latestHeadMarker(conversationId))?.head;\n\tconst inbox = await tx.doc(InboxDoc, conversationId);\n\treturn {\n\t\tconversationId,\n\t\tinbox,\n\t\tsteeringMode: modes.steeringMode,\n\t\tfollowUpMode: modes.followUpMode,\n\t\thead,\n\t};\n}\n\n/**\n * Place the queued items a boundary selects (spec §6): every write, the first or all steers, and at `final` the first\n * or all follow-ups. A selected reset turns a `postTools` boundary into `final`. Writes are placed first and user\n * items after them, each in ID order, so user items queued before a reset run in the new context. A write whose head\n * targets an entry before the active range, including a range started earlier in this commit, is stale. Selected and\n * stale items are removed positionally.\n */\nexport async function applyBoundary(\n\ttx: Tx,\n\tboundary: Boundary,\n\tat: \"postTools\" | \"final\",\n\tnow: number,\n): Promise<BoundaryResult> {\n\tconst { conversationId, inbox } = boundary;\n\tconst items = inbox.items;\n\tconst reset = items.some((item) => item.mode === \"write\" && item.entry.head === \"self\");\n\tconst final = at === \"final\" || reset;\n\tconst pick = (mode: \"steer\" | \"followUp\", queueMode: QueueMode): number[] => {\n\t\tconst indexes = items.flatMap((item, index) => (item.mode === mode ? [index] : []));\n\t\treturn queueMode === \"all\" ? indexes : indexes.slice(0, 1);\n\t};\n\tconst writes = items.flatMap((item, index) => (item.mode === \"write\" ? [index] : []));\n\tconst users = [...pick(\"steer\", boundary.steeringMode), ...(final ? pick(\"followUp\", boundary.followUpMode) : [])];\n\tusers.sort((a, b) => a - b);\n\n\t// `appendEntry()` copies the drafts' values; the items are removed only afterwards.\n\tfor (const index of writes) {\n\t\tconst item = items[index] as Draft<Extract<InboxItem, { mode: \"write\" }>>;\n\t\tconst draft = item.entry as unknown as EntryDraft;\n\t\tif (isStale(boundary, draft)) {\n\t\t\ttx.settleSubmission(item.id, { status: \"unanswered\", reason: \"stale\" });\n\t\t\tcontinue;\n\t\t}\n\t\tconst entry = await tx.appendEntry(conversationId, draft);\n\t\tif (draft.head !== undefined) boundary.head = draft.head === \"self\" ? entry.id : draft.head;\n\t\ttx.placeSubmission(item.id, entry.id);\n\t}\n\tconst placed: SubmissionId[] = [];\n\tfor (const index of users) {\n\t\tconst item = items[index] as Draft<Extract<InboxItem, { mode: \"steer\" | \"followUp\" }>>;\n\t\tconst message = { role: \"user\", content: item.content as UserInput, timestamp: now } as const;\n\t\tconst entry = await tx.appendEntry(UserEntry, conversationId, { model: [message] });\n\t\ttx.placeSubmission(item.id, entry.id);\n\t\tplaced.push(item.id);\n\t}\n\tconst removed = [...writes, ...users].sort((a, b) => b - a);\n\tfor (const index of removed) items.splice(index, 1);\n\treturn { users: placed, reset };\n}\n\n/** Whether a head write targets an entry before the active range, so placing it would bring back cut history. */\nexport function isStale(boundary: Boundary, entry: EntryDraft): boolean {\n\treturn typeof entry.head === \"number\" && boundary.head !== undefined && entry.head < boundary.head;\n}\n\n/** Remove a withdrawn submission's item; the caller settles the submission. */\nexport async function removeInboxItem(tx: Tx, conversationId: ConversationId, id: SubmissionId): Promise<void> {\n\tconst items = (await tx.doc(InboxDoc, conversationId)).items;\n\tconst index = items.findIndex((item) => item.id === id);\n\tif (index >= 0) items.splice(index, 1);\n}\n\n/**\n * Withdraw every queued input of a conversation, as `Conversation.abort()` and abort cascades do: each settles\n * `unanswered` with `aborted` and leaves the inbox; queued writes stay for later placement.\n */\nexport async function withdrawQueuedInputs(tx: Tx, conversationId: ConversationId): Promise<void> {\n\tconst items = (await tx.doc(InboxDoc, conversationId)).items;\n\tfor (let index = items.length - 1; index >= 0; index--) {\n\t\tconst item = items[index]!;\n\t\tif (item.mode === \"write\") continue;\n\t\ttx.settleSubmission(item.id, { status: \"unanswered\", reason: \"aborted\" });\n\t\titems.splice(index, 1);\n\t}\n}\n", "import type { JsonValue } from \"@earendil-works/chord\";\n\ntype JsonContainer = Record<string, JsonValue> | JsonValue[];\n\n/**\n * Assign `value` at `target[key]` leaf by leaf. Chord records a container assignment as one full set and only emits an\n * append when a string leaf is reassigned with a longer string, so writing the partial whole would store and publish the\n * complete message on every flush.\n */\nexport function assignJson(target: JsonContainer, key: string | number, value: JsonValue): void {\n\tconst slots = target as Record<string | number, JsonValue>;\n\tconst current = slots[key];\n\tif (isRecord(current) && isRecord(value)) {\n\t\tfor (const name of Object.keys(current)) if (!Object.hasOwn(value, name)) delete current[name];\n\t\tfor (const [name, child] of Object.entries(value)) assignJson(current, name, child);\n\t\treturn;\n\t}\n\tif (Array.isArray(current) && Array.isArray(value) && current.length <= value.length) {\n\t\tconst items = current as JsonValue[];\n\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\tif (index < items.length) assignJson(items, index, value[index]!);\n\t\t\telse items.push(value[index]!);\n\t\t}\n\t\treturn;\n\t}\n\tif (current !== value) slots[key] = value;\n}\n\nfunction isRecord(value: JsonValue | undefined): value is Record<string, JsonValue> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "import type { Context } from \"@earendil-works/chord\";\nimport type { Message, SystemMessage, Tool, ToolReference } from \"@earendil-works/pi-ai\";\nimport { declarationsEqual, getCurrentTools, toToolDeclaration } from \"@earendil-works/pi-ai/utils/transcript\";\nimport { SystemEntry } from \"../entries.ts\";\nimport type { ContextEdit, TypedEntryDraft } from \"../types.ts\";\nimport type { ContextView, PromptInput, PromptSection, ToolRegistration } from \"./types.ts\";\n\n/** Sections in effect after replaying system messages in order: set in place, `null` deletes, re-adding appends. */\nexport function replaySections(messages: readonly Message[]): Map<string, string> {\n\tconst shown = new Map<string, string>();\n\tfor (const message of messages) {\n\t\tif (message.role !== \"system\" || message.sections === undefined) continue;\n\t\tfor (const [key, value] of Object.entries(message.sections)) {\n\t\t\tif (value === null) shown.delete(key);\n\t\t\telse shown.set(key, value);\n\t\t}\n\t}\n\treturn shown;\n}\n\n/**\n * Render the agent's sections in order. `undefined` omits a section; tagged text is wrapped as `<key>\\n...\\n</key>`. A\n * section that throws keeps its shown text, if any, and is reported; errors after `context` is aborted propagate.\n */\nexport async function renderSections<Tool extends ToolRegistration>(\n\tsections: readonly PromptSection<Tool>[],\n\tinput: PromptInput<Tool>,\n\tshown: ReadonlyMap<string, string>,\n\treport: (error: unknown) => void,\n\tcontext: Context,\n): Promise<Map<string, string>> {\n\tconst desired = new Map<string, string>();\n\tfor (const section of sections) {\n\t\tlet text: string | undefined;\n\t\ttry {\n\t\t\ttext = await section.render(input, context);\n\t\t} catch (error) {\n\t\t\tif (context.abortSignal?.aborted) throw error;\n\t\t\treport(error);\n\t\t\tconst kept = shown.get(section.key);\n\t\t\tif (kept !== undefined) desired.set(section.key, kept);\n\t\t\tcontinue;\n\t\t}\n\t\tif (text === undefined) continue;\n\t\tdesired.set(section.key, section.tag === false ? text : `<${section.key}>\\n${text}\\n</${section.key}>`);\n\t}\n\treturn desired;\n}\n\ntype SystemDraft = TypedEntryDraft<never>;\n\ntype ToolChanges = { readonly toolsRemoved: ToolReference[]; readonly toolsAdded: Tool[] };\n\n/**\n * Plan the `pi.system` entries that make the replayed sections and tools of `view` equal `desired` and `tools` in values\n * and order.\n *\n * - A head marker with no later `pi.system` entry in context: one complete baseline that omits every retained earlier\n * `pi.system` entry, written even when it restates the replayed values.\n * - Otherwise, when a minimal section patch would leave a different order: remove every shown section, then re-add\n * every desired section in order.\n * - Otherwise the minimal patch of changed values and `null` removals, or nothing.\n *\n * Tool changes ride on the last planned entry, or on one entry of their own.\n */\nexport function planSystemEntries(\n\tview: ContextView,\n\tdesired: ReadonlyMap<string, string>,\n\ttools: readonly Tool[],\n\ttimestamp: number,\n): SystemDraft[] {\n\tconst head = view.head;\n\tif (head !== undefined && !view.entries.some((entry) => SystemEntry.is(entry) && entry.id > head.id)) {\n\t\tconst edits: ContextEdit[] = view.entries\n\t\t\t.filter((entry) => SystemEntry.is(entry))\n\t\t\t.map((entry) => ({ target: entry.id, action: \"omit\" }));\n\t\tconst baseline = systemEntry(\n\t\t\tObject.fromEntries(desired),\n\t\t\t{ toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) },\n\t\t\ttimestamp,\n\t\t);\n\t\treturn [edits.length === 0 ? baseline : { ...baseline, edits }];\n\t}\n\tconst sections = planSections(replaySections(view.messages), desired);\n\tconst changes = planTools(getCurrentTools(view.messages), tools);\n\tif (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) {\n\t\treturn sections.map((patch) => systemEntry(patch, undefined, timestamp));\n\t}\n\tif (sections.length === 0) return [systemEntry(undefined, changes, timestamp)];\n\treturn sections.map((patch, index) =>\n\t\tsystemEntry(patch, index === sections.length - 1 ? changes : undefined, timestamp),\n\t);\n}\n\n/**\n * Tool changes from `offered` to `desired`. A changed declaration is removed and re-added. Replay keeps retained tools\n * in place and appends additions; when that would not yield the desired order, every offered tool is removed and\n * every desired tool re-added in order.\n */\nfunction planTools(offered: readonly Tool[], desired: readonly Tool[]): ToolChanges {\n\tconst wanted = new Map(desired.map((tool) => [tool.name, tool]));\n\tconst kept = offered.filter((tool) => {\n\t\tconst next = wanted.get(tool.name);\n\t\treturn next !== undefined && declarationsEqual(tool, next);\n\t});\n\tconst keptNames = new Set(kept.map((tool) => tool.name));\n\tconst added = desired.filter((tool) => !keptNames.has(tool.name));\n\tconst replayed = [...kept, ...added];\n\tif (replayed.some((tool, index) => tool.name !== desired[index]!.name)) {\n\t\treturn {\n\t\t\ttoolsRemoved: offered.map((tool) => ({ name: tool.name })),\n\t\t\ttoolsAdded: desired.map(toToolDeclaration),\n\t\t};\n\t}\n\treturn {\n\t\ttoolsRemoved: offered.filter((tool) => !keptNames.has(tool.name)).map((tool) => ({ name: tool.name })),\n\t\ttoolsAdded: added.map(toToolDeclaration),\n\t};\n}\n\n/** Section patches: none, the minimal patch, or a remove-all/re-add-all pair when the order would differ. */\nfunction planSections(\n\tshown: ReadonlyMap<string, string>,\n\tdesired: ReadonlyMap<string, string>,\n): Record<string, string | null>[] {\n\tconst patchedOrder = [\n\t\t...[...shown.keys()].filter((key) => desired.has(key)),\n\t\t...[...desired.keys()].filter((key) => !shown.has(key)),\n\t];\n\tconst desiredOrder = [...desired.keys()];\n\tif (patchedOrder.some((key, index) => key !== desiredOrder[index])) {\n\t\treturn [Object.fromEntries([...shown.keys()].map((key) => [key, null])), Object.fromEntries(desired)];\n\t}\n\n\tconst patch: Record<string, string | null> = {};\n\tfor (const [key, value] of shown) {\n\t\tconst next = desired.get(key);\n\t\tif (next !== value) patch[key] = next ?? null;\n\t}\n\tfor (const [key, value] of desired) if (!shown.has(key)) patch[key] = value;\n\treturn Object.keys(patch).length === 0 ? [] : [patch];\n}\n\nfunction systemEntry(\n\tsections: Record<string, string | null> | undefined,\n\ttools: ToolChanges | undefined,\n\ttimestamp: number,\n): SystemDraft {\n\tconst message: SystemMessage = {\n\t\trole: \"system\",\n\t\tcontent: \"\",\n\t\t...(sections === undefined ? {} : { sections }),\n\t\t...(tools === undefined || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }),\n\t\t...(tools === undefined || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }),\n\t\ttimestamp,\n\t};\n\treturn { model: [message] };\n}\n", "const MAX_UUID_V7_TIMESTAMP = 0xffffffffffff;\nconst MAX_SEQUENCE = (1n << 41n) - 1n;\n\nlet lastOrdinaryTimestamp = -1;\nlet sequence: bigint | undefined;\n\n/** Generate a time-ordered UUIDv7. A supplied timestamp is preserved for follower ids. */\nexport function uuidv7(timestampMs?: number): string {\n\tconst requestedTimestamp = timestampMs ?? Date.now();\n\tif (!Number.isInteger(requestedTimestamp) || requestedTimestamp < 0 || requestedTimestamp > MAX_UUID_V7_TIMESTAMP) {\n\t\tthrow new RangeError(`UUIDv7 timestamp must be an integer between 0 and ${MAX_UUID_V7_TIMESTAMP}`);\n\t}\n\n\tconst effectiveTimestamp =\n\t\ttimestampMs === undefined ? Math.max(requestedTimestamp, lastOrdinaryTimestamp) : timestampMs;\n\tif (timestampMs === undefined) lastOrdinaryTimestamp = effectiveTimestamp;\n\n\tconst bytes = new Uint8Array(16);\n\tglobalThis.crypto.getRandomValues(bytes);\n\tif (sequence === undefined) {\n\t\tsequence =\n\t\t\t(BigInt(bytes[1]) << 32n) |\n\t\t\t(BigInt(bytes[2]) << 24n) |\n\t\t\t(BigInt(bytes[3]) << 16n) |\n\t\t\t(BigInt(bytes[4]) << 8n) |\n\t\t\tBigInt(bytes[5]);\n\t} else {\n\t\tif (sequence === MAX_SEQUENCE) throw new RangeError(\"UUIDv7 generator sequence exhausted\");\n\t\tsequence++;\n\t}\n\n\tconst timestamp = BigInt(effectiveTimestamp);\n\tfor (let index = 5; index >= 0; index--) {\n\t\tbytes[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 0xff;\n\t}\n\tbytes[6] = 0x70 | Number((sequence >> 37n) & 0x0fn);\n\tbytes[7] = Number((sequence >> 29n) & 0xffn);\n\tbytes[8] = 0x80 | Number((sequence >> 23n) & 0x3fn);\n\tbytes[9] = Number((sequence >> 15n) & 0xffn);\n\tbytes[10] = Number((sequence >> 7n) & 0xffn);\n\tbytes[11] = Number((sequence & 0x7fn) << 1n) | (bytes[11] & 0x01);\n\n\tconst hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\"));\n\treturn `${hex.slice(0, 4).join(\"\")}-${hex.slice(4, 6).join(\"\")}-${hex.slice(6, 8).join(\"\")}-${hex.slice(8, 10).join(\"\")}-${hex.slice(10).join(\"\")}`;\n}\n", "import type { Context } from \"@earendil-works/chord\";\nimport { uuidv7 } from \"@earendil-works/pi-ai/utils/uuid\";\nimport { defineDoc } from \"../documents.ts\";\nimport type { TaskRuntime } from \"../types.ts\";\n\n/** Stable provider-facing identity of one conversation. */\nexport type ProviderState = {\n\tsessionId: string;\n};\n\n/** Built-in provider state; every fork starts with a fresh identity instead of copying its parent. */\nexport const ProviderDoc = defineDoc<ProviderState>({\n\tkind: \"pi.provider\",\n\tversion: 1,\n\tscope: \"conversation\",\n\thistory: \"latest\",\n\tfork: \"initial\",\n\tinitial: () => ({ sessionId: uuidv7() }),\n\tcheckpointWhen: () => true,\n});\n\n/**\n * Return the persisted identity without writing in the normal path. A legacy conversation without `pi.provider` gets\n * one migration commit whose `tx.doc()` runs `initial()` before the provider request starts.\n */\nexport async function ensureProviderSessionId<I, S, R, H extends object>(\n\truntime: TaskRuntime<I, S, R, H>,\n\tcontext: Context,\n): Promise<string> {\n\tconst existing = await runtime.snapshot(ProviderDoc, runtime.conversationId, context);\n\tif (existing !== undefined) return existing.sessionId;\n\tlet created: string | undefined;\n\tawait runtime.commit(async (tx) => {\n\t\tcreated = (await tx.doc(ProviderDoc, runtime.conversationId)).sessionId;\n\t\treturn undefined;\n\t}, context);\n\tif (created === undefined) throw new Error(`Conversation ${runtime.conversationId} has no provider session ID`);\n\treturn created;\n}\n", "import { Compile } from \"typebox/compile\";\nimport type { TLocalizedValidationError } from \"typebox/error\";\nimport { Value } from \"typebox/value\";\nimport type { Tool, ToolCall } from \"../types.ts\";\n\nconst validatorCache = new WeakMap<object, ReturnType<typeof Compile>>();\nconst TYPEBOX_KIND = Symbol.for(\"TypeBox.Kind\");\n\ninterface JsonSchemaObject {\n\ttype?: string | string[];\n\tproperties?: Record<string, JsonSchemaObject>;\n\trequired?: string[];\n\titems?: JsonSchemaObject | JsonSchemaObject[];\n\tadditionalProperties?: boolean | JsonSchemaObject;\n\tallOf?: JsonSchemaObject[];\n\tanyOf?: JsonSchemaObject[];\n\toneOf?: JsonSchemaObject[];\n}\n\nfunction getSchemaTypes(schema: JsonSchemaObject): string[] {\n\tif (typeof schema.type === \"string\") {\n\t\treturn [schema.type];\n\t}\n\tif (Array.isArray(schema.type)) {\n\t\treturn schema.type.filter((type): type is string => typeof type === \"string\");\n\t}\n\treturn [];\n}\n\nfunction matchesJsonType(value: unknown, type: string): boolean {\n\tswitch (type) {\n\t\tcase \"number\":\n\t\t\treturn typeof value === \"number\";\n\t\tcase \"integer\":\n\t\t\treturn typeof value === \"number\" && Number.isInteger(value);\n\t\tcase \"boolean\":\n\t\t\treturn typeof value === \"boolean\";\n\t\tcase \"string\":\n\t\t\treturn typeof value === \"string\";\n\t\tcase \"null\":\n\t\t\treturn value === null;\n\t\tcase \"array\":\n\t\t\treturn Array.isArray(value);\n\t\tcase \"object\":\n\t\t\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction getSubSchemaValidator(schema: JsonSchemaObject): ReturnType<typeof Compile> | undefined {\n\ttry {\n\t\treturn getValidator(schema as Tool[\"parameters\"]);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction coercePrimitiveByType(value: unknown, type: string): unknown {\n\tswitch (type) {\n\t\tcase \"number\": {\n\t\t\tif (value === null) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (typeof value === \"string\" && value.trim() !== \"\") {\n\t\t\t\tconst parsed = Number(value);\n\t\t\t\tif (Number.isFinite(parsed)) {\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (typeof value === \"boolean\") {\n\t\t\t\treturn value ? 1 : 0;\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tcase \"integer\": {\n\t\t\tif (value === null) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (typeof value === \"string\" && value.trim() !== \"\") {\n\t\t\t\tconst parsed = Number(value);\n\t\t\t\tif (Number.isInteger(parsed)) {\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (typeof value === \"boolean\") {\n\t\t\t\treturn value ? 1 : 0;\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tcase \"boolean\": {\n\t\t\tif (value === null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (typeof value === \"string\") {\n\t\t\t\tif (value === \"true\") {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (value === \"false\") {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (typeof value === \"number\") {\n\t\t\t\tif (value === 1) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tcase \"string\": {\n\t\t\tif (value === null) {\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t\tif (typeof value === \"number\" || typeof value === \"boolean\") {\n\t\t\t\treturn String(value);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tcase \"null\": {\n\t\t\tif (value === \"\" || value === 0 || value === false) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tdefault:\n\t\t\treturn value;\n\t}\n}\n\nfunction applySchemaObjectCoercion(value: Record<string, unknown>, schema: JsonSchemaObject): void {\n\tconst properties = schema.properties;\n\tconst definedKeys = new Set<string>(properties ? Object.keys(properties) : []);\n\n\tif (properties) {\n\t\tfor (const [key, propertySchema] of Object.entries(properties)) {\n\t\t\tif (!(key in value)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalue[key] = coerceWithJsonSchema(value[key], propertySchema);\n\t\t}\n\t}\n\n\tif (schema.additionalProperties && typeof schema.additionalProperties === \"object\") {\n\t\tfor (const [key, propertyValue] of Object.entries(value)) {\n\t\t\tif (definedKeys.has(key)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalue[key] = coerceWithJsonSchema(propertyValue, schema.additionalProperties);\n\t\t}\n\t}\n}\n\nfunction applySchemaArrayCoercion(value: unknown[], schema: JsonSchemaObject): void {\n\tif (Array.isArray(schema.items)) {\n\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\tconst itemSchema = schema.items[index];\n\t\t\tif (!itemSchema) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalue[index] = coerceWithJsonSchema(value[index], itemSchema);\n\t\t}\n\t\treturn;\n\t}\n\n\tif (schema.items && typeof schema.items === \"object\") {\n\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\tvalue[index] = coerceWithJsonSchema(value[index], schema.items);\n\t\t}\n\t}\n}\n\nfunction coerceWithUnionSchema(value: unknown, schemas: JsonSchemaObject[]): unknown {\n\tfor (const schema of schemas) {\n\t\tconst validator = getSubSchemaValidator(schema);\n\t\tif (validator?.Check(value)) {\n\t\t\treturn value;\n\t\t}\n\t}\n\n\tfor (const schema of schemas) {\n\t\tconst candidate = structuredClone(value);\n\t\tconst coerced = coerceWithJsonSchema(candidate, schema);\n\t\tconst validator = getSubSchemaValidator(schema);\n\t\tif (validator?.Check(coerced)) {\n\t\t\treturn coerced;\n\t\t}\n\t}\n\treturn value;\n}\n\nfunction coerceWithJsonSchema(value: unknown, schema: JsonSchemaObject): unknown {\n\tlet nextValue = value;\n\n\tif (Array.isArray(schema.allOf)) {\n\t\tfor (const nested of schema.allOf) {\n\t\t\tnextValue = coerceWithJsonSchema(nextValue, nested);\n\t\t}\n\t}\n\n\tif (Array.isArray(schema.anyOf)) {\n\t\tnextValue = coerceWithUnionSchema(nextValue, schema.anyOf);\n\t}\n\n\tif (Array.isArray(schema.oneOf)) {\n\t\tnextValue = coerceWithUnionSchema(nextValue, schema.oneOf);\n\t}\n\n\tconst schemaTypes = getSchemaTypes(schema);\n\tconst matchesUnionMember =\n\t\tschemaTypes.length > 1 && schemaTypes.some((schemaType) => matchesJsonType(nextValue, schemaType));\n\tif (schemaTypes.length > 0 && !matchesUnionMember) {\n\t\tfor (const schemaType of schemaTypes) {\n\t\t\tconst candidate = coercePrimitiveByType(nextValue, schemaType);\n\t\t\tif (candidate !== nextValue) {\n\t\t\t\tnextValue = candidate;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (\n\t\tschemaTypes.includes(\"object\") &&\n\t\ttypeof nextValue === \"object\" &&\n\t\tnextValue !== null &&\n\t\t!Array.isArray(nextValue)\n\t) {\n\t\tapplySchemaObjectCoercion(nextValue as Record<string, unknown>, schema);\n\t}\n\n\tif (schemaTypes.includes(\"array\") && Array.isArray(nextValue)) {\n\t\tapplySchemaArrayCoercion(nextValue, schema);\n\t}\n\n\treturn nextValue;\n}\n\nfunction normalizeOptionalNulls(value: unknown, schema: JsonSchemaObject): void {\n\tif (Array.isArray(value)) {\n\t\tif (Array.isArray(schema.items)) {\n\t\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\t\tconst itemSchema = schema.items[index];\n\t\t\t\tif (itemSchema) normalizeOptionalNulls(value[index], itemSchema);\n\t\t\t}\n\t\t} else if (schema.items) {\n\t\t\tfor (const item of value) normalizeOptionalNulls(item, schema.items);\n\t\t}\n\t\treturn;\n\t}\n\tif (typeof value !== \"object\" || value === null || !schema.properties) return;\n\n\tconst object = value as Record<string, unknown>;\n\tconst required = new Set(schema.required ?? []);\n\tfor (const [key, propertySchema] of Object.entries(schema.properties)) {\n\t\tif (!(key in object)) continue;\n\t\tif (\n\t\t\tobject[key] === null &&\n\t\t\t!required.has(key) &&\n\t\t\ttypeof (propertySchema as { $ref?: unknown }).$ref !== \"string\" &&\n\t\t\tgetSubSchemaValidator(propertySchema)?.Check(null) === false\n\t\t) {\n\t\t\tdelete object[key];\n\t\t} else {\n\t\t\tnormalizeOptionalNulls(object[key], propertySchema);\n\t\t}\n\t}\n}\n\nfunction getValidator(schema: Tool[\"parameters\"]): ReturnType<typeof Compile> {\n\tconst key = schema as object;\n\tconst cached = validatorCache.get(key);\n\tif (cached) {\n\t\treturn cached;\n\t}\n\tconst validator = Compile(schema);\n\tvalidatorCache.set(key, validator);\n\treturn validator;\n}\n\nfunction formatValidationPath(error: TLocalizedValidationError): string {\n\tif (error.keyword === \"required\") {\n\t\tconst requiredProperties = (error.params as { requiredProperties?: string[] }).requiredProperties;\n\t\tconst requiredProperty = requiredProperties?.[0];\n\t\tif (requiredProperty) {\n\t\t\tconst basePath = error.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\");\n\t\t\treturn basePath ? `${basePath}.${requiredProperty}` : requiredProperty;\n\t\t}\n\t}\n\tconst path = error.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\");\n\treturn path || \"root\";\n}\n\n/**\n * Finds a tool by name and validates the tool call arguments against its TypeBox schema\n * @param tools Array of tool definitions\n * @param toolCall The tool call from the LLM\n * @returns The validated arguments\n * @throws Error if tool is not found or validation fails\n */\nexport function validateToolCall(tools: Tool[], toolCall: ToolCall): any {\n\tconst tool = tools.find((t) => t.name === toolCall.name);\n\tif (!tool) {\n\t\tthrow new Error(`Tool \"${toolCall.name}\" not found`);\n\t}\n\treturn validateToolArguments(tool, toolCall);\n}\n\n/**\n * Validates tool call arguments against the tool's TypeBox schema\n * @param tool The tool definition with TypeBox schema\n * @param toolCall The tool call from the LLM\n * @returns The validated (and potentially coerced) arguments\n * @throws Error with formatted message if validation fails\n */\nexport function validateToolArguments(tool: Tool, toolCall: ToolCall): any {\n\tconst args = structuredClone(toolCall.arguments);\n\tnormalizeOptionalNulls(args, tool.parameters as JsonSchemaObject);\n\tValue.Convert(tool.parameters, args);\n\n\tconst validator = getValidator(tool.parameters);\n\tif (!Object.getOwnPropertySymbols(tool.parameters).includes(TYPEBOX_KIND)) {\n\t\tconst coerced = coerceWithJsonSchema(args, tool.parameters as JsonSchemaObject);\n\t\tif (coerced !== args) {\n\t\t\tif (typeof args === \"object\" && args !== null && typeof coerced === \"object\" && coerced !== null) {\n\t\t\t\tfor (const key of Object.keys(args)) {\n\t\t\t\t\tdelete args[key];\n\t\t\t\t}\n\t\t\t\tObject.assign(args, coerced);\n\t\t\t} else {\n\t\t\t\treturn validator.Check(coerced) ? coerced : args;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (validator.Check(args)) {\n\t\treturn args;\n\t}\n\n\tconst errors =\n\t\tvalidator\n\t\t\t.Errors(args)\n\t\t\t.map((error) => ` - ${formatValidationPath(error)}: ${error.message}`)\n\t\t\t.join(\"\\n\") || \"Unknown validation error\";\n\n\tconst errorMessage = `Validation failed for tool \"${toolCall.name}\":\\n${errors}\\n\\nReceived arguments:\\n${JSON.stringify(toolCall.arguments, null, 2)}`;\n\n\tthrow new Error(errorMessage);\n}\n", "/**\n * Shared truncation utilities for tool outputs.\n *\n * Truncation is based on two independent limits - whichever is hit first wins:\n * - Line limit (default: 2000 lines)\n * - Byte limit (default: 50KB)\n *\n * Never returns partial lines. Tool output streams are bounded by `src/harness/output.ts` instead.\n */\n\nexport const DEFAULT_MAX_LINES = 2000;\nexport const DEFAULT_MAX_BYTES = 50 * 1024; // 50KB\n\nexport interface TruncationResult {\n\t/** The truncated content */\n\tcontent: string;\n\t/** Whether truncation occurred */\n\ttruncated: boolean;\n\t/** Which limit was hit: \"lines\", \"bytes\", or null if not truncated */\n\ttruncatedBy: \"lines\" | \"bytes\" | null;\n\t/** Total number of lines in the original content */\n\ttotalLines: number;\n\t/** Total number of bytes in the original content */\n\ttotalBytes: number;\n\t/** Number of complete lines in the truncated output */\n\toutputLines: number;\n\t/** Number of bytes in the truncated output */\n\toutputBytes: number;\n\t/** Whether the last line was partially truncated (only for tail truncation edge case) */\n\tlastLinePartial: boolean;\n\t/** Whether the first line exceeded the byte limit (for head truncation) */\n\tfirstLineExceedsLimit: boolean;\n\t/** The max lines limit that was applied */\n\tmaxLines: number;\n\t/** The max bytes limit that was applied */\n\tmaxBytes: number;\n}\n\nexport interface TruncationOptions {\n\t/** Maximum number of lines (default: 2000) */\n\tmaxLines?: number;\n\t/** Maximum number of bytes (default: 50KB) */\n\tmaxBytes?: number;\n}\n\ninterface RuntimeBuffer {\n\tbyteLength(content: string, encoding: \"utf8\"): number;\n}\n\nconst runtimeBuffer = (globalThis as { Buffer?: RuntimeBuffer }).Buffer;\nconst nonAsciiPattern = /[^\\x00-\\x7f]/;\n\nexport function utf8ByteLength(content: string): number {\n\tif (runtimeBuffer) return runtimeBuffer.byteLength(content, \"utf8\");\n\n\tconst firstNonAscii = content.search(nonAsciiPattern);\n\tif (firstNonAscii === -1) return content.length;\n\n\tlet bytes = firstNonAscii;\n\tfor (let i = firstNonAscii; i < content.length; i++) {\n\t\tconst code = content.charCodeAt(i);\n\t\tif (code <= 0x7f) {\n\t\t\tbytes += 1;\n\t\t} else if (code <= 0x7ff) {\n\t\t\tbytes += 2;\n\t\t} else if (code >= 0xd800 && code <= 0xdbff && i + 1 < content.length) {\n\t\t\tconst next = content.charCodeAt(i + 1);\n\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\tbytes += 4;\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\tbytes += 3;\n\t\t\t}\n\t\t} else {\n\t\t\tbytes += 3;\n\t\t}\n\t}\n\treturn bytes;\n}\n\nfunction splitLinesForCounting(content: string): string[] {\n\tif (content.length === 0) return [];\n\tconst lines = content.split(\"\\n\");\n\tif (content.endsWith(\"\\n\")) lines.pop();\n\treturn lines;\n}\n\n/**\n * Format bytes as human-readable size.\n */\nexport function formatSize(bytes: number): string {\n\tif (bytes < 1024) {\n\t\treturn `${bytes}B`;\n\t} else if (bytes < 1024 * 1024) {\n\t\treturn `${(bytes / 1024).toFixed(1)}KB`;\n\t} else {\n\t\treturn `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\n\t}\n}\n\n/**\n * Truncate content from the head (keep first N lines/bytes).\n * Suitable for file reads where you want to see the beginning.\n *\n * Never returns partial lines. If first line exceeds byte limit,\n * returns empty content with firstLineExceedsLimit=true.\n */\nexport function truncateHead(content: string, options: TruncationOptions = {}): TruncationResult {\n\treturn truncateHeadOf(\n\t\tcontent,\n\t\t{ lines: splitLinesForCounting(content).length, bytes: utf8ByteLength(content) },\n\t\toptions,\n\t);\n}\n\n/**\n * `truncateHead` of a text known by a prefix and its totals (`lines` counted like `truncateHead`, ignoring a trailing\n * newline). The prefix must be the whole text, or longer than `maxBytes + 1` UTF-8 bytes, or hold at least `maxLines`\n * newlines; then the result equals `truncateHead` of the whole text.\n */\nexport function truncateHeadOf(\n\tprefix: string,\n\ttotals: { readonly lines: number; readonly bytes: number },\n\toptions: TruncationOptions = {},\n): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = totals.bytes;\n\tconst lines = splitLinesForCounting(prefix);\n\tconst totalLines = totals.lines;\n\n\t// Check if no truncation needed\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent: prefix,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Check if first line alone exceeds byte limit\n\tconst firstLineBytes = utf8ByteLength(lines[0]);\n\tif (firstLineBytes > maxBytes) {\n\t\treturn {\n\t\t\tcontent: \"\",\n\t\t\ttruncated: true,\n\t\t\ttruncatedBy: \"bytes\",\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: 0,\n\t\t\toutputBytes: 0,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: true,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Collect complete lines that fit\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\n\tfor (let i = 0; i < lines.length && i < maxLines; i++) {\n\t\tconst line = lines[i];\n\t\tconst lineBytes = utf8ByteLength(line) + (i > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.push(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\t// Without a byte break, only omitted lines prove the line limit was reached; otherwise a trailing newline exceeded bytes.\n\tif (truncatedBy !== \"bytes\") truncatedBy = outputLinesArr.length < totalLines ? \"lines\" : \"bytes\";\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = utf8ByteLength(outputContent);\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial: false,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n", "import type { ShellOutputSkip } from \"../env/index.ts\";\nimport { utf8ByteLength } from \"../truncate.ts\";\n\n/** Retention limits of one tool's output. */\nexport type OutputLimits = { readonly maxBytes: number; readonly maxLines: number; readonly retain: \"head\" | \"tail\" };\n\n/** Retained output and what the limits dropped. */\nexport type BoundedOutput = { readonly text: string; readonly droppedBytes: number; readonly droppedLines: number };\n\n/** An exact slice of the input within the limits, and what it left out. */\nexport type OutputSlice = {\n\treadonly text: string;\n\treadonly bytes: number;\n\treadonly droppedBytes: number;\n\treadonly droppedLines: number;\n};\n\nconst NEWLINE = 0x0a;\nconst INVALID_OUTPUT = /[\\x00-\\x08\\x0b-\\x1f\\ufff9-\\ufffb]/g;\nconst encoder = new TextEncoder();\n/** Slices decode exactly: a U+FEFF at a slice's start is text, not a byte-order mark. */\nconst decoder = new TextDecoder(\"utf-8\", { ignoreBOM: true });\n\n/** Remove control characters that break display and transcripts; tabs and newlines stay. */\nexport function sanitizeOutput(text: string): string {\n\treturn text.replace(INVALID_OUTPUT, \"\");\n}\n\n/**\n * Bound `text` to whole lines within the limits: the first lines for `head`, the last lines for `tail`. The result is an\n * exact slice, trailing newline included. A single line longer than `maxBytes` is cut at the byte limit on a character\n * boundary.\n */\nexport function boundOutput(text: string, limits: OutputLimits): OutputSlice {\n\tconst bytes = encoder.encode(text);\n\tconst [from, to] = limits.retain === \"head\" ? headRange(bytes, limits) : tailRange(bytes, limits);\n\tconst kept = bytes.subarray(from, to);\n\treturn {\n\t\ttext: kept.length === bytes.length ? text : decoder.decode(kept),\n\t\tbytes: kept.length,\n\t\tdroppedBytes: bytes.length - kept.length,\n\t\tdroppedLines: lineCount(bytes) - lineCount(kept),\n\t};\n}\n\nfunction headRange(bytes: Uint8Array, limits: OutputLimits): [number, number] {\n\tif (limits.maxLines === 0 || limits.maxBytes === 0) return [0, 0];\n\tlet end = bytes.length;\n\tlet lines = 0;\n\tfor (let index = bytes.indexOf(NEWLINE); index !== -1; index = bytes.indexOf(NEWLINE, index + 1)) {\n\t\tif (++lines === limits.maxLines) {\n\t\t\tend = index + 1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (end > limits.maxBytes) {\n\t\tconst newline = bytes.lastIndexOf(NEWLINE, limits.maxBytes - 1);\n\t\tend = newline === -1 ? characterEnd(bytes, limits.maxBytes) : newline + 1;\n\t}\n\treturn [0, end];\n}\n\nfunction tailRange(bytes: Uint8Array, limits: OutputLimits): [number, number] {\n\tif (limits.maxLines === 0 || limits.maxBytes === 0) return [bytes.length, bytes.length];\n\t// A trailing newline ends the last line rather than starting another.\n\tconst last = bytes[bytes.length - 1] === NEWLINE ? bytes.length - 2 : bytes.length - 1;\n\tlet start = 0;\n\tlet lines = 1;\n\tfor (let index = last < 0 ? -1 : bytes.lastIndexOf(NEWLINE, last); index !== -1; ) {\n\t\tif (lines === limits.maxLines) {\n\t\t\tstart = index + 1;\n\t\t\tbreak;\n\t\t}\n\t\tlines++;\n\t\tindex = index === 0 ? -1 : bytes.lastIndexOf(NEWLINE, index - 1);\n\t}\n\tif (bytes.length - start > limits.maxBytes) {\n\t\tconst from = bytes.length - limits.maxBytes;\n\t\tconst newline = bytes.indexOf(NEWLINE, from - 1);\n\t\t// The first line starting inside the byte window, or a cut of the last line when it alone is too long.\n\t\tstart = newline !== -1 && newline + 1 < bytes.length ? newline + 1 : characterStart(bytes, from);\n\t}\n\treturn [start, bytes.length];\n}\n\n/** The last character boundary at or before `index`. */\nexport function characterEnd(bytes: Uint8Array, index: number): number {\n\tlet end = index;\n\twhile (end > 0 && ((bytes[end] ?? 0) & 0xc0) === 0x80) end--;\n\treturn end;\n}\n\n/** The first character boundary at or after `index`. */\nfunction characterStart(bytes: Uint8Array, index: number): number {\n\tlet start = index;\n\twhile (start < bytes.length && ((bytes[start] ?? 0) & 0xc0) === 0x80) start++;\n\treturn start;\n}\n\nfunction lineCount(bytes: Uint8Array): number {\n\tif (bytes.length === 0) return 0;\n\tlet newlines = 0;\n\tfor (let index = bytes.indexOf(NEWLINE); index !== -1; index = bytes.indexOf(NEWLINE, index + 1)) newlines++;\n\treturn newlines + (bytes[bytes.length - 1] === NEWLINE ? 0 : 1);\n}\n\n/**\n * Bounded running output of one tool call. Accepting a chunk costs time proportional to the chunk: head retention stops\n * storing once the window is full, and tail retention drops stored text the window no longer needs when it snapshots.\n * Counts of the whole stream are kept so the dropped totals stay exact.\n */\nexport class OutputBuffer {\n\treadonly #limits: OutputLimits;\n\t/**\n\t * Decoder of byte chunks. A string chunk or a skip ends an incomplete character of earlier bytes (it becomes U+FFFD);\n\t * the next byte chunk then starts a new character. As in `StreamDecoder`, only a byte-order mark at the very start of\n\t * the output is dropped, never a U+FEFF later in it.\n\t */\n\treadonly #decoder = new TextDecoder(\"utf-8\", { ignoreBOM: true });\n\t#started = false;\n\t/** Stored chunks: for head the start of the stream, for tail a suffix that still contains the next window. */\n\t#chunks: { readonly text: string; readonly bytes: number; readonly newlines: number }[] = [];\n\t#storedBytes = 0;\n\t#storedNewlines = 0;\n\t#full = false;\n\t#totalBytes = 0;\n\t#totalNewlines = 0;\n\t#endsWithNewline = true;\n\n\tconstructor(limits: OutputLimits) {\n\t\tthis.#limits = limits;\n\t}\n\n\t/** Bytes currently held; bounded by the limits plus one chunk. */\n\tget storedBytes(): number {\n\t\treturn this.#storedBytes;\n\t}\n\n\t/**\n\t * Accept a chunk; returns whether anything was accepted. `skipped` is output omitted right before the chunk, which\n\t * must be more than the tail window by at least one byte or line (`ShellOutputInfo.skipped`); only tail retention\n\t * accepts it.\n\t */\n\tpush(chunk: string | Uint8Array, skipped?: ShellOutputSkip): boolean {\n\t\t// Bytes of an incomplete character from an earlier byte chunk come first.\n\t\tconst pending = typeof chunk === \"string\" || skipped !== undefined ? this.#decoder.decode() : \"\";\n\t\tlet text = typeof chunk === \"string\" ? chunk : this.#decoder.decode(chunk, { stream: true });\n\t\tconst first = !this.#started && pending === \"\" && skipped === undefined;\n\t\tif (pending !== \"\" || text !== \"\" || skipped !== undefined) this.#started = true;\n\t\tif (first && typeof chunk !== \"string\" && text.startsWith(\"\\ufeff\")) text = text.slice(1);\n\t\tif (skipped === undefined) return this.#accept(pending + text);\n\t\tif (this.#limits.retain !== \"tail\") throw new Error(\"Skipped output requires tail retention\");\n\t\tthis.#accept(pending);\n\t\tthis.#skip(skipped);\n\t\tthis.#accept(text);\n\t\treturn true;\n\t}\n\n\t/** Count omitted output; nothing stored before it can be in the window once the text after it arrives. */\n\t#skip(skipped: ShellOutputSkip): void {\n\t\tif (skipped.bytes === 0) return;\n\t\tthis.#totalBytes += skipped.bytes;\n\t\tthis.#totalNewlines += skipped.newlines;\n\t\tthis.#endsWithNewline = skipped.endsWithNewline;\n\t\tthis.#chunks = [];\n\t\tthis.#storedBytes = 0;\n\t\tthis.#storedNewlines = 0;\n\t}\n\n\t/** Flush an incomplete trailing character as a replacement character; call when the stream ends. */\n\tend(): void {\n\t\tthis.#accept(this.#decoder.decode());\n\t}\n\n\t#accept(text: string): boolean {\n\t\tif (text.length === 0) return false;\n\t\tconst bytes = utf8ByteLength(text);\n\t\tconst newlines = countNewlines(text);\n\t\tthis.#totalBytes += bytes;\n\t\tthis.#totalNewlines += newlines;\n\t\tthis.#endsWithNewline = text.endsWith(\"\\n\");\n\t\tif (this.#full) return true;\n\t\tthis.#chunks.push({ text, bytes, newlines });\n\t\tthis.#storedBytes += bytes;\n\t\tthis.#storedNewlines += newlines;\n\t\tif (this.#limits.retain === \"head\") {\n\t\t\t// Nothing past a full window is ever needed.\n\t\t\tthis.#full = this.#storedBytes > this.#limits.maxBytes || this.#storedNewlines >= this.#limits.maxLines;\n\t\t\treturn true;\n\t\t}\n\t\t// Drop leading chunks while the rest still holds more than a window: more than `maxBytes` bytes or `maxLines`\n\t\t// newlines, plus one, so the window's line start can still be found. Each chunk is dropped once.\n\t\twhile (this.#chunks.length > 1) {\n\t\t\tconst first = this.#chunks[0]!;\n\t\t\tconst bytesAfter = this.#storedBytes - first.bytes;\n\t\t\tconst newlinesAfter = this.#storedNewlines - first.newlines;\n\t\t\tif (bytesAfter <= this.#limits.maxBytes + 1 && newlinesAfter <= this.#limits.maxLines + 1) break;\n\t\t\tthis.#chunks.shift();\n\t\t\tthis.#storedBytes = bytesAfter;\n\t\t\tthis.#storedNewlines = newlinesAfter;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/** Retained, sanitized output and what the limits dropped from the whole stream. */\n\tsnapshot(): BoundedOutput {\n\t\tconst stored =\n\t\t\tthis.#chunks.length === 1 ? this.#chunks[0]!.text : this.#chunks.map((chunk) => chunk.text).join(\"\");\n\t\tconst kept = boundOutput(stored, this.#limits);\n\t\tconst storedLines = lines(this.#storedNewlines, stored === \"\" || stored.endsWith(\"\\n\"));\n\t\tconst keptLines = storedLines - kept.droppedLines;\n\t\t// Tail windows never reach back before this one, but finding a later window's first line needs what precedes it:\n\t\t// keep the shortest suffix longer than the window by a byte or a line, as `#accept` does.\n\t\tif (this.#limits.retain === \"tail\" || this.#chunks.length > 1) {\n\t\t\tconst text = this.#limits.retain === \"tail\" ? tailMargin(stored, this.#limits) : stored;\n\t\t\tconst bytes = this.#limits.retain === \"tail\" ? utf8ByteLength(text) : this.#storedBytes;\n\t\t\tthis.#chunks = text === \"\" ? [] : [{ text, bytes, newlines: countNewlines(text) }];\n\t\t\tthis.#storedBytes = bytes;\n\t\t\tthis.#storedNewlines = this.#chunks[0]?.newlines ?? 0;\n\t\t}\n\t\treturn {\n\t\t\ttext: sanitizeOutput(kept.text),\n\t\t\tdroppedBytes: this.#totalBytes - kept.bytes,\n\t\t\tdroppedLines: lines(this.#totalNewlines, this.#endsWithNewline) - keptLines,\n\t\t};\n\t}\n}\n\n/**\n * The shortest suffix of `text` with more than `maxBytes` bytes or more than `maxLines` newlines, or all of it. The\n * tail window of any text that ends with this suffix, followed by anything, is the same as of `text` followed by it.\n */\nfunction tailMargin(text: string, limits: OutputLimits): string {\n\tconst bytes = encoder.encode(text);\n\tconst byteStart = bytes.length > limits.maxBytes ? characterEnd(bytes, bytes.length - limits.maxBytes - 1) : 0;\n\tlet lineStart = 0;\n\tlet newlines = 0;\n\tfor (let index = bytes.lastIndexOf(NEWLINE); index !== -1; index = bytes.lastIndexOf(NEWLINE, index - 1)) {\n\t\tif (++newlines > limits.maxLines) {\n\t\t\tlineStart = index;\n\t\t\tbreak;\n\t\t}\n\t\tif (index === 0) break;\n\t}\n\tconst start = Math.max(byteStart, lineStart);\n\treturn start === 0 ? text : decoder.decode(bytes.subarray(start));\n}\n\n/** Lines of text with `newlines` newlines; a final unterminated line counts. */\nfunction lines(newlines: number, terminated: boolean): number {\n\treturn newlines + (terminated ? 0 : 1);\n}\n\nfunction countNewlines(text: string): number {\n\tlet count = 0;\n\tfor (let index = text.indexOf(\"\\n\"); index !== -1; index = text.indexOf(\"\\n\", index + 1)) count++;\n\treturn count;\n}\n\n/** Each progress commit also buys a pause proportional to what it wrote. */\nexport const PROGRESS_BYTES_PER_SECOND = 100 * 1024;\n\n/**\n * Adaptive progress commits: the first change after an idle period commits at once; each commit then delays the next\n * by at least `minIntervalMs` and by its written size at 100 KiB/s. At most one commit is in flight; changes made\n * meanwhile coalesce into the next one.\n */\nexport class Progress {\n\treadonly #write: () => Promise<number>;\n\treadonly #onError: (error: unknown) => void;\n\treadonly #minIntervalMs: number;\n\t#waiters: PromiseWithResolvers<void>[] = [];\n\t#timer: ReturnType<typeof setTimeout> | undefined;\n\t#inFlight: Promise<void> | undefined;\n\t#nextAt = 0;\n\t#dirty = false;\n\t#stopped = false;\n\n\tconstructor(write: () => Promise<number>, onError: (error: unknown) => void, minIntervalMs: number) {\n\t\tthis.#write = write;\n\t\tthis.#onError = onError;\n\t\tthis.#minIntervalMs = minIntervalMs;\n\t}\n\n\t/** Schedule a commit. */\n\tmark(): void {\n\t\tthis.#dirty = true;\n\t\tthis.#schedule();\n\t}\n\n\t/** Schedule a commit; the promise settles with the commit that includes this change. */\n\tmarkAndWait(): Promise<void> {\n\t\tconst waiter = Promise.withResolvers<void>();\n\t\tthis.#waiters.push(waiter);\n\t\tthis.mark();\n\t\treturn waiter.promise;\n\t}\n\n\t/** Stop committing and wait for the commit in flight; returns the waiters the final commit must settle. */\n\tasync stop(): Promise<PromiseWithResolvers<void>[]> {\n\t\tthis.#stopped = true;\n\t\tclearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tawait this.#inFlight;\n\t\treturn this.#waiters.splice(0);\n\t}\n\n\t#schedule(): void {\n\t\tif (this.#stopped || this.#timer !== undefined || this.#inFlight !== undefined) return;\n\t\tconst wait = this.#nextAt - Date.now();\n\t\tif (wait <= 0) this.#flush();\n\t\telse\n\t\t\tthis.#timer = setTimeout(() => {\n\t\t\t\tthis.#timer = undefined;\n\t\t\t\tthis.#flush();\n\t\t\t}, wait);\n\t}\n\n\t#flush(): void {\n\t\tif (this.#stopped || !this.#dirty) return;\n\t\tthis.#dirty = false;\n\t\tconst waiters = this.#waiters.splice(0);\n\t\tconst started = Date.now();\n\t\tthis.#inFlight = this.#write()\n\t\t\t.then(\n\t\t\t\t(bytes) => {\n\t\t\t\t\tthis.#nextAt = started + Math.max(this.#minIntervalMs, (bytes * 1000) / PROGRESS_BYTES_PER_SECOND);\n\t\t\t\t\tfor (const waiter of waiters) waiter.resolve();\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tthis.#nextAt = started + this.#minIntervalMs;\n\t\t\t\t\tfor (const waiter of waiters) waiter.reject(error);\n\t\t\t\t\tthis.#onError(error);\n\t\t\t\t},\n\t\t\t)\n\t\t\t.finally(() => {\n\t\t\t\tthis.#inFlight = undefined;\n\t\t\t\tif (this.#dirty) this.#schedule();\n\t\t\t});\n\t}\n}\n", "import { copyJson, type Draft, type JsonRepresentation } from \"@earendil-works/chord\";\nimport type { Usage } from \"@earendil-works/pi-ai\";\nimport { defineDoc } from \"../documents.ts\";\nimport type { ConversationId, Tx } from \"../types.ts\";\n\n/** Ledger of one conversation's own spend: its entries, and compaction summarization attempts, which have none. */\nexport type UsageState = {\n\t/** Assistant entries and summarization attempts, keyed `provider/modelId`. */\n\tmodels: Record<string, JsonRepresentation<Usage>>;\n\t/** Tool results, keyed by tool name; their usage has no model identity. */\n\ttools: Record<string, JsonRepresentation<Usage>>;\n};\n\nexport const UsageDoc = defineDoc<UsageState>({\n\tkind: \"pi.usage\",\n\tversion: 1,\n\tscope: \"conversation\",\n\thistory: \"latest\",\n\tfork: \"initial\",\n\tinitial: () => ({ models: {}, tools: {} }),\n\tcheckpointWhen: () => true,\n});\n\n/** Add `usage` to one bucket of the conversation's `pi.usage`, in the commit that records the response. */\nexport async function recordUsage(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tbucket: keyof UsageState,\n\tkey: string,\n\tusage: Usage,\n): Promise<void> {\n\tconst totals = (await tx.doc(UsageDoc, conversationId))[bucket];\n\t// Own keys only: a tool may be called `toString`.\n\tconst total = Object.hasOwn(totals, key) ? totals[key] : undefined;\n\t// Providers may leave optional counters `undefined`; drafts take strict JSON.\n\tif (total === undefined)\n\t\ttotals[key] = copyJson(usage, { omitUndefinedProperties: true }) as JsonRepresentation<Usage>;\n\telse addUsage(total, usage);\n}\n\n/** Add every counter of `usage` to `total`; optional counters are added once either side reports them. */\nexport function addUsage(total: Draft<Usage> | Usage, usage: Usage): void {\n\ttotal.input += usage.input;\n\ttotal.output += usage.output;\n\ttotal.cacheRead += usage.cacheRead;\n\ttotal.cacheWrite += usage.cacheWrite;\n\ttotal.totalTokens += usage.totalTokens;\n\tif (usage.cacheWrite1h !== undefined) total.cacheWrite1h = (total.cacheWrite1h ?? 0) + usage.cacheWrite1h;\n\tif (usage.reasoning !== undefined) total.reasoning = (total.reasoning ?? 0) + usage.reasoning;\n\ttotal.cost.input += usage.cost.input;\n\ttotal.cost.output += usage.cost.output;\n\ttotal.cost.cacheRead += usage.cost.cacheRead;\n\ttotal.cost.cacheWrite += usage.cost.cacheWrite;\n\ttotal.cost.total += usage.cost.total;\n}\n\n/** Add every bucket of `state` into `sum`. */\nexport function addUsageState(sum: UsageState, state: Readonly<UsageState>): void {\n\tfor (const bucket of [\"models\", \"tools\"] as const) {\n\t\tfor (const [key, usage] of Object.entries(state[bucket])) {\n\t\t\tconst total = Object.hasOwn(sum[bucket], key) ? sum[bucket][key] : undefined;\n\t\t\t// Define rather than assign: assigning a tool named `__proto__` would set the prototype.\n\t\t\tif (total !== undefined) addUsage(total, usage);\n\t\t\telse\n\t\t\t\tObject.defineProperty(sum[bucket], key, {\n\t\t\t\t\tvalue: structuredClone(usage),\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\twritable: true,\n\t\t\t\t});\n\t\t}\n\t}\n}\n", "import { type Context, copyJson, type JsonValue } from \"@earendil-works/chord\";\nimport { awaitWithContext } from \"@earendil-works/chord/context\";\nimport { overlap } from \"@earendil-works/chord/delta\";\nimport type { ImageContent, TextContent, ToolCall, ToolResultMessage } from \"@earendil-works/pi-ai\";\nimport { validateToolArguments } from \"@earendil-works/pi-ai/utils/validation\";\nimport { AssistantEntry, ToolResultEntry } from \"../entries.ts\";\nimport { defineTask } from \"../tasks.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, utf8ByteLength } from \"../truncate.ts\";\nimport type {\n\tConversationId,\n\tEntryId,\n\tJsonObject,\n\tTask,\n\tTaskId,\n\tTaskOptions,\n\tTaskRuntime,\n\tTx,\n\tTypedEntry,\n} from \"../types.ts\";\nimport { assignJson } from \"./json.ts\";\nimport { clearProgress, finishSlot, LiveDoc, type ToolSlot, toolSlot } from \"./live.ts\";\nimport { boundOutput, OutputBuffer, type OutputLimits, PROGRESS_BYTES_PER_SECOND, Progress } from \"./output.ts\";\nimport type {\n\tToolControl,\n\tToolDiagnostic,\n\tToolExecutionApi,\n\tToolExecutionResult,\n\tToolHooks,\n\tToolRegistration,\n} from \"./types.ts\";\nimport { recordUsage } from \"./usage.ts\";\n\nexport type ToolTaskInput = { assistant: EntryId; callId: string };\n\nexport type ToolTaskCheckpoint =\n\t| { phase: \"call\" }\n\t/** Durable intent: the final arguments and the replay policy recorded before execution. */\n\t| { phase: \"execute\"; arguments: JsonObject; replay: \"safe\" | \"unsafe\" };\n\nexport type ToolTaskResult = { entryId: EntryId; control?: ToolControl };\n\ntype Runtime = TaskRuntime<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>;\ntype Content = (TextContent | ImageContent)[];\n\n/**\n * Built-in tool task: resolves the called tool among its phase agent's tools, validates, runs `beforeTool`, records intent,\n * executes, runs `afterTool`, and appends the result, all in one `call` handler so nothing separates resolution from\n * settlement. `execute` is reached only by recovery and applies the replay rule.\n */\nexport const ToolTask = defineTask<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>({\n\tname: \"pi.tool\",\n\tversion: 1,\n\tinitial: () => ({ phase: \"call\" }),\n\tphases: {\n\t\tcall: async (task, runtime, context) => {\n\t\t\tconst call = await readCall(runtime, task.input, context);\n\t\t\tconst tool = (await runtime.agent(context)).tools.find((each) => each.name === call.name);\n\t\t\tif (tool === undefined) {\n\t\t\t\tconst error = harnessError(\"tool_unavailable\", `Tool ${call.name} is not available`);\n\t\t\t\treturn settle(runtime, call, COMPLETED, () => error, context);\n\t\t\t}\n\t\t\tconst prepared = prepare(tool, call.arguments as JsonObject);\n\t\t\tconst checked = \"error\" in prepared ? prepared : validate(tool, call, prepared.args);\n\t\t\tif (\"error\" in checked) return settle(runtime, call, COMPLETED, () => invalid(checked.error), context);\n\t\t\tlet args = checked.args;\n\t\t\tlet block: string | undefined;\n\t\t\tawait runtime.hooks.each(\"beforeTool\", async (hook) => {\n\t\t\t\tif (block !== undefined) return;\n\t\t\t\ttry {\n\t\t\t\t\tconst decision = await hook({ ...call, arguments: args }, runtime, context);\n\t\t\t\t\tif (decision?.block !== undefined) block = decision.block;\n\t\t\t\t\telse if (decision?.arguments !== undefined) args = decision.arguments;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (runtime.signal.aborted) throw error;\n\t\t\t\t\tblock = errorText(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (block !== undefined) {\n\t\t\t\tconst blocked = harnessError(\"blocked\", `Tool call blocked: ${block}`);\n\t\t\t\treturn settle(runtime, call, COMPLETED, () => blocked, context);\n\t\t\t}\n\t\t\tconst validated = validate(tool, call, args);\n\t\t\tif (\"error\" in validated) return settle(runtime, call, COMPLETED, () => invalid(validated.error), context);\n\t\t\tconst final = validated.args;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\tif (slot !== undefined) slot.status = \"running\";\n\t\t\t\tconst intent = { phase: \"execute\", arguments: final, replay: tool.replay ?? \"unsafe\" } as const;\n\t\t\t\treturn { status: \"running\", checkpoint: intent };\n\t\t\t}, context);\n\t\t\tawait run(runtime, call, tool, final, context);\n\t\t},\n\t\t/** Recovery after intent: rerun only when the stored and the current policy both say `safe`. */\n\t\texecute: async (task, runtime, context) => {\n\t\t\tconst { arguments: args, replay } = task.state.checkpoint;\n\t\t\tconst call = await readCall(runtime, task.input, context);\n\t\t\tconst tool = (await runtime.agent(context)).tools.find((each) => each.name === call.name);\n\t\t\tif (replay === \"safe\" && tool?.replay === \"safe\") {\n\t\t\t\t// The rerun reports from scratch; clear what the interrupted attempt published.\n\t\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\t\tif (slot !== undefined) clearProgress(slot);\n\t\t\t\t\treturn undefined;\n\t\t\t\t}, context);\n\t\t\t\treturn run(runtime, call, tool, args, context);\n\t\t\t}\n\t\t\tconst message = `Tool ${call.name} was interrupted and may have partially run`;\n\t\t\t// `failed` records cancellation intent, so the call's owned conversations, left unsupervised, are aborted.\n\t\t\tconst ending = { status: \"failed\", message } as const;\n\t\t\tawait settle(runtime, call, ending, (slot) => fromSlot(slot, \"interrupted\", message), context);\n\t\t},\n\t},\n\tabort: async (task, runtime, context) => {\n\t\tconst call = await readCall(runtime, task.input, context);\n\t\tconst message = `Tool ${call.name} was aborted`;\n\t\tawait settle(runtime, call, { status: \"aborted\" }, (slot) => fromSlot(slot, \"aborted\", message), context);\n\t},\n});\n\n/** The tool call `callId` of the assistant entry. */\nasync function readCall(runtime: Runtime, input: ToolTaskInput, context: Context): Promise<ToolCall> {\n\tconst entry = await runtime.entry(AssistantEntry, input.assistant, context);\n\tconst message = entry?.model?.[0];\n\tconst call =\n\t\tmessage?.role === \"assistant\"\n\t\t\t? message.content.find(\n\t\t\t\t\t(content): content is ToolCall => content.type === \"toolCall\" && content.id === input.callId,\n\t\t\t\t)\n\t\t\t: undefined;\n\tif (call === undefined) throw new Error(`Entry ${input.assistant} has no tool call ${input.callId}`);\n\treturn call;\n}\n\n/** Arguments, or why they are invalid. */\ntype Checked = { readonly args: JsonObject } | { readonly error: string };\n\n/** The call's arguments as repaired by the tool; a throwing repair makes them invalid. */\nfunction prepare(tool: ToolRegistration, args: JsonObject): Checked {\n\tif (tool.prepareArguments === undefined) return { args };\n\ttry {\n\t\treturn { args: tool.prepareArguments(args) as JsonObject };\n\t} catch (error) {\n\t\treturn { error: errorText(error) };\n\t}\n}\n\n/** Arguments validated and coerced against the implementation's schema. */\nfunction validate(tool: ToolRegistration, call: ToolCall, args: JsonObject): Checked {\n\ttry {\n\t\treturn { args: validateToolArguments(tool, { ...call, arguments: args }) as JsonObject };\n\t} catch (error) {\n\t\treturn { error: errorText(error) };\n\t}\n}\n\nfunction invalid(message: string): ToolExecutionResult {\n\treturn harnessError(\"invalid_arguments\", message);\n}\n\n/** What a running tool reported through its api: output, the last details, and diagnostics. */\ntype Reported = {\n\treadonly output: OutputBuffer;\n\treadonly limits: OutputLimits;\n\treadonly diagnostics: ToolDiagnostic[];\n\tdetails: JsonValue | undefined;\n};\n\n/** Execute with the resolved implementation, then settle its result. */\nasync function run(\n\truntime: Runtime,\n\tcall: ToolCall,\n\ttool: ToolRegistration,\n\targs: JsonObject,\n\tcontext: Context,\n): Promise<void> {\n\tconst limits: OutputLimits = {\n\t\tmaxBytes: tool.outputLimits?.maxBytes ?? DEFAULT_MAX_BYTES,\n\t\tmaxLines: tool.outputLimits?.maxLines ?? DEFAULT_MAX_LINES,\n\t\tretain: tool.outputLimits?.retain ?? \"head\",\n\t};\n\tconst reported: Reported = { output: new OutputBuffer(limits), limits, diagnostics: [], details: undefined };\n\tconst progress = publishProgress(runtime, reported, context);\n\tlet ended = false;\n\tconst assertLive = (): void => {\n\t\tif (ended) throw new Error(`Tool call ${call.id} has settled`);\n\t};\n\tconst api: Omit<ToolExecutionApi, \"env\"> = {\n\t\ttaskId: runtime.taskId,\n\t\tconversationId: runtime.conversationId,\n\t\tcallId: call.id,\n\t\tregistry: runtime.registry,\n\t\tagent: runtime.agent,\n\t\toutput: (chunk, skipped) => {\n\t\t\tassertLive();\n\t\t\tif (reported.output.push(chunk, skipped)) progress.mark();\n\t\t},\n\t\toutputWindow:\n\t\t\tlimits.retain === \"tail\"\n\t\t\t\t? {\n\t\t\t\t\t\tmaxBytes: limits.maxBytes,\n\t\t\t\t\t\tmaxLines: limits.maxLines,\n\t\t\t\t\t\tminIntervalMs: runtime.settings.progress.outputIntervalMs,\n\t\t\t\t\t\tbytesPerSecond: PROGRESS_BYTES_PER_SECOND,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\tdiagnostic: (diagnostic) => {\n\t\t\tassertLive();\n\t\t\treported.diagnostics.push(copyJson(diagnostic, { omitUndefinedProperties: true }) as ToolDiagnostic);\n\t\t\tprogress.mark();\n\t\t},\n\t\tdetails: async (value, detailsContext) => {\n\t\t\tassertLive();\n\t\t\tdetailsContext.abortSignal?.throwIfAborted();\n\t\t\treported.details = copyJson(value, { omitUndefinedProperties: true });\n\t\t\tconst committed = progress.markAndWait();\n\t\t\t// Cancelling the wait leaves the update in place; the commit's own outcome stays observed.\n\t\t\tcommitted.catch(() => {});\n\t\t\treturn awaitWithContext(committed, detailsContext);\n\t\t},\n\t\tcommit: async (change, commitContext) => {\n\t\t\tlet result: Awaited<ReturnType<typeof change>> | undefined;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tresult = await change(tx);\n\t\t\t\treturn undefined;\n\t\t\t}, commitContext);\n\t\t\treturn result as Awaited<ReturnType<typeof change>>;\n\t\t},\n\t\tmemo: runtime.memo,\n\t\tcreateTask: async <I, S extends { phase: string }, R, H extends object>(\n\t\t\ttask: Task<I, S, R, H>,\n\t\t\tinput: I,\n\t\t\toptions: Omit<TaskOptions, \"conversationId\">,\n\t\t\ttaskContext: Context,\n\t\t): Promise<TaskId<R>> => {\n\t\t\tlet id: TaskId<R> | undefined;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tid = await tx.createTask(task, input, options);\n\t\t\t\treturn undefined;\n\t\t\t}, taskContext);\n\t\t\treturn id!;\n\t\t},\n\t\tgetTask: runtime.getTask,\n\t\twaitForTask: runtime.waitForTask,\n\t\tconversation: runtime.conversation,\n\t\tsnapshot: runtime.snapshot,\n\t\tsnapshotAsOf: runtime.snapshotAsOf,\n\t\twatchDoc: runtime.watchDoc,\n\t};\n\n\tlet result: ToolExecutionResult;\n\tlet ending = COMPLETED;\n\ttry {\n\t\t// Built for this call, so a rerun after recovery gets the conversation's environment at that time.\n\t\tconst env = await runtime.env(context);\n\t\tresult = await tool.execute(args, { ...api, env }, context);\n\t} catch (error) {\n\t\tif (runtime.signal.aborted) {\n\t\t\tended = true;\n\t\t\tfor (const waiter of await progress.stop()) waiter.reject(error);\n\t\t\tthrow error;\n\t\t}\n\t\tresult = { isError: true, diagnostics: [toolDiagnostic(\"tool_error\", errorText(error))] };\n\t\t// A throw, from `execute()` or from building the environment, ends the task `failed`, which cancels what the call owned; it no longer supervises it. The error text\n\t\t// is already in the result entry.\n\t\tending = { status: \"failed\", message: `Tool ${call.name} threw` };\n\t}\n\tended = true;\n\treported.output.end();\n\t// Details still waiting for a progress commit settle with the terminal commit, the final flush.\n\tconst pending = await progress.stop();\n\ttry {\n\t\tconst settled = await finalResult(runtime, call, result, reported, context);\n\t\tawait settle(runtime, call, ending, () => settled, context);\n\t} catch (error) {\n\t\tfor (const waiter of pending) waiter.reject(error);\n\t\tthrow error;\n\t}\n\tfor (const waiter of pending) waiter.resolve();\n}\n\n/**\n * Throttled commits of what the tool reported into its `pi.live.tools` slot, each writing only what changed since the\n * last one.\n */\nfunction publishProgress(runtime: Runtime, reported: Reported, context: Context): Progress {\n\tlet written = { text: \"\", details: undefined as JsonValue | undefined, diagnostics: 0 };\n\treturn new Progress(\n\t\tasync () => {\n\t\t\t// Capture everything synchronously: the tool keeps reporting while the commit is in flight.\n\t\t\tconst snapshot = reported.output.snapshot();\n\t\t\tconst current = { text: snapshot.text, details: reported.details, diagnostics: reported.diagnostics.length };\n\t\t\tconst added = reported.diagnostics.slice(written.diagnostics, current.diagnostics);\n\t\t\tconst detailsChanged = current.details !== written.details;\n\t\t\t// What the commit writes, as Chord diffs the string: an append, a trim plus an append of what follows the shared\n\t\t\t// part, or the whole window when its bounded overlap search finds nothing.\n\t\t\tlet bytes = 0;\n\t\t\tif (snapshot.text !== written.text) {\n\t\t\t\tconst shared = snapshot.text.startsWith(written.text)\n\t\t\t\t\t? written.text.length\n\t\t\t\t\t: overlap(written.text, snapshot.text, 65_536);\n\t\t\t\tbytes += utf8ByteLength(snapshot.text.slice(shared));\n\t\t\t}\n\t\t\tif (detailsChanged) bytes += utf8ByteLength(JSON.stringify(current.details ?? null));\n\t\t\tif (added.length > 0) bytes += utf8ByteLength(JSON.stringify(added));\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\tif (slot === undefined) return undefined;\n\t\t\t\t// REMINDER: assign `output` as one string field. Chord then diffs it into an append, or a trim plus an\n\t\t\t\t// append for a sliding tail; replacing the slot object would record the whole window on every commit.\n\t\t\t\tif ((slot.output ?? \"\") !== snapshot.text) slot.output = snapshot.text;\n\t\t\t\tif (snapshot.droppedBytes > 0) slot.droppedBytes = snapshot.droppedBytes;\n\t\t\t\tif (snapshot.droppedLines > 0) slot.droppedLines = snapshot.droppedLines;\n\t\t\t\t// Diff details leaf by leaf and append new diagnostics, so each commit writes only what changed.\n\t\t\t\tif (detailsChanged && current.details !== undefined) {\n\t\t\t\t\tassignJson(slot as unknown as Record<string, JsonValue>, \"details\", current.details);\n\t\t\t\t}\n\t\t\t\tif (added.length > 0) {\n\t\t\t\t\tif (slot.diagnostics === undefined) slot.diagnostics = [];\n\t\t\t\t\tfor (const diagnostic of added) slot.diagnostics.push(diagnostic);\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t}, context);\n\t\t\twritten = current;\n\t\t\treturn bytes;\n\t\t},\n\t\t(error) => {\n\t\t\t// Rejections after an abort mark or close are expected; the committed state stays consistent.\n\t\t\tif (!runtime.signal.aborted) runtime.report(error);\n\t\t},\n\t\truntime.settings.progress.outputIntervalMs,\n\t);\n}\n\n/**\n * The settled result: the tool's result with the retained output and last details as fallbacks, its diagnostics after\n * those reported through the api, `afterTool` applied, and explicit text bounded, with the Harness's truncation\n * diagnostic last.\n */\nasync function finalResult(\n\truntime: Runtime,\n\tcall: ToolCall,\n\tresult: ToolExecutionResult,\n\treported: Reported,\n\tcontext: Context,\n): Promise<ToolExecutionResult> {\n\tconst harness: ToolDiagnostic[] = [];\n\tconst retained = result.content === undefined ? reported.output.snapshot() : undefined;\n\tconst content: Content =\n\t\tretained === undefined ? result.content! : retained.text === \"\" ? [] : [{ type: \"text\", text: retained.text }];\n\tlet final: ToolExecutionResult = {\n\t\t...result,\n\t\tcontent,\n\t\tdetails: result.details === undefined ? reported.details : result.details,\n\t\tdiagnostics: [...reported.diagnostics, ...(result.diagnostics ?? [])],\n\t};\n\tawait runtime.hooks.each(\"afterTool\", async (hook) => {\n\t\tfinal = (await hook(call, final, runtime, context)) ?? final;\n\t});\n\t// The retained output's truncation applies only while afterTool kept that content.\n\tif (retained !== undefined && retained.droppedBytes > 0 && final.content === content) {\n\t\tharness.push(truncated(retained, reported.limits.retain));\n\t}\n\tconst bounded = boundContent(final.content ?? [], reported.limits);\n\tif (bounded.droppedBytes > 0) harness.push(truncated(bounded, reported.limits.retain));\n\treturn { ...final, content: bounded.content, diagnostics: [...(final.diagnostics ?? []), ...harness] };\n}\n\n/**\n * Commit the tool's terminal state: append its result entry, mark its slot done, and complete or end aborted with the\n * entry ID. `build` receives the slot so interruption and abort can report the durable partial output.\n */\nasync function settle(\n\truntime: Runtime,\n\tcall: ToolCall,\n\tending: Ending,\n\tbuild: (slot: Readonly<ToolSlot> | undefined) => ToolExecutionResult,\n\tcontext: Context,\n): Promise<void> {\n\tawait runtime.commit(async (tx) => {\n\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\tconst result = build(slot);\n\t\tconst entry = await appendToolResult(tx, runtime.conversationId, call, result, runtime.now());\n\t\tif (slot !== undefined) finishSlot(slot, entry.id);\n\t\tconst entryId = entry.id;\n\t\tif (ending.status === \"aborted\")\n\t\t\treturn { status: \"terminal\", outcome: { status: \"aborted\", result: { entryId } } };\n\t\tif (ending.status === \"failed\") {\n\t\t\tconst error = { message: ending.message };\n\t\t\treturn { status: \"terminal\", outcome: { status: \"failed\", error, result: { entryId } } };\n\t\t}\n\t\t// Tools build control objects freely; drop keys set to undefined so the task result is strict JSON.\n\t\tconst control =\n\t\t\tresult.control === undefined\n\t\t\t\t? {}\n\t\t\t\t: { control: copyJson(result.control as JsonValue, { omitUndefinedProperties: true }) as ToolControl };\n\t\treturn { status: \"terminal\", outcome: { status: \"completed\", result: { entryId, ...control } } };\n\t}, context);\n}\n\n/**\n * How a tool task ends; the result entry is appended either way. `failed` (execution threw or was interrupted)\n * records cancellation intent for the conversations the call owns; a result with `isError` still completes.\n */\ntype Ending = { readonly status: \"completed\" | \"aborted\" } | { readonly status: \"failed\"; readonly message: string };\n\nconst COMPLETED: Ending = { status: \"completed\" };\n\n/** An error result from the slot's durable partial output, details, and diagnostics. */\nfunction fromSlot(slot: Readonly<ToolSlot> | undefined, code: string, message: string): ToolExecutionResult {\n\tconst diagnostics = [...(slot?.diagnostics ?? [])];\n\tconst droppedBytes = slot?.droppedBytes ?? 0;\n\tif (droppedBytes > 0) diagnostics.push(truncated({ droppedBytes, droppedLines: slot?.droppedLines ?? 0 }));\n\tdiagnostics.push(toolDiagnostic(code, message));\n\treturn {\n\t\tcontent: slot?.output === undefined || slot.output === \"\" ? [] : [{ type: \"text\", text: slot.output }],\n\t\tisError: true,\n\t\t...(slot?.details === undefined ? {} : { details: slot.details }),\n\t\tdiagnostics,\n\t};\n}\n\n/** An error result the Harness writes itself: no content and one `error` diagnostic with `code`. */\nexport function harnessError(code: string, message: string): ToolExecutionResult {\n\treturn { content: [], isError: true, diagnostics: [toolDiagnostic(code, message)] };\n}\n\nfunction toolDiagnostic(code: string, message: string): ToolDiagnostic {\n\treturn { severity: \"error\", code, message };\n}\n\n/** The Harness's truncation diagnostic; `retain` is unknown when rebuilt from a slot after recovery. */\nfunction truncated(\n\tdropped: { readonly droppedLines: number; readonly droppedBytes: number },\n\tretain?: \"head\" | \"tail\",\n): ToolDiagnostic {\n\tconst kept = retain === undefined ? \"\" : ` to its ${retain === \"head\" ? \"beginning\" : \"end\"}`;\n\treturn {\n\t\tseverity: \"warn\",\n\t\tcode: \"truncated\",\n\t\tmessage: `Output truncated${kept}: ${dropped.droppedLines} lines, ${dropped.droppedBytes} bytes dropped`,\n\t};\n}\n\n/**\n * Append a `pi.tool-result` entry. The content ends with the rendered diagnostics, so the stored message is exactly\n * what the model sees; `data` keeps the structured list. A result's usage is added to `pi.usage` in the same commit.\n */\nexport async function appendToolResult(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tcall: ToolCall,\n\tresult: ToolExecutionResult,\n\ttimestamp: number,\n): Promise<TypedEntry<{ diagnostics: ToolDiagnostic[] }>> {\n\tconst diagnostics = [...(result.diagnostics ?? [])];\n\tconst content: Content = [...(result.content ?? [])];\n\tif (diagnostics.length > 0) content.push({ type: \"text\", text: renderDiagnostics(diagnostics) });\n\tconst message = {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: call.id,\n\t\ttoolName: call.name,\n\t\tcontent,\n\t\t...(result.details === undefined ? {} : { details: result.details }),\n\t\t...(result.usage === undefined ? {} : { usage: result.usage }),\n\t\tisError: result.isError ?? false,\n\t\ttimestamp,\n\t} as ToolResultMessage;\n\tif (result.usage !== undefined) await recordUsage(tx, conversationId, \"tools\", call.name, result.usage);\n\treturn tx.appendEntry(ToolResultEntry, conversationId, { model: [message], data: { diagnostics } });\n}\n\nfunction renderDiagnostics(diagnostics: readonly ToolDiagnostic[]): string {\n\treturn `<harness>\\n${diagnostics.map((diagnostic) => `[${diagnostic.severity}] ${diagnostic.message}`).join(\"\\n\")}\\n</harness>`;\n}\n\n/**\n * Bound the text of result content. When the joined text exceeds the limits, the text items are replaced by one bounded\n * item at the position of the first (head) or last (tail) text item; other content is kept.\n */\nfunction boundContent(\n\tcontent: Content,\n\tlimits: OutputLimits,\n): { content: Content; droppedBytes: number; droppedLines: number } {\n\tconst texts = content.filter((item): item is TextContent => item.type === \"text\");\n\tconst bounded = boundOutput(texts.map((item) => item.text).join(\"\"), limits);\n\tif (bounded.droppedBytes === 0) return { content, droppedBytes: 0, droppedLines: 0 };\n\tconst keep = limits.retain === \"head\" ? texts[0] : texts.at(-1);\n\tconst result: Content = [];\n\tfor (const item of content) {\n\t\tif (item.type !== \"text\") result.push(item);\n\t\telse if (item === keep) result.push({ ...item, text: bounded.text });\n\t}\n\treturn { content: result, droppedBytes: bounded.droppedBytes, droppedLines: bounded.droppedLines };\n}\n\nfunction errorText(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n", "import { type Context, copyJson, type Draft, type JsonValue } from \"@earendil-works/chord\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tDeferredHandle,\n\tMessage,\n\tModel,\n\tModelThinkingLevel,\n\tSimpleStreamOptions,\n\tToolCall,\n} from \"@earendil-works/pi-ai\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/utils/overflow\";\nimport { isRetryableAssistantError, retryDelayMs } from \"@earendil-works/pi-ai/utils/retry\";\nimport { getCurrentTools } from \"@earendil-works/pi-ai/utils/transcript\";\nimport { AssistantEntry, ResetEntry, SystemEntry, UserEntry } from \"../entries.ts\";\nimport type { ExecutionEnv } from \"../env/index.ts\";\nimport { defineTask } from \"../tasks.ts\";\nimport type {\n\tConversationId,\n\tEntryId,\n\tNextTaskState,\n\tSubmissionId,\n\tTaskId,\n\tTaskRuntime,\n\tTx,\n\tTypedEntry,\n} from \"../types.ts\";\nimport { addTools } from \"./agent.ts\";\nimport { createCompaction, estimateContext, selectCut } from \"./compaction.ts\";\nimport { applyBoundary, prepareBoundary } from \"./inbox.ts\";\nimport { assignJson } from \"./json.ts\";\nimport { endRun, LiveDoc, type LiveState, type ToolSlot } from \"./live.ts\";\nimport { planSystemEntries, renderSections, replaySections } from \"./prompt.ts\";\nimport { ensureProviderSessionId } from \"./provider.ts\";\nimport { appendToolResult, harnessError, ToolTask, type ToolTaskResult } from \"./tool.ts\";\nimport type {\n\tCompactionPolicy,\n\tCompactionResult,\n\tContextView,\n\tConversationStreamOptions,\n\tGenerationHooks,\n\tModelRef,\n\tPromptInput,\n\tToolControl,\n\tUserInput,\n} from \"./types.ts\";\nimport { recordUsage } from \"./usage.ts\";\n\nexport type GenerationInput = Record<string, never>;\n\nexport type GenerationCheckpoint =\n\t| {\n\t\t\tphase: \"prepare\";\n\t\t\tattempt: number;\n\t\t\t/** The blocking compaction this generation waited for; it starts no other compaction (spec §8.3). */\n\t\t\tcompacted?: TaskId<CompactionResult>;\n\t\t\t/** Error text of the overflow that started `compacted`; checked once when `prepare` resumes. */\n\t\t\toverflow?: string;\n\t }\n\t| {\n\t\t\tphase: \"request\";\n\t\t\tattempt: number;\n\t\t\tcompacted?: TaskId<CompactionResult>;\n\t\t\tmodel: ModelRef;\n\t\t\tthinkingLevel: ModelThinkingLevel;\n\t\t\t/** The settings' request options when preparation committed; a resend after recovery uses them unchanged. */\n\t\t\tstreamOptions: ConversationStreamOptions;\n\t\t\t/** Newest entry included in the request. */\n\t\t\tcutoff: EntryId;\n\t }\n\t| { phase: \"retry\"; attempt: number; compacted?: TaskId<CompactionResult>; until: number }\n\t| {\n\t\t\tphase: \"poll\";\n\t\t\tattempt: number;\n\t\t\tcompacted?: TaskId<CompactionResult>;\n\t\t\tmodel: ModelRef;\n\t\t\tcutoff: EntryId;\n\t\t\thandle: DeferredHandle;\n\t\t\tpollAt: number;\n\t }\n\t| {\n\t\t\t/** Waiting on the round's tool tasks, which the generation owns (spec §8.5). */\n\t\t\tphase: \"tools\";\n\t\t\t/** The tool-calling answer. */\n\t\t\tassistant: EntryId;\n\t\t\t/** Tool tasks created so far, in call order; grows by one per started call of a sequential round. */\n\t\t\ttools: TaskId<ToolTaskResult>[];\n\t\t\t/** Calls of a sequential round not started yet, in call order. */\n\t\t\tpending: string[];\n\t };\n\nexport type GenerationResult = { entryId: EntryId };\n\ntype Runtime = TaskRuntime<GenerationInput, GenerationCheckpoint, GenerationResult, GenerationHooks>;\ntype Next = NextTaskState<GenerationCheckpoint, GenerationResult>;\n\n/** What classification needs from the request that produced a message. */\ntype Request = {\n\treadonly attempt: number;\n\treadonly compacted: TaskId<CompactionResult> | undefined;\n\treadonly model: ModelRef;\n\treadonly cutoff: EntryId;\n\t/** Committed model context through `cutoff`, when the phase already derived it. */\n\treadonly messages?: readonly Message[];\n\t/** Set when the message came from polling, so a still deferred result polls strictly later. */\n\treadonly pollAt?: number;\n};\n\nconst DEFAULT_POLL_AFTER_MS = 5000;\n\n/**\n * Built-in generation task: prepares the positional system prompt and tool loadout, requests or polls the model,\n * retries, and classifies the response. The run's inputs live in `pi.live.run`.\n */\nexport const GenerationTask = defineTask<GenerationInput, GenerationCheckpoint, GenerationResult, GenerationHooks>({\n\tname: \"pi.generation\",\n\tversion: 1,\n\tinitial: () => ({ phase: \"prepare\", attempt: 1 }),\n\tphases: {\n\t\t/**\n\t\t * Render the system prompt and tool loadout and append the positional `pi.system` entries they need, then move to\n\t\t * `request`. The agent and settings resolved here are fixed for this request. Only the Harness writes to a busy\n\t\t * conversation, so the transcript read here is still the tail at the commit.\n\t\t */\n\t\tprepare: async (task, runtime, context) => {\n\t\t\tconst { conversationId } = runtime;\n\t\t\tconst agent = await runtime.agent(context);\n\t\t\tconst settings = runtime.settings;\n\t\t\tconst { model, thinkingLevel } = agent;\n\t\t\tconst resolved = model === undefined ? undefined : runtime.models.getModel(model.provider, model.modelId);\n\t\t\tif (model === undefined || resolved === undefined) return failNoModel(runtime, model, context);\n\t\t\tconst { attempt, compacted, overflow } = task.state.checkpoint;\n\t\t\tif (compacted !== undefined && overflow !== undefined) {\n\t\t\t\tconst [outcome] = await runtime.outcomes([compacted], context);\n\t\t\t\tif (outcome?.status !== \"completed\" || outcome.result.entryId === undefined) {\n\t\t\t\t\treturn failModelError(runtime, overflow, context);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst view = await runtime.context(conversationId, context);\n\t\t\tconst shown = replaySections(view.messages);\n\t\t\tconst report = (error: unknown) => runtime.report(error);\n\t\t\tlet env: ExecutionEnv | undefined;\n\t\t\ttry {\n\t\t\t\tenv = await runtime.env(context);\n\t\t\t} catch (error) {\n\t\t\t\tif (context.abortSignal?.aborted) throw error;\n\t\t\t\treport(error);\n\t\t\t}\n\t\t\tconst input: PromptInput = { conversationId, agent, env, shown: Object.fromEntries(shown), read: runtime };\n\t\t\tconst desired = await renderSections(agent.sections, input, shown, report, context);\n\t\t\tconst entries = planSystemEntries(view, desired, agent.tools, runtime.now());\n\t\t\tconst threshold =\n\t\t\t\tcompacted === undefined\n\t\t\t\t\t? thresholdCompaction(view, entries, resolved.contextWindow, settings.compaction)\n\t\t\t\t\t: undefined;\n\t\t\tif (threshold === \"blocking\") {\n\t\t\t\t// Compact first and prepare again; the transcript is unchanged until the compaction appends.\n\t\t\t\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\t\t\t\tconst child = await createCompaction(tx, conversationId, { reason: \"threshold\" }, runtime.taskId);\n\t\t\t\t\tconst checkpoint = { phase: \"prepare\", attempt, compacted: child } as const;\n\t\t\t\t\treturn { status: \"waiting\", checkpoint, on: [child], policy: \"allSettled\" };\n\t\t\t\t}, context);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tlet cutoff = (await tx.scanEntries({ conversationId }, 1)).items[0]?.id;\n\t\t\t\tfor (const entry of entries) cutoff = (await tx.appendEntry(SystemEntry, conversationId, entry)).id;\n\t\t\t\tif (cutoff === undefined) throw new Error(`Conversation ${conversationId} has no entries to send`);\n\t\t\t\t// Checked in this commit, so a compaction admitted during preparation counts.\n\t\t\t\tif (threshold === \"background\" && (await tx.doc(LiveDoc, conversationId)).compactions === undefined) {\n\t\t\t\t\tawait createCompaction(tx, conversationId, { reason: \"threshold\" });\n\t\t\t\t}\n\t\t\t\tconst request = {\n\t\t\t\t\tattempt,\n\t\t\t\t\t...(compacted === undefined ? {} : { compacted }),\n\t\t\t\t\tmodel,\n\t\t\t\t\tthinkingLevel,\n\t\t\t\t\tstreamOptions: settings.stream,\n\t\t\t\t\tcutoff,\n\t\t\t\t};\n\t\t\t\treturn { status: \"running\", checkpoint: { phase: \"request\", ...request } };\n\t\t\t}, context);\n\t\t},\n\t\trequest: async (task, runtime, context) => {\n\t\t\tconst { attempt, compacted, model: ref, thinkingLevel, streamOptions, cutoff } = task.state.checkpoint;\n\t\t\tconst conversationId = runtime.conversationId;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\t\t\tawait convertPartial(tx, live, conversationId);\n\t\t\t\tlive.generation = { attempt };\n\t\t\t\treturn undefined;\n\t\t\t}, context);\n\t\t\tconst model = runtime.models.getModel(ref.provider, ref.modelId);\n\t\t\tif (model === undefined) return failNoModel(runtime, ref, context);\n\t\t\tconst view = await runtime.context(conversationId, context, cutoff);\n\t\t\tlet messages = view.messages;\n\t\t\tawait runtime.hooks.each(\"beforeRequest\", async (hook) => {\n\t\t\t\tconst replaced = await hook({ messages }, runtime, context);\n\t\t\t\tif (replaced !== undefined) messages = replaced.messages;\n\t\t\t});\n\t\t\tconst options: SimpleStreamOptions = {\n\t\t\t\t...streamOptions,\n\t\t\t\tsignal: runtime.signal,\n\t\t\t\tsessionId: await ensureProviderSessionId(runtime, context),\n\t\t\t\t...(thinkingLevel === \"off\" ? {} : { reasoning: thinkingLevel }),\n\t\t\t};\n\t\t\tconst message = await streamResponse(runtime, model, messages, options, attempt, context);\n\t\t\tconst request = { attempt, compacted, model: ref, cutoff, messages: view.messages };\n\t\t\tawait classify(runtime, request, message, context);\n\t\t},\n\t\tretry: async (task, runtime, context) => {\n\t\t\tconst { attempt, compacted, until } = task.state.checkpoint;\n\t\t\tawait runtime.sleep(until, context);\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\t(await tx.doc(LiveDoc, runtime.conversationId)).generation = { attempt: attempt + 1 };\n\t\t\t\tconst checkpoint: GenerationCheckpoint = {\n\t\t\t\t\tphase: \"prepare\",\n\t\t\t\t\tattempt: attempt + 1,\n\t\t\t\t\t...(compacted === undefined ? {} : { compacted }),\n\t\t\t\t};\n\t\t\t\treturn { status: \"running\", checkpoint };\n\t\t\t}, context);\n\t\t},\n\t\tpoll: async (task, runtime, context) => {\n\t\t\tconst { attempt, compacted, model: ref, cutoff, handle, pollAt } = task.state.checkpoint;\n\t\t\tconst model = runtime.models.getModel(ref.provider, ref.modelId);\n\t\t\tif (model === undefined) return failNoModel(runtime, ref, context);\n\t\t\tawait runtime.sleep(pollAt, context);\n\t\t\tconst message = await runtime.models.fetchDeferred(model, handle, { signal: runtime.signal });\n\t\t\tconst request = { attempt, compacted, model: ref, cutoff, pollAt };\n\t\t\tawait classify(runtime, request, message, context);\n\t\t},\n\t\ttools: async (task, runtime, context) => {\n\t\t\tconst { assistant, tools, pending } = task.state.checkpoint;\n\t\t\tconst [next, ...rest] = pending;\n\t\t\tif (next === undefined) return finishToolRound(runtime, assistant, tools, context);\n\t\t\t// Sequential round: start the next call and wait for it.\n\t\t\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\t\t\tconst live = await tx.doc(LiveDoc, runtime.conversationId);\n\t\t\t\tconst taskId = await createToolTask(tx, runtime, assistant, next);\n\t\t\t\tconst slot = live.tools?.find((slot) => slot.callId === next && slot.taskId === undefined);\n\t\t\t\tif (slot !== undefined) slot.taskId = taskId;\n\t\t\t\tconst checkpoint: GenerationCheckpoint = {\n\t\t\t\t\tphase: \"tools\",\n\t\t\t\t\tassistant,\n\t\t\t\t\ttools: [...tools, taskId],\n\t\t\t\t\tpending: rest,\n\t\t\t\t};\n\t\t\t\treturn { status: \"waiting\", checkpoint, on: [taskId], policy: \"allSettled\" };\n\t\t\t}, context);\n\t\t},\n\t},\n\tabort: async (task, runtime, context) => {\n\t\tconst checkpoint = task.state.checkpoint;\n\t\tif (checkpoint.phase === \"poll\") {\n\t\t\tconst model = runtime.models.getModel(checkpoint.model.provider, checkpoint.model.modelId);\n\t\t\tif (model !== undefined) {\n\t\t\t\ttry {\n\t\t\t\t\tawait runtime.models.cancelDeferred(model, checkpoint.handle, { signal: runtime.signal });\n\t\t\t\t} catch (error) {\n\t\t\t\t\truntime.report(error);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst conversationId = runtime.conversationId;\n\t\t// Runs after the round's tool tasks are terminal; calls never started get `aborted` results (spec §8.5).\n\t\tconst unstarted =\n\t\t\tcheckpoint.phase === \"tools\"\n\t\t\t\t? await readCalls(runtime, checkpoint.assistant, checkpoint.pending, context)\n\t\t\t\t: [];\n\t\tawait runtime.commit(async (tx) => {\n\t\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\t\tawait convertPartial(tx, live, conversationId);\n\t\t\tfor (const call of unstarted) {\n\t\t\t\tconst result = harnessError(\"aborted\", `Tool ${call.name} was aborted`);\n\t\t\t\tawait appendToolResult(tx, conversationId, call, result, runtime.now());\n\t\t\t}\n\t\t\tendRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"aborted\" });\n\t\t\treturn { status: \"terminal\", outcome: { status: \"aborted\" } };\n\t\t}, context);\n\t},\n});\n\n/** The calls `callIds` of the assistant entry, in the given order. */\nasync function readCalls(\n\truntime: Runtime,\n\tassistant: EntryId,\n\tcallIds: readonly string[],\n\tcontext: Context,\n): Promise<ToolCall[]> {\n\tconst message = (await runtime.entry(AssistantEntry, assistant, context))?.model?.[0];\n\tconst calls = message?.role === \"assistant\" ? message.content.filter((content) => content.type === \"toolCall\") : [];\n\treturn callIds.flatMap((id) => calls.filter((call) => call.id === id).slice(0, 1));\n}\n\n/** A tool task for call `callId`, owned by the generation. */\nfunction createToolTask(tx: Tx, runtime: Runtime, assistant: EntryId, callId: string): Promise<TaskId<ToolTaskResult>> {\n\treturn tx.createTask(ToolTask, { assistant, callId }, { ownership: { kind: \"task\", taskId: runtime.taskId } });\n}\n\n/**\n * Which threshold compaction preparation starts before its request (spec §8.3): `blocking` above\n * `contextWindow - reserveTokens`, `background` above the background threshold, and only when range selection finds a\n * cut. The caller starts a background one only while no compaction is listed.\n */\nfunction thresholdCompaction(\n\tview: ContextView,\n\tplanned: readonly { readonly model?: readonly Message[] }[],\n\tcontextWindow: number,\n\tpolicy: CompactionPolicy,\n): \"blocking\" | \"background\" | undefined {\n\tif (!policy.enabled || contextWindow <= 0) return undefined;\n\tconst tokens = estimateContext(\n\t\tview,\n\t\tplanned.flatMap((entry) => entry.model ?? []),\n\t);\n\tconst blocking = contextWindow - policy.reserveTokens;\n\tconst background = blocking - policy.backgroundTokens;\n\tconst over =\n\t\ttokens > blocking ? \"blocking\" : policy.backgroundTokens > 0 && tokens > background ? \"background\" : undefined;\n\tif (over === undefined || selectCut(view, policy.keepRecentTokens) === undefined) return undefined;\n\treturn over;\n}\n\n/** Settle the run's inputs `unanswered` with `model_error` and fail with `text`. */\nasync function failModelError(runtime: Runtime, text: string, context: Context): Promise<void> {\n\tawait runtime.commit(async (tx) => {\n\t\tconst live = await tx.doc(LiveDoc, runtime.conversationId);\n\t\tendRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"model_error\", detail: text });\n\t\treturn {\n\t\t\tstatus: \"terminal\",\n\t\t\toutcome: { status: \"failed\", error: { message: text, detail: { reason: \"model_error\" } } },\n\t\t};\n\t}, context);\n}\n\n/** Settle the run's inputs `unanswered` with `no_model` and fail. */\nasync function failNoModel(runtime: Runtime, ref: ModelRef | undefined, context: Context): Promise<void> {\n\tconst message =\n\t\tref === undefined ? \"No model is configured\" : `Model ${ref.provider}/${ref.modelId} is not available`;\n\tawait runtime.commit(async (tx) => {\n\t\tconst live = await tx.doc(LiveDoc, runtime.conversationId);\n\t\tendRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"no_model\" });\n\t\treturn { status: \"terminal\", outcome: { status: \"failed\", error: { message, detail: { reason: \"no_model\" } } } };\n\t}, context);\n}\n\n/**\n * Append a committed partial left by an interrupted, aborted, faulted, or orphaned attempt as an aborted assistant\n * entry; the caller replaces or removes `generation`.\n */\nexport async function convertPartial(tx: Tx, live: Draft<LiveState>, conversationId: ConversationId): Promise<void> {\n\tconst partial = live.generation?.message;\n\tif (partial === undefined) return;\n\tconst message = copyJson(partial) as unknown as AssistantMessage;\n\tawait appendAssistant(tx, conversationId, { ...message, stopReason: \"aborted\" });\n}\n\n/**\n * Stream one request and return the terminal message. Partials commit as trailing writes at most every\n * `progress.partialIntervalMs` (default 100 ms) with one commit in flight; `finally` stops the throttle and awaits that\n * commit, so no stale partial lands after the outcome.\n */\nasync function streamResponse(\n\truntime: Runtime,\n\tmodel: Model<Api>,\n\tmessages: readonly Message[],\n\toptions: SimpleStreamOptions,\n\tattempt: number,\n\tcontext: Context,\n): Promise<AssistantMessage> {\n\tconst interval = runtime.settings.progress.partialIntervalMs;\n\tlet pending: AssistantMessage | undefined;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet inFlight: Promise<void> | undefined;\n\tlet stopped = false;\n\tconst flush = (): void => {\n\t\ttimer = undefined;\n\t\tconst partial = pending;\n\t\tpending = undefined;\n\t\tif (partial === undefined || stopped) return;\n\t\tinFlight = (async () => {\n\t\t\t// Copy synchronously: the provider keeps mutating its partial.\n\t\t\tconst message = copyJson(partial, { omitUndefinedProperties: true });\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst live = await tx.doc(LiveDoc, runtime.conversationId);\n\t\t\t\tlive.generation ??= { attempt };\n\t\t\t\tassignJson(live.generation as Draft<Record<string, JsonValue>>, \"message\", message);\n\t\t\t\treturn undefined;\n\t\t\t}, context);\n\t\t})()\n\t\t\t.catch((error: unknown) => {\n\t\t\t\t// Rejections after an abort mark or close are expected; the committed state stays consistent.\n\t\t\t\tif (!runtime.signal.aborted) runtime.report(error);\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tinFlight = undefined;\n\t\t\t\tif (pending !== undefined && !stopped) timer = setTimeout(flush, interval);\n\t\t\t});\n\t};\n\ttry {\n\t\tconst events = runtime.models.streamSimple(model, { messages: [...messages] }, options);\n\t\tfor await (const event of events) {\n\t\t\t// A partial without content, such as pi-ai's opening `start` event, shows nothing; a deferred response\n\t\t\t// never gets past it, so it never leaves a partial.\n\t\t\tif (event.type === \"done\" || event.type === \"error\" || event.partial.content.length === 0) continue;\n\t\t\tpending = event.partial;\n\t\t\tif (timer === undefined && inFlight === undefined) timer = setTimeout(flush, interval);\n\t\t}\n\t\treturn await events.result();\n\t} finally {\n\t\tstopped = true;\n\t\tclearTimeout(timer);\n\t\tawait inFlight;\n\t}\n}\n\n/** Classify a terminal provider message in one commit that also clears the partial. */\nasync function classify(\n\truntime: Runtime,\n\trequest: Request,\n\tmessage: AssistantMessage,\n\tcontext: Context,\n): Promise<void> {\n\t// An abort mark or close: the abort invocation or the reopened run handles the committed state.\n\truntime.signal.throwIfAborted();\n\tconst conversationId = runtime.conversationId;\n\tconst { attempt, compacted, model: ref, cutoff } = request;\n\tif (message.stopReason === \"deferred\" && message.deferred !== undefined) {\n\t\tconst handle = message.deferred;\n\t\tconst pollAt = Math.max(\n\t\t\truntime.now() + (handle.pollAfterMs ?? DEFAULT_POLL_AFTER_MS),\n\t\t\trequest.pollAt === undefined ? Number.NEGATIVE_INFINITY : request.pollAt + 1,\n\t\t);\n\t\tawait runtime.commit(async (tx) => {\n\t\t\t(await tx.doc(LiveDoc, conversationId)).generation = { attempt, deferred: { pollAt } };\n\t\t\tconst checkpoint = {\n\t\t\t\tphase: \"poll\",\n\t\t\t\tattempt,\n\t\t\t\t...(compacted === undefined ? {} : { compacted }),\n\t\t\t\tmodel: ref,\n\t\t\t\tcutoff,\n\t\t\t\thandle,\n\t\t\t\tpollAt,\n\t\t\t} as const;\n\t\t\treturn { status: \"running\", checkpoint };\n\t\t}, context);\n\t\treturn;\n\t}\n\tawait runtime.hooks.each(\"afterResponse\", (hook) => hook(message, runtime, context));\n\tconst calls = message.content.filter((content): content is ToolCall => content.type === \"toolCall\");\n\tif (message.stopReason === \"toolUse\" && calls.length > 0) {\n\t\treturn startToolRound(runtime, request, message, calls, context);\n\t}\n\tif (message.stopReason === \"stop\" || message.stopReason === \"length\" || message.stopReason === \"toolUse\") {\n\t\treturn answer(runtime, message, context);\n\t}\n\t// The retry and compaction policies govern the next attempt, so they are read now rather than pinned at preparation.\n\tconst settings = runtime.settings;\n\tconst overflow = message.stopReason === \"error\" && isContextOverflow(message);\n\tif (overflow && compacted === undefined && settings.compaction.enabled) {\n\t\tconst policy = settings.compaction;\n\t\tconst view = await runtime.context(conversationId, context, cutoff);\n\t\tif (selectCut(view, policy.keepRecentTokens) !== undefined) {\n\t\t\tconst text = message.errorMessage ?? \"Context overflow\";\n\t\t\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\t\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\t\t\tawait appendAssistant(tx, conversationId, message);\n\t\t\t\tdelete live.generation;\n\t\t\t\tconst child = await createCompaction(tx, conversationId, { reason: \"overflow\" }, runtime.taskId);\n\t\t\t\tconst checkpoint = { phase: \"prepare\", attempt, compacted: child, overflow: text } as const;\n\t\t\t\treturn { status: \"waiting\", checkpoint, on: [child], policy: \"allSettled\" };\n\t\t\t}, context);\n\t\t\treturn;\n\t\t}\n\t}\n\tconst policy = settings.retry;\n\t// An overflow is never retried: only a compaction can make the next request fit.\n\tconst retry =\n\t\tmessage.stopReason === \"error\" &&\n\t\t!overflow &&\n\t\tisRetryableAssistantError(message) &&\n\t\tpolicy.enabled &&\n\t\tattempt <= policy.maxRetries;\n\tconst until = retry ? runtime.now() + retryDelayMs(policy, attempt) : 0;\n\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\tawait appendAssistant(tx, conversationId, message);\n\t\tif (retry) {\n\t\t\tlive.generation = { attempt, retry: { at: until, error: message.errorMessage ?? \"\" } };\n\t\t\tconst checkpoint = {\n\t\t\t\tphase: \"retry\",\n\t\t\t\tattempt,\n\t\t\t\t...(compacted === undefined ? {} : { compacted }),\n\t\t\t\tuntil,\n\t\t\t} as const;\n\t\t\treturn { status: \"running\", checkpoint };\n\t\t}\n\t\tconst text = message.errorMessage ?? `Model response ended with stop reason ${message.stopReason}`;\n\t\tendRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"model_error\", detail: text });\n\t\treturn {\n\t\t\tstatus: \"terminal\",\n\t\t\toutcome: { status: \"failed\", error: { message: text, detail: { reason: \"model_error\" } } },\n\t\t};\n\t}, context);\n}\n\n/**\n * A final answer; the final boundary places queued items (spec §6). The first `onYield` continuation appends a user\n * message and hands the run to a successor generation, but only when the boundary selected no user item and no reset.\n * Otherwise the run's inputs settle `done`, and selected user items start the next run.\n */\nasync function answer(runtime: Runtime, message: AssistantMessage, context: Context): Promise<void> {\n\tlet continuation: UserInput | undefined;\n\tawait runtime.hooks.each(\"onYield\", async (hook) => {\n\t\tif (continuation !== undefined) return;\n\t\tcontinuation = (await hook(message, runtime, context))?.continue;\n\t});\n\tconst conversationId = runtime.conversationId;\n\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\t// Queue modes are read on the Session line, when the boundary is decided.\n\t\tconst boundary = await prepareBoundary(tx, conversationId, runtime.settings);\n\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\tconst entry = await appendAssistant(tx, conversationId, message);\n\t\tconst result: Next = { status: \"terminal\", outcome: { status: \"completed\", result: { entryId: entry.id } } };\n\t\tconst { users, reset } = await applyBoundary(tx, boundary, \"final\", runtime.now());\n\t\tif (continuation !== undefined && users.length === 0 && !reset) {\n\t\t\tconst user = { role: \"user\", content: continuation, timestamp: runtime.now() } as const;\n\t\t\tawait tx.appendEntry(UserEntry, conversationId, { model: [user] });\n\t\t\thandOver(live, runtime.taskId, await createGeneration(tx, conversationId));\n\t\t\tdelete live.generation;\n\t\t\treturn result;\n\t\t}\n\t\tendRun(tx, live, runtime.taskId, { status: \"done\", answer: entry.id });\n\t\tif (users.length > 0) await startRun(tx, conversationId, live, users);\n\t\treturn result;\n\t}, context);\n}\n\n/**\n * Append the tool-calling answer and start its tool round in one commit (spec §8.3). A call to a tool the request did\n * not offer gets its `tool_unavailable` result here; every other call gets a tool task owned by the generation, only the\n * first one now when the round is sequential. The generation then waits for them in its `tools` phase, keeping the run.\n */\nasync function startToolRound(\n\truntime: Runtime,\n\trequest: Request,\n\tmessage: AssistantMessage,\n\tcalls: readonly ToolCall[],\n\tcontext: Context,\n): Promise<void> {\n\tconst conversationId = runtime.conversationId;\n\tconst messages = request.messages ?? (await runtime.context(conversationId, context, request.cutoff)).messages;\n\tconst offered = new Set(getCurrentTools(messages).map((tool) => tool.name));\n\t// Read as the round starts; a tool is resolved as its tool task resolves it.\n\tconst tools = (await runtime.agent(context)).tools;\n\tconst sequential =\n\t\truntime.settings.toolExecution === \"sequential\" ||\n\t\tcalls.some(\n\t\t\t(call) =>\n\t\t\t\toffered.has(call.name) && tools.find((tool) => tool.name === call.name)?.executionMode === \"sequential\",\n\t\t);\n\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\tconst entry = await appendAssistant(tx, conversationId, message);\n\t\tconst slots: ToolSlot[] = [];\n\t\tconst tools: TaskId<ToolTaskResult>[] = [];\n\t\tconst pending: string[] = [];\n\t\tfor (const call of calls) {\n\t\t\tif (!offered.has(call.name)) {\n\t\t\t\tconst unavailable = harnessError(\"tool_unavailable\", `Tool ${call.name} is not available`);\n\t\t\t\tconst result = await appendToolResult(tx, conversationId, call, unavailable, runtime.now());\n\t\t\t\tslots.push({ callId: call.id, name: call.name, status: \"done\", entry: result.id });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (sequential && tools.length > 0) {\n\t\t\t\tpending.push(call.id);\n\t\t\t\tslots.push({ callId: call.id, name: call.name, status: \"pending\" });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst taskId = await createToolTask(tx, runtime, entry.id, call.id);\n\t\t\ttools.push(taskId);\n\t\t\tslots.push({ callId: call.id, name: call.name, taskId, status: \"pending\" });\n\t\t}\n\t\tdelete live.generation;\n\t\tlive.tools = slots;\n\t\tconst checkpoint = { phase: \"tools\", assistant: entry.id, tools, pending } as const;\n\t\treturn { status: \"waiting\", checkpoint, on: tools, policy: \"allSettled\" };\n\t}, context);\n}\n\n/**\n * The round's tools are terminal: apply their controls and either end the run at the final boundary (`terminate`,\n * `handoff`, or a queued reset) or hand it to the next generation at the `postTools` boundary (spec §8.5).\n */\nasync function finishToolRound(\n\truntime: Runtime,\n\tassistant: EntryId,\n\ttools: readonly TaskId<ToolTaskResult>[],\n\tcontext: Context,\n): Promise<void> {\n\tconst conversationId = runtime.conversationId;\n\tconst controls = new Map<TaskId, ToolControl | undefined>();\n\tconst outcomes = await runtime.outcomes(tools, context);\n\ttools.forEach((id, index) => {\n\t\tconst outcome = outcomes[index]!;\n\t\tcontrols.set(id, outcome.status === \"completed\" ? outcome.result.control : undefined);\n\t});\n\tconst slots = (await runtime.snapshot(LiveDoc, conversationId, context))?.tools ?? [];\n\tconst results = slots.flatMap((slot) => (slot.entry === undefined ? [] : [slot.entry]));\n\tawait runtime.hooks.each(\"afterTools\", (hook) => hook(assistant, results, runtime, context));\n\t// Every call of the round, including those answered without a task, must ask to terminate.\n\tconst terminate =\n\t\tslots.length > 0 &&\n\t\tslots.every((slot) => slot.taskId !== undefined && controls.get(slot.taskId)?.terminate === true);\n\tconst added = [...controls.values()].flatMap((control) => control?.addTools ?? []);\n\t// The last handoff in call order wins.\n\tconst handoff = [...controls.values()].findLast((control) => control?.handoff !== undefined)?.handoff;\n\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\tconst boundary = await prepareBoundary(tx, conversationId, runtime.settings);\n\t\tif (added.length > 0) await addTools(tx, conversationId, added);\n\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\tconst now = runtime.now();\n\t\tif (terminate || handoff !== undefined) {\n\t\t\tif (handoff !== undefined) {\n\t\t\t\tconst message = { role: \"user\", content: handoff, timestamp: now } as const;\n\t\t\t\tconst entry = await tx.appendEntry(ResetEntry, conversationId, { head: \"self\", model: [message] });\n\t\t\t\tboundary.head = entry.id;\n\t\t\t}\n\t\t\tconst { users } = await applyBoundary(tx, boundary, \"final\", now);\n\t\t\tendRun(tx, live, runtime.taskId, { status: \"done\", answer: assistant });\n\t\t\tif (users.length > 0) await startRun(tx, conversationId, live, users);\n\t\t} else {\n\t\t\tconst { users, reset } = await applyBoundary(tx, boundary, \"postTools\", now);\n\t\t\tif (reset) {\n\t\t\t\t// The queued reset cut the run's context before an answer.\n\t\t\t\tendRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"reset\" });\n\t\t\t\tif (users.length > 0) await startRun(tx, conversationId, live, users);\n\t\t\t} else {\n\t\t\t\tdelete live.tools;\n\t\t\t\tif (live.run?.taskId === runtime.taskId) live.run.inputs.push(...users);\n\t\t\t\thandOver(live, runtime.taskId, await createGeneration(tx, conversationId));\n\t\t\t}\n\t\t}\n\t\treturn { status: \"terminal\", outcome: { status: \"completed\", result: { entryId: assistant } } };\n\t}, context);\n}\n\n/**\n * Append a provider result and add its usage to `pi.usage` in the same commit.\n * REMINDER: every built-in writer of assistant entries goes through here, so the usage ledger stays complete.\n */\nasync function appendAssistant(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tmessage: AssistantMessage,\n): Promise<TypedEntry<never>> {\n\tawait recordUsage(tx, conversationId, \"models\", `${message.provider}/${message.model}`, message.usage);\n\treturn tx.appendEntry(AssistantEntry, conversationId, { model: [message] });\n}\n\n/** Start a run for `inputs`, placed input submissions: a new generation takes `pi.live.run`. */\nexport async function startRun(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tlive: Draft<LiveState>,\n\tinputs: SubmissionId[],\n): Promise<void> {\n\tlive.run = { taskId: await createGeneration(tx, conversationId), inputs };\n}\n\n/** A generation owned by its conversation. */\nfunction createGeneration(tx: Tx, conversationId: ConversationId): Promise<TaskId<GenerationResult>> {\n\treturn tx.createTask(GenerationTask, {}, { ownership: { kind: \"conversation\" }, conversationId });\n}\n\n/** Hand run control from `from` to `to`; the run's inputs move with it. */\nexport function handOver(live: Draft<LiveState>, from: TaskId, to: TaskId): void {\n\tif (live.run?.taskId === from) live.run.taskId = to;\n}\n", "import type { Draft, JsonRepresentation, JsonValue } from \"@earendil-works/chord\";\nimport type { AssistantMessage } from \"@earendil-works/pi-ai\";\nimport { defineDoc } from \"../documents.ts\";\nimport type { Transaction } from \"../session/transaction.ts\";\nimport type { EntryId, SubmissionId, SubmissionSettlement, TaskId, TaskRecord, Tx } from \"../types.ts\";\nimport { convertPartial } from \"./generation.ts\";\nimport type { SchedulerOutcome } from \"./scheduler.ts\";\nimport type { CompactionReason, CompactionResult, ToolDiagnostic } from \"./types.ts\";\n\n/** Presentation of one tool call of the current round. */\nexport type ToolSlot = {\n\tcallId: string;\n\tname: string;\n\t/**\n\t * Absent for a call not started yet (sequential round) and for a call its request did not offer, which starts `done`\n\t * with the `entry` generation wrote.\n\t */\n\ttaskId?: TaskId;\n\tstatus: \"pending\" | \"running\" | \"done\";\n\t/** Retained running output and what the bounds dropped. */\n\toutput?: string;\n\tdroppedBytes?: number;\n\tdroppedLines?: number;\n\t/** Last `details()` value. */\n\tdetails?: JsonValue;\n\t/** Diagnostics recorded through `api.diagnostic()`. */\n\tdiagnostics?: ToolDiagnostic[];\n\t/** Result entry once done; absent when the tool task faulted or was orphaned. */\n\tentry?: EntryId;\n};\n\n/** Presentation of one live compaction task (spec §8.7). */\nexport type CompactionStatus = {\n\ttaskId: TaskId<CompactionResult>;\n\treason: CompactionReason;\n\t/** Whether a generation waits for it: a compaction the generation owns. */\n\tblocking: boolean;\n\tattempt: number;\n\t/** Durable backoff before the next summarization attempt. */\n\tretry?: { at: number; error: string };\n};\n\n/** Built-in live conversation state: run control and presentation of the current generation and tool round. */\nexport type LiveState = {\n\t/** Run control: the task that settles the run's inputs, and those inputs; present exactly while busy. */\n\trun?: { taskId: TaskId; inputs: SubmissionId[] };\n\t/** Presentation of the current generation attempt. */\n\tgeneration?: {\n\t\tattempt: number;\n\t\t/** Committed throttled partial of the in-flight response. */\n\t\tmessage?: JsonRepresentation<AssistantMessage>;\n\t\t/** Durable backoff before the next attempt. */\n\t\tretry?: { at: number; error: string };\n\t\t/** Provider-side deferred response being polled. */\n\t\tdeferred?: { pollAt: number };\n\t};\n\t/** The current tool round in call order, from the tool-calling answer until the generation's `tools` phase ends it. */\n\ttools?: ToolSlot[];\n\t/** Live compaction tasks in task ID order; absent when none. */\n\tcompactions?: CompactionStatus[];\n};\n\nexport const LiveDoc = defineDoc<LiveState>({\n\tkind: \"pi.live\",\n\tversion: 1,\n\tscope: \"conversation\",\n\thistory: \"latest\",\n\tfork: \"initial\",\n\tinitial: () => ({}),\n\t// REMINDER: a complete base whenever nothing runs (spec §8.2): no generation and no running tool slot. That holds\n\t// while idle, in the commit handing a generation over to its tool round, and between tools, so the delta chain\n\t// spans at most one generation or the overlapping execution of one round's tools. A slot holds output only while\n\t// running, so every base is small. Do not add a delta-count bound; the tool output benchmark checks this rule.\n\tcheckpointWhen: (value) =>\n\t\tvalue.generation === undefined && !(value.tools ?? []).some((slot) => slot.status === \"running\"),\n});\n\n/** Built-in task kinds that can own `pi.live.run`. */\nconst RUN_TASK_KINDS: ReadonlySet<string> = new Set([\"pi.generation\"]);\nconst TOOL_TASK_KIND = \"pi.tool\";\nconst COMPACTION_TASK_KIND = \"pi.compaction\";\n\n/**\n * End the run owned by `taskId`: settle each of its inputs and remove `run`. Always removes `generation` and `tools`,\n * whose presentation belongs to the ending run.\n */\nexport function endRun(tx: Tx, live: Draft<LiveState>, taskId: TaskId, settlement: SubmissionSettlement): void {\n\tif (live.run?.taskId === taskId) {\n\t\tfor (const id of live.run.inputs) tx.settleSubmission(id, settlement);\n\t\tdelete live.run;\n\t}\n\tdelete live.generation;\n\tdelete live.tools;\n}\n\n/** Add the status of a compaction task created in this commit; statuses stay in task ID order. */\nexport function addCompactionStatus(live: Draft<LiveState>, status: CompactionStatus): void {\n\tlive.compactions ??= [];\n\tlive.compactions.push(status);\n}\n\n/** The status of compaction task `taskId`, if listed. */\nexport function compactionStatus(live: Draft<LiveState>, taskId: TaskId): Draft<CompactionStatus> | undefined {\n\treturn live.compactions?.find((status) => status.taskId === taskId);\n}\n\n/** Remove the status of compaction task `taskId`, and the list once empty. */\nexport function removeCompactionStatus(live: Draft<LiveState>, taskId: TaskId): void {\n\tconst statuses = live.compactions;\n\tif (statuses === undefined) return;\n\tconst index = statuses.findIndex((status) => status.taskId === taskId);\n\tif (index >= 0) statuses.splice(index, 1);\n\tif (statuses.length === 0) delete live.compactions;\n}\n\n/** The slot of tool task `taskId` in the current round, if the round still lists it. */\nexport function toolSlot(live: Draft<LiveState>, taskId: TaskId): Draft<ToolSlot> | undefined {\n\treturn live.tools?.find((slot) => slot.taskId === taskId);\n}\n\n/** Mark a slot done: the result entry, if any, now carries its running output, details, and diagnostics. */\nexport function finishSlot(slot: Draft<ToolSlot>, entry: EntryId | undefined): void {\n\tslot.status = \"done\";\n\tif (entry !== undefined) slot.entry = entry;\n\tclearProgress(slot);\n}\n\n/** Remove what a tool published while running; its result entry or a rerun replaces it. */\nexport function clearProgress(slot: Draft<ToolSlot>): void {\n\tdelete slot.output;\n\tdelete slot.droppedBytes;\n\tdelete slot.droppedLines;\n\tdelete slot.details;\n\tdelete slot.diagnostics;\n}\n\n/**\n * Harness cleanup for a terminal outcome the scheduler writes itself (`faulted` or `orphaned`). A run task ends its\n * run; a tool task's slot is marked done without an entry, and context derivation synthesizes the missing result; a\n * compaction task's status is removed.\n * Ignores other kinds so it never creates `pi.live` elsewhere. The scheduler calls this without knowing task kinds;\n * the Harness passes it in (spec §5.4).\n * REMINDER: a committed generation partial becomes an aborted assistant entry here, exactly as in the generation abort\n * handler, so the transcript keeps what the model produced and `pi.usage` counts its spend. The scheduler's commit has\n * no task scope, so that entry has no `byTaskId`. Faults come from task bugs\n * or malformed provider data (a non-JSON value in a response), or a commit the Storage rejected without effect; an\n * uncertain storage failure poisons the Session instead and writes no outcome.\n */\nexport async function settleSchedulerOutcome(\n\ttx: Transaction,\n\trecord: TaskRecord<JsonValue, JsonValue, JsonValue>,\n\toutcome: SchedulerOutcome,\n): Promise<void> {\n\tif (record.kind === TOOL_TASK_KIND) {\n\t\tconst slot = toolSlot(await tx.doc(LiveDoc, record.conversationId), record.id);\n\t\tif (slot !== undefined) finishSlot(slot, undefined);\n\t\treturn;\n\t}\n\tif (record.kind === COMPACTION_TASK_KIND) {\n\t\tremoveCompactionStatus(await tx.doc(LiveDoc, record.conversationId), record.id);\n\t\treturn;\n\t}\n\tif (!RUN_TASK_KINDS.has(record.kind)) return;\n\tconst live = await tx.doc(LiveDoc, record.conversationId);\n\tif (live.run?.taskId !== record.id) return;\n\tawait convertPartial(tx, live, record.conversationId);\n\tendRun(\n\t\ttx,\n\t\tlive,\n\t\trecord.id,\n\t\toutcome.status === \"faulted\"\n\t\t\t? { status: \"unanswered\", reason: \"faulted\", detail: outcome.error.message }\n\t\t\t: { status: \"unanswered\", reason: outcome.reason },\n\t);\n}\n", "import type { Context } from \"@earendil-works/chord\";\nimport type { Cursor, Page } from \"../types.ts\";\n\n/** Pending waits by key. Each settles once: through `resolve`, `rejectAll`, or cancellation of its context. */\nexport class Waiters<K, T> {\n\treadonly #sets = new Map<K, Set<PromiseWithResolvers<T>>>();\n\n\tadd(key: K, context: Context): Promise<T> {\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) return Promise.reject(signal.reason);\n\t\tconst waiter = Promise.withResolvers<T>();\n\t\tconst set = this.#sets.get(key) ?? new Set();\n\t\tthis.#sets.set(key, set.add(waiter));\n\t\tif (signal !== undefined) {\n\t\t\tconst onAbort = (): void => {\n\t\t\t\tset.delete(waiter);\n\t\t\t\tif (set.size === 0 && this.#sets.get(key) === set) this.#sets.delete(key);\n\t\t\t\twaiter.reject(signal.reason);\n\t\t\t};\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tconst detach = (): void => signal.removeEventListener(\"abort\", onAbort);\n\t\t\twaiter.promise.then(detach, detach);\n\t\t}\n\t\treturn waiter.promise;\n\t}\n\n\tkeys(): K[] {\n\t\treturn [...this.#sets.keys()];\n\t}\n\n\tresolve(key: K, value: T): void {\n\t\tconst set = this.#sets.get(key);\n\t\tthis.#sets.delete(key);\n\t\tfor (const waiter of set ?? []) waiter.resolve(value);\n\t}\n\n\trejectAll(error: unknown): void {\n\t\tconst sets = [...this.#sets.values()];\n\t\tthis.#sets.clear();\n\t\tfor (const set of sets) for (const waiter of set) waiter.reject(error);\n\t}\n}\n\n/** Every item of a paginated scan, in page order. */\nexport async function scanAll<T>(scan: (cursor: Cursor | undefined) => Promise<Page<T, Cursor>>): Promise<T[]> {\n\tconst items: T[] = [];\n\tlet cursor: Cursor | undefined;\n\tdo {\n\t\tconst page = await scan(cursor);\n\t\titems.push(...page.items);\n\t\tcursor = page.next;\n\t} while (cursor !== undefined);\n\treturn items;\n}\n\nexport function closedError(): Error {\n\treturn new Error(\"Harness is closed\");\n}\n", "import { type Context, copyJson, type JsonRepresentation } from \"@earendil-works/chord\";\nimport { UserEntry } from \"../entries.ts\";\nimport { ConversationBusy } from \"../errors.ts\";\nimport type { SessionImpl } from \"../session/session.ts\";\nimport type {\n\tCommitPublication,\n\tConversationId,\n\tJsonObject,\n\tStorage,\n\tSubmissionId,\n\tSubmissionRecord,\n\tTx,\n} from \"../types.ts\";\nimport { startRun } from \"./generation.ts\";\nimport { applyBoundary, InboxDoc, isStale, prepareBoundary, type QueueModes, removeInboxItem } from \"./inbox.ts\";\nimport { LiveDoc } from \"./live.ts\";\nimport type { SettledSubmissionRecord, Submission, SubmissionDraft, UserInput } from \"./types.ts\";\nimport { closedError, Waiters } from \"./util.ts\";\n\ntype AbortResult = \"aborted\" | \"already_placed\" | \"settled\";\n\n/** Admission, waits, and withdrawal of the durable submissions of one Harness. */\nexport class Submissions {\n\treadonly #session: SessionImpl;\n\treadonly #storage: Storage;\n\treadonly #now: () => number;\n\t/** Read at each admission, on the Session line. */\n\treadonly #queueModes: () => QueueModes;\n\t/** Enable task scheduling; submitting or waiting asks for progress. */\n\treadonly #resume: () => void;\n\treadonly #waiters = new Waiters<SubmissionId, SettledSubmissionRecord>();\n\t#closed = false;\n\n\tconstructor(\n\t\tsession: SessionImpl,\n\t\tstorage: Storage,\n\t\tnow: () => number,\n\t\tqueueModes: () => QueueModes,\n\t\tresume: () => void,\n\t) {\n\t\tthis.#session = session;\n\t\tthis.#storage = storage;\n\t\tthis.#now = now;\n\t\tthis.#queueModes = queueModes;\n\t\tthis.#resume = resume;\n\t\tsession.subscribeCommits((publication) => this.#observe(publication));\n\t\tsession.subscribeClose(() => {\n\t\t\tthis.#closed = true;\n\t\t\tthis.#waiters.rejectAll(closedError());\n\t\t});\n\t}\n\n\t/** Admit a submission in one commit; see `admitSubmission()`. */\n\tasync submit(conversationId: ConversationId, draft: SubmissionDraft, context: Context): Promise<Submission> {\n\t\tthis.#resume();\n\t\tconst id = await this.#session.commitWith(\n\t\t\t(tx) => admitSubmission(tx, conversationId, draft, this.#now(), this.#queueModes()),\n\t\t\tcontext,\n\t\t);\n\t\treturn new SubmissionHandle(id, this);\n\t}\n\n\t/** Handle for an existing submission, or `undefined`. */\n\tasync get(id: SubmissionId, context: Context): Promise<Submission | undefined> {\n\t\tconst record = await this.#session.readOnLine(() => this.#storage.submission(id, context));\n\t\treturn record === undefined ? undefined : new SubmissionHandle(record.id, this);\n\t}\n\n\tasync status(id: SubmissionId, context: Context): Promise<SubmissionRecord> {\n\t\tconst record = await this.#session.readOnLine(() => this.#storage.submission(id, context));\n\t\tif (record === undefined) throw new Error(`Submission ${id} does not exist`);\n\t\treturn record;\n\t}\n\n\tasync wait(id: SubmissionId, context: Context): Promise<SettledSubmissionRecord> {\n\t\tthis.#resume();\n\t\t// Check and register on the line so no settling publication falls between them.\n\t\tconst found = await this.#session.readOnLine(async () => {\n\t\t\tconst record = await this.#storage.submission(id, context);\n\t\t\tif (record === undefined) throw new Error(`Submission ${id} does not exist`);\n\t\t\tif (isSettled(record)) return { promise: Promise.resolve(record) };\n\t\t\t// Close rejects registered waiters synchronously and may begin during the read.\n\t\t\tif (this.#closed) throw closedError();\n\t\t\treturn { promise: this.#waiters.add(id, context) };\n\t\t});\n\t\treturn found.promise;\n\t}\n\n\t/** Withdraw a queued submission and remove its inbox item; placed inputs and settled submissions are reported. */\n\tabort(id: SubmissionId, context: Context, conversationId?: ConversationId): Promise<AbortResult | \"not_found\"> {\n\t\treturn this.#session.commitWith(async (tx) => {\n\t\t\tconst record = await tx.submission(id);\n\t\t\tif (record === undefined || (conversationId !== undefined && record.conversationId !== conversationId)) {\n\t\t\t\treturn \"not_found\";\n\t\t\t}\n\t\t\tif (record.status === \"queued\") {\n\t\t\t\ttx.settleSubmission(id, { status: \"unanswered\", reason: \"aborted\" });\n\t\t\t\tawait removeInboxItem(tx, record.conversationId, id);\n\t\t\t\treturn \"aborted\";\n\t\t\t}\n\t\t\treturn record.status === \"placed\" ? \"already_placed\" : \"settled\";\n\t\t}, context);\n\t}\n\n\t#observe(publication: CommitPublication): void {\n\t\tfor (const change of publication.changes) {\n\t\t\tif (change.type !== \"submission\" || !isSettled(change.value)) continue;\n\t\t\tthis.#waiters.resolve(change.value.id, change.value);\n\t\t}\n\t}\n}\n\nclass SubmissionHandle implements Submission {\n\treadonly id: SubmissionId;\n\treadonly #submissions: Submissions;\n\n\tconstructor(id: SubmissionId, submissions: Submissions) {\n\t\tthis.id = id;\n\t\tthis.#submissions = submissions;\n\t}\n\n\tstatus(context: Context): Promise<SubmissionRecord> {\n\t\treturn this.#submissions.status(this.id, context);\n\t}\n\n\twait(context: Context): Promise<SettledSubmissionRecord> {\n\t\treturn this.#submissions.wait(this.id, context);\n\t}\n\n\tasync abort(context: Context): Promise<AbortResult> {\n\t\tconst result = await this.#submissions.abort(this.id, context);\n\t\tif (result === \"not_found\") throw new Error(`Submission ${this.id} does not exist`);\n\t\treturn result;\n\t}\n}\n\nfunction isSettled(record: SubmissionRecord): record is SettledSubmissionRecord {\n\treturn record.status === \"done\" || record.status === \"unanswered\";\n}\n\n/**\n * Admit a submission inside a commit (spec §6); `Conversation.submit()` and conversation-owned compactions share it. A\n * known request ID returns its existing submission without writing. A busy conversation queues it in `pi.inbox`, or\n * rejects `whenBusy: \"reject\"` input with `ConversationBusy`. An idle conversation with queued items queues it behind\n * them and runs a final boundary. Otherwise idle input places a user entry and starts a run, and an idle write appends\n * its entry and settles `done`, or `stale` when its head reaches before the active range.\n */\nexport async function admitSubmission(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tdraft: SubmissionDraft,\n\tnow: number,\n\tqueueModes: QueueModes,\n): Promise<SubmissionId> {\n\tif (draft.requestId !== undefined) {\n\t\tconst existing = await tx.submissionByRequest(conversationId, draft.requestId);\n\t\tif (existing !== undefined) {\n\t\t\tif (existing.type !== draft.type) {\n\t\t\t\tthrow new Error(`Request ${draft.requestId} already identifies a submission of type ${existing.type}`);\n\t\t\t}\n\t\t\treturn existing.id;\n\t\t}\n\t}\n\tconst live = await tx.doc(LiveDoc, conversationId);\n\tconst busy = live.run !== undefined;\n\tif (busy && draft.type === \"input\" && draft.whenBusy === \"reject\") throw new ConversationBusy(conversationId);\n\tconst requestId = draft.requestId === undefined ? {} : { requestId: draft.requestId };\n\t// A boundary reads the table, so it is prepared before the first table write; a busy one needs none.\n\tconst boundary = busy ? undefined : await prepareBoundary(tx, conversationId, queueModes);\n\tif (boundary === undefined || boundary.inbox.items.length > 0) {\n\t\tconst { id } = await tx.createSubmission({\n\t\t\tconversationId,\n\t\t\t...requestId,\n\t\t\ttype: draft.type,\n\t\t\tstatus: \"queued\",\n\t\t});\n\t\t// Hosts may leave optional fields `undefined`; drafts take strict JSON.\n\t\tconst value = copyJson(draft.type === \"write\" ? draft.entry : draft.content, {\n\t\t\tomitUndefinedProperties: true,\n\t\t});\n\t\tconst items = (boundary?.inbox ?? (await tx.doc(InboxDoc, conversationId))).items;\n\t\tif (draft.type === \"write\") items.push({ id, mode: \"write\", entry: value as JsonObject });\n\t\telse {\n\t\t\tconst mode = draft.whenBusy === \"steer\" ? \"steer\" : \"followUp\";\n\t\t\titems.push({ id, mode, content: value as JsonRepresentation<UserInput> });\n\t\t}\n\t\tif (boundary === undefined) return id;\n\t\tconst { users } = await applyBoundary(tx, boundary, \"final\", now);\n\t\tif (users.length > 0) await startRun(tx, conversationId, live, users);\n\t\treturn id;\n\t}\n\tif (draft.type === \"write\") {\n\t\tif (isStale(boundary, draft.entry)) {\n\t\t\tconst stale = { status: \"unanswered\", reason: \"stale\" } as const;\n\t\t\treturn (await tx.createSubmission({ conversationId, ...requestId, type: \"write\", ...stale })).id;\n\t\t}\n\t\tconst entry = await tx.appendEntry(conversationId, draft.entry);\n\t\tconst write = { conversationId, ...requestId, type: \"write\", status: \"done\", entry: entry.id } as const;\n\t\treturn (await tx.createSubmission(write)).id;\n\t}\n\tconst message = { role: \"user\", content: draft.content, timestamp: now } as const;\n\tconst entry = await tx.appendEntry(UserEntry, conversationId, { model: [message] });\n\tconst input = { conversationId, ...requestId, type: \"input\", status: \"placed\", entry: entry.id } as const;\n\tconst { id } = await tx.createSubmission(input);\n\tawait startRun(tx, conversationId, live, [id]);\n\treturn id;\n}\n", "import type { Context, Draft } from \"@earendil-works/chord\";\nimport type { AssistantMessage, Message, ModelThinkingLevel, SimpleStreamOptions } from \"@earendil-works/pi-ai\";\nimport { calculateContextTokens, estimateMessageTokens } from \"@earendil-works/pi-ai/utils/estimate\";\nimport { isRetryableAssistantError, retryDelayMs } from \"@earendil-works/pi-ai/utils/retry\";\nimport { CompactionEntry } from \"../entries.ts\";\nimport { defineTask } from \"../tasks.ts\";\nimport type {\n\tConversationId,\n\tEntryDraft,\n\tEntryId,\n\tNextTaskState,\n\tRunningTask,\n\tTaskId,\n\tTaskRuntime,\n\tTx,\n} from \"../types.ts\";\nimport { orderToolResults } from \"./context.ts\";\nimport { addCompactionStatus, compactionStatus, LiveDoc, type LiveState, removeCompactionStatus } from \"./live.ts\";\nimport { ensureProviderSessionId } from \"./provider.ts\";\nimport { admitSubmission } from \"./submissions.ts\";\nimport type {\n\tCompactionHooks,\n\tCompactionReason,\n\tCompactionResult,\n\tContextView,\n\tConversationStreamOptions,\n\tModelRef,\n} from \"./types.ts\";\nimport { recordUsage } from \"./usage.ts\";\n\nexport type CompactionInput = { reason: CompactionReason; instructions?: string };\n\n/** The pinned summarization request. */\nexport type SummaryRequest = {\n\tattempt: number;\n\tmodel: ModelRef;\n\tthinkingLevel: ModelThinkingLevel;\n\tstreamOptions: ConversationStreamOptions;\n\tmaxTokens: number;\n\t/** Newest entry of the context the range was selected from. */\n\ttail: EntryId;\n\t/** First entry kept verbatim; the summary's `head`. */\n\tfirstKept: EntryId;\n};\n\nexport type CompactionCheckpoint =\n\t| { phase: \"select\" }\n\t| ({ phase: \"summarize\" } & SummaryRequest)\n\t| ({ phase: \"retry\"; until: number } & SummaryRequest);\n\ntype Runtime = TaskRuntime<CompactionInput, CompactionCheckpoint, CompactionResult, CompactionHooks>;\ntype Next = NextTaskState<CompactionCheckpoint, CompactionResult>;\n\n/** Longest tool result text a serialized summary source keeps. */\nconst TOOL_RESULT_MAX_CHARS = 2000;\n\nconst SUMMARY_PREFIX =\n\t\"The conversation history before this point was compacted into the following summary:\\n\\n<summary>\\n\";\nconst SUMMARY_SUFFIX = \"\\n</summary>\";\n\nconst SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;\n\nconst SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work. If the conversation starts with an earlier summary, preserve its information and fold the newer messages into it.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Built-in compaction task (spec §8.7): select an old prefix of the model context, summarize it, and place a summary\n * entry whose `head` is the first kept entry. A compaction the generation owns blocks it and appends directly; a\n * conversation-owned one places its summary through a write submission.\n */\nexport const CompactionTask = defineTask<CompactionInput, CompactionCheckpoint, CompactionResult, CompactionHooks>({\n\tname: \"pi.compaction\",\n\tversion: 1,\n\tinitial: () => ({ phase: \"select\" }),\n\tphases: {\n\t\tselect: async (task, runtime, context) => {\n\t\t\tconst { conversationId } = runtime;\n\t\t\tconst agent = await runtime.agent(context);\n\t\t\tconst settings = runtime.settings;\n\t\t\tconst ref = agent.model;\n\t\t\tconst model = ref === undefined ? undefined : runtime.models.getModel(ref.provider, ref.modelId);\n\t\t\tif (ref === undefined || model === undefined) return failNoModel(runtime, ref, context);\n\t\t\tconst policy = settings.compaction;\n\t\t\tconst view = await runtime.context(conversationId, context);\n\t\t\tconst cut = selectCut(view, policy.keepRecentTokens);\n\t\t\tif (cut === undefined) return complete(runtime, context);\n\t\t\tconst firstKept = view.entries[cut]!.id;\n\t\t\tconst { reason, instructions } = task.input;\n\t\t\tconst compaction = {\n\t\t\t\treason,\n\t\t\t\tentries: view.entries.slice(0, cut),\n\t\t\t\tmessages: summarizedMessages(view, cut),\n\t\t\t\tfirstKept,\n\t\t\t\t...(instructions === undefined ? {} : { instructions }),\n\t\t\t};\n\t\t\tlet decision: { readonly decline: true } | { readonly summary: string } | undefined;\n\t\t\tawait runtime.hooks.each(\"beforeCompact\", async (hook) => {\n\t\t\t\tif (decision === undefined) decision = await hook(compaction, runtime, context);\n\t\t\t});\n\t\t\tif (decision !== undefined && \"decline\" in decision) return complete(runtime, context);\n\t\t\tif (decision !== undefined) return place(runtime, firstKept, decision.summary, context);\n\t\t\tconst request: SummaryRequest = {\n\t\t\t\tattempt: 1,\n\t\t\t\tmodel: ref,\n\t\t\t\tthinkingLevel: agent.thinkingLevel,\n\t\t\t\tstreamOptions: settings.stream,\n\t\t\t\tmaxTokens: Math.min(\n\t\t\t\t\tMath.floor(0.8 * policy.reserveTokens),\n\t\t\t\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t\t\t\t),\n\t\t\t\ttail: view.entries.reduce((tail, entry) => (entry.id > tail ? entry.id : tail), firstKept),\n\t\t\t\tfirstKept,\n\t\t\t};\n\t\t\tawait runtime.commit(() => ({ status: \"running\", checkpoint: { phase: \"summarize\", ...request } }), context);\n\t\t},\n\t\tsummarize: async (task, runtime, context) => {\n\t\t\tconst { phase: _, ...request } = task.state.checkpoint;\n\t\t\tconst { model: ref, thinkingLevel, streamOptions, maxTokens, tail, firstKept, attempt } = request;\n\t\t\tconst model = runtime.models.getModel(ref.provider, ref.modelId);\n\t\t\tif (model === undefined) return failNoModel(runtime, ref, context);\n\t\t\t// The context at `tail` is immutable, so this is the range `select` chose.\n\t\t\tconst view = await runtime.context(runtime.conversationId, context, tail);\n\t\t\tconst cut = view.entries.findIndex((entry) => entry.id === firstKept);\n\t\t\tconst now = runtime.now();\n\t\t\tconst messages: Message[] = [\n\t\t\t\t{ role: \"system\", content: SUMMARIZATION_SYSTEM_PROMPT, timestamp: now },\n\t\t\t\t{\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [{ type: \"text\", text: summaryPrompt(summarizedMessages(view, cut), task.input.instructions) }],\n\t\t\t\t\ttimestamp: now,\n\t\t\t\t},\n\t\t\t];\n\t\t\tconst { deferred: _deferred, ...forwarded } = streamOptions;\n\t\t\tconst options: SimpleStreamOptions = {\n\t\t\t\t...forwarded,\n\t\t\t\tcacheRetention: \"none\",\n\t\t\t\tmaxTokens,\n\t\t\t\tsignal: runtime.signal,\n\t\t\t\tsessionId: await ensureProviderSessionId(runtime, context),\n\t\t\t\t...(thinkingLevel === \"off\" ? {} : { reasoning: thinkingLevel }),\n\t\t\t};\n\t\t\tconst message = await runtime.models.completeSimple(model, { messages }, options);\n\t\t\t// An abort mark or close: the abort invocation or the reopened task handles the committed state.\n\t\t\truntime.signal.throwIfAborted();\n\t\t\tconst summary = summaryText(message);\n\t\t\tconst policy = runtime.settings.retry;\n\t\t\tconst retry =\n\t\t\t\tmessage.stopReason === \"error\" &&\n\t\t\t\tisRetryableAssistantError(message) &&\n\t\t\t\tpolicy.enabled &&\n\t\t\t\tattempt <= policy.maxRetries;\n\t\t\tconst until = retry ? runtime.now() + retryDelayMs(policy, attempt) : 0;\n\t\t\tawait runtime.commit(async (tx, current): Promise<Next> => {\n\t\t\t\tawait recordUsage(\n\t\t\t\t\ttx,\n\t\t\t\t\truntime.conversationId,\n\t\t\t\t\t\"models\",\n\t\t\t\t\t`${message.provider}/${message.model}`,\n\t\t\t\t\tmessage.usage,\n\t\t\t\t);\n\t\t\t\tconst live = await tx.doc(LiveDoc, runtime.conversationId);\n\t\t\t\tif (summary !== undefined) return placeSummary(tx, runtime, current, live, firstKept, summary);\n\t\t\t\tif (retry) {\n\t\t\t\t\tconst status = compactionStatus(live, runtime.taskId);\n\t\t\t\t\tif (status !== undefined) status.retry = { at: until, error: message.errorMessage ?? \"\" };\n\t\t\t\t\treturn { status: \"running\", checkpoint: { phase: \"retry\", ...request, until } };\n\t\t\t\t}\n\t\t\t\tremoveCompactionStatus(live, runtime.taskId);\n\t\t\t\tconst text = summaryFailure(message);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"terminal\",\n\t\t\t\t\toutcome: { status: \"failed\", error: { message: text, detail: { reason: \"model_error\" } } },\n\t\t\t\t};\n\t\t\t}, context);\n\t\t},\n\t\tretry: async (task, runtime, context) => {\n\t\t\tconst { phase: _, until, ...request } = task.state.checkpoint;\n\t\t\tawait runtime.sleep(until, context);\n\t\t\tconst attempt = request.attempt + 1;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst status = compactionStatus(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\tif (status !== undefined) {\n\t\t\t\t\tstatus.attempt = attempt;\n\t\t\t\t\tdelete status.retry;\n\t\t\t\t}\n\t\t\t\treturn { status: \"running\", checkpoint: { phase: \"summarize\", ...request, attempt } };\n\t\t\t}, context);\n\t\t},\n\t},\n\tabort: async (_task, runtime, context) => {\n\t\tawait runtime.commit(async (tx) => {\n\t\t\tremoveCompactionStatus(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\treturn { status: \"terminal\", outcome: { status: \"aborted\" } };\n\t\t}, context);\n\t},\n});\n\n/**\n * Create a compaction task with its status in this commit. `owner` is the generation that waits for it (a blocking\n * compaction); without one it is conversation-owned, and `background` unless it is manual.\n */\nexport async function createCompaction(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tinput: CompactionInput,\n\towner?: TaskId,\n): Promise<TaskId<CompactionResult>> {\n\tconst ownership =\n\t\towner === undefined ? ({ kind: \"conversation\" } as const) : { kind: \"task\" as const, taskId: owner };\n\tconst background = owner === undefined && input.reason !== \"manual\";\n\tconst taskId = await tx.createTask(CompactionTask, input, { ownership, conversationId, background });\n\tconst status = { taskId, reason: input.reason, blocking: owner !== undefined, attempt: 1 };\n\taddCompactionStatus(await tx.doc(LiveDoc, conversationId), status);\n\treturn taskId;\n}\n\n/**\n * Index in `view.entries` of the first entry a summary keeps, or `undefined` when there is nothing to compact\n * (spec §8.7). Walks back from the tail until `keepRecentTokens` are kept, then cuts at the first candidate at or after\n * that entry: an entry whose contribution starts with a user or assistant message, never a tool result, and never a\n * user entry that a result of the preceding assistant's calls still follows.\n */\nexport function selectCut(view: ContextView, keepRecentTokens: number): number | undefined {\n\tconst { contributions } = view;\n\tconst start = view.head === undefined ? 0 : 1;\n\tconst candidates: number[] = [];\n\tfor (let index = start; index < contributions.length; index++) {\n\t\tif (isCandidate(contributions, index)) candidates.push(index);\n\t}\n\tlet kept = 0;\n\tlet cut: number | undefined;\n\tfor (let index = contributions.length - 1; index >= start; index--) {\n\t\tfor (const message of contributions[index]!) kept += estimateMessageTokens(message);\n\t\tif (kept < keepRecentTokens) continue;\n\t\tcut = candidates.find((candidate) => candidate >= index) ?? candidates.at(-1);\n\t\tbreak;\n\t}\n\tif (cut === undefined) return undefined;\n\tfor (let index = start; index < cut; index++) if (contributions[index]!.length > 0) return cut;\n\treturn undefined;\n}\n\nfunction isCandidate(contributions: ContextView[\"contributions\"], index: number): boolean {\n\tconst first = contributions[index]![0];\n\tif (first?.role === \"assistant\") return true;\n\tif (first?.role !== \"user\") return false;\n\t// A result of the preceding assistant's calls that follows this entry, before the next assistant, belongs before it.\n\tlet calls: ReadonlySet<string> = new Set();\n\tfor (let before = index - 1; before >= 0; before--) {\n\t\tconst assistant = contributions[before]!.findLast((message) => message.role === \"assistant\");\n\t\tif (assistant === undefined) continue;\n\t\tcalls = new Set(assistant.content.flatMap((content) => (content.type === \"toolCall\" ? [content.id] : [])));\n\t\tbreak;\n\t}\n\tif (calls.size === 0) return true;\n\tfor (let after = index; after < contributions.length; after++) {\n\t\tfor (const [position, message] of contributions[after]!.entries()) {\n\t\t\tif (message.role === \"assistant\" && (after > index || position > 0)) return true;\n\t\t\tif (message.role === \"toolResult\" && calls.has(message.toolCallId)) return false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** Model messages of the entries before `cut`: the head marker first, ordered like model context (spec §2.1). */\nexport function summarizedMessages(view: ContextView, cut: number): Message[] {\n\treturn orderToolResults(view.contributions.slice(0, cut).flat());\n}\n\n/**\n * Size of a request over `view` followed by `extra` (spec §8.3): the usage of the newest assistant appended after the\n * head marker, whose request included the marker, plus estimates of the messages after it; without one, estimates of\n * every message.\n */\nexport function estimateContext(view: ContextView, extra: readonly Message[]): number {\n\tlet measured: AssistantMessage | undefined;\n\tconst after = view.head?.id ?? Number.NEGATIVE_INFINITY;\n\tfor (let index = view.entries.length - 1; index >= 0 && measured === undefined; index--) {\n\t\tif (view.entries[index]!.id <= after) continue;\n\t\tmeasured = view.contributions[index]!.findLast(\n\t\t\t(message): message is AssistantMessage =>\n\t\t\t\tmessage.role === \"assistant\" && calculateContextTokens(message.usage) > 0,\n\t\t);\n\t}\n\tconst from = measured === undefined ? 0 : view.messages.lastIndexOf(measured) + 1;\n\tlet tokens = measured === undefined ? 0 : calculateContextTokens(measured.usage);\n\tfor (const message of view.messages.slice(from)) tokens += estimateMessageTokens(message);\n\tfor (const message of extra) tokens += estimateMessageTokens(message);\n\treturn tokens;\n}\n\n/** The summary of a clean `stop` with text and no tool call; anything else is not a summary. */\nfunction summaryText(message: AssistantMessage): string | undefined {\n\tif (message.stopReason !== \"stop\" || message.content.some((content) => content.type === \"toolCall\"))\n\t\treturn undefined;\n\tconst text = message.content\n\t\t.flatMap((content) => (content.type === \"text\" ? [content.text] : []))\n\t\t.join(\"\\n\")\n\t\t.trim();\n\treturn text.length === 0 ? undefined : text;\n}\n\nfunction summaryFailure(message: AssistantMessage): string {\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\treturn `Summarization failed: ${message.errorMessage ?? message.stopReason}`;\n\t}\n\tif (message.stopReason === \"length\") return \"Summarization hit the token limit; the summary is incomplete\";\n\tif (message.content.some((content) => content.type === \"toolCall\")) return \"Summarization attempted to call a tool\";\n\treturn \"Summarization produced no text\";\n}\n\n/** The summarizer's user message: the serialized conversation, the prompt, and any instructions. */\nfunction summaryPrompt(messages: readonly Message[], instructions: string | undefined): string {\n\tconst focus = instructions === undefined ? \"\" : `\\n\\nAdditional focus: ${instructions}`;\n\treturn `<conversation>\\n${serializeConversation(messages)}\\n</conversation>\\n\\n${SUMMARIZATION_PROMPT}${focus}`;\n}\n\n/** Messages as plain text, so the summarizer reads a transcript instead of continuing it. System messages are omitted. */\nexport function serializeConversation(messages: readonly Message[]): string {\n\tconst parts: string[] = [];\n\tfor (const message of messages) {\n\t\tif (message.role === \"user\") {\n\t\t\tconst text = contentText(message.content);\n\t\t\tif (text.length > 0) parts.push(`[User]: ${text}`);\n\t\t} else if (message.role === \"assistant\") {\n\t\t\tconst thinking = message.content.flatMap((content) => (content.type === \"thinking\" ? [content.thinking] : []));\n\t\t\tconst text = message.content.flatMap((content) => (content.type === \"text\" ? [content.text] : []));\n\t\t\tconst calls = message.content.flatMap((content) =>\n\t\t\t\tcontent.type === \"toolCall\"\n\t\t\t\t\t? [\n\t\t\t\t\t\t\t`${content.name}(${Object.entries(content.arguments)\n\t\t\t\t\t\t\t\t.map(([key, value]) => `${key}=${JSON.stringify(value)}`)\n\t\t\t\t\t\t\t\t.join(\", \")})`,\n\t\t\t\t\t\t]\n\t\t\t\t\t: [],\n\t\t\t);\n\t\t\tif (thinking.length > 0) parts.push(`[Assistant thinking]: ${thinking.join(\"\\n\")}`);\n\t\t\tif (text.length > 0) parts.push(`[Assistant]: ${text.join(\"\\n\")}`);\n\t\t\tif (calls.length > 0) parts.push(`[Assistant tool calls]: ${calls.join(\"; \")}`);\n\t\t} else if (message.role === \"toolResult\") {\n\t\t\tconst text = contentText(message.content);\n\t\t\tif (text.length > 0) parts.push(`[Tool result]: ${truncate(text, TOOL_RESULT_MAX_CHARS)}`);\n\t\t}\n\t}\n\treturn parts.join(\"\\n\\n\");\n}\n\nfunction contentText(content: string | readonly { readonly type: string; readonly text?: string }[]): string {\n\tif (typeof content === \"string\") return content;\n\treturn content\n\t\t.flatMap((block) => (block.type === \"text\" && block.text !== undefined ? [block.text] : []))\n\t\t.join(\"\\n\");\n}\n\nfunction truncate(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}\\n\\n[... ${text.length - maxChars} more characters truncated]`;\n}\n\n/** Place a summary supplied by a hook in its own commit. */\nasync function place(runtime: Runtime, firstKept: EntryId, summary: string, context: Context): Promise<void> {\n\tawait runtime.commit(\n\t\tasync (tx, current) =>\n\t\t\tplaceSummary(tx, runtime, current, await tx.doc(LiveDoc, runtime.conversationId), firstKept, summary),\n\t\tcontext,\n\t);\n}\n\n/**\n * Place the summary entry and complete (spec §8.7). A blocking compaction, owned by its generation, appends it: the\n * generation holds the run and waits. A conversation-owned one admits it as a write submission, placed at once when\n * idle, otherwise at the next boundary, or settled `stale`.\n * REMINDER: nothing else may append to a busy conversation, so every non-blocking summary goes through admission.\n */\nasync function placeSummary(\n\ttx: Tx,\n\truntime: Runtime,\n\tcurrent: RunningTask<CompactionInput, CompactionCheckpoint, CompactionResult>,\n\tlive: Draft<LiveState>,\n\tfirstKept: EntryId,\n\tsummary: string,\n): Promise<Next> {\n\tremoveCompactionStatus(live, runtime.taskId);\n\tconst text = `${SUMMARY_PREFIX}${summary}${SUMMARY_SUFFIX}`;\n\tconst entry = {\n\t\tkind: CompactionEntry.kind,\n\t\thead: firstKept,\n\t\tmodel: [{ role: \"user\", content: [{ type: \"text\", text }], timestamp: runtime.now() }],\n\t\tdata: { reason: current.input.reason },\n\t} satisfies EntryDraft;\n\tconst result: CompactionResult =\n\t\tcurrent.owner === undefined\n\t\t\t? {\n\t\t\t\t\tsubmissionId: await admitSubmission(\n\t\t\t\t\t\ttx,\n\t\t\t\t\t\truntime.conversationId,\n\t\t\t\t\t\t{ type: \"write\", requestId: `compaction:${runtime.taskId}`, entry },\n\t\t\t\t\t\truntime.now(),\n\t\t\t\t\t\truntime.settings,\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: { entryId: (await tx.appendEntry(runtime.conversationId, entry)).id };\n\treturn { status: \"terminal\", outcome: { status: \"completed\", result } };\n}\n\n/** Remove the status and complete without a summary. */\nasync function complete(runtime: Runtime, context: Context): Promise<void> {\n\tawait runtime.commit(async (tx) => {\n\t\tremoveCompactionStatus(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\treturn { status: \"terminal\", outcome: { status: \"completed\", result: {} } };\n\t}, context);\n}\n\nasync function failNoModel(runtime: Runtime, ref: ModelRef | undefined, context: Context): Promise<void> {\n\tconst message =\n\t\tref === undefined ? \"No model is configured\" : `Model ${ref.provider}/${ref.modelId} is not available`;\n\tawait runtime.commit(async (tx) => {\n\t\tremoveCompactionStatus(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\treturn { status: \"terminal\", outcome: { status: \"failed\", error: { message, detail: { reason: \"no_model\" } } } };\n\t}, context);\n}\n", "import type { JsonValue } from \"@earendil-works/chord\";\nimport type { TSchema } from \"@earendil-works/pi-ai\";\nimport type { AnyTask, Extension, HookRegistration, HooksOf, PromptSection, ToolRegistration, Wrap } from \"./types.ts\";\n\n/** Identity function that types an extension. */\nexport function defineExtension<Tool extends ToolRegistration = ToolRegistration>(\n\textension: Extension<Tool>,\n): Extension<Tool> {\n\treturn extension;\n}\n\n/** Identity function that types a tool: `args` from `parameters`, details from what it reports. */\nexport function defineTool<TParameters extends TSchema, TDetails extends JsonValue = JsonValue>(\n\ttool: ToolRegistration<TParameters, TDetails>,\n): ToolRegistration<TParameters, TDetails> {\n\treturn tool;\n}\n\n/** A prompt section; tagged unless `tag` is false. */\nexport function section<Tool extends ToolRegistration = ToolRegistration>(\n\tkey: string,\n\trender: PromptSection<Tool>[\"render\"],\n\toptions?: { readonly tag?: boolean },\n): PromptSection<Tool> {\n\treturn options?.tag === undefined ? { key, render } : { key, render, tag: options.tag };\n}\n\n/** Hook handlers for tasks with `task`'s name. */\nexport function hook<K extends AnyTask>(task: K, handlers: Partial<HooksOf<K>>): HookRegistration {\n\treturn { task: task.definition.name, handlers };\n}\n\n/** Wrap the tool named like `tool` wherever the wrapping extension is selected. */\nexport function wrapTool<Tool extends ToolRegistration>(tool: Tool, wrapper: (tool: Tool) => Tool): Wrap<Tool> {\n\treturn { tool: tool.name, wrap: wrapper };\n}\n\n/** Wrap the section `key` wherever the wrapping extension is selected. */\nexport function wrapSection<Tool extends ToolRegistration = ToolRegistration>(\n\tkey: string,\n\twrapper: (section: PromptSection<Tool>) => PromptSection<Tool>,\n): Wrap<Tool> {\n\treturn { section: key, wrap: wrapper };\n}\n", "import type {\n\tContext,\n\tJsonValue,\n\tReplicatedStateSource,\n\tReplicatedStateSourceAttachment,\n\tReplicatedStateSourceFrame,\n} from \"@earendil-works/chord\";\nimport { withoutAbortSignal } from \"@earendil-works/chord/context\";\nimport type { Op } from \"@earendil-works/chord/delta\";\nimport type { JsonObject, WatchEnd, WatchHandle } from \"../types.ts\";\n\nexport type ObservedDocumentValue = Readonly<JsonObject> | null;\n\n/** Maximum exact committed frames retained behind one unavailable watch listener. */\nconst MAX_PENDING_WATCH_FRAMES = 100;\n\n/** Canonical terminal update for a retired document incarnation. */\nexport const RETIREMENT_OPERATIONS: readonly Op[] = [[\"r\", null]];\n\n/**\n * Session-to-Chord bridge owned one-to-one by one attached state: a document, or a conversation view. A `null` value\n * retires it. @internal\n */\nexport class CommittedStateSource<T = ObservedDocumentValue> implements ReplicatedStateSource<T> {\n\treadonly #attachments = new Set<SessionSourceAttachment<T>>();\n\t#release: (() => void) | undefined;\n\t/** Released on disposal. */\n\t#value: T | undefined;\n\t#cursor = 0;\n\t#retired = false;\n\t#closed = false;\n\n\tconstructor(value: T, release: () => void) {\n\t\tthis.#value = value;\n\t\tthis.#release = release;\n\t}\n\n\tattach(): ReplicatedStateSourceAttachment<T> {\n\t\tif (this.#closed) throw new Error(\"State source is closed\");\n\t\tconst attachment = new SessionSourceAttachment({ value: this.#value as T, cursor: this.#cursor }, () => {\n\t\t\tthis.#attachments.delete(attachment);\n\t\t\tif (this.#attachments.size === 0) this.#finishDisposal();\n\t\t});\n\t\tthis.#attachments.add(attachment);\n\t\treturn attachment;\n\t}\n\n\tadvance(value: T, ops: readonly Op[], context: Context): void {\n\t\tif (this.#closed || this.#retired) return;\n\t\tthis.#value = value;\n\t\tthis.#cursor += 1;\n\t\tif (value === null) this.#retired = true;\n\t\tconst frame: ReplicatedStateSourceFrame<T> = {\n\t\t\tcursor: this.#cursor,\n\t\t\tvalue,\n\t\t\tops,\n\t\t\tcontext,\n\t\t};\n\t\tfor (const attachment of [...this.#attachments]) attachment.publish(frame);\n\t}\n\n\tcloseSession(): void {\n\t\tif (this.#closed) return;\n\t\tfor (const attachment of [...this.#attachments]) attachment.dispose();\n\t\tthis.#finishDisposal();\n\t}\n\n\t#finishDisposal(): void {\n\t\tif (this.#closed) return;\n\t\tthis.#closed = true;\n\t\tthis.#value = undefined;\n\t\tconst release = this.#release;\n\t\tthis.#release = undefined;\n\t\trelease?.();\n\t}\n}\n\nclass SessionSourceAttachment<T> implements ReplicatedStateSourceAttachment<T> {\n\treadonly snapshot: { readonly value: T; readonly cursor: number };\n\t#release: (() => void) | undefined;\n\treadonly #frames: ReplicatedStateSourceFrame<T>[] = [];\n\t#listener: ((frame: ReplicatedStateSourceFrame<T>) => void) | undefined;\n\t#activated = false;\n\t#disposed = false;\n\t#scheduled = false;\n\t#delivering = false;\n\n\tconstructor(snapshot: { readonly value: T; readonly cursor: number }, release: () => void) {\n\t\tthis.snapshot = snapshot;\n\t\tthis.#release = release;\n\t}\n\n\tactivate(listener: (frame: ReplicatedStateSourceFrame<T>) => void): void {\n\t\tif (this.#activated) throw new Error(\"State attachment is already active\");\n\t\tif (this.#disposed) throw new Error(\"State attachment is disposed\");\n\t\tthis.#activated = true;\n\t\tthis.#listener = listener;\n\t\tthis.#drain();\n\t}\n\n\tpublish(frame: ReplicatedStateSourceFrame<T>): void {\n\t\tif (this.#disposed) return;\n\t\tthis.#frames.push(frame);\n\t\tif (!this.#activated || this.#delivering || this.#scheduled) return;\n\t\tthis.#scheduled = true;\n\t\tqueueMicrotask(() => {\n\t\t\tthis.#scheduled = false;\n\t\t\tif (this.#disposed) return;\n\t\t\ttry {\n\t\t\t\tthis.#drain();\n\t\t\t} catch {\n\t\t\t\t// Chord's frame listener contains source-contract failures. Isolate an\n\t\t\t\t// unexpected direct listener failure to this attachment as well.\n\t\t\t\tthis.dispose();\n\t\t\t}\n\t\t});\n\t}\n\n\tdispose(): void {\n\t\tif (this.#disposed) return;\n\t\tthis.#disposed = true;\n\t\tthis.#frames.length = 0;\n\t\tthis.#listener = undefined;\n\t\tconst release = this.#release;\n\t\tthis.#release = undefined;\n\t\trelease?.();\n\t}\n\n\t#drain(): void {\n\t\tconst listener = this.#listener;\n\t\tif (listener === undefined || this.#delivering || this.#disposed) return;\n\t\tthis.#delivering = true;\n\t\ttry {\n\t\t\twhile (!this.#disposed) {\n\t\t\t\tconst frame = this.#frames.shift();\n\t\t\t\tif (frame === undefined) break;\n\t\t\t\tlistener(frame);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.#delivering = false;\n\t\t}\n\t}\n}\n\ntype WatchFrame<T> = {\n\treadonly value: T;\n\treadonly ops: readonly Op[];\n\treadonly context: Context;\n};\n\n/**\n * Serialized exact-frame watch bound to one document incarnation or conversation view. A `null` value retires it.\n * @internal\n */\nexport class CommittedWatch<T = ObservedDocumentValue> implements WatchHandle<T> {\n\treadonly #detach: () => void;\n\treadonly #replace: (() => T) | undefined;\n\treadonly #closedPromise: Promise<WatchEnd>;\n\treadonly #pending: WatchFrame<T>[] = [];\n\t#resolveClosed!: (end: WatchEnd) => void;\n\t#value: T;\n\t#listener: ((value: T, ops: readonly Op[], context: Context) => Promise<void>) | undefined;\n\t#started = false;\n\t#scheduled = false;\n\t#running = false;\n\t#detached = false;\n\t#retired = false;\n\t#end: WatchEnd | undefined;\n\t#resolved = false;\n\t#cancellationSignal: AbortSignal | undefined;\n\t#cancellationListener: (() => void) | undefined;\n\n\t/** `replace` gives the value an overflow delivers; by default the newest value. */\n\tconstructor(value: T, detach: () => void, replace?: () => T) {\n\t\tthis.#value = value;\n\t\tthis.#detach = detach;\n\t\tthis.#replace = replace;\n\t\tthis.#closedPromise = new Promise((resolve) => {\n\t\t\tthis.#resolveClosed = resolve;\n\t\t});\n\t}\n\n\tget value(): T {\n\t\treturn this.#value;\n\t}\n\n\tget closed(): Promise<WatchEnd> {\n\t\treturn this.#closedPromise;\n\t}\n\n\tstart(listener: (value: T, ops: readonly Op[], context: Context) => Promise<void>): void {\n\t\tif (this.#started) throw new Error(\"Watch is already started\");\n\t\tif (this.#end !== undefined) throw new Error(\"Watch is stopped\");\n\t\tthis.#started = true;\n\t\tthis.#listener = listener;\n\t\tif (this.#pending.length > 0) this.#schedule();\n\t}\n\n\tstop(): Promise<WatchEnd> {\n\t\tthis.#terminate({ reason: \"stopped\" });\n\t\treturn this.#closedPromise;\n\t}\n\n\tobserveCancellation(signal: AbortSignal): void {\n\t\tif (this.#cancellationSignal !== undefined) throw new Error(\"Watch cancellation is already installed\");\n\t\tif (this.#end !== undefined) return;\n\t\tthis.#cancellationSignal = signal;\n\t\tthis.#cancellationListener = () => this.cancel();\n\t\tsignal.addEventListener(\"abort\", this.#cancellationListener, { once: true });\n\t\tif (signal.aborted) this.cancel();\n\t}\n\n\tcancel(): void {\n\t\tthis.#terminate({ reason: \"cancelled\" });\n\t}\n\n\tcloseSession(): void {\n\t\tthis.#terminate({ reason: \"session_closed\" });\n\t}\n\n\tadvance(value: T, ops: readonly Op[], context: Context): void {\n\t\tif (this.#end !== undefined || this.#retired) return;\n\t\tif (value === null) this.#retired = true;\n\t\tif (this.#pending.length >= MAX_PENDING_WATCH_FRAMES) {\n\t\t\tthis.#pending.length = 0;\n\t\t\tconst replacement = this.#replace?.() ?? value;\n\t\t\tthis.#pending.push({ value: replacement, ops: [[\"r\", replacement as JsonValue]], context });\n\t\t} else {\n\t\t\tthis.#pending.push({ value, ops, context });\n\t\t}\n\t\tif (this.#started) this.#schedule();\n\t}\n\n\t#schedule(): void {\n\t\tif (this.#scheduled || this.#running || this.#end !== undefined) return;\n\t\tthis.#scheduled = true;\n\t\tqueueMicrotask(() => {\n\t\t\tthis.#scheduled = false;\n\t\t\tvoid this.#drain();\n\t\t});\n\t}\n\n\tasync #drain(): Promise<void> {\n\t\tif (this.#running || this.#end !== undefined || !this.#started) {\n\t\t\tthis.#finishIfReady();\n\t\t\treturn;\n\t\t}\n\t\tthis.#running = true;\n\t\ttry {\n\t\t\twhile (this.#end === undefined) {\n\t\t\t\tconst frame = this.#pending.shift();\n\t\t\t\tif (frame === undefined) break;\n\t\t\t\tthis.#value = frame.value;\n\t\t\t\tconst deliveryContext = withoutAbortSignal(frame.context);\n\t\t\t\ttry {\n\t\t\t\t\tawait this.#listener!(frame.value, frame.ops, deliveryContext);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (this.#end === undefined) {\n\t\t\t\t\t\tthis.#terminate({ reason: \"listener_error\", error: toError(error) });\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (frame.value === null) {\n\t\t\t\t\tthis.#terminate({ reason: \"retired\" });\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.#running = false;\n\t\t\tif (this.#end === undefined && this.#pending.length > 0) this.#schedule();\n\t\t\tthis.#finishIfReady();\n\t\t}\n\t}\n\n\t#terminate(end: WatchEnd): void {\n\t\tif (this.#end !== undefined) return;\n\t\tthis.#end = end;\n\t\tthis.#detachNow();\n\t\tthis.#pending.length = 0;\n\t\tthis.#finishIfReady();\n\t}\n\n\t#detachNow(): void {\n\t\tif (this.#detached) return;\n\t\tthis.#detached = true;\n\t\tthis.#detach();\n\t}\n\n\t#finishIfReady(): void {\n\t\tif (this.#resolved || this.#end === undefined) return;\n\t\tthis.#resolved = true;\n\t\tif (this.#cancellationSignal !== undefined && this.#cancellationListener !== undefined) {\n\t\t\tthis.#cancellationSignal.removeEventListener(\"abort\", this.#cancellationListener);\n\t\t}\n\t\tthis.#resolveClosed(this.#end);\n\t}\n}\n\nfunction toError(error: unknown): Error {\n\treturn error instanceof Error ? error : new Error(String(error));\n}\n", "import { type AttachedReplicatedState, type Context, type JsonValue, replicatedState } from \"@earendil-works/chord\";\nimport { withoutAbortSignal } from \"@earendil-works/chord/context\";\nimport { applyImmutable, type NonEmptyPath, type Op, type Path } from \"@earendil-works/chord/delta\";\nimport { CommittedStateSource, CommittedWatch } from \"../session/observation.ts\";\nimport type { SessionImpl } from \"../session/session.ts\";\nimport type {\n\tCommitPublication,\n\tConversationDocToken,\n\tConversationId,\n\tConversationRecord,\n\tDocumentId,\n\tEntryRecord,\n\tJsonObject,\n\tStorage,\n\tWatchHandle,\n} from \"../types.ts\";\nimport { AgentDoc } from \"./agent.ts\";\nimport { activeEntries, captureContextBounds } from \"./context.ts\";\nimport { InboxDoc } from \"./inbox.ts\";\nimport { LiveDoc } from \"./live.ts\";\nimport { ProviderDoc } from \"./provider.ts\";\nimport { UsageDoc } from \"./usage.ts\";\nimport { closedError } from \"./util.ts\";\n\n/** Structural mount of one conversation's active transcript and built-in documents (spec §9.3). */\nexport type ConversationView = {\n\treadonly conversation: ConversationRecord;\n\t/** Raw active entries, as `ContextView.entries`: the head marker, then the non-head entries from its head. */\n\treadonly entries: readonly EntryRecord[];\n\t/** Built-in conversation documents keyed by kind; absent documents are absent. */\n\treadonly docs: Readonly<Record<string, JsonObject>>;\n};\n\n/** Receives each next revision of a mount, and the Session's close. */\nexport type ViewObserver = {\n\tadvance?(value: ConversationView, ops: readonly Op[], context: Context): void;\n\t/** Every publication, after the mount took it; `ops` are the mount's, possibly none. */\n\tpublication?(\n\t\tbefore: ConversationView,\n\t\tafter: ConversationView,\n\t\tops: readonly Op[],\n\t\tpublication: CommitPublication,\n\t\tcontext: Context,\n\t): void;\n\tcloseSession(): void;\n};\n\nconst MOUNTED = [\n\tAgentDoc,\n\tLiveDoc,\n\tInboxDoc,\n\tProviderDoc,\n\tUsageDoc,\n] as unknown as readonly ConversationDocToken<JsonObject>[];\nconst MOUNTED_KINDS: ReadonlySet<string> = new Set(MOUNTED.map((token) => token.definition.kind));\n\n/** One conversation's mount: its current revision, the document incarnations it shows, and its observers. */\ntype Mount = {\n\tvalue: ConversationView;\n\t/** Mounted incarnation and definition version per kind; another incarnation or version is set whole. */\n\treadonly docs: Map<string, { id: DocumentId; version: number }>;\n\treadonly observers: Set<ViewObserver>;\n};\n\nconst VIEWS = new WeakMap<object, ConversationViews>();\n\n/** The view mounts of a Harness, for adapters built on them. */\nexport function conversationViews(harness: object): ConversationViews {\n\tconst views = VIEWS.get(harness);\n\tif (views === undefined) throw new Error(\"Not a Harness\");\n\treturn views;\n}\n\n/**\n * The Harness's conversation view mounts: at most one per conversation, built on the Session line by its first\n * observer and dropped with its last. Each mount advances from the Session's commit publications, which are durable.\n */\nexport class ConversationViews {\n\treadonly #session: SessionImpl;\n\treadonly #storage: Storage;\n\treadonly #mounts = new Map<ConversationId, Mount>();\n\t#closed = false;\n\n\tconstructor(session: SessionImpl, storage: Storage) {\n\t\tthis.#session = session;\n\t\tthis.#storage = storage;\n\t\tVIEWS.set(session, this);\n\t\tsession.subscribeCommits((publication, context) => {\n\t\t\tfor (const [id, mount] of this.#mounts) advance(id, mount, publication, context);\n\t\t});\n\t\tsession.subscribeClose(() => {\n\t\t\tthis.#closed = true;\n\t\t\tfor (const mount of this.#mounts.values())\n\t\t\t\tfor (const observer of [...mount.observers]) observer.closeSession();\n\t\t\tthis.#mounts.clear();\n\t\t});\n\t}\n\n\t/** A disposable read-only Chord state of the view. */\n\tasync state(id: ConversationId, context: Context): Promise<AttachedReplicatedState<ConversationView>> {\n\t\tconst { observer, detach } = await this.attach(\n\t\t\tid,\n\t\t\t(value, release) => new CommittedStateSource<ConversationView>(value, release),\n\t\t\tcontext,\n\t\t);\n\t\ttry {\n\t\t\treturn replicatedState(observer);\n\t\t} catch (error) {\n\t\t\tdetach();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/** A serialized exact-frame watch of the view; cancelling `context` stops it. */\n\tasync watch(id: ConversationId, context: Context): Promise<WatchHandle<ConversationView>> {\n\t\tconst { observer } = await this.attach(\n\t\t\tid,\n\t\t\t(value, release) => new CommittedWatch<ConversationView>(value, release),\n\t\t\tcontext,\n\t\t);\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) {\n\t\t\tobserver.cancel();\n\t\t\tthrow signal.reason;\n\t\t}\n\t\tif (signal !== undefined) observer.observeCancellation(signal);\n\t\treturn observer;\n\t}\n\n\t/**\n\t * Register an observer created from the current revision, atomically on the Session line: it sees every later\n\t * publication and nothing earlier. `create` may read committed Storage, still on the line. `release` drops it, and\n\t * the mount with its last observer.\n\t */\n\tattach<O extends ViewObserver>(\n\t\tid: ConversationId,\n\t\tcreate: (value: ConversationView, release: () => void, storage: Storage) => O | Promise<O>,\n\t\tcontext: Context,\n\t): Promise<{ observer: O; detach: () => void }> {\n\t\treturn this.#session.readOnLine(async () => {\n\t\t\tconst mount = this.#mounts.get(id) ?? (await this.#build(id, context));\n\t\t\tconst detach = (): void => {\n\t\t\t\tmount.observers.delete(observer);\n\t\t\t\tif (mount.observers.size === 0 && this.#mounts.get(id) === mount) this.#mounts.delete(id);\n\t\t\t};\n\t\t\tconst observer = await create(mount.value, detach, this.#storage);\n\t\t\t// Close or cancellation may begin while the mount hydrates; register nothing then.\n\t\t\tif (this.#closed) throw closedError();\n\t\t\tcontext.abortSignal?.throwIfAborted();\n\t\t\tthis.#mounts.set(id, mount);\n\t\t\tmount.observers.add(observer);\n\t\t\treturn { observer, detach };\n\t\t});\n\t}\n\n\tasync #build(id: ConversationId, context: Context): Promise<Mount> {\n\t\tconst conversation = await this.#storage.conversation(id, context);\n\t\tif (conversation === undefined) throw new Error(`Conversation ${id} does not exist`);\n\t\tconst bounds = await captureContextBounds(this.#storage, id, context);\n\t\tconst entries = await activeEntries(this.#storage, id, bounds, context);\n\t\tconst docs: Record<string, JsonObject> = {};\n\t\tconst incarnations = new Map<string, { id: DocumentId; version: number }>();\n\t\tfor (const token of MOUNTED) {\n\t\t\tconst loaded = await this.#session.conversationDocumentOnLine(token, id, context);\n\t\t\tif (loaded === undefined) continue;\n\t\t\tdocs[token.definition.kind] = loaded.value;\n\t\t\tincarnations.set(token.definition.kind, { id: loaded.record.id, version: loaded.version });\n\t\t}\n\t\treturn { value: { conversation, entries, docs }, docs: incarnations, observers: new Set() };\n\t}\n}\n\n/** Derive the mount's operations from one publication, apply them, and hand the revision to every observer. */\nfunction advance(id: ConversationId, mount: Mount, publication: CommitPublication, context: Context): void {\n\tconst docOps: Op[] = [];\n\tconst entryOps: Op[] = [];\n\tlet entries = mount.value.entries;\n\t// Entry writes are published in ID order.\n\tfor (const change of publication.changes) {\n\t\tif (change.type === \"entry\" && change.value.conversationId === id) {\n\t\t\tconst entry = change.value;\n\t\t\tconst value = entry as unknown as JsonValue;\n\t\t\tif (entry.head === undefined) {\n\t\t\t\tentryOps.push([\"p\", [\"entries\"], entries.length, 0, [value]]);\n\t\t\t\tentries = [...entries, entry];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// A head marker keeps the non-head entries from its head, which are always a suffix, and goes in front.\n\t\t\tconst target = entry.head;\n\t\t\tlet kept = entries.findIndex((candidate) => candidate.head === undefined && candidate.id >= target);\n\t\t\tif (kept < 0) kept = entries.length;\n\t\t\tentryOps.push([\"p\", [\"entries\"], 0, kept, [value]]);\n\t\t\tentries = [entry, ...entries.slice(kept)];\n\t\t\tcontinue;\n\t\t}\n\t\tif (change.type !== \"document\" || change.conversationId !== id) continue;\n\t\tconst kind = change.record.kind;\n\t\tif (!MOUNTED_KINDS.has(kind) || change.record.key !== undefined) continue;\n\t\tconst path: NonEmptyPath = [\"docs\", kind];\n\t\tconst mounted = mount.docs.get(kind);\n\t\tif (change.value === null) {\n\t\t\tif (mounted?.id !== change.record.id) continue;\n\t\t\tmount.docs.delete(kind);\n\t\t\tdocOps.push([\"d\", path]);\n\t\t} else if (mounted?.id === change.record.id && mounted.version === change.version) {\n\t\t\tfor (const op of change.ops) docOps.push(prefixed(op, path));\n\t\t} else {\n\t\t\tmount.docs.set(kind, { id: change.record.id, version: change.version! });\n\t\t\tdocOps.push([\"s\", path, change.value]);\n\t\t}\n\t}\n\tconst before = mount.value;\n\tconst ops = [...docOps, ...entryOps];\n\tconst frameContext = withoutAbortSignal(context);\n\tif (ops.length > 0) {\n\t\tconst value = docOps.length === 0 ? mount.value : applyImmutable(mount.value, docOps);\n\t\tmount.value = entries === value.entries ? value : { ...value, entries };\n\t\tfor (const observer of [...mount.observers]) observer.advance?.(mount.value, ops, frameContext);\n\t}\n\tfor (const observer of [...mount.observers]) {\n\t\tobserver.publication?.(before, mount.value, ops, publication, frameContext);\n\t}\n}\n\n/** `op` moved under `prefix`; a root replacement becomes a set of the prefix. */\nfunction prefixed(op: Op, prefix: NonEmptyPath): Op {\n\tconst at = (path: Path): NonEmptyPath => [...prefix, ...path] as unknown as NonEmptyPath;\n\tswitch (op[0]) {\n\t\tcase \"r\":\n\t\t\treturn [\"s\", prefix, op[1]];\n\t\tcase \"p\":\n\t\t\treturn [\"p\", at(op[1]), op[2], op[3], op[4]];\n\t\tcase \"m\":\n\t\t\treturn [\"m\", at(op[1]), op[2]];\n\t\tcase \"s\":\n\t\t\treturn [\"s\", at(op[1]), op[2]];\n\t\tcase \"d\":\n\t\t\treturn [\"d\", at(op[1])];\n\t\tcase \"a\":\n\t\t\treturn [\"a\", at(op[1]), op[2]];\n\t\tcase \"t\":\n\t\t\treturn [\"t\", at(op[1]), op[2]];\n\t}\n}\n", "import type { Context, JsonValue } from \"@earendil-works/chord\";\nimport type { Op, Path } from \"@earendil-works/chord/delta\";\nimport type { AssistantMessage, Message, Usage } from \"@earendil-works/pi-ai\";\nimport { CommittedWatch } from \"../session/observation.ts\";\nimport type {\n\tCommitChange,\n\tCommitPublication,\n\tConversationId,\n\tEntryRecord,\n\tJsonObject,\n\tSubmissionId,\n\tSubmissionRecord,\n\tTaskId,\n\tWatchEnd,\n} from \"../types.ts\";\nimport { AgentDoc } from \"./agent.ts\";\nimport type { InboxItem, InboxState } from \"./inbox.ts\";\nimport type { CompactionStatus, LiveState, ToolSlot } from \"./live.ts\";\nimport type { AgentState, CompactionReason, Harness, ToolDiagnostic } from \"./types.ts\";\nimport { UsageDoc, type UsageState } from \"./usage.ts\";\nimport { scanAll } from \"./util.ts\";\nimport { type ConversationView, conversationViews } from \"./view.ts\";\n\ntype Block = AssistantMessage[\"content\"][number];\ntype QueuedItem = { id: SubmissionId; mode: InboxItem[\"mode\"] };\n\n/** One change to the in-flight assistant message, relative to that message. */\nexport type MessageChange =\n\t| { type: \"text_start\" | \"thinking_start\" | \"toolcall_start\"; contentIndex: number; block: Block }\n\t| { type: \"text_delta\" | \"thinking_delta\"; contentIndex: number; delta: string }\n\t| { type: \"toolcall_delta\"; contentIndex: number; path: readonly (string | number)[]; delta: string }\n\t| { type: \"block\"; contentIndex: number; block: Block }\n\t| { type: \"message\"; message: AssistantMessage };\n\nexport type SnapshotEvent = {\n\ttype: \"snapshot\";\n\tentries: readonly EntryRecord[];\n\trun?: { inputs: readonly SubmissionId[] };\n\t/** Current generation attempt: its in-flight partial, retry backoff, or deferred poll. */\n\tgeneration?: {\n\t\tattempt: number;\n\t\tmessage?: AssistantMessage;\n\t\tretry?: { at: number; error: string };\n\t\tdeferred?: { pollAt: number };\n\t};\n\ttools: readonly ToolSlot[];\n\t/** `pi.live.compactions`: live compactions with their attempt and retry backoff. */\n\tcompactions: readonly CompactionStatus[];\n\tinbox: readonly QueuedItem[];\n\t/** `pi.agent`; `{}` when absent. */\n\tagent: AgentState;\n\tusage: UsageState;\n};\n\n/** Experimental agent event, shaped like the coding agent's session events (spec §9.4). */\nexport type AgentEvent =\n\t| SnapshotEvent\n\t| { type: \"run_start\"; inputs: readonly SubmissionId[] }\n\t| { type: \"run_end\"; inputs: readonly SubmissionId[] }\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\" }\n\t| { type: \"message_start\"; message: Message }\n\t/** `usage` is the partial's current usage, as in the coding agent's JSON mode. */\n\t| { type: \"message_update\"; usage: Usage; changes: readonly MessageChange[] }\n\t| { type: \"message_end\"; entry: EntryRecord }\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: JsonObject }\n\t| {\n\t\t\ttype: \"tool_execution_update\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\t/** A front trim and then an append of the retained window, or its replacement. */\n\t\t\toutput?: { trimStart?: number; append?: string } | { set: string };\n\t\t\tdetails?: JsonValue;\n\t\t\tdiagnostics?: readonly ToolDiagnostic[];\n\t }\n\t/** `entry` is absent when the tool task faulted or was orphaned. */\n\t| { type: \"tool_execution_end\"; toolCallId: string; toolName: string; entry?: EntryRecord }\n\t| { type: \"inbox_update\"; items: readonly QueuedItem[] }\n\t| { type: \"submission\"; record: SubmissionRecord }\n\t| { type: \"auto_retry_start\"; attempt: number; at: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; attempt: number }\n\t| { type: \"deferred_poll\"; pollAt: number }\n\t| { type: \"entry_appended\"; entry: EntryRecord }\n\t| { type: \"agent_changed\"; agent: AgentState }\n\t| { type: \"usage_changed\"; usage: UsageState }\n\t| { type: \"task_failed\"; taskId: TaskId; kind: string; message: string }\n\t| { type: \"compaction_start\"; taskId: TaskId; reason: CompactionReason; blocking: boolean }\n\t/** The task's receipt tells whether it produced a summary; the summary entry has its own events. */\n\t| { type: \"compaction_end\"; taskId: TaskId; reason: CompactionReason };\n\n/** Serialized stream of one conversation's event batches, one per commit. */\nexport interface AgentEventStream {\n\t/** The `snapshot` event at attachment. */\n\treadonly snapshot: SnapshotEvent;\n\tstart(listener: (events: readonly AgentEvent[], context: Context) => Promise<void>): void;\n\tstop(): Promise<WatchEnd>;\n\treadonly closed: Promise<WatchEnd>;\n}\n\n/** The typed parts of a view the events read. */\ntype Parts = {\n\tlive: LiveState;\n\tinbox: InboxState | undefined;\n\tagent: AgentState | undefined;\n\tusage: UsageState | undefined;\n};\n\nfunction parts(view: ConversationView): Parts {\n\treturn {\n\t\tlive: (view.docs[\"pi.live\"] ?? {}) as LiveState,\n\t\tinbox: view.docs[\"pi.inbox\"] as InboxState | undefined,\n\t\tagent: view.docs[\"pi.agent\"] as AgentState | undefined,\n\t\tusage: view.docs[\"pi.usage\"] as UsageState | undefined,\n\t};\n}\n\nfunction snapshotOf(view: ConversationView): SnapshotEvent {\n\tconst { live, inbox, agent, usage } = parts(view);\n\treturn {\n\t\ttype: \"snapshot\",\n\t\tentries: view.entries,\n\t\t...(live.run === undefined ? {} : { run: { inputs: live.run.inputs } }),\n\t\t...(live.generation === undefined ? {} : { generation: live.generation as SnapshotEvent[\"generation\"] }),\n\t\ttools: live.tools ?? [],\n\t\tcompactions: live.compactions ?? [],\n\t\tinbox: queued(inbox),\n\t\tagent: agent ?? AgentDoc.definition.initial(),\n\t\tusage: usage ?? UsageDoc.definition.initial(),\n\t};\n}\n\nfunction queued(inbox: InboxState | undefined): QueuedItem[] {\n\treturn (inbox?.items ?? []).map((item) => ({ id: item.id, mode: item.mode }));\n}\n\n/**\n * Experimental: attach to one conversation's agent events (spec §9.4). The snapshot and the registration for later\n * commits are captured atomically on the Session line; overflow replaces undelivered batches with one snapshot.\n */\nexport async function watchEvents(\n\tharness: Harness,\n\tconversationId: ConversationId,\n\tcontext: Context,\n): Promise<AgentEventStream> {\n\tlet watch!: CommittedWatch<readonly AgentEvent[]>;\n\tlet snapshot!: SnapshotEvent;\n\tawait conversationViews(harness).attach(\n\t\tconversationId,\n\t\tasync (initial, release, storage) => {\n\t\t\t// Generations whose held outcome already ended their turn, read on the line with the snapshot.\n\t\t\tconst query = { conversationId, kind: \"pi.generation\", status: \"completing\" } as const;\n\t\t\tconst completing = await scanAll((cursor) => storage.scanTasks(query, 100, cursor, context));\n\t\t\tconst held = new Set<TaskId>(completing.map((record) => record.id));\n\t\t\tlet current = initial;\n\t\t\tsnapshot = snapshotOf(initial);\n\t\t\t// Batches are the watch's values; an overflow delivers a snapshot of the newest view instead.\n\t\t\twatch = new CommittedWatch<readonly AgentEvent[]>([], release, () => [snapshotOf(current)]);\n\t\t\treturn {\n\t\t\t\tpublication: (before, after, ops, publication, commitContext) => {\n\t\t\t\t\tcurrent = after;\n\t\t\t\t\tconst events = translate(conversationId, before, after, ops, publication, held);\n\t\t\t\t\tif (events.length > 0) watch.advance(events, [], commitContext);\n\t\t\t\t},\n\t\t\t\tcloseSession: () => watch.closeSession(),\n\t\t\t};\n\t\t},\n\t\tcontext,\n\t);\n\t// Like a watch, the acquisition context governs the stream's lifetime.\n\tconst signal = context.abortSignal;\n\tif (signal?.aborted) {\n\t\twatch.cancel();\n\t\tthrow signal.reason;\n\t}\n\tif (signal !== undefined) watch.observeCancellation(signal);\n\treturn {\n\t\tsnapshot,\n\t\tstart: (listener) => watch.start((events, _ops, deliveryContext) => listener(events, deliveryContext)),\n\t\tstop: () => watch.stop(),\n\t\tclosed: watch.closed,\n\t};\n}\n\ntype TaskChange = Extract<CommitChange, { type: \"task\" }>;\n\n/** The tool result for `callId` among `entries`. */\nfunction resultOf(entries: readonly EntryRecord[], callId: string): EntryRecord | undefined {\n\treturn entries.find((entry) => {\n\t\tconst message = entry.model?.[0];\n\t\treturn message?.role === \"toolResult\" && message.toolCallId === callId;\n\t});\n}\n\n/** Every event one publication causes, in the order of spec §9.4. */\nfunction translate(\n\tconversationId: ConversationId,\n\tbefore: ConversationView,\n\tafter: ConversationView,\n\tviewOps: readonly Op[],\n\tpublication: CommitPublication,\n\theld: Set<TaskId>,\n): AgentEvent[] {\n\tconst entries: EntryRecord[] = [];\n\tconst tasks = new Map<TaskId, TaskChange[\"value\"]>();\n\tconst submissions: SubmissionRecord[] = [];\n\tfor (const change of publication.changes) {\n\t\tif (change.type === \"entry\" && change.value.conversationId === conversationId) entries.push(change.value);\n\t\tif (change.type === \"task\" && change.value.conversationId === conversationId)\n\t\t\ttasks.set(change.value.id, change.value);\n\t\tif (change.type === \"submission\" && change.value.conversationId === conversationId) {\n\t\t\tsubmissions.push(change.value);\n\t\t}\n\t}\n\tif (viewOps.length === 0 && entries.length === 0 && tasks.size === 0 && submissions.length === 0) return [];\n\t// Entries are appended in ID order; submission records are published in the order the commit first touched them.\n\tsubmissions.sort((a, b) => a.id - b.id);\n\tconst was = parts(before);\n\tconst now = parts(after);\n\tconst events: AgentEvent[] = [];\n\n\t// Progress: tool starts, the in-flight message, tool updates, retry and deferred state.\n\tconst slotsBefore = new Map((was.live.tools ?? []).map((slot) => [slot.callId, slot]));\n\tconst slots = now.live.tools ?? [];\n\tfor (const slot of slots) {\n\t\tif (slot.status !== \"running\" || slotsBefore.get(slot.callId)?.status === \"running\") continue;\n\t\tconst checkpoint = slot.taskId === undefined ? undefined : tasks.get(slot.taskId)?.state.checkpoint;\n\t\tconst args = (checkpoint as { arguments?: JsonObject } | undefined)?.arguments ?? {};\n\t\tevents.push({ type: \"tool_execution_start\", toolCallId: slot.callId, toolName: slot.name, args });\n\t}\n\tconst partialBefore = was.live.generation?.message as AssistantMessage | undefined;\n\tconst partial = now.live.generation?.message as AssistantMessage | undefined;\n\tif (partial !== undefined && partialBefore === undefined) events.push({ type: \"message_start\", message: partial });\n\telse if (partial !== undefined && partial !== partialBefore) {\n\t\tevents.push({ type: \"message_update\", usage: partial.usage, changes: messageChanges(viewOps, partial) });\n\t}\n\tfor (const [index, slot] of slots.entries()) {\n\t\tconst previous = slotsBefore.get(slot.callId);\n\t\tif (slot.status !== \"running\" || previous?.status !== \"running\") continue;\n\t\tconst update = toolUpdate(viewOps, index, slot, previous);\n\t\tif (update === undefined) continue;\n\t\tevents.push({ type: \"tool_execution_update\", toolCallId: slot.callId, toolName: slot.name, ...update });\n\t}\n\tconst generation = now.live.generation;\n\tconst generationBefore = was.live.generation;\n\tif (generation?.retry !== undefined && generationBefore?.retry === undefined) {\n\t\tconst { at, error } = generation.retry;\n\t\tevents.push({ type: \"auto_retry_start\", attempt: generation.attempt, at, errorMessage: error });\n\t}\n\tif (generationBefore?.retry !== undefined && generation?.retry === undefined) {\n\t\tevents.push({ type: \"auto_retry_end\", attempt: generationBefore.attempt });\n\t}\n\tif (generation?.deferred !== undefined && generation.deferred.pollAt !== generationBefore?.deferred?.pollAt) {\n\t\tevents.push({ type: \"deferred_poll\", pollAt: generation.deferred.pollAt });\n\t}\n\n\t// Tools that end in this commit: a slot that becomes done, one created done (a call not offered), or an unfinished\n\t// one that vanishes because its run ended. A done slot that vanishes ended earlier.\n\tconst toolEnds: Extract<AgentEvent, { type: \"tool_execution_end\" }>[] = [];\n\tconst endTool = (callId: string, name: string, entryId: number | undefined): void => {\n\t\tconst entry = entries.find((candidate) => candidate.id === entryId);\n\t\ttoolEnds.push({\n\t\t\ttype: \"tool_execution_end\",\n\t\t\ttoolCallId: callId,\n\t\t\ttoolName: name,\n\t\t\t...(entry === undefined ? {} : { entry }),\n\t\t});\n\t};\n\tfor (const previous of slotsBefore.values()) {\n\t\tif (previous.status === \"done\") continue;\n\t\tconst slot = slots.find((candidate) => candidate.callId === previous.callId);\n\t\tif (slot?.status === \"done\") endTool(previous.callId, previous.name, slot.entry);\n\t\t// A slot whose run ended in this commit may have had its result appended with it, as for unstarted calls.\n\t\telse if (slot === undefined) endTool(previous.callId, previous.name, resultOf(entries, previous.callId)?.id);\n\t}\n\tfor (const slot of slots) {\n\t\tif (slot.status === \"done\" && !slotsBefore.has(slot.callId)) endTool(slot.callId, slot.name, slot.entry);\n\t}\n\n\t// Entries in append order; a tool's end directly precedes its result's message, as in the coding agent.\n\tlet assistantAppended = false;\n\tfor (const entry of entries) {\n\t\tevents.push(...toolEnds.filter((end) => end.entry === entry));\n\t\tconst message = entry.model?.[0];\n\t\tif (message === undefined) {\n\t\t\tevents.push({ type: \"entry_appended\", entry });\n\t\t\tcontinue;\n\t\t}\n\t\t// A streamed answer already started with its first partial.\n\t\tconst streamed = message.role === \"assistant\" && partialBefore !== undefined && !assistantAppended;\n\t\tif (message.role === \"assistant\") assistantAppended = true;\n\t\tif (!streamed) events.push({ type: \"message_start\", message });\n\t\tevents.push({ type: \"message_end\", entry });\n\t}\n\t// Ends without a result entry: a faulted or orphaned tool, or one whose run ended.\n\tevents.push(...toolEnds.filter((end) => end.entry === undefined));\n\n\t// Compaction ends, task failures, then turn and run ends.\n\tconst compactionsBefore = was.live.compactions ?? [];\n\tconst compactions = now.live.compactions ?? [];\n\tfor (const { taskId, reason } of compactionsBefore) {\n\t\tif (!compactions.some((status) => status.taskId === taskId)) {\n\t\t\tevents.push({ type: \"compaction_end\", taskId, reason });\n\t\t}\n\t}\n\t// A generation's turn ends when its outcome is committed: at a `completing` hold or at terminal, whichever comes\n\t// first, so a successor created at the hold starts after it.\n\tlet turnEnded = false;\n\tfor (const task of tasks.values()) {\n\t\tconst status = task.state.status;\n\t\tif (task.kind === \"pi.generation\" && status === \"completing\" && !held.has(task.id)) {\n\t\t\theld.add(task.id);\n\t\t\tturnEnded = true;\n\t\t}\n\t\tif (status !== \"terminal\") continue;\n\t\tif (task.kind === \"pi.generation\" && !held.delete(task.id)) turnEnded = true;\n\t\tconst outcome = task.state.outcome;\n\t\tif (outcome.status === \"faulted\" || outcome.status === \"orphaned\") {\n\t\t\tconst message = outcome.status === \"faulted\" ? outcome.error.message : outcome.reason;\n\t\t\tevents.push({ type: \"task_failed\", taskId: task.id, kind: task.kind, message });\n\t\t}\n\t}\n\tif (turnEnded) events.push({ type: \"turn_end\" });\n\tconst run = now.live.run;\n\tconst runBefore = was.live.run;\n\tconst runChanged = run?.inputs[0] !== runBefore?.inputs[0];\n\tif (runBefore !== undefined && runChanged) events.push({ type: \"run_end\", inputs: runBefore.inputs });\n\n\t// Submissions, document state, then what began.\n\tfor (const record of submissions) events.push({ type: \"submission\", record });\n\tif (now.inbox !== was.inbox) events.push({ type: \"inbox_update\", items: queued(now.inbox) });\n\t// A retired document reads as its initial value, as in a snapshot.\n\tif (now.agent !== was.agent) {\n\t\tevents.push({ type: \"agent_changed\", agent: now.agent ?? AgentDoc.definition.initial() });\n\t}\n\tif (now.usage !== was.usage)\n\t\tevents.push({ type: \"usage_changed\", usage: now.usage ?? UsageDoc.definition.initial() });\n\tfor (const { taskId, reason, blocking } of compactions) {\n\t\tif (!compactionsBefore.some((status) => status.taskId === taskId)) {\n\t\t\tevents.push({ type: \"compaction_start\", taskId, reason, blocking });\n\t\t}\n\t}\n\tif (run !== undefined && runChanged) events.push({ type: \"run_start\", inputs: run.inputs });\n\tif (run !== undefined && run.taskId !== runBefore?.taskId && tasks.get(run.taskId)?.kind === \"pi.generation\") {\n\t\tevents.push({ type: \"turn_start\" });\n\t}\n\treturn events;\n}\n\nconst PARTIAL_PATH = [\"docs\", \"pi.live\", \"generation\", \"message\"];\n\n/** Translate the view operations on the in-flight message into message changes (spec §9.4). */\nfunction messageChanges(viewOps: readonly Op[], message: AssistantMessage): MessageChange[] {\n\tconst changes: MessageChange[] = [];\n\t// A block sent whole already holds every later change to it in this batch.\n\tconst whole = new Set<number>();\n\tfor (const op of viewOps) {\n\t\t// View operations never replace the root.\n\t\tconst path = op[1] as Path;\n\t\tif (!startsWith(path, PARTIAL_PATH)) {\n\t\t\t// The whole message or generation was replaced.\n\t\t\tif (startsWith(PARTIAL_PATH, path)) return [{ type: \"message\", message }];\n\t\t\tcontinue;\n\t\t}\n\t\tconst rest = path.slice(PARTIAL_PATH.length);\n\t\tif (rest[0] === \"usage\") continue;\n\t\tif (rest[0] !== \"content\") return [{ type: \"message\", message }];\n\t\tif (rest.length === 1) {\n\t\t\tif (op[0] !== \"p\" || op[3] !== 0) return [{ type: \"message\", message }];\n\t\t\tfor (const [offset, block] of (op[4] as unknown as Block[]).entries()) {\n\t\t\t\tconst type =\n\t\t\t\t\tblock.type === \"text\" ? \"text_start\" : block.type === \"thinking\" ? \"thinking_start\" : \"toolcall_start\";\n\t\t\t\tchanges.push({ type, contentIndex: op[2] + offset, block });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst contentIndex = rest[1] as number;\n\t\tconst field = rest[2];\n\t\tif (whole.has(contentIndex)) continue;\n\t\tif (op[0] === \"a\" && rest.length === 3 && (field === \"text\" || field === \"thinking\")) {\n\t\t\tchanges.push({ type: field === \"text\" ? \"text_delta\" : \"thinking_delta\", contentIndex, delta: op[2] });\n\t\t} else if (op[0] === \"a\" && field === \"arguments\") {\n\t\t\tchanges.push({ type: \"toolcall_delta\", contentIndex, path: rest.slice(3), delta: op[2] });\n\t\t} else {\n\t\t\twhole.add(contentIndex);\n\t\t\tchanges.push({ type: \"block\", contentIndex, block: message.content[contentIndex]! });\n\t\t}\n\t}\n\treturn changes;\n}\n\n/** Output, details, and diagnostics changes of a running slot, from the view operations on it. */\nfunction toolUpdate(\n\tviewOps: readonly Op[],\n\tindex: number,\n\tslot: ToolSlot,\n\tprevious: ToolSlot,\n): Omit<Extract<AgentEvent, { type: \"tool_execution_update\" }>, \"type\" | \"toolCallId\" | \"toolName\"> | undefined {\n\tconst outputPath = [\"docs\", \"pi.live\", \"tools\", index, \"output\"];\n\tlet trimStart = 0;\n\tlet append = \"\";\n\tlet set = false;\n\tfor (const op of viewOps) {\n\t\tif (!startsWith(op[1] as Path, outputPath)) continue;\n\t\tif (op[0] === \"t\") trimStart += op[2];\n\t\telse if (op[0] === \"a\") append += op[2];\n\t\telse set = true;\n\t}\n\tlet output: { trimStart?: number; append?: string } | { set: string } | undefined;\n\tif (set || (slot.output !== previous.output && trimStart === 0 && append === \"\"))\n\t\toutput = { set: slot.output ?? \"\" };\n\telse if (trimStart > 0 || append !== \"\") {\n\t\toutput = { ...(trimStart > 0 ? { trimStart } : {}), ...(append === \"\" ? {} : { append }) };\n\t}\n\t// A safe replay clears a running slot's progress: removed details send `null`, removed diagnostics `[]`.\n\tconst update = {\n\t\t...(output === undefined ? {} : { output }),\n\t\t...(slot.details === previous.details ? {} : { details: slot.details ?? null }),\n\t\t...(slot.diagnostics === previous.diagnostics ? {} : { diagnostics: slot.diagnostics ?? [] }),\n\t};\n\treturn Object.keys(update).length === 0 ? undefined : update;\n}\n\nfunction startsWith(path: Path, prefix: readonly (string | number)[]): boolean {\n\treturn prefix.length <= path.length && prefix.every((segment, index) => path[index] === segment);\n}\n", "import type { AttachedReplicatedState, Context, Draft, JsonValue } from \"@earendil-works/chord\";\nimport type { Op } from \"@earendil-works/chord/delta\";\nimport type { Message, Models } from \"@earendil-works/pi-ai\";\nimport type { ExecutionEnv } from \"./env/index.ts\";\nimport type {\n\tAgent,\n\tContextView,\n\tConversationHandle,\n\tRegistrySnapshot,\n\tSettings,\n\tSettledTask,\n} from \"./harness/types.ts\";\n\n/** JSON object used as the root of every durable document. */\nexport type JsonObject = { [key: string]: JsonValue };\n\ndeclare const idBrand: unique symbol;\n\n/** Erased nominal number identifying one durable record kind. */\nexport type Id<Kind extends string, Type = unknown> = number & {\n\treadonly [idBrand]: {\n\t\treadonly kind: Kind;\n\t\treadonly type: Type;\n\t};\n};\n\nexport type ConversationId = Id<\"conversation\">;\nexport type EntryId = Id<\"entry\">;\nexport type TaskId<Result = unknown> = Id<\"task\", Result>;\nexport type SubmissionId = Id<\"submission\">;\nexport type DocumentId = Id<\"document\">;\n\ndeclare const seqBrand: unique symbol;\n\n/** Strictly increasing sequence assigned to one atomic storage commit; gaps are permitted. */\nexport type Seq = number & { readonly [seqBrand]: \"sequence\" };\n\n/** The root conversation always uses this reserved ID. */\nexport const ROOT_CONVERSATION_ID = 1 as ConversationId;\n\n/** Conversation document that retains only its current state. */\nexport type LatestConversationSemantics = {\n\treadonly scope: \"conversation\";\n\treadonly history: \"latest\";\n\treadonly fork: \"current\" | \"initial\";\n};\n\n/** Conversation document whose history remains addressable for as-of reads. */\nexport type RewindableConversationSemantics = {\n\treadonly scope: \"conversation\";\n\treadonly history: \"rewindable\";\n\treadonly fork: \"asOf\" | \"current\" | \"initial\";\n};\n\n/** Ownership and lifetime of a document; only conversation documents declare history and fork behavior. */\nexport type DocumentSemantics =\n\t| { readonly scope: \"session\"; readonly history?: never; readonly fork?: never }\n\t| LatestConversationSemantics\n\t| RewindableConversationSemantics\n\t| { readonly scope: \"task\"; readonly history?: never; readonly fork?: never };\n\n/** Stored replay state supplied to a document's checkpoint predicate. */\nexport type CheckpointInfo = {\n\t/** Deltas already stored after the newest base, excluding the change being evaluated. */\n\treadonly deltasSinceBase: number;\n};\n\n/** Definition fields shared by singleton documents and document families. */\nexport type CommonDocDefinition<T extends JsonObject> = {\n\t/** Stable persisted kind; part of the public protocol. */\n\treadonly kind: string;\n\t/** Positive integer version of the stored value shape. */\n\treadonly version: number;\n\tinitial(): T;\n\tmigrate?(value: JsonObject, fromVersion: number): T;\n\t/** Return true to store this ordinary change as a complete base instead of a delta. */\n\tcheckpointWhen?(value: Readonly<T>, ops: readonly Op[], info: CheckpointInfo): boolean;\n};\n\n/** Singleton document definition. */\nexport type DocDefinition<T extends JsonObject> = CommonDocDefinition<T> & DocumentSemantics;\n\n/** Keyed document family definition; `initial(seed)` runs only when a member is absent. */\nexport type DocFamilyDefinition<T extends JsonObject, I extends JsonValue> = Omit<CommonDocDefinition<T>, \"initial\"> &\n\tDocumentSemantics & {\n\t\treadonly family: true;\n\t\tinitial(seed: I): T;\n\t};\n\ndeclare const docType: unique symbol;\n\n/** Typed singleton document token passed explicitly to typed access. */\nexport interface DocToken<T extends JsonObject, D extends DocDefinition<T>> {\n\treadonly definition: D;\n\treadonly [docType]?: T;\n}\n\n/** Typed document family token passed explicitly to typed access. */\nexport interface DocFamilyToken<T extends JsonObject, I extends JsonValue, D extends DocFamilyDefinition<T, I>> {\n\treadonly definition: D;\n\treadonly [docType]?: T;\n}\n\nexport type SessionDocToken<T extends JsonObject> = DocToken<T, CommonDocDefinition<T> & { readonly scope: \"session\" }>;\nexport type ConversationDocToken<T extends JsonObject> = DocToken<\n\tT,\n\tCommonDocDefinition<T> & (LatestConversationSemantics | RewindableConversationSemantics)\n>;\nexport type RewindableConversationDocToken<T extends JsonObject> = DocToken<\n\tT,\n\tCommonDocDefinition<T> & RewindableConversationSemantics\n>;\nexport type TaskDocToken<T extends JsonObject> = DocToken<T, CommonDocDefinition<T> & { readonly scope: \"task\" }>;\n\nexport type SessionDocFamilyToken<T extends JsonObject, I extends JsonValue> = DocFamilyToken<\n\tT,\n\tI,\n\tDocFamilyDefinition<T, I> & { readonly scope: \"session\" }\n>;\nexport type ConversationDocFamilyToken<T extends JsonObject, I extends JsonValue> = DocFamilyToken<\n\tT,\n\tI,\n\tDocFamilyDefinition<T, I> & (LatestConversationSemantics | RewindableConversationSemantics)\n>;\nexport type RewindableConversationDocFamilyToken<T extends JsonObject, I extends JsonValue> = DocFamilyToken<\n\tT,\n\tI,\n\tDocFamilyDefinition<T, I> & RewindableConversationSemantics\n>;\nexport type TaskDocFamilyToken<T extends JsonObject, I extends JsonValue> = DocFamilyToken<\n\tT,\n\tI,\n\tDocFamilyDefinition<T, I> & { readonly scope: \"task\" }\n>;\n\n/** Live task record reserved by one invocation. */\nexport type RunningTask<I, S, R> = TaskRecord<I, S, R> & {\n\treadonly state: Extract<TaskState<S, R>, { readonly status: \"running\" }>;\n};\n\n/**\n * Next state a task commits for itself: a replacement checkpoint, a wait, or its outcome. A returned `terminal` state is\n * stored as `completing` while ordinary owned work below the task is live (spec §5.5).\n */\nexport type NextTaskState<S, R> = Extract<TaskState<S, R>, { readonly status: \"running\" | \"waiting\" | \"terminal\" }>;\n\n/**\n * Runs one checkpoint phase. It must commit a changed checkpoint or a terminal outcome through `runtime.commit()`;\n * returning without durable progress faults the task.\n */\nexport type PhaseHandler<I, P, S, R, H extends object> = (\n\ttask: RunningTask<I, P, R>,\n\truntime: TaskRuntime<I, S, R, H>,\n\tcontext: Context,\n) => Promise<void>;\n\n/** Dispatches one hook of a task to every matching registered handler, in registry order of the phase snapshot. */\nexport interface HookRunner<H extends object> {\n\t/**\n\t * Call `invoke` with each matching handler named `name`. An ordinary throw from `invoke` is reported and the next\n\t * handler runs; once the invocation is signalled, the error propagates. Composition happens inside `invoke`.\n\t */\n\teach<K extends keyof H>(name: K, invoke: (handler: NonNullable<H[K]>) => void | Promise<void>): Promise<void>;\n}\n\n/**\n * Operations of one task invocation. Every operation rejects after the invocation ends; watches acquired through it\n * stop at invocation end.\n */\nexport interface TaskRuntime<I, S, R, H extends object> extends DocumentObserver, DocumentReader {\n\treadonly taskId: TaskId<R>;\n\treadonly conversationId: ConversationId;\n\t/**\n\t * Aborted when the run is signalled by `abortTask()`, the Harness closes, or the invocation ends. Work still using it\n\t * after the invocation ended, such as a detached wait, is cancelled; it could not write anything anyway.\n\t */\n\treadonly signal: AbortSignal;\n\t/** Registry snapshot of the current phase; refreshed at every phase boundary. */\n\treadonly registry: RegistrySnapshot;\n\t/** The task's conversation's agent, resolved at most once per phase, at first use, and fixed for the phase. */\n\tagent(context: Context): Promise<Agent>;\n\t/** `HarnessOptions.settings`, resolved at each access. */\n\treadonly settings: Settings;\n\treadonly models: Models;\n\t/** Calls `HarnessOptions.env` for the task's conversation; rejects with its error. */\n\tenv(context: Context): Promise<ExecutionEnv | undefined>;\n\t/** Handlers of this task's name from the extensions its conversation selects, in extension order. */\n\treadonly hooks: HookRunner<H>;\n\n\t/**\n\t * Commit on the Session line after rereading the task. Rejects when the task is terminal, the invocation ended, the\n\t * Harness is closing, or, in a run invocation, the task carries an abort mark. A returned state replaces the task's\n\t * state in the same commit; returning nothing leaves it unchanged. `tx.createTask()` defaults to the task's\n\t * conversation.\n\t */\n\tcommit(\n\t\tchange: (\n\t\t\ttx: Tx,\n\t\t\tcurrent: RunningTask<I, S, R>,\n\t\t) => NextTaskState<S, R> | undefined | Promise<NextTaskState<S, R> | undefined>,\n\t\tcontext: Context,\n\t): Promise<void>;\n\t/** Read a durable memo of this task. */\n\tmemo<T extends JsonValue>(name: string, context: Context): Promise<T | undefined>;\n\t/** Store `candidate` unless a memo already exists; return the durable winner. */\n\tmemo<T extends JsonValue>(name: string, candidate: T, context: Context): Promise<T>;\n\t/** Committed task record. */\n\tgetTask<T>(id: TaskId<T>, context: Context): Promise<TaskRecord<JsonValue, JsonValue, T> | undefined>;\n\t/** Resolve with the task's terminal receipt; rejects when the invocation ends. */\n\twaitForTask<T>(id: TaskId<T>, context: Context): Promise<SettledTask<T>>;\n\t/** Outcomes of terminal tasks, in order; rejects when one is missing or not terminal. Used after a wait. */\n\toutcomes<T>(ids: readonly TaskId<T>[], context: Context): Promise<TaskOutcome<T>[]>;\n\t/**\n\t * Invocation-bound handle of an existing conversation, for example one this task owns; `undefined` when absent. Its\n\t * operations and the submissions it returns reject after the invocation ends; admitted work stays durable.\n\t */\n\tconversation(id: ConversationId, context: Context): Promise<ConversationHandle | undefined>;\n\t/** Committed entry visible from the task's conversation. */\n\tentry(id: EntryId, context: Context): Promise<EntryRecord | undefined>;\n\t/** Undefined when the entry is absent, not visible, or has another kind. */\n\tentry<D extends JsonValue>(token: Entry<D>, id: EntryId, context: Context): Promise<TypedEntry<D> | undefined>;\n\t/** Committed raw active transcript and model context, optionally cut off at the visible entry `at`. */\n\tcontext(conversationId: ConversationId, context: Context, at?: EntryId): Promise<ContextView>;\n\t/** The Harness clock. */\n\tnow(): number;\n\t/** Forward a non-fatal failure to `HarnessOptions.onReport`. */\n\treport(error: unknown): void;\n\t/** Resolve once the Harness clock reaches `until`; rejects when the invocation or `context` is cancelled. */\n\tsleep(until: number, context: Context): Promise<void>;\n}\n\n/** Executable durable state machine definition, registered in the registry by `name`. */\nexport type TaskDefinition<I, S extends { phase: string }, R, H extends object> = {\n\t/** Registered task kind persisted in `TaskRecord.kind`. */\n\treadonly name: string;\n\t/** Definition version persisted with live input and checkpoints. */\n\treadonly version: number;\n\t/** First durable checkpoint for a newly created task. */\n\tinitial(input: I): S;\n\t/** Exhaustive phase map; each handler receives the task narrowed to its phase. */\n\treadonly phases: {\n\t\treadonly [P in S[\"phase\"]]: PhaseHandler<I, Extract<S, { phase: P }>, S, R, H>;\n\t};\n\t/** Runs in a fresh invocation after an abort mark and must commit a terminal outcome. */\n\tabort(task: RunningTask<I, S, R>, runtime: TaskRuntime<I, S, R, H>, context: Context): Promise<void>;\n\t/** Convert a record stored by any older supported version; runs at reservation. */\n\tmigrate?(\n\t\tinput: JsonValue,\n\t\tcheckpoint: JsonValue,\n\t\tfromVersion: number,\n\t): {\n\t\tinput: I;\n\t\tcheckpoint: S;\n\t};\n\treadonly hooks?: H;\n};\n\n/** Typed executable task definition. */\nexport interface Task<I, S extends { phase: string }, R, H extends object> {\n\treadonly definition: TaskDefinition<I, S, R, H>;\n}\n\n/** Who owns a task: its conversation (a top-level task) or another task of the same conversation (a child task). */\nexport type TaskOwnership = { readonly kind: \"conversation\" } | { readonly kind: \"task\"; readonly taskId: TaskId };\n\n/** How a waiting task treats the tasks it waits on (spec §5.5). */\nexport type JoinPolicy = \"failFast\" | \"allSettled\";\n\n/** Creation options for a durable task. */\nexport type TaskOptions = {\n\t/** Required: a task always names its owner (spec §5.5). */\n\treadonly ownership: TaskOwnership;\n\t/**\n\t * Default: the owner task's conversation, or the transaction's bound conversation; required for conversation-owned\n\t * tasks created by Session commits that are not bound to a conversation.\n\t */\n\treadonly conversationId?: ConversationId;\n\t/** Conversation-owned tasks only: excluded from ordinary idle waits, conversation aborts, and cascades. */\n\treadonly background?: boolean;\n};\n\n/** Ownership selected explicitly whenever a conversation is created. */\nexport type ConversationOwnership = { readonly kind: \"ownerless\" } | { readonly kind: \"task\"; readonly taskId: TaskId };\n\n/** Immutable identity, history ancestry, and task ownership of a transcript scope. */\nexport type ConversationRecord = {\n\treadonly id: ConversationId;\n\t/** Fork source and inclusive parent entry through which history is inherited. */\n\treadonly parent?: {\n\t\treadonly conversationId: ConversationId;\n\t\treadonly at: EntryId;\n\t};\n\t/** Creator edge used for attribution, subtree abort, and subtree idle waits. */\n\treadonly owner?: {\n\t\treadonly conversationId: ConversationId;\n\t\treadonly taskId: TaskId;\n\t};\n};\n\n/** An immutable override of one visible entry's contribution to model context. */\nexport type ContextEdit = {\n\t/** Entry whose model messages are omitted or replaced. */\n\treadonly target: EntryId;\n} & (\n\t| {\n\t\t\treadonly action: \"omit\";\n\t\t\treadonly messages?: never;\n\t }\n\t| {\n\t\t\treadonly action: \"replace\";\n\t\t\t/** Messages contributed instead of the target entry's model messages. */\n\t\t\treadonly messages: readonly Message[];\n\t }\n);\n\n/** Immutable transcript event with separate model-facing and application-facing payloads. */\nexport type EntryRecord = {\n\treadonly id: EntryId;\n\treadonly conversationId: ConversationId;\n\t/** Application-defined entry discriminator. */\n\treadonly kind: string;\n\t/** Messages contributed to model context; absent for display or bookkeeping entries. */\n\treadonly model?: readonly Message[];\n\t/** JSON payload consumed by views, extensions, or bookkeeping logic. */\n\treadonly data?: JsonValue;\n\t/** First entry in the active context selected by this entry. */\n\treadonly head?: EntryId;\n\t/** Context-only overrides of earlier visible entries. */\n\treadonly edits?: readonly ContextEdit[];\n\t/** Task that appended this entry, when it was produced by durable work. */\n\treadonly byTaskId?: TaskId;\n};\n\n/** Entry content supplied before the Session assigns identity and task attribution. */\nexport type EntryDraft = Omit<EntryRecord, \"id\" | \"conversationId\" | \"byTaskId\" | \"head\"> & {\n\t/** `\"self\"` starts active context at the newly assigned entry ID. */\n\treadonly head?: EntryId | \"self\";\n};\n\n/** Entry whose `data` has type `D`; `never` means the kind carries no data. */\nexport type TypedEntry<D extends JsonValue> = Omit<EntryRecord, \"data\"> &\n\t([D] extends [never] ? { readonly data?: never } : { readonly data: D });\n\n/** Entry content of a typed kind; the token supplies `kind`. */\nexport type TypedEntryDraft<D extends JsonValue> = Omit<EntryDraft, \"kind\" | \"data\"> &\n\t([D] extends [never] ? { readonly data?: never } : { readonly data: D });\n\n/** Typed entry kind with a narrowing guard. */\nexport interface Entry<D extends JsonValue = never> {\n\treadonly kind: string;\n\tis(entry: EntryRecord | undefined): entry is TypedEntry<D>;\n}\n\n/** Identity fields shared by every durable submission state. */\ntype SubmissionRecordBase = {\n\treadonly id: SubmissionId;\n\treadonly conversationId: ConversationId;\n\t/** Host-provided deduplication key, scoped to the conversation. */\n\treadonly requestId?: string;\n};\n\n/** Durable lifecycle of one admitted user input or passive entry write. */\nexport type SubmissionRecord =\n\t| (SubmissionRecordBase & {\n\t\t\treadonly type: \"input\";\n\t } & (\n\t\t\t\t| {\n\t\t\t\t\t\t/** Admitted but not yet represented in the transcript. */\n\t\t\t\t\t\treadonly status: \"queued\";\n\t\t\t\t\t\treadonly entry?: never;\n\t\t\t\t\t\treadonly answer?: never;\n\t\t\t\t\t\treadonly reason?: never;\n\t\t\t\t\t\treadonly detail?: never;\n\t\t\t\t }\n\t\t\t\t| {\n\t\t\t\t\t\t/** Added to the transcript and owned by an active run. */\n\t\t\t\t\t\treadonly status: \"placed\";\n\t\t\t\t\t\treadonly entry: EntryId;\n\t\t\t\t\t\treadonly answer?: never;\n\t\t\t\t\t\treadonly reason?: never;\n\t\t\t\t\t\treadonly detail?: never;\n\t\t\t\t }\n\t\t\t\t| {\n\t\t\t\t\t\t/** Successfully answered user input. */\n\t\t\t\t\t\treadonly status: \"done\";\n\t\t\t\t\t\treadonly entry: EntryId;\n\t\t\t\t\t\treadonly answer: EntryId;\n\t\t\t\t\t\treadonly reason?: never;\n\t\t\t\t\t\treadonly detail?: never;\n\t\t\t\t }\n\t\t\t\t| {\n\t\t\t\t\t\t/** Terminal input that can no longer receive an answer. */\n\t\t\t\t\t\treadonly status: \"unanswered\";\n\t\t\t\t\t\treadonly entry?: EntryId;\n\t\t\t\t\t\treadonly answer?: never;\n\t\t\t\t\t\treadonly reason: string;\n\t\t\t\t\t\treadonly detail?: JsonValue;\n\t\t\t\t }\n\t\t\t))\n\t| (SubmissionRecordBase & {\n\t\t\treadonly type: \"write\";\n\t } & (\n\t\t\t\t| {\n\t\t\t\t\t\t/** Admitted but not yet appended to the transcript. */\n\t\t\t\t\t\treadonly status: \"queued\";\n\t\t\t\t\t\treadonly entry?: never;\n\t\t\t\t\t\treadonly answer?: never;\n\t\t\t\t\t\treadonly reason?: never;\n\t\t\t\t\t\treadonly detail?: never;\n\t\t\t\t }\n\t\t\t\t| {\n\t\t\t\t\t\t/** Successfully appended passive entry. */\n\t\t\t\t\t\treadonly status: \"done\";\n\t\t\t\t\t\treadonly entry: EntryId;\n\t\t\t\t\t\treadonly answer?: never;\n\t\t\t\t\t\treadonly reason?: never;\n\t\t\t\t\t\treadonly detail?: never;\n\t\t\t\t }\n\t\t\t\t| {\n\t\t\t\t\t\t/** Terminal passive write that could not be placed. */\n\t\t\t\t\t\treadonly status: \"unanswered\";\n\t\t\t\t\t\treadonly entry?: never;\n\t\t\t\t\t\treadonly answer?: never;\n\t\t\t\t\t\treadonly reason: string;\n\t\t\t\t\t\treadonly detail?: JsonValue;\n\t\t\t\t }\n\t\t\t));\n\n/** Terminal status staged for a submission; identity, type, and entry come from its current record. */\nexport type SubmissionSettlement =\n\t| { readonly status: \"done\"; readonly answer: EntryId }\n\t| { readonly status: \"unanswered\"; readonly reason: string; readonly detail?: JsonValue };\n\n/** Submission fields supplied before the Session assigns an ID. */\nexport type SubmissionCreate = SubmissionRecord extends infer Record\n\t? Record extends SubmissionRecord\n\t\t? Omit<Record, \"id\">\n\t\t: never\n\t: never;\n\n/** JSON-safe error snapshot persisted instead of a runtime `Error` object. */\nexport type TaskOutcomeError = {\n\treadonly message: string;\n\t/** Optional structured diagnostic data for inspection or recovery. */\n\treadonly detail?: JsonValue;\n};\n\n/** Durable reason and optional result recorded when a task becomes terminal. */\nexport type TaskOutcome<R> =\n\t| {\n\t\t\treadonly status: \"completed\";\n\t\t\treadonly result: R;\n\t\t\treadonly error?: never;\n\t\t\treadonly reason?: never;\n\t }\n\t/** Expected task or domain failure explicitly committed by its implementation. */\n\t| {\n\t\t\treadonly status: \"failed\";\n\t\t\treadonly error: TaskOutcomeError;\n\t\t\treadonly result?: R;\n\t\t\treadonly reason?: never;\n\t }\n\t/** Explicit cancellation handled by the task's abort protocol. */\n\t| {\n\t\t\treadonly status: \"aborted\";\n\t\t\treadonly reason?: string;\n\t\t\treadonly result?: R;\n\t\t\treadonly error?: never;\n\t }\n\t/** Task that cannot resume because its definition or migration is unavailable. */\n\t| {\n\t\t\treadonly status: \"orphaned\";\n\t\t\treadonly reason: string;\n\t\t\treadonly result?: never;\n\t\t\treadonly error?: never;\n\t }\n\t/** Runtime-detected contract failure, such as an uncaught throw or no durable progress. */\n\t| {\n\t\t\treadonly status: \"faulted\";\n\t\t\treadonly error: TaskOutcomeError;\n\t\t\treadonly result?: never;\n\t\t\treadonly reason?: never;\n\t };\n\n/** Complete durable execution state of a task. */\nexport type TaskState<S, R> =\n\t| {\n\t\t\t/** Eligible for scheduling. */\n\t\t\treadonly status: \"pending\";\n\t\t\t/** Complete durable state from which execution resumes. */\n\t\t\treadonly checkpoint: S;\n\t\t\treadonly outcome?: never;\n\t }\n\t| {\n\t\t\t/** Reserved by one in-memory task invocation. */\n\t\t\treadonly status: \"running\";\n\t\t\t/** Complete durable state from which execution resumes. */\n\t\t\treadonly checkpoint: S;\n\t\t\treadonly outcome?: never;\n\t }\n\t| {\n\t\t\t/** Parked without an invocation until every task in `on` is terminal; then resumes at `checkpoint`. */\n\t\t\treadonly status: \"waiting\";\n\t\t\treadonly checkpoint: S;\n\t\t\treadonly on: readonly TaskId[];\n\t\t\treadonly policy: JoinPolicy;\n\t\t\treadonly outcome?: never;\n\t }\n\t| {\n\t\t\t/** Outcome decided; becomes terminal once no ordinary owned work below is live. Runs no more code. */\n\t\t\treadonly status: \"completing\";\n\t\t\treadonly checkpoint?: never;\n\t\t\treadonly outcome: TaskOutcome<R>;\n\t }\n\t| {\n\t\t\t/** Permanently settled durable result receipt. */\n\t\t\treadonly status: \"terminal\";\n\t\t\treadonly checkpoint?: never;\n\t\t\treadonly outcome: TaskOutcome<R>;\n\t };\n\n/** Identity, definition, and scheduling fields shared by every task state. */\ntype TaskRecordBase<I, R> = {\n\treadonly id: TaskId<R>;\n\treadonly conversationId: ConversationId;\n\t/** Registered task definition name. */\n\treadonly kind: string;\n\t/** Definition version used to migrate live input and checkpoints. */\n\treadonly version: number;\n\t/** Original task input retained while the task is live or terminal. */\n\treadonly input: I;\n\t/** Owning task of a child task; absent for a task its conversation owns. Immutable. */\n\treadonly owner?: TaskId;\n\t/** Whether this conversation-owned task is excluded from ordinary idle waits, conversation aborts, and cascades. */\n\treadonly background: boolean;\n\t/** Durable abort mark checked before run-mode progress is committed. */\n\treadonly abortRequested: boolean;\n};\n\n/** Complete replacement record for one durable task state machine. */\nexport type TaskRecord<I, S, R> = TaskRecordBase<I, R> &\n\t(\n\t\t| {\n\t\t\t\treadonly state: Extract<TaskState<S, R>, { readonly status: \"pending\" | \"running\" | \"waiting\" }>;\n\t\t\t\t/** Small first-writer-wins values retained while the task can run. */\n\t\t\t\treadonly memos?: Readonly<Record<string, JsonValue>>;\n\t\t }\n\t\t| {\n\t\t\t\treadonly state: Extract<TaskState<S, R>, { readonly status: \"completing\" | \"terminal\" }>;\n\t\t\t\treadonly memos?: never;\n\t\t }\n\t);\n\n/** Persisted lifecycle record for one create-to-retire document incarnation. */\nexport type DocumentRecord = {\n\t/** Unique incarnation ID; never reused when the same logical document is recreated. */\n\treadonly id: DocumentId;\n\t/** Stable document definition kind. */\n\treadonly kind: string;\n\t/** Family member key; absent for singleton documents. */\n\treadonly key?: string;\n\t/** Commit that created the incarnation, stamped by storage. */\n\treadonly createdAt: Seq;\n\t/** Commit that retired the incarnation; absent while it is current. */\n\treadonly retiredAt?: Seq;\n} & (\n\t| {\n\t\t\treadonly scope: { readonly kind: \"session\" };\n\t\t\treadonly history?: never;\n\t\t\treadonly fork?: never;\n\t }\n\t| ({ readonly scope: { readonly kind: \"conversation\"; readonly conversationId: ConversationId } } & (\n\t\t\t| {\n\t\t\t\t\t/** Retain only current state. */\n\t\t\t\t\treadonly history: \"latest\";\n\t\t\t\t\t/** Initialize a fork from current source state or the definition's initial value. */\n\t\t\t\t\treadonly fork: \"current\" | \"initial\";\n\t\t\t }\n\t\t\t| {\n\t\t\t\t\t/** Retain history needed for as-of reads. */\n\t\t\t\t\treadonly history: \"rewindable\";\n\t\t\t\t\t/** Initialize a fork at its cutoff, from current state, or from the initial value. */\n\t\t\t\t\treadonly fork: \"asOf\" | \"current\" | \"initial\";\n\t\t\t }\n\t ))\n\t| {\n\t\t\treadonly scope: { readonly kind: \"task\"; readonly taskId: TaskId };\n\t\t\treadonly history?: never;\n\t\t\treadonly fork?: never;\n\t }\n);\n\n/** Fields supplied when storage creates and stamps a new `DocumentRecord`. */\nexport type DocumentCreate = DocumentRecord extends infer Record\n\t? Record extends DocumentRecord\n\t\t? Omit<Record, \"createdAt\" | \"retiredAt\">\n\t\t: never\n\t: never;\n\n/** One ordered scan result and its optional continuation state. */\nexport type Page<T, C> = {\n\treadonly items: readonly T[];\n\treadonly next?: C;\n};\n\n/** Backend-owned JSON continuation state that callers only round-trip to the same scan. */\nexport type Cursor = Readonly<Record<string, JsonValue>>;\n\n/** Optional filters for an ordered conversation scan. */\nexport type ConversationQuery = {\n\treadonly ownerConversationId?: ConversationId;\n\treadonly ownerTaskId?: TaskId;\n};\n\n/** Inclusive ID bounds for a newest-first scan of one conversation's fork-aware history. */\nexport type EntryQuery = {\n\treadonly conversationId: ConversationId;\n\t/** Oldest entry ID that may be returned. */\n\treadonly minEntryId?: EntryId;\n\t/** Newest entry ID that may be returned. */\n\treadonly maxEntryId?: EntryId;\n};\n\n/** Optional filters for an ordered scan of durable task records. */\nexport type TaskQuery = {\n\treadonly conversationId?: ConversationId;\n\treadonly kind?: string;\n\treadonly status?: TaskState<JsonValue, JsonValue>[\"status\"];\n\treadonly abortRequested?: boolean;\n\treadonly background?: boolean;\n};\n\n/** Optional filters for an ordered scan of submission records. */\nexport type SubmissionQuery = {\n\treadonly conversationId?: ConversationId;\n\treadonly status?: SubmissionRecord[\"status\"];\n};\n\n/** Current state or one historical commit sequence used for document membership and content reads. */\nexport type DocumentPoint = Seq | \"current\";\n\n/** Exact logical identity of a singleton or one keyed family member. */\nexport type DocumentAddress = {\n\treadonly kind: string;\n\treadonly scope: DocumentRecord[\"scope\"];\n\t/** Absent selects the singleton; present selects one family member. */\n\treadonly key?: string;\n};\n\n/** Ordered scan of document incarnations alive in one exact scope at one point. */\nexport type DocumentQuery = {\n\treadonly scope: DocumentRecord[\"scope\"];\n\treadonly at: DocumentPoint;\n\treadonly kind?: string;\n};\n\n/** Complete checkpoint or Chord operation batch selected by the owning Session. */\nexport type DocumentContent =\n\t| {\n\t\t\treadonly version: number;\n\t\t\treadonly kind: \"base\";\n\t\t\treadonly value: JsonObject;\n\t }\n\t| {\n\t\t\treadonly version: number;\n\t\t\treadonly kind: \"delta\";\n\t\t\treadonly ops: readonly Op[];\n\t };\n\n/** Exact persisted source selected for a definition-free document copy. */\nexport type DocumentCopySource = {\n\treadonly id: DocumentId;\n\treadonly at: DocumentPoint;\n};\n\n/** Detached materialized value and stored definition version at a selected point. */\nexport type StoredDocument = {\n\treadonly record: DocumentRecord;\n\treadonly version: number;\n\treadonly value: JsonObject;\n\t/** Deltas replayed after the selected base to materialize `value`. */\n\treadonly deltasSinceBase: number;\n};\n\n/** One record or document mutation in an atomic storage commit. */\nexport type StorageWrite =\n\t| { readonly type: \"conversation\"; readonly value: ConversationRecord }\n\t| { readonly type: \"entry\"; readonly value: EntryRecord }\n\t| { readonly type: \"task\"; readonly value: TaskRecord<JsonValue, JsonValue, JsonValue> }\n\t| { readonly type: \"submission\"; readonly value: SubmissionRecord }\n\t| {\n\t\t\treadonly type: \"document.create\";\n\t\t\treadonly record: DocumentCreate;\n\t\t\treadonly content: Extract<DocumentContent, { readonly kind: \"base\" }>;\n\t }\n\t| { readonly type: \"document.copy\"; readonly record: DocumentCreate; readonly source: DocumentCopySource }\n\t| {\n\t\t\treadonly type: \"document.change\";\n\t\t\treadonly id: DocumentId;\n\t\t\treadonly content: DocumentContent;\n\t }\n\t| { readonly type: \"document.retire\"; readonly id: DocumentId };\n\n/** Committed change of one document incarnation. */\nexport type DocumentCommitChange =\n\t| {\n\t\t\treadonly type: \"document\";\n\t\t\treadonly record: DocumentRecord;\n\t\t\t/** Conversation owning the document; task documents derive it from their task record. Undefined only for Session documents. */\n\t\t\treadonly conversationId: ConversationId | undefined;\n\t\t\t/** Definition version of `value`; absent when this commit retired the incarnation. */\n\t\t\treadonly version: number | undefined;\n\t\t\t/** Exact adopted immutable revision, or `null` when this commit retired the incarnation. */\n\t\t\treadonly value: JsonObject | null;\n\t\t\t/** Exact adopted operations for an ordinary update; empty for creation and retirement. */\n\t\t\treadonly ops: readonly Op[];\n\t }\n\t| {\n\t\t\t/** Definition-free child initialization; consumers hydrate through state or watch acquisition. */\n\t\t\treadonly type: \"document.copy\";\n\t\t\treadonly record: DocumentRecord;\n\t\t\treadonly conversationId: ConversationId;\n\t\t\treadonly source: DocumentCopySource;\n\t };\n\n/** Complete table record committed without another publication copy. */\nexport type TableCommitChange = Extract<\n\tStorageWrite,\n\t{ readonly type: \"conversation\" | \"entry\" | \"task\" | \"submission\" }\n>;\n\nexport type CommitChange = TableCommitChange | DocumentCommitChange;\n\n/** Every immutable change from one successful Session commit. Change order is unspecified. */\nexport type CommitPublication = {\n\treadonly seq: Seq;\n\treadonly changes: readonly CommitChange[];\n};\n\n/**\n * Transaction surface of one Session commit callback.\n * Table reads and creation results are trusted immutable values and may be shared with internal commit state.\n */\nexport interface Tx {\n\tconversation(id: ConversationId): Promise<ConversationRecord | undefined>;\n\tentry(id: EntryId): Promise<EntryRecord | undefined>;\n\t/** Undefined when the entry is absent or has another kind. */\n\tentry<D extends JsonValue>(token: Entry<D>, id: EntryId): Promise<TypedEntry<D> | undefined>;\n\ttask(id: TaskId): Promise<TaskRecord<JsonValue, JsonValue, JsonValue> | undefined>;\n\tscanConversations(\n\t\tquery: ConversationQuery,\n\t\tlimit: number,\n\t\tcursor?: Cursor,\n\t): Promise<Page<ConversationRecord, Cursor>>;\n\tscanEntries(query: EntryQuery, limit: number, cursor?: Cursor): Promise<Page<EntryRecord, Cursor>>;\n\t/** Newest visible entry of the conversation that carries a `head`. */\n\tlatestHeadMarker(conversationId: ConversationId): Promise<(EntryRecord & { readonly head: EntryId }) | undefined>;\n\tscanTasks(\n\t\tquery: TaskQuery,\n\t\tlimit: number,\n\t\tcursor?: Cursor,\n\t): Promise<Page<TaskRecord<JsonValue, JsonValue, JsonValue>, Cursor>>;\n\t/** Committed submission with a conversation-scoped request ID. */\n\tsubmissionByRequest(conversationId: ConversationId, requestId: string): Promise<SubmissionRecord | undefined>;\n\n\t/** Create a conversation with explicitly selected ownership. */\n\tcreateConversation(options: { readonly ownership: ConversationOwnership }): Promise<ConversationRecord>;\n\t/** Create a history fork at one concrete visible entry with explicitly selected ownership. */\n\tforkConversation(\n\t\tparentConversationId: ConversationId,\n\t\tat: EntryId,\n\t\toptions: { readonly ownership: ConversationOwnership },\n\t): Promise<ConversationRecord>;\n\t/** Returned records are Session-owned immutable values and may be shared with commit listeners. */\n\tappendEntry(conversationId: ConversationId, value: EntryDraft): Promise<EntryRecord>;\n\t/** The token supplies `kind` and types `data`. */\n\tappendEntry<D extends JsonValue>(\n\t\ttoken: Entry<D>,\n\t\tconversationId: ConversationId,\n\t\tvalue: TypedEntryDraft<NoInfer<D>>,\n\t): Promise<TypedEntry<D>>;\n\tcreateTask<I, S extends { phase: string }, R, H extends object>(\n\t\ttask: Task<I, S, R, H>,\n\t\tinput: I,\n\t\toptions: TaskOptions,\n\t): Promise<TaskId<R>>;\n\t/**\n\t * Create a raw submission record with a fresh ID. No admission rules apply: no busy check, no inbox queueing, no\n\t * placement. Use `Conversation.submit()` or a conversation handle unless the caller implements admission itself.\n\t */\n\tcreateSubmission(create: SubmissionCreate): Promise<SubmissionRecord>;\n\t/**\n\t * Settle a queued or placed submission; only a placed input can be answered, and a settled submission stays\n\t * unchanged. Resolved against this transaction's latest record of the submission, so it works after table writes.\n\t * Run tasks settle the inputs they answer.\n\t */\n\tsettleSubmission(id: SubmissionId, settlement: SubmissionSettlement): void;\n\t/**\n\t * Place a queued submission at `entry`: an input becomes `placed`, a write `done`. Resolved like\n\t * `settleSubmission()`. Inbox boundaries place the submissions they select.\n\t */\n\tplaceSubmission(id: SubmissionId, entry: EntryId): void;\n\n\tdoc<T extends JsonObject>(token: SessionDocToken<T>): Promise<Draft<T>>;\n\tdoc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId): Promise<Draft<T>>;\n\tdoc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId): Promise<Draft<T>>;\n\tdoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: SessionDocFamilyToken<T, I>,\n\t\tkey: string,\n\t\tseed: I,\n\t): Promise<Draft<T>>;\n\tdoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: ConversationDocFamilyToken<T, I>,\n\t\tconversationId: ConversationId,\n\t\tkey: string,\n\t\tseed: I,\n\t): Promise<Draft<T>>;\n\tdoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: TaskDocFamilyToken<T, I>,\n\t\ttaskId: TaskId,\n\t\tkey: string,\n\t\tseed: I,\n\t): Promise<Draft<T>>;\n\n\tretireDoc<T extends JsonObject>(token: SessionDocToken<T>): Promise<void>;\n\tretireDoc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId): Promise<void>;\n\tretireDoc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId): Promise<void>;\n\tretireDoc<T extends JsonObject, I extends JsonValue>(token: SessionDocFamilyToken<T, I>, key: string): Promise<void>;\n\tretireDoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: ConversationDocFamilyToken<T, I>,\n\t\tconversationId: ConversationId,\n\t\tkey: string,\n\t): Promise<void>;\n\tretireDoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: TaskDocFamilyToken<T, I>,\n\t\ttaskId: TaskId,\n\t\tkey: string,\n\t): Promise<void>;\n}\n\n/** Disposable, read-only Chord state bound to one committed document incarnation. */\nexport type DocumentState<T extends JsonObject> = AttachedReplicatedState<Readonly<T> | null>;\n\n/** Terminal result of one document watch. */\nexport type WatchEnd =\n\t| { readonly reason: \"stopped\" | \"cancelled\" | \"session_closed\" | \"retired\" }\n\t| { readonly reason: \"listener_error\"; readonly error: Error };\n\n/** Serialized exact-frame observation of an immutable value with bounded pending delivery. */\nexport interface WatchHandle<T> {\n\t/** Acquisition revision before start; latest delivered immutable revision afterward. */\n\treadonly value: T;\n\t/** Install the sole asynchronous listener. Never invokes it inline. */\n\tstart(listener: (value: T, ops: readonly Op[], context: Context) => Promise<void>): void;\n\t/** Idempotently stop future callbacks and return this watch's terminal result. */\n\tstop(): Promise<WatchEnd>;\n\t/** Settle when the watch terminates; an already-running callback remains caller-owned. */\n\treadonly closed: Promise<WatchEnd>;\n}\n\nexport type DocumentWatch<T extends JsonObject> = WatchHandle<Readonly<T> | null>;\n\n/** Committed document reads. */\nexport type DocumentReader = Pick<Session, \"snapshot\" | \"snapshotAsOf\">;\n\n/** Non-creating document watch acquisition shared by Session and later invocation APIs. */\nexport interface DocumentObserver {\n\twatchDoc<T extends JsonObject>(token: SessionDocToken<T>, context: Context): Promise<DocumentWatch<T> | undefined>;\n\twatchDoc<T extends JsonObject>(\n\t\ttoken: ConversationDocToken<T>,\n\t\tconversationId: ConversationId,\n\t\tcontext: Context,\n\t): Promise<DocumentWatch<T> | undefined>;\n\twatchDoc<T extends JsonObject>(\n\t\ttoken: TaskDocToken<T>,\n\t\ttaskId: TaskId,\n\t\tcontext: Context,\n\t): Promise<DocumentWatch<T> | undefined>;\n\twatchDoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: SessionDocFamilyToken<T, I>,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<DocumentWatch<T> | undefined>;\n\twatchDoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: ConversationDocFamilyToken<T, I>,\n\t\tconversationId: ConversationId,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<DocumentWatch<T> | undefined>;\n\twatchDoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: TaskDocFamilyToken<T, I>,\n\t\ttaskId: TaskId,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<DocumentWatch<T> | undefined>;\n}\n\n/** Owner of one mutation line, its records, and its tracked documents. */\nexport interface Session extends DocumentObserver {\n\t/** Run one atomic transaction on the Session mutation line. */\n\tcommit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T>;\n\t/** Seal admission, settle admitted commits, then close storage. */\n\tclose(context: Context): Promise<void>;\n\t/** Observe complete commits synchronously after adoption. The listener must not throw, block, or call Session APIs. */\n\tsubscribeCommits(listener: (publication: CommitPublication, context: Context) => void): () => void;\n\t/** Observe close synchronously when it begins. The listener must not throw, block, or call Session APIs. */\n\tsubscribeClose(listener: () => void): () => void;\n\n\tsnapshot<T extends JsonObject>(token: SessionDocToken<T>, context: Context): Promise<Readonly<T> | undefined>;\n\tsnapshot<T extends JsonObject>(\n\t\ttoken: ConversationDocToken<T>,\n\t\tconversationId: ConversationId,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n\tsnapshot<T extends JsonObject>(\n\t\ttoken: TaskDocToken<T>,\n\t\ttaskId: TaskId,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n\tsnapshot<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: SessionDocFamilyToken<T, I>,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n\tsnapshot<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: ConversationDocFamilyToken<T, I>,\n\t\tconversationId: ConversationId,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n\tsnapshot<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: TaskDocFamilyToken<T, I>,\n\t\ttaskId: TaskId,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n\n\tdocumentState<T extends JsonObject>(\n\t\ttoken: SessionDocToken<T>,\n\t\tcontext: Context,\n\t): Promise<DocumentState<T> | undefined>;\n\tdocumentState<T extends JsonObject>(\n\t\ttoken: ConversationDocToken<T>,\n\t\tconversationId: ConversationId,\n\t\tcontext: Context,\n\t): Promise<DocumentState<T> | undefined>;\n\tdocumentState<T extends JsonObject>(\n\t\ttoken: TaskDocToken<T>,\n\t\ttaskId: TaskId,\n\t\tcontext: Context,\n\t): Promise<DocumentState<T> | undefined>;\n\tdocumentState<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: SessionDocFamilyToken<T, I>,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<DocumentState<T> | undefined>;\n\tdocumentState<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: ConversationDocFamilyToken<T, I>,\n\t\tconversationId: ConversationId,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<DocumentState<T> | undefined>;\n\tdocumentState<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: TaskDocFamilyToken<T, I>,\n\t\ttaskId: TaskId,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<DocumentState<T> | undefined>;\n\n\tsnapshotAsOf<T extends JsonObject>(\n\t\ttoken: RewindableConversationDocToken<T>,\n\t\tconversationId: ConversationId,\n\t\tat: EntryId,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n\tsnapshotAsOf<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: RewindableConversationDocFamilyToken<T, I>,\n\t\tconversationId: ConversationId,\n\t\tkey: string,\n\t\tat: EntryId,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n}\n\n/**\n * Atomic persistence boundary for Session records.\n *\n * Storage trusts the owning Session to supply semantically valid records, references,\n * ancestry, and transitions. Implementations enforce atomicity, global ID ownership,\n * immutable conversation/entry creation, document record consistency, and detached values;\n * Session serializes commits.\n */\nexport interface Storage {\n\t/**\n\t * Atomically persist one batch and return its sequence. Once resolved, later reads through this storage observe it.\n\t */\n\tcommit(writes: readonly StorageWrite[], context: Context): Promise<Seq>;\n\n\t/** Return a fresh branded candidate from the Session-global numeric ID namespace. */\n\tmintId<I extends Id<string>>(): Promise<I>;\n\n\t/** Look up one conversation by exact ID. */\n\tconversation(id: ConversationId, context: Context): Promise<ConversationRecord | undefined>;\n\n\t/** Scan conversations in ascending ID order. */\n\tscanConversations(\n\t\tquery: ConversationQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\tcontext: Context,\n\t): Promise<Page<ConversationRecord, Cursor>>;\n\n\t/** Look up one global entry and the sequence of the commit that persisted it. */\n\tentry(id: EntryId, context: Context): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\t/** Look up one entry only when it is visible through the requested conversation's ancestry. */\n\tentry(\n\t\tconversationId: ConversationId,\n\t\tid: EntryId,\n\t\tcontext: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\n\t/**\n\t * Return the newest visible entry with a `head` at or below the optional inclusive cutoff.\n\t * The returned entry is the marker; its `head` value is the range's actual lower bound.\n\t */\n\tfindLatestHeadMarker(\n\t\tconversationId: ConversationId,\n\t\tatOrBeforeEntryId: EntryId | undefined,\n\t\tcontext: Context,\n\t): Promise<(EntryRecord & { readonly head: EntryId }) | undefined>;\n\n\t/** Scan the inclusive visible range newest-first, returning at most `limit` entries. */\n\tscanEntries(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\tcontext: Context,\n\t): Promise<Page<EntryRecord, Cursor>>;\n\n\t/** Look up the latest complete record for one task. */\n\ttask(id: TaskId, context: Context): Promise<TaskRecord<JsonValue, JsonValue, JsonValue> | undefined>;\n\n\t/** Scan task records matching every supplied filter. */\n\tscanTasks(\n\t\tquery: TaskQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\tcontext: Context,\n\t): Promise<Page<TaskRecord<JsonValue, JsonValue, JsonValue>, Cursor>>;\n\n\t/** Look up the latest complete record for one admitted submission. */\n\tsubmission(id: SubmissionId, context: Context): Promise<SubmissionRecord | undefined>;\n\n\t/** Scan submissions matching every supplied filter in ascending ID order. */\n\tscanSubmissions(\n\t\tquery: SubmissionQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\tcontext: Context,\n\t): Promise<Page<SubmissionRecord, Cursor>>;\n\n\t/** Find a submission by its conversation-scoped host deduplication key. */\n\tsubmissionByRequest(\n\t\tconversationId: ConversationId,\n\t\trequestId: string,\n\t\tcontext: Context,\n\t): Promise<SubmissionRecord | undefined>;\n\n\t/** Resolve the incarnation occupying one exact logical address at the selected point. */\n\tfindDocument(address: DocumentAddress, at: DocumentPoint, context: Context): Promise<DocumentRecord | undefined>;\n\n\t/** Materialize one specific incarnation by ID at the selected point without following a replacement at its address. */\n\tdocument(id: DocumentId, at: DocumentPoint, context: Context): Promise<StoredDocument | undefined>;\n\n\t/** Scan incarnations alive in one exact scope at the selected point. */\n\tscanDocuments(\n\t\tquery: DocumentQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\tcontext: Context,\n\t): Promise<Page<DocumentRecord, Cursor>>;\n\n\t/** Release backend resources; all later operations must reject. */\n\tclose(context: Context): Promise<void>;\n}\n", "import type { Context } from \"@earendil-works/chord\";\nimport { addressId } from \"../documents.ts\";\nimport type {\n\tConversationId,\n\tCursor,\n\tDocumentCopySource,\n\tDocumentCreate,\n\tDocumentId,\n\tDocumentPoint,\n\tDocumentRecord,\n\tEntryId,\n\tStorage,\n} from \"../types.ts\";\n\nconst SCAN_PAGE_SIZE = 256;\n\ntype ForkPolicy = \"asOf\" | \"current\";\n\n/** One definition-free document copy to create with a forked conversation. */\nexport type ForkDocumentCopy = {\n\treadonly record: DocumentCreate;\n\treadonly source: DocumentCopySource;\n};\n\n/** Select every persisted conversation document copied by one fork. */\nexport async function prepareForkDocumentCopies(\n\tstorage: Storage,\n\tparentConversationId: ConversationId,\n\tat: EntryId,\n\tchildConversationId: ConversationId,\n\tcontext: Context,\n): Promise<readonly ForkDocumentCopy[]> {\n\tconst entry = await storage.entry(parentConversationId, at, context);\n\tif (entry === undefined) throw new Error(`Entry ${at} is not visible from conversation ${parentConversationId}`);\n\n\tconst copies: ForkDocumentCopy[] = [];\n\tconst copiedAddresses = new Set<string>();\n\tawait collectCopies(\n\t\tstorage,\n\t\t{ kind: \"conversation\", conversationId: entry.entry.conversationId },\n\t\tentry.commitSeq,\n\t\t\"asOf\",\n\t\tchildConversationId,\n\t\tcopies,\n\t\tcopiedAddresses,\n\t\tcontext,\n\t);\n\tawait collectCopies(\n\t\tstorage,\n\t\t{ kind: \"conversation\", conversationId: parentConversationId },\n\t\t\"current\",\n\t\t\"current\",\n\t\tchildConversationId,\n\t\tcopies,\n\t\tcopiedAddresses,\n\t\tcontext,\n\t);\n\treturn copies;\n}\n\nasync function collectCopies(\n\tstorage: Storage,\n\tscope: Extract<DocumentRecord[\"scope\"], { readonly kind: \"conversation\" }>,\n\tat: DocumentPoint,\n\tpolicy: ForkPolicy,\n\tchildConversationId: ConversationId,\n\tcopies: ForkDocumentCopy[],\n\tcopiedAddresses: Set<string>,\n\tcontext: Context,\n): Promise<void> {\n\tlet cursor: Cursor | undefined;\n\tdo {\n\t\tconst page = await storage.scanDocuments({ scope, at }, SCAN_PAGE_SIZE, cursor, context);\n\t\tfor (const source of page.items) {\n\t\t\tif (source.scope.kind !== \"conversation\" || source.fork !== policy) continue;\n\t\t\tconst id = await storage.mintId<DocumentId>();\n\t\t\tconst identity = {\n\t\t\t\tid,\n\t\t\t\tkind: source.kind,\n\t\t\t\t...(source.key === undefined ? {} : { key: source.key }),\n\t\t\t\tscope: { kind: \"conversation\" as const, conversationId: childConversationId },\n\t\t\t};\n\t\t\tconst record: DocumentCreate =\n\t\t\t\tsource.history === \"latest\"\n\t\t\t\t\t? { ...identity, history: \"latest\", fork: source.fork }\n\t\t\t\t\t: { ...identity, history: \"rewindable\", fork: source.fork };\n\t\t\tconst copyAddress = addressId(record);\n\t\t\tif (copiedAddresses.has(copyAddress)) {\n\t\t\t\tconst member = record.key === undefined ? record.kind : `${record.kind}/${record.key}`;\n\t\t\t\tthrow new Error(`Fork selects multiple source documents for ${member}`);\n\t\t\t}\n\t\t\tcopiedAddresses.add(copyAddress);\n\t\t\tcopies.push({ record, source: { id: source.id, at } });\n\t\t}\n\t\tcursor = page.next;\n\t} while (cursor !== undefined);\n}\n", "import { type Context, copyJson, type Draft, type JsonValue } from \"@earendil-works/chord\";\nimport { type Change, type Op, type Prepared, type Tracker, track } from \"@earendil-works/chord/delta\";\nimport {\n\ttype AnyDocDefinition,\n\ttype AnyDocToken,\n\taddressId,\n\tcheckRecordScope,\n\tcheckRecordVersion,\n\tdocumentCreate,\n\tmaterializeDocumentValue,\n\ttype ResolvedAddress,\n\tresolveAddress,\n} from \"../documents.ts\";\nimport { ReadAfterWrite } from \"../errors.ts\";\nimport type {\n\tConversationDocFamilyToken,\n\tConversationDocToken,\n\tConversationId,\n\tConversationOwnership,\n\tConversationQuery,\n\tConversationRecord,\n\tCursor,\n\tDocumentAddress,\n\tDocumentCommitChange,\n\tDocumentCopySource,\n\tDocumentCreate,\n\tDocumentId,\n\tDocumentRecord,\n\tEntry,\n\tEntryDraft,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tJsonObject,\n\tSeq,\n\tSessionDocFamilyToken,\n\tSessionDocToken,\n\tStorage,\n\tStorageWrite,\n\tSubmissionCreate,\n\tSubmissionId,\n\tSubmissionRecord,\n\tSubmissionSettlement,\n\tTask,\n\tTaskDocFamilyToken,\n\tTaskDocToken,\n\tTaskId,\n\tTaskOptions,\n\tTaskQuery,\n\tTaskRecord,\n\tTx,\n\tTypedEntry,\n\tTypedEntryDraft,\n} from \"../types.ts\";\nimport { ROOT_CONVERSATION_ID } from \"../types.ts\";\nimport { prepareForkDocumentCopies } from \"./forks.ts\";\n\ntype AnyTaskRecord = TaskRecord<JsonValue, JsonValue, JsonValue>;\n\n/** A staged submission change: a settlement, or the placement of a queued submission at its entry. */\ntype SubmissionChange = SubmissionSettlement | { readonly status: \"placed\"; readonly entry: EntryId };\n\n/**\n * Complete record after applying one change. Placement turns a queued input `placed` and a queued write `done`; only a\n * placed input can be answered. A settled record stays.\n */\nfunction applySubmissionChange(current: SubmissionRecord, change: SubmissionChange): SubmissionRecord {\n\tif (current.status === \"done\" || current.status === \"unanswered\") return current;\n\tif (change.status === \"placed\") {\n\t\tif (current.status !== \"queued\") throw new Error(`Submission ${current.id} is not queued`);\n\t\tconst status = current.type === \"input\" ? \"placed\" : \"done\";\n\t\treturn { ...current, status, entry: change.entry } as SubmissionRecord;\n\t}\n\tif (change.status === \"done\" && current.status !== \"placed\") {\n\t\tthrow new Error(`Submission ${current.id} is not a placed input`);\n\t}\n\t// Queued and placed records carry no answer, reason, or detail; an unanswered input keeps its entry.\n\treturn { ...current, ...change } as SubmissionRecord;\n}\n\nconst INTERNAL_SCAN_PAGE_SIZE = 256;\nconst EMPTY_OPERATIONS: readonly Op[] = [];\nconst TABLE_JSON_COPY_OPTIONS = { omitUndefinedProperties: true } as const;\n\n/** One committed document incarnation owned by the Session tracker cache. */\nexport type LoadedDocument = {\n\treadonly addressId: string;\n\treadonly record: DocumentRecord;\n\t/** Persisted definition version; older while the tracked value is migrated only in memory. */\n\tstoredVersion: number;\n\t/** Definition version whose shape the tracked value has; access with another version reloads from Storage. */\n\treadonly valueVersion: number;\n\t/** Stored deltas after the newest base; advanced by adoption so the next predicate call needs no read. */\n\tdeltasSinceBase: number;\n\treadonly tracker: Tracker<JsonObject>;\n};\n\n/** Session services used by a transaction while it holds the mutation line. */\nexport interface TransactionHost {\n\treadonly storage: Storage;\n\t/** Return the cached current incarnation without loading. */\n\tcached(addressId: string): LoadedDocument | undefined;\n\t/** Return the cached current incarnation, cold-loading and migrating it when necessary. */\n\tload(\n\t\tdefinition: AnyDocDefinition,\n\t\taddressId: string,\n\t\taddress: DocumentAddress,\n\t\tcontext: Context,\n\t): Promise<LoadedDocument | undefined>;\n\t/** Install a newly committed incarnation. */\n\tinstall(document: LoadedDocument): void;\n\t/** Remove a retired incarnation if it is still the cached occupant of its address. */\n\tevict(addressId: string, recordId: DocumentId): void;\n\t/** Stage writes that belong to every newly created or forked conversation, in its creating transaction. */\n\tconversationCreated(tx: Transaction, record: ConversationRecord): Promise<void>;\n}\n\n/** Committed and candidate state for one task touched by this transaction. */\ntype TransactionTask = {\n\tcommittedRead?: Promise<AnyTaskRecord | undefined>;\n\twrite?: { readonly kind: \"create\" | \"replace\"; readonly record: AnyTaskRecord };\n\tpublicationConversationId?: ConversationId;\n};\n\n/** Defaults a commit binds to: `tx.createTask()` conversation and the task attributed to appended entries. */\nexport type TransactionScope = {\n\treadonly conversationId?: ConversationId;\n\t/** Task whose runtime commit this is; stamped as `byTaskId` on appended entries. */\n\treadonly taskId?: TaskId;\n};\n\n/** Storage/cache provenance of one staged document incarnation. */\ntype DocumentTarget =\n\t| { readonly kind: \"loaded\"; readonly document: LoadedDocument }\n\t| {\n\t\t\treadonly kind: \"created\";\n\t\t\treadonly record: DocumentCreate;\n\t\t\treadonly version: number;\n\t\t\treadonly tracker: Tracker<JsonObject>;\n\t }\n\t| {\n\t\t\treadonly kind: \"fork-copy\";\n\t\t\treadonly record: DocumentCreate;\n\t\t\treadonly source: DocumentCopySource;\n\t }\n\t| { readonly kind: \"retire-only\"; readonly record: DocumentRecord };\n\n/** One document incarnation acquired, created, or retired by this transaction. */\ntype DocumentEntry = {\n\treadonly addressId: string;\n\treadonly address: DocumentAddress;\n\t/** Absent for definition-free fork copies and retirement entries discovered by a terminal-task scan. */\n\tdefinition?: AnyDocDefinition;\n\t/** Memoized public acquisition; absent for metadata-only retirement. */\n\tdraftPromise?: Promise<Draft<JsonObject>>;\n\t/** Set after acquisition or retirement lookup finds the affected incarnation. */\n\ttarget?: DocumentTarget;\n\tchange?: Change<JsonObject>;\n\tprepared?: Prepared<JsonObject>;\n\tretireOnCommit: boolean;\n};\n\n/**\n * What one staged incarnation writes and publishes, decided once before Storage admission so adoption only applies it.\n * `record` is a `DocumentRecord` for an incarnation that is already committed and a `DocumentCreate` for a new one.\n */\ntype DocumentPlan = {\n\treadonly addressId: string;\n\treadonly record: DocumentCreate | DocumentRecord;\n\tretire: boolean;\n\t/** Creation, copy, or change content; absent when only retirement is written. */\n\tcontent?: Extract<StorageWrite, { readonly type: \"document.create\" | \"document.copy\" | \"document.change\" }>;\n\t/** Prepared change of a tracked incarnation; absent for fork copies and retirement-only entries. */\n\treadonly change?: {\n\t\treadonly tracker: Tracker<JsonObject>;\n\t\treadonly prepared: Prepared<JsonObject>;\n\t\treadonly version: number;\n\t\t/** The cached incarnation this change updates; absent when it creates one. */\n\t\treadonly loaded?: LoadedDocument;\n\t\treadonly definition?: AnyDocDefinition;\n\t};\n\t/** Resolved before Storage admission so adoption performs no reads. */\n\tconversationId?: ConversationId;\n};\n\n/**\n * Transaction for one Session commit callback.\n *\n * Every asynchronous operation is tracked so callback settlement can reject and drain unfinished work. Session calls\n * one settlement method, then either discards prepared changes or adopts them once after Storage succeeds.\n */\nexport class Transaction implements Tx {\n\treadonly #host: TransactionHost;\n\treadonly #context: Context;\n\treadonly #scope: TransactionScope;\n\treadonly #pendingOperations = new Set<Promise<unknown>>();\n\t#sealed = false;\n\t#hasTableWrite = false;\n\n\t/** Atomic batch; conversation and entry writes stage eagerly, while task and document writes assemble later. */\n\treadonly #writes: StorageWrite[] = [];\n\treadonly #createdConversationIds = new Set<ConversationId>();\n\treadonly #forkSourceConversationIds = new Set<ConversationId>();\n\treadonly #forkSourceDocumentIds = new Set<DocumentId>();\n\t/** One entry per task touched by a public read, candidate write, or document-owner lookup. */\n\treadonly #tasksById = new Map<TaskId, TransactionTask>();\n\t/** Submissions created by this transaction, by ID. */\n\treadonly #submissions = new Map<SubmissionId, SubmissionRecord>();\n\t/** Submission settlements and placements in staging order; resolved against the latest candidate record during assembly. */\n\treadonly #submissionChanges: { readonly id: SubmissionId; readonly change: SubmissionChange }[] = [];\n\n\t/** Write and publication plans of every staged incarnation, built during assembly. */\n\treadonly #plans: DocumentPlan[] = [];\n\t/** Every document acquisition or retirement marker in staging order. */\n\treadonly #documents: DocumentEntry[] = [];\n\t/** Latest transaction-local incarnation or retirement marker at each logical address. */\n\treadonly #latestDocumentByAddress = new Map<string, DocumentEntry>();\n\n\tconstructor(host: TransactionHost, context: Context, scope: TransactionScope = {}) {\n\t\tthis.#host = host;\n\t\tthis.#context = context;\n\t\tthis.#scope = scope;\n\t}\n\n\t// ─── Table reads ────────────────────────────────────────────────────────\n\n\tconversation(id: ConversationId): Promise<ConversationRecord | undefined> {\n\t\treturn this.#read(\"conversation\", () => this.#host.storage.conversation(id, this.#context));\n\t}\n\n\tentry(id: EntryId): Promise<EntryRecord | undefined>;\n\tentry<D extends JsonValue>(token: Entry<D>, id: EntryId): Promise<TypedEntry<D> | undefined>;\n\tentry(first: EntryId | { readonly kind: string }, second?: EntryId): Promise<EntryRecord | undefined> {\n\t\tconst kind = typeof first === \"number\" ? undefined : first.kind;\n\t\tconst id = typeof first === \"number\" ? first : second!;\n\t\treturn this.#read(\"entry\", async () => {\n\t\t\tconst entry = (await this.#host.storage.entry(id, this.#context))?.entry;\n\t\t\treturn kind === undefined || entry?.kind === kind ? entry : undefined;\n\t\t});\n\t}\n\n\ttask(id: TaskId): Promise<AnyTaskRecord | undefined> {\n\t\treturn this.#read(\"task\", () => this.#committedTask(id));\n\t}\n\n\tscanConversations(query: ConversationQuery, limit: number, cursor?: Cursor) {\n\t\treturn this.#read(\"scanConversations\", () =>\n\t\t\tthis.#host.storage.scanConversations(query, limit, cursor, this.#context),\n\t\t);\n\t}\n\n\tscanEntries(query: EntryQuery, limit: number, cursor?: Cursor) {\n\t\treturn this.#read(\"scanEntries\", () => this.#host.storage.scanEntries(query, limit, cursor, this.#context));\n\t}\n\n\tlatestHeadMarker(conversationId: ConversationId) {\n\t\treturn this.#read(\"latestHeadMarker\", () =>\n\t\t\tthis.#host.storage.findLatestHeadMarker(conversationId, undefined, this.#context),\n\t\t);\n\t}\n\n\tscanTasks(query: TaskQuery, limit: number, cursor?: Cursor) {\n\t\treturn this.#read(\"scanTasks\", () => this.#host.storage.scanTasks(query, limit, cursor, this.#context));\n\t}\n\n\t/** Internal: committed submission record. */\n\tsubmission(id: SubmissionId): Promise<SubmissionRecord | undefined> {\n\t\treturn this.#read(\"submission\", () => this.#host.storage.submission(id, this.#context));\n\t}\n\n\t/** Committed submission with a conversation-scoped request ID. */\n\tsubmissionByRequest(conversationId: ConversationId, requestId: string): Promise<SubmissionRecord | undefined> {\n\t\treturn this.#read(\"submissionByRequest\", () =>\n\t\t\tthis.#host.storage.submissionByRequest(conversationId, requestId, this.#context),\n\t\t);\n\t}\n\n\t// ─── Table writes ───────────────────────────────────────────────────────\n\n\tcreateConversation(options: { readonly ownership: ConversationOwnership }): Promise<ConversationRecord> {\n\t\treturn this.#write(() => this.#stageConversation(undefined, options.ownership));\n\t}\n\n\t/** Internal final-form bootstrap path for the reserved root identity. */\n\tcreateRootConversation(): Promise<ConversationRecord> {\n\t\treturn this.#write(() => this.#stageConversation(undefined, { kind: \"ownerless\" }, ROOT_CONVERSATION_ID));\n\t}\n\n\tforkConversation(\n\t\tparentConversationId: ConversationId,\n\t\tat: EntryId,\n\t\toptions: { readonly ownership: ConversationOwnership },\n\t): Promise<ConversationRecord> {\n\t\treturn this.#write(() =>\n\t\t\tthis.#stageConversation({ conversationId: parentConversationId, at }, options.ownership),\n\t\t);\n\t}\n\n\tasync #stageConversation(\n\t\tparent: NonNullable<ConversationRecord[\"parent\"]> | undefined,\n\t\townership: ConversationOwnership,\n\t\treservedId?: ConversationId,\n\t): Promise<ConversationRecord> {\n\t\tconst ownerTaskId = ownership.kind === \"task\" ? ownership.taskId : undefined;\n\t\tconst id = reservedId ?? (await this.#host.storage.mintId<ConversationId>());\n\t\tthis.#assertOpen();\n\t\tlet owner: ConversationRecord[\"owner\"];\n\t\tif (ownerTaskId !== undefined) {\n\t\t\tconst task = await this.#currentTask(ownerTaskId);\n\t\t\tthis.#assertOpen();\n\t\t\tif (task === undefined) throw new Error(`Conversation owner task ${ownerTaskId} does not exist`);\n\t\t\towner = { conversationId: task.conversationId, taskId: ownerTaskId };\n\t\t}\n\t\tconst record: ConversationRecord = {\n\t\t\tid,\n\t\t\t...(parent === undefined ? {} : { parent }),\n\t\t\t...(owner === undefined ? {} : { owner }),\n\t\t};\n\t\tconst copies =\n\t\t\tparent === undefined\n\t\t\t\t? []\n\t\t\t\t: await prepareForkDocumentCopies(this.#host.storage, parent.conversationId, parent.at, id, this.#context);\n\t\tthis.#assertOpen();\n\t\tfor (const copy of copies) {\n\t\t\tthis.#forkSourceDocumentIds.add(copy.source.id);\n\t\t\tconst entry: DocumentEntry = {\n\t\t\t\taddressId: addressId(copy.record),\n\t\t\t\taddress: copy.record,\n\t\t\t\ttarget: { kind: \"fork-copy\", ...copy },\n\t\t\t\tretireOnCommit: false,\n\t\t\t};\n\t\t\tthis.#documents.push(entry);\n\t\t\tthis.#latestDocumentByAddress.set(entry.addressId, entry);\n\t\t}\n\t\tif (parent !== undefined) this.#forkSourceConversationIds.add(parent.conversationId);\n\t\tthis.#createdConversationIds.add(id);\n\t\tthis.#writes.push({ type: \"conversation\", value: record });\n\t\tawait this.#host.conversationCreated(this, record);\n\t\tthis.#assertOpen();\n\t\treturn record;\n\t}\n\n\tappendEntry(conversationId: ConversationId, value: EntryDraft): Promise<EntryRecord>;\n\tappendEntry<D extends JsonValue>(\n\t\ttoken: Entry<D>,\n\t\tconversationId: ConversationId,\n\t\tvalue: TypedEntryDraft<NoInfer<D>>,\n\t): Promise<TypedEntry<D>>;\n\tappendEntry(\n\t\tfirst: ConversationId | { readonly kind: string },\n\t\tsecond: ConversationId | EntryDraft,\n\t\tthird?: object,\n\t): Promise<EntryRecord> {\n\t\tif (typeof first === \"number\") return this.#appendEntry(first, second as EntryDraft);\n\t\treturn this.#appendEntry(second as ConversationId, { ...third, kind: first.kind } as EntryDraft);\n\t}\n\n\t#appendEntry(conversationId: ConversationId, value: EntryDraft): Promise<EntryRecord> {\n\t\treturn this.#write(async () => {\n\t\t\tawait this.#requireConversation(conversationId);\n\t\t\tthis.#assertOpen();\n\t\t\tconst id = await this.#host.storage.mintId<EntryId>();\n\t\t\tthis.#assertOpen();\n\t\t\tconst { head, ...rest } = value;\n\t\t\t// Undefined `head` and `byTaskId` are omitted by the copy.\n\t\t\tconst record = copyJson(\n\t\t\t\t{\n\t\t\t\t\t...rest,\n\t\t\t\t\tid,\n\t\t\t\t\tconversationId,\n\t\t\t\t\thead: head === \"self\" ? id : head,\n\t\t\t\t\tbyTaskId: this.#scope.taskId,\n\t\t\t\t},\n\t\t\t\tTABLE_JSON_COPY_OPTIONS,\n\t\t\t) as unknown as EntryRecord;\n\t\t\tthis.#writes.push({ type: \"entry\", value: record });\n\t\t\treturn record;\n\t\t});\n\t}\n\n\tcreateTask<I, S extends { phase: string }, R, H extends object>(\n\t\ttask: Task<I, S, R, H>,\n\t\tinput: I,\n\t\toptions: TaskOptions,\n\t): Promise<TaskId<R>> {\n\t\treturn this.#write(async () => {\n\t\t\tconst ownership = options.ownership;\n\t\t\tlet owner: AnyTaskRecord | undefined;\n\t\t\tif (ownership.kind === \"task\") {\n\t\t\t\t// Validated again against the owner's final candidate during assembly.\n\t\t\t\towner = await this.#currentTask(ownership.taskId);\n\t\t\t\tthis.#assertOpen();\n\t\t\t\tif (owner === undefined) throw new Error(`Task owner ${ownership.taskId} does not exist`);\n\t\t\t\tif (options.background === true) throw new TypeError(\"A child task cannot be background\");\n\t\t\t\tif (options.conversationId !== undefined && options.conversationId !== owner.conversationId) {\n\t\t\t\t\tthrow new Error(`A child task lives in its owner's conversation ${owner.conversationId}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst conversationId = owner?.conversationId ?? options.conversationId ?? this.#scope.conversationId;\n\t\t\tif (conversationId === undefined) throw new TypeError(\"Tx.createTask() requires options.conversationId\");\n\t\t\tawait this.#requireConversation(conversationId);\n\t\t\tthis.#assertOpen();\n\t\t\tconst definition = task.definition;\n\t\t\tconst checkpoint = definition.initial(input);\n\t\t\tconst id = await this.#host.storage.mintId<TaskId<R>>();\n\t\t\tthis.#assertOpen();\n\t\t\tconst record = copyJson(\n\t\t\t\t{\n\t\t\t\t\tid,\n\t\t\t\t\tconversationId,\n\t\t\t\t\tkind: definition.name,\n\t\t\t\t\tversion: definition.version,\n\t\t\t\t\tinput,\n\t\t\t\t\t...(owner === undefined ? {} : { owner: owner.id }),\n\t\t\t\t\tbackground: options.background ?? false,\n\t\t\t\t\tabortRequested: false,\n\t\t\t\t\tstate: { status: \"pending\", checkpoint },\n\t\t\t\t},\n\t\t\t\tTABLE_JSON_COPY_OPTIONS,\n\t\t\t) as unknown as AnyTaskRecord;\n\t\t\tthis.#tasksById.set(id, { write: { kind: \"create\", record } });\n\t\t\treturn id;\n\t\t});\n\t}\n\n\t/** Create a raw submission record with a fresh ID; no admission rules apply. */\n\tcreateSubmission(create: SubmissionCreate): Promise<SubmissionRecord> {\n\t\treturn this.#write(async () => {\n\t\t\tawait this.#requireConversation(create.conversationId);\n\t\t\tthis.#assertOpen();\n\t\t\tconst id = await this.#host.storage.mintId<SubmissionId>();\n\t\t\tthis.#assertOpen();\n\t\t\tconst record = copyJson({ ...create, id }, TABLE_JSON_COPY_OPTIONS) as unknown as SubmissionRecord;\n\t\t\tthis.#submissions.set(id, record);\n\t\t\treturn record;\n\t\t});\n\t}\n\n\t/**\n\t * Settle a submission. Resolved during assembly against the transaction's latest candidate record, falling back to\n\t * committed state, so it is not a caller table read and works after the first table write.\n\t */\n\tsettleSubmission(id: SubmissionId, settlement: SubmissionSettlement): void {\n\t\tthis.#assertOpen();\n\t\tthis.#hasTableWrite = true;\n\t\tthis.#submissionChanges.push({ id, change: copyJson(settlement) as SubmissionSettlement });\n\t}\n\n\t/** Place a queued submission at `entry`; resolved during assembly like `settleSubmission()`. */\n\tplaceSubmission(id: SubmissionId, entry: EntryId): void {\n\t\tthis.#assertOpen();\n\t\tthis.#hasTableWrite = true;\n\t\tthis.#submissionChanges.push({ id, change: { status: \"placed\", entry } });\n\t}\n\n\t/** Internal: replace one task record completely. Tasks change their own state through their runtime. */\n\tsetTask(value: AnyTaskRecord): void {\n\t\tthis.#assertOpen();\n\t\tthis.#hasTableWrite = true;\n\t\tconst task = this.#taskEntry(value.id);\n\t\tconst candidate = task.write?.record;\n\t\tif (candidate?.state.status === \"terminal\") {\n\t\t\tthrow new Error(`Task ${value.id} already has a terminal candidate`);\n\t\t}\n\t\tif (candidate !== undefined && candidate.conversationId !== value.conversationId) {\n\t\t\tthrow new Error(`Task ${value.id} cannot change conversations`);\n\t\t}\n\t\ttask.write = {\n\t\t\tkind: task.write?.kind === \"create\" ? \"create\" : \"replace\",\n\t\t\trecord: copyJson(value, TABLE_JSON_COPY_OPTIONS) as unknown as AnyTaskRecord,\n\t\t};\n\t}\n\n\t/** Internal: candidate records of the tasks this transaction created or replaced so far. */\n\tstagedTasks(): AnyTaskRecord[] {\n\t\tconst records: AnyTaskRecord[] = [];\n\t\tfor (const task of this.#tasksById.values()) if (task.write !== undefined) records.push(task.write.record);\n\t\treturn records;\n\t}\n\n\t/** Internal: conversations this transaction created or forked so far. */\n\tstagedConversations(): ConversationRecord[] {\n\t\tconst records: ConversationRecord[] = [];\n\t\tfor (const write of this.#writes) if (write.type === \"conversation\") records.push(write.value);\n\t\treturn records;\n\t}\n\n\t// ─── Documents ──────────────────────────────────────────────────────────\n\tdoc<T extends JsonObject>(token: SessionDocToken<T>): Promise<Draft<T>>;\n\tdoc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId): Promise<Draft<T>>;\n\tdoc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId): Promise<Draft<T>>;\n\tdoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: SessionDocFamilyToken<T, I>,\n\t\tkey: string,\n\t\tseed: I,\n\t): Promise<Draft<T>>;\n\tdoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: ConversationDocFamilyToken<T, I>,\n\t\tconversationId: ConversationId,\n\t\tkey: string,\n\t\tseed: I,\n\t): Promise<Draft<T>>;\n\tdoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: TaskDocFamilyToken<T, I>,\n\t\ttaskId: TaskId,\n\t\tkey: string,\n\t\tseed: I,\n\t): Promise<Draft<T>>;\n\tdoc(token: AnyDocToken, ...args: readonly unknown[]): Promise<Draft<JsonObject>> {\n\t\ttry {\n\t\t\tthis.#assertOpen();\n\t\t\tconst definition = token.definition;\n\t\t\tconst resolved = resolveAddress(definition, args);\n\t\t\tthis.#assertTaskDocumentsOpen(resolved);\n\t\t\tconst latest = this.#latestDocumentByAddress.get(resolved.id);\n\t\t\tif (latest !== undefined && !latest.retireOnCommit) {\n\t\t\t\tif (latest.draftPromise !== undefined) return latest.draftPromise;\n\t\t\t\tif (latest.target?.kind === \"fork-copy\") {\n\t\t\t\t\tlatest.draftPromise = this.#track(this.#acquireForkCopy(latest, definition, latest.target));\n\t\t\t\t\treturn latest.draftPromise;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst seed = definition.family === true ? copyJson(args[resolved.nextArgument]) : undefined;\n\t\t\tconst docEntry: DocumentEntry = {\n\t\t\t\taddressId: resolved.id,\n\t\t\t\taddress: resolved.address,\n\t\t\t\tdefinition,\n\t\t\t\tretireOnCommit: false,\n\t\t\t};\n\t\t\tthis.#documents.push(docEntry);\n\t\t\tthis.#latestDocumentByAddress.set(docEntry.addressId, docEntry);\n\t\t\t// Capture retirement before awaiting so a pending old acquisition and its replacement stay distinct.\n\t\t\tdocEntry.draftPromise = this.#track(this.#acquire(docEntry, seed, latest?.retireOnCommit === true));\n\t\t\treturn docEntry.draftPromise;\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t}\n\n\tretireDoc<T extends JsonObject>(token: SessionDocToken<T>): Promise<void>;\n\tretireDoc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId): Promise<void>;\n\tretireDoc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId): Promise<void>;\n\tretireDoc<T extends JsonObject, I extends JsonValue>(token: SessionDocFamilyToken<T, I>, key: string): Promise<void>;\n\tretireDoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: ConversationDocFamilyToken<T, I>,\n\t\tconversationId: ConversationId,\n\t\tkey: string,\n\t): Promise<void>;\n\tretireDoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: TaskDocFamilyToken<T, I>,\n\t\ttaskId: TaskId,\n\t\tkey: string,\n\t): Promise<void>;\n\tretireDoc(token: AnyDocToken, ...args: readonly unknown[]): Promise<void> {\n\t\ttry {\n\t\t\tthis.#assertOpen();\n\t\t\tconst definition = token.definition;\n\t\t\tconst resolved = resolveAddress(definition, args);\n\t\t\tconst latest = this.#latestDocumentByAddress.get(resolved.id);\n\t\t\tif (latest?.retireOnCommit) return Promise.resolve();\n\t\t\tif (latest?.target?.kind === \"fork-copy\") {\n\t\t\t\tcheckRecordScope(definition, latest.target.record);\n\t\t\t\tlatest.retireOnCommit = true;\n\t\t\t\treturn Promise.resolve();\n\t\t\t}\n\t\t\tif (latest?.draftPromise !== undefined) {\n\t\t\t\t// Retirement of an acquired draft persists its final content before retirement.\n\t\t\t\tlatest.retireOnCommit = true;\n\t\t\t\treturn this.#track(latest.draftPromise.then(() => undefined));\n\t\t\t}\n\t\t\tconst entry: DocumentEntry = {\n\t\t\t\taddressId: resolved.id,\n\t\t\t\taddress: resolved.address,\n\t\t\t\tdefinition,\n\t\t\t\tretireOnCommit: true,\n\t\t\t};\n\t\t\tthis.#documents.push(entry);\n\t\t\tthis.#latestDocumentByAddress.set(entry.addressId, entry);\n\t\t\treturn this.#track(this.#findRetirement(entry));\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t}\n\n\tasync #acquire(entry: DocumentEntry, seed: JsonValue | undefined, skipLoad: boolean): Promise<Draft<JsonObject>> {\n\t\tconst definition = entry.definition!;\n\t\tconst loaded = skipLoad\n\t\t\t? undefined\n\t\t\t: await this.#host.load(definition, entry.addressId, entry.address, this.#context);\n\t\tthis.#assertOpen();\n\t\tif (loaded !== undefined) {\n\t\t\tcheckRecordScope(definition, loaded.record);\n\t\t\tcheckRecordVersion(definition, loaded.record, loaded.storedVersion);\n\t\t\tentry.target = { kind: \"loaded\", document: loaded };\n\t\t\tentry.change = loaded.tracker.beginChange();\n\t\t\treturn entry.change.state;\n\t\t}\n\t\tconst scope = entry.address.scope;\n\t\tif (scope.kind === \"conversation\") await this.#requireConversation(scope.conversationId);\n\t\tif (scope.kind === \"task\") {\n\t\t\tconst task = await this.#currentTask(scope.taskId);\n\t\t\tif (task === undefined) throw new Error(`Task ${scope.taskId} does not exist`);\n\t\t\tif (task.state.status === \"terminal\") throw new Error(`Task ${scope.taskId} is terminal`);\n\t\t}\n\t\tthis.#assertOpen();\n\t\tconst value = copyJson(\n\t\t\tdefinition.family === true ? definition.initial(seed) : definition.initial(),\n\t\t) as JsonObject;\n\t\tconst id = await this.#host.storage.mintId<DocumentId>();\n\t\tthis.#assertOpen();\n\t\tconst tracker = track(value);\n\t\tentry.target = {\n\t\t\tkind: \"created\",\n\t\t\trecord: documentCreate(definition, entry.address, id),\n\t\t\tversion: definition.version,\n\t\t\ttracker,\n\t\t};\n\t\tentry.change = tracker.beginChange();\n\t\treturn entry.change.state;\n\t}\n\n\tasync #acquireForkCopy(\n\t\tentry: DocumentEntry,\n\t\tdefinition: AnyDocDefinition,\n\t\ttarget: Extract<DocumentTarget, { readonly kind: \"fork-copy\" }>,\n\t): Promise<Draft<JsonObject>> {\n\t\tconst stored = await this.#host.storage.document(target.source.id, target.source.at, this.#context);\n\t\tthis.#assertOpen();\n\t\tif (stored === undefined) {\n\t\t\tthrow new Error(`Fork source document ${target.source.id} cannot be read`);\n\t\t}\n\t\tif (\n\t\t\tstored.record.scope.kind !== \"conversation\" ||\n\t\t\tstored.record.kind !== target.record.kind ||\n\t\t\tstored.record.key !== target.record.key ||\n\t\t\tstored.record.history !== target.record.history ||\n\t\t\tstored.record.fork !== target.record.fork\n\t\t) {\n\t\t\tthrow new Error(`Fork source document ${target.source.id} does not match the copied record`);\n\t\t}\n\t\tconst value = materializeDocumentValue(definition, target.record, stored.version, stored.value);\n\t\tconst tracker = track(value);\n\t\tentry.definition = definition;\n\t\tentry.target = { kind: \"created\", record: target.record, version: definition.version, tracker };\n\t\tentry.change = tracker.beginChange();\n\t\treturn entry.change.state;\n\t}\n\n\tasync #findRetirement(entry: DocumentEntry): Promise<void> {\n\t\tconst record =\n\t\t\tthis.#host.cached(entry.addressId)?.record ??\n\t\t\t(await this.#host.storage.findDocument(entry.address, \"current\", this.#context));\n\t\tthis.#assertOpen();\n\t\tif (record === undefined) return;\n\t\tcheckRecordScope(entry.definition!, record);\n\t\tentry.target = { kind: \"retire-only\", record };\n\t}\n\n\t// ─── Settlement ─────────────────────────────────────────────────────────\n\n\t/** Seal after callback failure: abort every change and observe every pending operation. */\n\tasync settleFailure(): Promise<void> {\n\t\tthis.#sealed = true;\n\t\tthis.#abortChanges();\n\t\tawait Promise.allSettled(this.#pendingOperations);\n\t}\n\n\t/**\n\t * Seal after callback success, prepare every open change, and assemble the atomic batch.\n\t * Any failure aborts every change before Storage admission.\n\t */\n\tasync settleSuccess(): Promise<readonly StorageWrite[]> {\n\t\tthis.#sealed = true;\n\t\tif (this.#pendingOperations.size > 0) {\n\t\t\tthis.#abortChanges();\n\t\t\tawait Promise.allSettled(this.#pendingOperations);\n\t\t\tthrow new Error(\"Session commit callback settled before its pending Tx operations\");\n\t\t}\n\t\ttry {\n\t\t\t// Synchronously prepare every open change; this revokes every draft.\n\t\t\tfor (const document of this.#documents) {\n\t\t\t\tif (document.change !== undefined) document.prepared = document.change.prepare();\n\t\t\t}\n\t\t\treturn await this.#assemble();\n\t\t} catch (error) {\n\t\t\tthis.#abortChanges();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/** Abort every prepared change after Storage failure or when no write is required. */\n\tdiscard(): void {\n\t\tthis.#abortChanges();\n\t}\n\n\t/** Adopt every prepared change by pointer swap after Storage success and describe the publication. */\n\tadopt(seq: Seq): DocumentCommitChange[] {\n\t\tconst publications: DocumentCommitChange[] = [];\n\t\tfor (const plan of this.#plans) {\n\t\t\tconst committed = \"createdAt\" in plan.record;\n\t\t\tlet record: DocumentRecord = committed ? (plan.record as DocumentRecord) : { ...plan.record, createdAt: seq };\n\t\t\tif (plan.retire) record = { ...record, retiredAt: seq };\n\t\t\tconst change = plan.change;\n\t\t\tif (change !== undefined) {\n\t\t\t\tconst { tracker, prepared, loaded, version } = change;\n\t\t\t\t// A new incarnation is adopted unless it retires in the same commit; a loaded one only when it changed.\n\t\t\t\tif (loaded === undefined ? !plan.retire : prepared.ops.length > 0) tracker.adopt(prepared);\n\t\t\t\telse prepared.abort();\n\t\t\t\tif (loaded !== undefined) {\n\t\t\t\t\tif (loaded.storedVersion < version) loaded.storedVersion = version;\n\t\t\t\t\tif (plan.content?.type === \"document.change\") {\n\t\t\t\t\t\tif (plan.content.content.kind === \"base\") loaded.deltasSinceBase = 0;\n\t\t\t\t\t\telse loaded.deltasSinceBase++;\n\t\t\t\t\t}\n\t\t\t\t} else if (!plan.retire) {\n\t\t\t\t\tthis.#host.install({\n\t\t\t\t\t\taddressId: plan.addressId,\n\t\t\t\t\t\trecord,\n\t\t\t\t\t\tstoredVersion: version,\n\t\t\t\t\t\tvalueVersion: version,\n\t\t\t\t\t\tdeltasSinceBase: 0,\n\t\t\t\t\t\ttracker,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst conversationId = plan.conversationId;\n\t\t\tif (plan.retire) {\n\t\t\t\tif (committed) this.#host.evict(plan.addressId, record.id);\n\t\t\t\tconst retired = { version: undefined, value: null, ops: EMPTY_OPERATIONS };\n\t\t\t\tpublications.push({ type: \"document\", record, conversationId, ...retired });\n\t\t\t} else if (plan.content?.type === \"document.copy\") {\n\t\t\t\tpublications.push({\n\t\t\t\t\ttype: \"document.copy\",\n\t\t\t\t\trecord,\n\t\t\t\t\tconversationId: conversationId!,\n\t\t\t\t\tsource: plan.content.source,\n\t\t\t\t});\n\t\t\t} else if (change !== undefined && publishes(plan)) {\n\t\t\t\tconst ops = change.loaded === undefined ? EMPTY_OPERATIONS : change.prepared.ops;\n\t\t\t\tpublications.push({\n\t\t\t\t\ttype: \"document\",\n\t\t\t\t\trecord,\n\t\t\t\t\tconversationId,\n\t\t\t\t\tversion: change.version,\n\t\t\t\t\tvalue: change.prepared.value,\n\t\t\t\t\tops,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn publications;\n\t}\n\n\tasync #assemble(): Promise<StorageWrite[]> {\n\t\tconst storage = this.#host.storage;\n\t\tconst plans = this.#plans;\n\t\tfor (const document of this.#documents) {\n\t\t\tconst plan = planDocument(document);\n\t\t\tif (plan !== undefined) plans.push(plan);\n\t\t}\n\t\tthis.#rejectForkSourceWrites(plans);\n\t\tawait this.#validateOwners();\n\t\tfor (const [id, task] of this.#tasksById) {\n\t\t\tif (task.write?.kind !== \"replace\") continue;\n\t\t\tconst committed = await this.#committedTask(id);\n\t\t\tif (committed === undefined) throw new Error(`Task ${id} does not exist`);\n\t\t\tif (committed.state.status === \"terminal\") throw new Error(`Task ${id} is already terminal`);\n\t\t\tif (committed.conversationId !== task.write.record.conversationId) {\n\t\t\t\tthrow new Error(`Task ${id} cannot change conversations`);\n\t\t\t}\n\t\t}\n\n\t\t// Terminal settlement retires every task document, including ones created by this transaction.\n\t\tconst terminalTaskIds = new Set<TaskId>();\n\t\tfor (const task of this.#tasksById.values()) {\n\t\t\tif (task.write?.record.state.status === \"terminal\") terminalTaskIds.add(task.write.record.id);\n\t\t}\n\t\tif (terminalTaskIds.size > 0) {\n\t\t\tconst retiring = new Set<DocumentId>();\n\t\t\tfor (const plan of plans) {\n\t\t\t\tconst scope = plan.record.scope;\n\t\t\t\tif (scope.kind !== \"task\" || !terminalTaskIds.has(scope.taskId)) continue;\n\t\t\t\tplan.retire = true;\n\t\t\t\tretiring.add(plan.record.id);\n\t\t\t}\n\t\t\tfor (const taskId of terminalTaskIds) {\n\t\t\t\tif (this.#tasksById.get(taskId)?.write?.kind === \"create\") continue;\n\t\t\t\tlet cursor: Cursor | undefined;\n\t\t\t\tdo {\n\t\t\t\t\tconst page = await storage.scanDocuments(\n\t\t\t\t\t\t{ scope: { kind: \"task\", taskId }, at: \"current\" },\n\t\t\t\t\t\tINTERNAL_SCAN_PAGE_SIZE,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t\tthis.#context,\n\t\t\t\t\t);\n\t\t\t\t\tfor (const record of page.items) {\n\t\t\t\t\t\tif (retiring.has(record.id)) continue;\n\t\t\t\t\t\tplans.push({ addressId: addressId(record), record, retire: true });\n\t\t\t\t\t\tretiring.add(record.id);\n\t\t\t\t\t}\n\t\t\t\t\tcursor = page.next;\n\t\t\t\t} while (cursor !== undefined);\n\t\t\t}\n\t\t}\n\n\t\t// Resolve publication ownership before Storage admission so adoption remains synchronous.\n\t\tfor (const plan of plans) {\n\t\t\tif (!publishes(plan)) continue;\n\t\t\tconst scope = plan.record.scope;\n\t\t\tif (scope.kind === \"conversation\") plan.conversationId = scope.conversationId;\n\t\t\tif (scope.kind !== \"task\") continue;\n\t\t\tconst task = this.#taskEntry(scope.taskId);\n\t\t\tif (task.publicationConversationId === undefined) {\n\t\t\t\tconst current = await this.#currentTask(scope.taskId);\n\t\t\t\tif (current !== undefined) task.publicationConversationId = current.conversationId;\n\t\t\t}\n\t\t\tplan.conversationId = task.publicationConversationId;\n\t\t}\n\n\t\tfor (const { id, change } of this.#submissionChanges) {\n\t\t\tconst current = this.#submissions.get(id) ?? (await storage.submission(id, this.#context));\n\t\t\tif (current === undefined) throw new Error(`Submission ${id} does not exist`);\n\t\t\tconst next = applySubmissionChange(current, change);\n\t\t\tif (next !== current) this.#submissions.set(id, next);\n\t\t}\n\n\t\tconst writes = this.#writes;\n\t\tfor (const value of this.#submissions.values()) writes.push({ type: \"submission\", value });\n\t\tfor (const task of this.#tasksById.values()) {\n\t\t\tif (task.write !== undefined) writes.push({ type: \"task\", value: task.write.record });\n\t\t}\n\t\tfor (const plan of plans) {\n\t\t\tconst change = plan.change;\n\t\t\t// Checkpoint predicates run last, after every validation.\n\t\t\tif (plan.content?.type === \"document.change\" && plan.content.content.kind === \"delta\" && change?.loaded) {\n\t\t\t\tconst { prepared, version } = change;\n\t\t\t\tconst info = { deltasSinceBase: change.loaded.deltasSinceBase };\n\t\t\t\tif (change.definition?.checkpointWhen?.(prepared.value, prepared.ops, info)) {\n\t\t\t\t\tplan.content = { ...plan.content, content: { version, kind: \"base\", value: prepared.value } };\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (plan.content !== undefined) writes.push(plan.content);\n\t\t\tif (plan.retire) writes.push({ type: \"document.retire\", id: plan.record.id });\n\t\t}\n\t\treturn writes;\n\t}\n\n\t// ─── Helpers ────────────────────────────────────────────────────────────\n\n\t/**\n\t * New owned work needs a live owner, judged on the owner's final candidate: not `completing`, terminal, or\n\t * abort-marked. A task therefore cannot create owned work in the commit that finishes it (spec §5.5).\n\t */\n\tasync #validateOwners(): Promise<void> {\n\t\tconst owners: { readonly what: string; readonly taskId: TaskId }[] = [];\n\t\tfor (const write of this.#writes) {\n\t\t\tif (write.type !== \"conversation\" || write.value.owner === undefined) continue;\n\t\t\towners.push({ what: \"Conversation owner task\", taskId: write.value.owner.taskId });\n\t\t}\n\t\tfor (const task of this.#tasksById.values()) {\n\t\t\tconst record = task.write?.kind === \"create\" ? task.write.record : undefined;\n\t\t\tif (record?.owner !== undefined) owners.push({ what: \"Task owner\", taskId: record.owner });\n\t\t}\n\t\tfor (const { what, taskId } of owners) {\n\t\t\tconst task = await this.#currentTask(taskId);\n\t\t\tif (task === undefined) throw new Error(`${what} ${taskId} does not exist`);\n\t\t\tif (task.state.status === \"terminal\" || task.state.status === \"completing\") {\n\t\t\t\tthrow new Error(`${what} ${taskId} is ${task.state.status}`);\n\t\t\t}\n\t\t\tif (task.abortRequested) throw new Error(`${what} ${taskId} is abort-marked`);\n\t\t}\n\t}\n\n\t#rejectForkSourceWrites(plans: readonly DocumentPlan[]): void {\n\t\tfor (const plan of plans) {\n\t\t\tif (plan.content === undefined && !plan.retire) continue;\n\t\t\tconst record = plan.record;\n\t\t\tif (this.#forkSourceDocumentIds.has(record.id)) {\n\t\t\t\tthrow new Error(`Cannot change fork source document ${record.id} in the fork transaction`);\n\t\t\t}\n\t\t\tconst scope = plan.record.scope;\n\t\t\tif (\n\t\t\t\tscope.kind === \"conversation\" &&\n\t\t\t\tthis.#forkSourceConversationIds.has(scope.conversationId) &&\n\t\t\t\trecord.scope.kind === \"conversation\" &&\n\t\t\t\trecord.fork === \"current\"\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Cannot fork conversation ${scope.conversationId} while changing its current-policy documents`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t#abortChanges(): void {\n\t\tfor (const document of this.#documents) document.change?.abort();\n\t}\n\n\t#assertOpen(): void {\n\t\tif (this.#sealed) throw new Error(\"Transaction has settled\");\n\t}\n\n\t#assertTaskDocumentsOpen(resolved: ResolvedAddress): void {\n\t\tconst scope = resolved.address.scope;\n\t\tif (scope.kind === \"task\" && this.#tasksById.get(scope.taskId)?.write?.record.state.status === \"terminal\") {\n\t\t\tthrow new Error(`Task ${scope.taskId} is terminal`);\n\t\t}\n\t}\n\n\t/** Register an operation so callback settlement can reject and drain it. */\n\t#track<T>(operation: Promise<T>): Promise<T> {\n\t\tthis.#pendingOperations.add(operation);\n\t\tconst settle = (): void => {\n\t\t\tthis.#pendingOperations.delete(operation);\n\t\t};\n\t\toperation.then(settle, settle);\n\t\treturn operation;\n\t}\n\n\t#read<T>(method: string, read: () => Promise<T>): Promise<T> {\n\t\ttry {\n\t\t\tthis.#assertOpen();\n\t\t\tif (this.#hasTableWrite) throw new ReadAfterWrite(method);\n\t\t\treturn this.#track(read());\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t}\n\n\t#write<T>(write: () => Promise<T>): Promise<T> {\n\t\ttry {\n\t\t\tthis.#assertOpen();\n\t\t\tthis.#hasTableWrite = true;\n\t\t\treturn this.#track(write());\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t}\n\n\tasync #requireConversation(id: ConversationId): Promise<void> {\n\t\tif (this.#createdConversationIds.has(id)) return;\n\t\tif ((await this.#host.storage.conversation(id, this.#context)) === undefined) {\n\t\t\tthrow new Error(`Conversation ${id} does not exist`);\n\t\t}\n\t}\n\n\t#taskEntry(id: TaskId): TransactionTask {\n\t\tlet task = this.#tasksById.get(id);\n\t\tif (task === undefined) {\n\t\t\ttask = {};\n\t\t\tthis.#tasksById.set(id, task);\n\t\t}\n\t\treturn task;\n\t}\n\n\t/** Latest candidate task record, falling back to committed state; not a caller table read. */\n\tasync #currentTask(id: TaskId): Promise<AnyTaskRecord | undefined> {\n\t\treturn this.#tasksById.get(id)?.write?.record ?? (await this.#committedTask(id));\n\t}\n\n\t#committedTask(id: TaskId): Promise<AnyTaskRecord | undefined> {\n\t\tconst task = this.#taskEntry(id);\n\t\ttask.committedRead ??= this.#host.storage.task(id, this.#context);\n\t\treturn task.committedRead;\n\t}\n}\n\n/** Plan of one staged document: its record, content write, and prepared change. Retirement is decided later. */\nfunction planDocument(document: DocumentEntry): DocumentPlan | undefined {\n\tconst target = document.target;\n\tif (target === undefined) return undefined;\n\tconst plan = { addressId: document.addressId, retire: document.retireOnCommit };\n\tswitch (target.kind) {\n\t\tcase \"created\": {\n\t\t\tconst prepared = document.prepared!;\n\t\t\tconst { record, version, tracker } = target;\n\t\t\tconst content = { version, kind: \"base\", value: prepared.value } as const;\n\t\t\treturn {\n\t\t\t\t...plan,\n\t\t\t\trecord,\n\t\t\t\tcontent: { type: \"document.create\", record, content },\n\t\t\t\tchange: { tracker, prepared, version },\n\t\t\t};\n\t\t}\n\t\tcase \"fork-copy\":\n\t\t\treturn {\n\t\t\t\t...plan,\n\t\t\t\trecord: target.record,\n\t\t\t\tcontent: { type: \"document.copy\", record: target.record, source: target.source },\n\t\t\t};\n\t\tcase \"retire-only\":\n\t\t\treturn { ...plan, record: target.record };\n\t\tcase \"loaded\": {\n\t\t\tconst loaded = target.document;\n\t\t\tconst definition = document.definition!;\n\t\t\tconst prepared = document.prepared!;\n\t\t\tconst version = definition.version;\n\t\t\tconst id = loaded.record.id;\n\t\t\t// A version change stores a base even without operations; otherwise only a change stores a delta.\n\t\t\tconst content =\n\t\t\t\tloaded.storedVersion < version\n\t\t\t\t\t? ({ type: \"document.change\", id, content: { version, kind: \"base\", value: prepared.value } } as const)\n\t\t\t\t\t: prepared.ops.length > 0\n\t\t\t\t\t\t? ({ type: \"document.change\", id, content: { version, kind: \"delta\", ops: prepared.ops } } as const)\n\t\t\t\t\t\t: undefined;\n\t\t\tconst change = {\n\t\t\t\ttracker: loaded.tracker,\n\t\t\t\tprepared,\n\t\t\t\tversion,\n\t\t\t\tloaded,\n\t\t\t\tdefinition,\n\t\t\t};\n\t\t\treturn { ...plan, record: loaded.record, change, ...(content === undefined ? {} : { content }) };\n\t\t}\n\t}\n}\n\n/**\n * Whether adoption publishes the plan: every creation, copy, and retirement, and a loaded incarnation that writes\n * content, which includes a migration-only base so observers of the older shape receive the new value.\n */\nfunction publishes(plan: DocumentPlan): boolean {\n\treturn plan.retire || plan.change?.loaded === undefined || plan.content !== undefined;\n}\n", "import { type Context, type JsonValue, replicatedState } from \"@earendil-works/chord\";\nimport { awaitWithContext, withoutAbortSignal } from \"@earendil-works/chord/context\";\nimport { type Op, track } from \"@earendil-works/chord/delta\";\nimport {\n\ttype AnyDocToken,\n\tcheckRecordScope,\n\tcheckRecordVersion,\n\tmaterializeDocument,\n\tresolveAddress,\n} from \"../documents.ts\";\nimport { StorageRejected } from \"../errors.ts\";\nimport { idFromNumber } from \"../ids.ts\";\nimport type {\n\tCommitChange,\n\tCommitPublication,\n\tConversationDocFamilyToken,\n\tConversationDocToken,\n\tConversationId,\n\tConversationRecord,\n\tDocumentAddress,\n\tDocumentCommitChange,\n\tDocumentRecord,\n\tDocumentState,\n\tDocumentWatch,\n\tEntryId,\n\tJsonObject,\n\tRewindableConversationDocFamilyToken,\n\tRewindableConversationDocToken,\n\tSeq,\n\tSession,\n\tSessionDocFamilyToken,\n\tSessionDocToken,\n\tStorage,\n\tStorageWrite,\n\tTaskDocFamilyToken,\n\tTaskDocToken,\n\tTaskId,\n\tTx,\n} from \"../types.ts\";\nimport {\n\tCommittedStateSource,\n\tCommittedWatch,\n\ttype ObservedDocumentValue,\n\tRETIREMENT_OPERATIONS,\n} from \"./observation.ts\";\nimport { type LoadedDocument, Transaction, type TransactionHost, type TransactionScope } from \"./transaction.ts\";\n\n/** Open a Session kernel over one storage backend. */\nexport function createSession(storage: Storage): Session {\n\treturn new SessionImpl(storage);\n}\n\n/**\n * Session kernel: one mutation line, the loaded document tracker cache, and committed publication.\n *\n * Only committed state is observable. Every commit callback, preparation, Storage settlement, adoption, and\n * publication enqueue runs while the line is held; listeners run later.\n */\nexport class SessionImpl implements Session {\n\treadonly #storage: Storage;\n\treadonly #documents = new Map<string, LoadedDocument>();\n\treadonly #commitListeners = new Set<(publication: CommitPublication, context: Context) => void>();\n\treadonly #closeListeners = new Set<() => void>();\n\treadonly #host: TransactionHost;\n\t#tail: Promise<void> = Promise.resolve();\n\t#closing: Promise<void> | undefined;\n\t#poison: { readonly error: unknown } | undefined;\n\n\tconstructor(storage: Storage) {\n\t\tthis.#storage = storage;\n\t\tthis.#host = {\n\t\t\tstorage,\n\t\t\tcached: (id) => this.#documents.get(id),\n\t\t\tload: (definition, addressId, address, context) => this.#loadDocument(definition, addressId, address, context),\n\t\t\tinstall: (document) => {\n\t\t\t\tthis.#documents.set(document.addressId, document);\n\t\t\t},\n\t\t\tevict: (id, recordId) => {\n\t\t\t\tif (this.#documents.get(id)?.record.id === recordId) this.#documents.delete(id);\n\t\t\t},\n\t\t\tconversationCreated: (tx, record) => this.conversationCreated(tx, record),\n\t\t};\n\t}\n\n\tcommit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T> {\n\t\treturn this.commitWith(change, context);\n\t}\n\n\t/**\n\t * Internal commit exposing the concrete transaction and its internal operations, such as the reserved-ID root\n\t * bootstrap and task replacement. `scope` sets the default `tx.createTask()` conversation and the task attributed to\n\t * appended entries.\n\t */\n\tcommitWith<T>(change: (tx: Transaction) => T | Promise<T>, context: Context, scope?: TransactionScope): Promise<T> {\n\t\ttry {\n\t\t\tthis.#assertUsable();\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t\treturn this.#enqueue(() => this.#runCommit(change, context, scope));\n\t}\n\n\t/** Internal: run a read-only job on the mutation line so multi-read derivations observe one committed state. */\n\treadOnLine<T>(job: () => Promise<T>): Promise<T> {\n\t\ttry {\n\t\t\tthis.#assertUsable();\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t\treturn this.#enqueue(async () => {\n\t\t\tthis.#assertHealthy();\n\t\t\treturn job();\n\t\t});\n\t}\n\n\t/**\n\t * Internal: a conversation document's current incarnation and value, for a job already running on the line (see\n\t * `readOnLine()`). Absent documents are `undefined`.\n\t */\n\tasync conversationDocumentOnLine(\n\t\ttoken: ConversationDocToken<JsonObject>,\n\t\tconversationId: ConversationId,\n\t\tcontext: Context,\n\t): Promise<{ readonly record: DocumentRecord; readonly version: number; readonly value: JsonObject } | undefined> {\n\t\tconst definition = token.definition;\n\t\tconst resolved = resolveAddress(definition, [conversationId, context]);\n\t\tconst loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context);\n\t\tif (loaded === undefined) return undefined;\n\t\tcheckRecordScope(definition, loaded.record);\n\t\tcheckRecordVersion(definition, loaded.record, loaded.storedVersion);\n\t\treturn { record: loaded.record, version: loaded.valueVersion, value: loaded.tracker.value };\n\t}\n\n\tsnapshot<T extends JsonObject>(token: SessionDocToken<T>, context: Context): Promise<Readonly<T> | undefined>;\n\tsnapshot<T extends JsonObject>(\n\t\ttoken: ConversationDocToken<T>,\n\t\tconversationId: ConversationId,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n\tsnapshot<T extends JsonObject>(\n\t\ttoken: TaskDocToken<T>,\n\t\ttaskId: TaskId,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n\tsnapshot<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: SessionDocFamilyToken<T, I>,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n\tsnapshot<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: ConversationDocFamilyToken<T, I>,\n\t\tconversationId: ConversationId,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n\tsnapshot<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: TaskDocFamilyToken<T, I>,\n\t\ttaskId: TaskId,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n\tasync snapshot(token: AnyDocToken, ...args: readonly unknown[]): Promise<JsonObject | undefined> {\n\t\tthis.#assertUsable();\n\t\tconst definition = token.definition;\n\t\tconst resolved = resolveAddress(definition, args);\n\t\tconst context = args[resolved.nextArgument] as Context;\n\t\tconst cached = this.#documents.get(resolved.id);\n\t\tconst loaded =\n\t\t\tcached?.valueVersion === definition.version\n\t\t\t\t? cached\n\t\t\t\t: await this.#enqueue(async () => {\n\t\t\t\t\t\tthis.#assertHealthy();\n\t\t\t\t\t\treturn this.#loadDocument(definition, resolved.id, resolved.address, context);\n\t\t\t\t\t});\n\t\tif (loaded === undefined) return undefined;\n\t\tcheckRecordScope(definition, loaded.record);\n\t\tcheckRecordVersion(definition, loaded.record, loaded.storedVersion);\n\t\treturn loaded.tracker.value;\n\t}\n\n\tdocumentState<T extends JsonObject>(\n\t\ttoken: SessionDocToken<T>,\n\t\tcontext: Context,\n\t): Promise<DocumentState<T> | undefined>;\n\tdocumentState<T extends JsonObject>(\n\t\ttoken: ConversationDocToken<T>,\n\t\tconversationId: ConversationId,\n\t\tcontext: Context,\n\t): Promise<DocumentState<T> | undefined>;\n\tdocumentState<T extends JsonObject>(\n\t\ttoken: TaskDocToken<T>,\n\t\ttaskId: TaskId,\n\t\tcontext: Context,\n\t): Promise<DocumentState<T> | undefined>;\n\tdocumentState<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: SessionDocFamilyToken<T, I>,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<DocumentState<T> | undefined>;\n\tdocumentState<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: ConversationDocFamilyToken<T, I>,\n\t\tconversationId: ConversationId,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<DocumentState<T> | undefined>;\n\tdocumentState<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: TaskDocFamilyToken<T, I>,\n\t\ttaskId: TaskId,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<DocumentState<T> | undefined>;\n\tdocumentState(token: AnyDocToken, ...args: readonly unknown[]): Promise<DocumentState<JsonObject> | undefined> {\n\t\ttry {\n\t\t\tthis.#assertUsable();\n\t\t\tconst definition = token.definition;\n\t\t\tconst resolved = resolveAddress(definition, args);\n\t\t\tconst context = args[resolved.nextArgument] as Context;\n\t\t\treturn this.#enqueue(async () => {\n\t\t\t\tthis.#assertHealthy();\n\t\t\t\tconst loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context);\n\t\t\t\tif (loaded === undefined) return undefined;\n\t\t\t\tconst { observer: source, detach } = this.#attachDocument(\n\t\t\t\t\tdefinition,\n\t\t\t\t\tloaded,\n\t\t\t\t\t(value, release) => new CommittedStateSource<ObservedDocumentValue>(value, release),\n\t\t\t\t);\n\t\t\t\ttry {\n\t\t\t\t\treturn replicatedState(source) as DocumentState<JsonObject>;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tdetach();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t}\n\n\twatchDoc<T extends JsonObject>(token: SessionDocToken<T>, context: Context): Promise<DocumentWatch<T> | undefined>;\n\twatchDoc<T extends JsonObject>(\n\t\ttoken: ConversationDocToken<T>,\n\t\tconversationId: ConversationId,\n\t\tcontext: Context,\n\t): Promise<DocumentWatch<T> | undefined>;\n\twatchDoc<T extends JsonObject>(\n\t\ttoken: TaskDocToken<T>,\n\t\ttaskId: TaskId,\n\t\tcontext: Context,\n\t): Promise<DocumentWatch<T> | undefined>;\n\twatchDoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: SessionDocFamilyToken<T, I>,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<DocumentWatch<T> | undefined>;\n\twatchDoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: ConversationDocFamilyToken<T, I>,\n\t\tconversationId: ConversationId,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<DocumentWatch<T> | undefined>;\n\twatchDoc<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: TaskDocFamilyToken<T, I>,\n\t\ttaskId: TaskId,\n\t\tkey: string,\n\t\tcontext: Context,\n\t): Promise<DocumentWatch<T> | undefined>;\n\tasync watchDoc(token: AnyDocToken, ...args: readonly unknown[]): Promise<DocumentWatch<JsonObject> | undefined> {\n\t\tthis.#assertUsable();\n\t\tconst definition = token.definition;\n\t\tconst resolved = resolveAddress(definition, args);\n\t\tconst context = args[resolved.nextArgument] as Context;\n\t\tconst signal = context.abortSignal;\n\t\tlet cancelled = signal?.aborted ?? false;\n\t\tconst markCancelled = (): void => {\n\t\t\tcancelled = true;\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", markCancelled, { once: true });\n\t\ttry {\n\t\t\tconst watch = await this.#enqueue(async () => {\n\t\t\t\tthis.#assertHealthy();\n\t\t\t\tif (cancelled) throw cancellationError(signal!);\n\t\t\t\tconst loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context);\n\t\t\t\tif (cancelled) throw cancellationError(signal!);\n\t\t\t\tif (loaded === undefined) return undefined;\n\t\t\t\treturn this.#attachDocument(\n\t\t\t\t\tdefinition,\n\t\t\t\t\tloaded,\n\t\t\t\t\t(value, release) => new CommittedWatch<ObservedDocumentValue>(value, release),\n\t\t\t\t).observer;\n\t\t\t});\n\t\t\tif (watch === undefined) return undefined;\n\t\t\tif (cancelled) {\n\t\t\t\twatch.cancel();\n\t\t\t\tthrow cancellationError(signal!);\n\t\t\t}\n\t\t\tif (signal !== undefined) watch.observeCancellation(signal);\n\t\t\treturn watch as DocumentWatch<JsonObject>;\n\t\t} finally {\n\t\t\tsignal?.removeEventListener(\"abort\", markCancelled);\n\t\t}\n\t}\n\n\tsnapshotAsOf<T extends JsonObject>(\n\t\ttoken: RewindableConversationDocToken<T>,\n\t\tconversationId: ConversationId,\n\t\tat: EntryId,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n\tsnapshotAsOf<T extends JsonObject, I extends JsonValue>(\n\t\ttoken: RewindableConversationDocFamilyToken<T, I>,\n\t\tconversationId: ConversationId,\n\t\tkey: string,\n\t\tat: EntryId,\n\t\tcontext: Context,\n\t): Promise<Readonly<T> | undefined>;\n\tasync snapshotAsOf(token: AnyDocToken, ...args: readonly unknown[]): Promise<JsonObject | undefined> {\n\t\tthis.#assertUsable();\n\t\tconst definition = token.definition;\n\t\tconst resolved = resolveAddress(definition, args);\n\t\tif (resolved.address.scope.kind !== \"conversation\") {\n\t\t\tthrow new TypeError(\"Session.snapshotAsOf() requires a conversation document\");\n\t\t}\n\t\tconst conversationId = resolved.address.scope.conversationId;\n\t\tconst atValue = args[resolved.nextArgument];\n\t\tif (typeof atValue !== \"number\" || !Number.isSafeInteger(atValue)) {\n\t\t\tthrow new TypeError(\"Session.snapshotAsOf() requires an entry ID\");\n\t\t}\n\t\tconst at = idFromNumber<EntryId>(atValue);\n\t\tconst context = args[resolved.nextArgument + 1] as Context;\n\t\treturn this.#enqueue(async () => {\n\t\t\tthis.#assertHealthy();\n\t\t\tconst storedEntry = await this.#storage.entry(conversationId, at, context);\n\t\t\tif (storedEntry === undefined) {\n\t\t\t\tthrow new Error(`Entry ${at} is not visible from conversation ${conversationId}`);\n\t\t\t}\n\t\t\tconst address: DocumentAddress = {\n\t\t\t\t...resolved.address,\n\t\t\t\tscope: { kind: \"conversation\", conversationId: storedEntry.entry.conversationId },\n\t\t\t};\n\t\t\tconst record = await this.#storage.findDocument(address, storedEntry.commitSeq, context);\n\t\t\tif (record === undefined) return undefined;\n\t\t\tconst stored = await this.#storage.document(record.id, storedEntry.commitSeq, context);\n\t\t\tif (stored === undefined) {\n\t\t\t\tthrow new Error(`Historical document ${record.id} (${record.kind}) cannot be read`);\n\t\t\t}\n\t\t\treturn materializeDocument(definition, stored);\n\t\t});\n\t}\n\n\tclose(context: Context): Promise<void> {\n\t\tif (this.#closing === undefined) {\n\t\t\tconst cleanup = withoutAbortSignal(context);\n\t\t\t// Seal admission before anything else runs, then stop observers; admitted work settles before Storage closes.\n\t\t\tthis.#closing = Promise.resolve()\n\t\t\t\t.then(() => this.beforeClose())\n\t\t\t\t.then(() =>\n\t\t\t\t\tthis.#enqueue(async () => {\n\t\t\t\t\t\tthis.#commitListeners.clear();\n\t\t\t\t\t\tthis.#documents.clear();\n\t\t\t\t\t\tawait this.#storage.close(cleanup);\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\tconst listeners = [...this.#closeListeners];\n\t\t\tthis.#closeListeners.clear();\n\t\t\tfor (const listener of listeners) listener();\n\t\t}\n\t\treturn awaitWithContext(this.#closing, context);\n\t}\n\n\t/**\n\t * Runs inside every transaction that creates or forks a conversation, after the conversation record is staged. A\n\t * plain Session stages nothing; a Harness stages its built-in documents.\n\t */\n\tprotected conversationCreated(_tx: Transaction, _record: ConversationRecord): Promise<void> {\n\t\treturn Promise.resolve();\n\t}\n\n\t/** Runs after close seals admission and before the line closes Storage; must not reject. */\n\tprotected beforeClose(): Promise<void> {\n\t\treturn Promise.resolve();\n\t}\n\n\t/** Register a synchronous post-adoption listener. It must not throw, block, or call Session operations. */\n\tsubscribeCommits(listener: (publication: CommitPublication, context: Context) => void): () => void {\n\t\tthis.#assertUsable();\n\t\tthis.#commitListeners.add(listener);\n\t\treturn () => this.#commitListeners.delete(listener);\n\t}\n\n\t/** Register a listener called synchronously when close begins. It must not throw, block, or call Session operations. */\n\tsubscribeClose(listener: () => void): () => void {\n\t\tthis.#assertUsable();\n\t\tthis.#closeListeners.add(listener);\n\t\treturn () => this.#closeListeners.delete(listener);\n\t}\n\n\t/** Drop every loaded tracker on the mutation line; later access cold-loads from Storage. */\n\tunloadDocuments(): Promise<void> {\n\t\treturn this.#enqueue(async () => {\n\t\t\tthis.#documents.clear();\n\t\t});\n\t}\n\n\tasync #runCommit<T>(\n\t\tchange: (tx: Transaction) => T | Promise<T>,\n\t\tcontext: Context,\n\t\tscope?: TransactionScope,\n\t): Promise<T> {\n\t\tthis.#assertHealthy();\n\t\tcontext.abortSignal?.throwIfAborted();\n\t\tconst tx = new Transaction(this.#host, context, scope);\n\t\tlet result: T;\n\t\ttry {\n\t\t\tresult = await change(tx);\n\t\t} catch (error) {\n\t\t\tawait tx.settleFailure();\n\t\t\tthrow error;\n\t\t}\n\t\tconst writes = await tx.settleSuccess();\n\t\tif (writes.length === 0) {\n\t\t\ttx.discard();\n\t\t\treturn result;\n\t\t}\n\t\tlet seq: Seq;\n\t\ttry {\n\t\t\t// Once admitted, caller cancellation does not interrupt Storage settlement.\n\t\t\tseq = await this.#storage.commit(writes, withoutAbortSignal(context));\n\t\t} catch (error) {\n\t\t\ttx.discard();\n\t\t\t// Callback errors never reach this branch; StorageRejected alone guarantees that no batch effect committed.\n\t\t\tif (!(error instanceof StorageRejected)) this.#poison = { error };\n\t\t\tthrow error;\n\t\t}\n\t\tlet documents: DocumentCommitChange[];\n\t\ttry {\n\t\t\tdocuments = tx.adopt(seq);\n\t\t} catch (error) {\n\t\t\t// Storage already committed; a failed adoption leaves memory behind durable state.\n\t\t\tthis.#poison = { error };\n\t\t\tthrow error;\n\t\t}\n\t\tthis.#publish(seq, writes, documents, context);\n\t\treturn result;\n\t}\n\n\t#publish(\n\t\tseq: Seq,\n\t\twrites: readonly StorageWrite[],\n\t\tdocuments: readonly DocumentCommitChange[],\n\t\tcontext: Context,\n\t): void {\n\t\tif (this.#commitListeners.size === 0) return;\n\t\tconst changes: CommitChange[] = [];\n\t\tfor (const write of writes) {\n\t\t\tswitch (write.type) {\n\t\t\t\tcase \"conversation\":\n\t\t\t\tcase \"entry\":\n\t\t\t\tcase \"task\":\n\t\t\t\tcase \"submission\":\n\t\t\t\t\tchanges.push(write);\n\t\t\t}\n\t\t}\n\t\tfor (const document of documents) changes.push(document);\n\t\tconst publication: CommitPublication = { seq, changes };\n\t\tfor (const listener of [...this.#commitListeners]) listener(publication, context);\n\t}\n\n\t/**\n\t * Attach an observer to one committed incarnation: check the definition, then forward this incarnation's committed\n\t * changes and close. `detach` removes both subscriptions.\n\t */\n\t#attachDocument<O extends CommittedStateSource | CommittedWatch>(\n\t\tdefinition: AnyDocToken[\"definition\"],\n\t\tloaded: LoadedDocument,\n\t\tcreate: (value: JsonObject, detach: () => void) => O,\n\t): { observer: O; detach: () => void } {\n\t\tcheckRecordScope(definition, loaded.record);\n\t\tcheckRecordVersion(definition, loaded.record, loaded.storedVersion);\n\t\tlet unsubscribeCommit = (): void => {};\n\t\tlet unsubscribeClose = (): void => {};\n\t\tconst detach = (): void => {\n\t\t\tunsubscribeCommit();\n\t\t\tunsubscribeClose();\n\t\t};\n\t\tconst observer = create(loaded.tracker.value, detach);\n\t\tconst observed = { version: loaded.valueVersion };\n\t\tunsubscribeCommit = this.subscribeCommits((publication, context) => {\n\t\t\tfor (const change of publication.changes) {\n\t\t\t\tif (change.type !== \"document\" || change.record.id !== loaded.record.id) continue;\n\t\t\t\t// A document state's frames carry no caller cancellation; a watch observes its own cancellation.\n\t\t\t\tconst frameContext = observer instanceof CommittedStateSource ? withoutAbortSignal(context) : context;\n\t\t\t\tconst ops = observedOperations(observed, change);\n\t\t\t\t// A migration-only base changes nothing for an observer of the new version.\n\t\t\t\tif (ops.length === 0) continue;\n\t\t\t\tobserver.advance(change.value, ops, frameContext);\n\t\t\t}\n\t\t});\n\t\tunsubscribeClose = this.subscribeClose(() => observer.closeSession());\n\t\treturn { observer, detach };\n\t}\n\n\tasync #loadDocument(\n\t\tdefinition: AnyDocToken[\"definition\"],\n\t\taddressId: string,\n\t\taddress: DocumentAddress,\n\t\tcontext: Context,\n\t): Promise<LoadedDocument | undefined> {\n\t\tconst cached = this.#documents.get(addressId);\n\t\t// A tracker serves only tokens of the version its value was materialized for; others reload from Storage.\n\t\tif (cached?.valueVersion === definition.version) return cached;\n\t\tif (cached !== undefined) this.#documents.delete(addressId);\n\t\tconst record = await this.#storage.findDocument(address, \"current\", context);\n\t\tif (record === undefined) return undefined;\n\t\tconst stored = await this.#storage.document(record.id, \"current\", context);\n\t\tif (stored === undefined) throw new Error(`Current document ${record.id} (${record.kind}) cannot be read`);\n\t\tconst value = materializeDocument(definition, stored);\n\t\tconst loaded: LoadedDocument = {\n\t\t\taddressId,\n\t\t\trecord: stored.record,\n\t\t\tstoredVersion: stored.version,\n\t\t\tvalueVersion: definition.version,\n\t\t\tdeltasSinceBase: stored.deltasSinceBase,\n\t\t\ttracker: track(value),\n\t\t};\n\t\tthis.#documents.set(addressId, loaded);\n\t\treturn loaded;\n\t}\n\n\t#enqueue<T>(job: () => Promise<T>): Promise<T> {\n\t\tconst run = this.#tail.then(job);\n\t\tthis.#tail = run.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn run;\n\t}\n\n\t#assertUsable(): void {\n\t\tif (this.#closing !== undefined) throw new Error(\"Session is closed\");\n\t\tthis.#assertHealthy();\n\t}\n\n\t#assertHealthy(): void {\n\t\tif (this.#poison !== undefined) {\n\t\t\tthrow new Error(\"Session is poisoned by a failed commit after storage admission; reopen it\", {\n\t\t\t\tcause: this.#poison.error,\n\t\t\t});\n\t\t}\n\t}\n}\n\n/**\n * Operations an observer applies for one committed change. An observer hydrated under another definition version holds\n * a differently shaped value, so it receives the new value as a root replacement instead of operations for that shape.\n */\nfunction observedOperations(\n\tobserved: { version: number },\n\tchange: Extract<DocumentCommitChange, { readonly type: \"document\" }>,\n): readonly Op[] {\n\tif (change.value === null) return RETIREMENT_OPERATIONS;\n\tif (change.version === observed.version) return change.ops;\n\tobserved.version = change.version!;\n\treturn [[\"r\", change.value]];\n}\n\nfunction cancellationError(signal: AbortSignal): Error {\n\treturn signal.reason instanceof Error ? signal.reason : new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n", "import { INSTRUCTIONS_KEY } from \"./agent.ts\";\nimport { CompactionTask } from \"./compaction.ts\";\nimport { GenerationTask } from \"./generation.ts\";\nimport { ToolTask } from \"./tool.ts\";\nimport type { AnyTask, Extension, PromptSection, Registry, RegistrySnapshot, ToolRegistration } from \"./types.ts\";\n\nconst SECTION_KEY = /^[a-z][a-z0-9_-]*$/;\n\n/** Built-in task definitions every registry holds; they are not an extension and cannot be removed or replaced. */\nexport const BUILTIN_TASKS: readonly AnyTask[] = [GenerationTask, ToolTask, CompactionTask];\n\n/** Immutable published registry state. */\nclass RegistryState<Tool extends ToolRegistration> implements RegistrySnapshot<Tool> {\n\treadonly #extensions: readonly Extension<Tool>[];\n\treadonly #byName: ReadonlyMap<string, Extension<Tool>>;\n\treadonly #tasks: ReadonlyMap<string, AnyTask>;\n\n\tconstructor(extensions: readonly Extension<Tool>[]) {\n\t\tthis.#extensions = extensions;\n\t\tthis.#byName = new Map(extensions.map((extension) => [extension.name, extension]));\n\t\tconst tasks = new Map<string, AnyTask>();\n\t\tfor (const task of BUILTIN_TASKS) tasks.set(task.definition.name, task);\n\t\tfor (const extension of extensions) {\n\t\t\tfor (const task of extension.tasks ?? []) {\n\t\t\t\tconst name = task.definition.name;\n\t\t\t\tif (tasks.has(name)) throw new Error(`Task ${name} of extension ${extension.name} is already installed`);\n\t\t\t\ttasks.set(name, task);\n\t\t\t}\n\t\t}\n\t\tthis.#tasks = tasks;\n\t}\n\n\tinstalled(): readonly Extension<Tool>[] {\n\t\treturn this.#extensions;\n\t}\n\n\textension(name: string): Extension<Tool> | undefined {\n\t\treturn this.#byName.get(name);\n\t}\n\n\ttools(): readonly { readonly extension: Extension<Tool>; readonly tool: Tool }[] {\n\t\treturn this.#extensions.flatMap((extension) => (extension.tools ?? []).map((tool) => ({ extension, tool })));\n\t}\n\n\tsections(): readonly { readonly extension: Extension<Tool>; readonly section: PromptSection<Tool> }[] {\n\t\treturn this.#extensions.flatMap((extension) =>\n\t\t\t(extension.sections ?? []).map((section) => ({ extension, section })),\n\t\t);\n\t}\n\n\ttasks(): readonly AnyTask[] {\n\t\treturn [...this.#tasks.values()];\n\t}\n\n\ttask(name: string): AnyTask | undefined {\n\t\treturn this.#tasks.get(name);\n\t}\n}\n\nclass RegistryImpl<Tool extends ToolRegistration> implements Registry<Tool> {\n\t#current = new RegistryState<Tool>([]);\n\treadonly #listeners = new Set<() => void>();\n\n\tsnapshot(): RegistrySnapshot<Tool> {\n\t\treturn this.#current;\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\tthis.#listeners.add(listener);\n\t\treturn () => this.#listeners.delete(listener);\n\t}\n\n\tinstall(extension: Extension<Tool>): void {\n\t\tvalidateExtension(extension);\n\t\tconst current = this.#current.installed();\n\t\tconst index = current.findIndex((installed) => installed.name === extension.name);\n\t\tconst next =\n\t\t\tindex < 0 ? [...current, extension] : current.map((installed, at) => (at === index ? extension : installed));\n\t\tthis.#publish(next);\n\t}\n\n\tuninstall(extension: Extension): void {\n\t\tconst current = this.#current.installed();\n\t\tif (!current.some((installed) => installed.name === extension.name)) return;\n\t\tthis.#publish(current.filter((installed) => installed.name !== extension.name));\n\t}\n\n\t/** Build and validate the next state, which throws on a task name collision, then publish it synchronously. */\n\t#publish(extensions: readonly Extension<Tool>[]): void {\n\t\tthis.#current = new RegistryState(extensions);\n\t\tfor (const listener of [...this.#listeners]) listener();\n\t}\n}\n\n/** Unique tool names and section keys within one extension; valid, unreserved section keys. */\nfunction validateExtension(extension: Extension): void {\n\tconst tools = new Set<string>();\n\tfor (const tool of extension.tools ?? []) {\n\t\tif (tools.has(tool.name)) throw new Error(`Extension ${extension.name} has two tools named ${tool.name}`);\n\t\ttools.add(tool.name);\n\t}\n\tconst sections = new Set<string>();\n\tfor (const { key } of extension.sections ?? []) {\n\t\tif (!SECTION_KEY.test(key)) throw new TypeError(`Section key ${JSON.stringify(key)} must match ${SECTION_KEY}`);\n\t\tif (key === INSTRUCTIONS_KEY) throw new Error(`Section key ${key} is reserved for the agent's instructions`);\n\t\tif (sections.has(key)) throw new Error(`Extension ${extension.name} has two sections with key ${key}`);\n\t\tsections.add(key);\n\t}\n}\n\n/** Create an application-owned registry holding only the built-in tasks. */\nexport function createRegistry<Tool extends ToolRegistration = ToolRegistration>(): Registry<Tool> {\n\treturn new RegistryImpl<Tool>();\n}\n", "import { type Context, copyJson, type JsonValue } from \"@earendil-works/chord\";\nimport { awaitWithContext, withAbortSignal } from \"@earendil-works/chord/context\";\nimport type { Models } from \"@earendil-works/pi-ai\";\nimport type { ExecutionEnv } from \"../env/index.ts\";\nimport type { SessionImpl } from \"../session/session.ts\";\nimport type { Transaction } from \"../session/transaction.ts\";\nimport type {\n\tCommitPublication,\n\tConversationId,\n\tDocumentWatch,\n\tEntryId,\n\tEntryRecord,\n\tHookRunner,\n\tJsonObject,\n\tNextTaskState,\n\tRunningTask,\n\tStorage,\n\tTaskDefinition,\n\tTaskId,\n\tTaskOutcome,\n\tTaskRecord,\n\tTaskRuntime,\n\tTaskState,\n} from \"../types.ts\";\nimport { agentHooks } from \"./agent.ts\";\nimport { readContext } from \"./context.ts\";\nimport type {\n\tAgent,\n\tAnyTask,\n\tConversationHandle,\n\tHarnessInspection,\n\tRegistryReader,\n\tRegistrySnapshot,\n\tSettings,\n\tSettledTask,\n\tTaskInspection,\n} from \"./types.ts\";\nimport { closedError, scanAll, Waiters } from \"./util.ts\";\n\ntype AnyTaskRecord = TaskRecord<JsonValue, JsonValue, JsonValue>;\n/** A record that can still run code: pending, running, or waiting. */\ntype RunnableTaskRecord = Extract<\n\tAnyTaskRecord,\n\t{ readonly state: { readonly status: \"pending\" | \"running\" | \"waiting\" } }\n>;\ntype Checkpoint = { readonly phase: string };\ntype ErasedDefinition = TaskDefinition<JsonValue, Checkpoint, JsonValue, object>;\ntype ErasedRuntime = TaskRuntime<JsonValue, Checkpoint, JsonValue, object>;\ntype ErasedRunningTask = RunningTask<JsonValue, Checkpoint, JsonValue>;\n\nconst SCAN_PAGE_SIZE = 256;\n/** Longest delay `setTimeout` supports; longer sleeps wait in several steps. */\nconst MAX_TIMER_DELAY = 2_147_483_647;\nconst LIVE_STATUSES = [\"pending\", \"running\", \"waiting\", \"completing\"] as const;\n\n/** Why a pending task cannot be reserved under a registry snapshot. Derived, never persisted. */\ntype BlockedReason = \"missing_task\" | \"task_too_old\" | \"migration_failed\";\n\ntype Resolution =\n\t| { readonly kind: \"ready\"; readonly task: AnyTask; readonly record: RunnableTaskRecord }\n\t| { readonly kind: \"blocked\"; readonly reason: BlockedReason };\n\n/** A definition that can take a record, or why none can; deciding it runs no task code. */\ntype Fit =\n\t| { readonly task: AnyTask; readonly migrates: boolean }\n\t| { readonly reason: BlockedReason; readonly error?: unknown };\n\n/** One in-memory execution of a task in run or abort mode. */\ntype Invocation = {\n\treadonly taskId: TaskId;\n\treadonly conversationId: ConversationId;\n\treadonly mode: \"run\" | \"abort\";\n\treadonly controller: AbortController;\n\t/** Context passed to handlers; cancelled by `controller`. */\n\treadonly context: Context;\n\t/** Watches acquired through the runtime; stopped at invocation end. */\n\treadonly watches: Set<DocumentWatch<JsonObject>>;\n\tended: boolean;\n\treadonly done: Promise<void>;\n\treadonly finish: () => void;\n};\n\n/** What a runtime reads for the phase handler it serves: the phase's snapshot and task, and its lazily resolved agent. */\ntype Phase = {\n\treadonly snapshot: () => RegistrySnapshot;\n\treadonly task: () => AnyTask;\n\tagent: Promise<Agent> | undefined;\n};\n\ntype Reservation = {\n\treadonly invocation: Invocation;\n\treadonly task: AnyTask;\n\treadonly snapshot: RegistrySnapshot;\n};\n\n/** Replacement definition already reported as unable to take over, per invocation. */\ntype ReportedTask = { readonly task: AnyTask | undefined } | undefined;\n\n/** Outcome of the phase that just returned, judged by the next step. */\ntype PhaseResult = { readonly checkpoint: Checkpoint; readonly failure?: { readonly error: unknown } };\n\n/** Step decision: continue with the next phase, end the invocation, or end it by writing `faulted`. */\ntype Decision = boolean | { readonly fault: unknown };\n\n/** Terminal outcomes the scheduler writes without running task code. */\nexport type SchedulerOutcome = Extract<TaskOutcome<JsonValue>, { readonly status: \"faulted\" | \"orphaned\" }>;\n\n/** An invocation a conversation handle is bound to: its signal, and a check that throws once it ended. */\nexport type InvocationBinding = { readonly signal: AbortSignal; check(): void };\n\n/** The immutable ownership fields of a task. */\ntype TaskNode = Pick<AnyTaskRecord, \"conversationId\" | \"owner\" | \"background\">;\n\n/** Where a walk up the ownership tree continues: an owner task, or a conversation. */\ntype Up = { readonly task: TaskId } | { readonly conversation: ConversationId };\n\n/** One step of a walk up: an owner task with its node, a conversation, or an owner edge that is not loaded yet. */\ntype Step =\n\t| { readonly task: TaskId; readonly node: TaskNode }\n\t| { readonly conversation: ConversationId }\n\t| { readonly unknown: true };\n\n/** Candidate records a commit staged; they override committed records in ownership walks. */\ntype Overlay = {\n\treadonly tasks: ReadonlyMap<TaskId, AnyTaskRecord>;\n\treadonly edges: ReadonlyMap<ConversationId, TaskId | null>;\n};\n\n/** Where ordinary ownership traversal starts: one conversation, or every ownerless conversation. */\ntype Scope = { readonly conversation: ConversationId } | { readonly roots: true };\n\nexport type TaskSchedulerOptions = {\n\treadonly session: SessionImpl;\n\treadonly storage: Storage;\n\treadonly registry: RegistryReader;\n\treadonly models: Models;\n\t/** Resolve a conversation's agent against a snapshot; the runtime calls it at most once per phase. */\n\treadonly agent: (conversationId: ConversationId, snapshot: RegistrySnapshot, context: Context) => Promise<Agent>;\n\t/** Resolve the settings; read at each access. */\n\treadonly settings: () => Settings;\n\t/** Build a conversation's environment with `HarnessOptions.env`. */\n\treadonly env: (conversationId: ConversationId, context: Context) => Promise<ExecutionEnv | undefined>;\n\treadonly now: () => number;\n\treadonly report: (error: unknown) => void;\n\t/** Harness cleanup staged in the commit that makes an outcome the scheduler wrote itself terminal. */\n\treadonly settleOutcome: (tx: Transaction, record: AnyTaskRecord, outcome: SchedulerOutcome) => Promise<void>;\n\t/** Withdraw a conversation's queued inputs, for conversation abort and abort cascades. */\n\treadonly withdrawInputs: (tx: Transaction, conversationId: ConversationId) => Promise<void>;\n\t/** Invocation-bound handle of an existing conversation, for task runtimes and tools. */\n\treadonly conversation: (\n\t\tid: ConversationId,\n\t\tbinding: InvocationBinding,\n\t\tcontext: Context,\n\t) => Promise<ConversationHandle | undefined>;\n\t/** Context for scheduler commits and invocations; carries no caller cancellation. */\n\treadonly context: Context;\n};\n\n/**\n * Durable task scheduler of one Harness.\n *\n * `#live` mirrors every committed non-terminal task record: pending, running, waiting, and completing. The synchronous\n * commit listener updates it on the Session line, so code running on the line reads exactly the committed state from it.\n *\n * Tasks and conversations form one ownership tree (spec §5.5): a task's parent is its owner task, or its conversation;\n * a conversation's parent is its owner task, if any. Walks up that tree decide cascades, idle scopes, and whether a\n * task's ordinary owned work is live, which holds its outcome as `completing` and delays its abort handler.\n *\n * Invariant: every task transition is decided and written by one callback serialized on the Session line. That covers\n * reservation, marks, runtime commits, finalization, and the synchronous step before each phase, which applies the\n * precedence rules and writes a fault or handover. Handlers and joins run off the line. An invocation ends inside the\n * step that decides its end, so a runtime commit it queued either lands before that decision or is rejected.\n */\nexport class TaskScheduler {\n\treadonly #session: SessionImpl;\n\treadonly #storage: Storage;\n\treadonly #registry: RegistryReader;\n\treadonly #models: Models;\n\treadonly #agent: TaskSchedulerOptions[\"agent\"];\n\treadonly #settings: TaskSchedulerOptions[\"settings\"];\n\treadonly #env: TaskSchedulerOptions[\"env\"];\n\treadonly #now: () => number;\n\treadonly #report: (error: unknown) => void;\n\treadonly #settleOutcome: TaskSchedulerOptions[\"settleOutcome\"];\n\treadonly #withdrawInputs: TaskSchedulerOptions[\"withdrawInputs\"];\n\treadonly #conversation: TaskSchedulerOptions[\"conversation\"];\n\treadonly #context: Context;\n\treadonly #live = new Map<TaskId, AnyTaskRecord>();\n\treadonly #invocations = new Map<TaskId, Invocation>();\n\treadonly #taskWaiters = new Waiters<TaskId, SettledTask<JsonValue>>();\n\t/** Idle waiters by conversation; `undefined` waits for the whole Harness. */\n\treadonly #idleWaiters = new Waiters<ConversationId | undefined, void>();\n\t/** Definition whose migration failed per task; retried only once the registry resolves another definition. */\n\treadonly #failedMigrations = new Map<TaskId, { readonly task: AnyTask; readonly error: unknown }>();\n\t/** Owner task of each loaded conversation, `null` when ownerless. */\n\treadonly #edges = new Map<ConversationId, TaskId | null>();\n\t/** Tasks that own a loaded conversation; their nodes stay in `#settled` once terminal. */\n\treadonly #conversationOwners = new Set<TaskId>();\n\t/** Ownership fields of terminal tasks that walks pass through. */\n\treadonly #settled = new Map<TaskId, TaskNode>();\n\t/**\n\t * `failFast` waiters the next reconcile checks for a failed task in `on`: at open, when they start waiting, and when\n\t * one of their tasks fails.\n\t */\n\treadonly #failFastChecks = new Set<TaskId>();\n\t#reconcileScheduled = false;\n\t#cascadePending = false;\n\t#unsubscribeRegistry: () => void = () => {};\n\t#enabled = false;\n\t#closing = false;\n\t#dirty = false;\n\t#draining = false;\n\n\tconstructor(options: TaskSchedulerOptions) {\n\t\tthis.#session = options.session;\n\t\tthis.#storage = options.storage;\n\t\tthis.#registry = options.registry;\n\t\tthis.#models = options.models;\n\t\tthis.#agent = options.agent;\n\t\tthis.#settings = options.settings;\n\t\tthis.#env = options.env;\n\t\tthis.#now = options.now;\n\t\tthis.#report = options.report;\n\t\tthis.#settleOutcome = options.settleOutcome;\n\t\tthis.#withdrawInputs = options.withdrawInputs;\n\t\tthis.#conversation = options.conversation;\n\t\tthis.#context = options.context;\n\t}\n\n\t/** Load live tasks and change surviving `running` tasks back to `pending`. Dispatches nothing. */\n\tasync open(context: Context): Promise<void> {\n\t\tthis.#session.subscribeCommits((publication) => this.#observe(publication));\n\t\tthis.#session.subscribeClose(() => this.#seal());\n\t\tthis.#unsubscribeRegistry = this.#registry.subscribe(() => this.#kick());\n\t\tawait this.#session.commitWith(async (tx) => {\n\t\t\t// Every table read before the first write.\n\t\t\tconst scans = [];\n\t\t\tfor (const status of LIVE_STATUSES) {\n\t\t\t\tscans.push(await scanAll((cursor) => tx.scanTasks({ status }, SCAN_PAGE_SIZE, cursor)));\n\t\t\t}\n\t\t\tfor (const records of scans) {\n\t\t\t\tfor (const record of records) {\n\t\t\t\t\tthis.#live.set(record.id, record);\n\t\t\t\t\tif (record.state.status === \"running\") {\n\t\t\t\t\t\ttx.setTask(withState(record, { status: \"pending\", checkpoint: record.state.checkpoint }));\n\t\t\t\t\t}\n\t\t\t\t\tif (record.state.status === \"waiting\" && record.state.policy === \"failFast\") {\n\t\t\t\t\t\tthis.#failFastChecks.add(record.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}, context);\n\t\t// Derive abort marks a crash left unapplied below cancelled owners, and finalize held outcomes.\n\t\tthis.#cascadePending = true;\n\t\tthis.#scheduleReconcile();\n\t}\n\n\t/** Enable scheduling. Idempotent; the kick does nothing once closing. */\n\tresume(): void {\n\t\tthis.#enabled = true;\n\t\tthis.#kick();\n\t}\n\n\t/** Wait for every invocation signalled by `#seal()`. Writes nothing. */\n\tasync join(): Promise<void> {\n\t\tawait Promise.allSettled([...this.#invocations.values()].map((invocation) => invocation.done));\n\t}\n\n\t/**\n\t * Commit the abort mark, or settle a task that no registered definition can take as `orphaned` when nothing it owns\n\t * is live, then join the run invocation seen on the line; the commit listener signalled it. The abort invocation\n\t * starts once the task's ordinary owned work is gone. A `completing` task is only marked.\n\t */\n\tasync abort(id: TaskId, context: Context): Promise<\"marked\" | \"terminal\"> {\n\t\tconst marked = await this.#session.commitWith(async (tx) => {\n\t\t\tconst current = await tx.task(id);\n\t\t\tif (current === undefined) throw new Error(`Task ${id} does not exist`);\n\t\t\tif (current.state.status === \"terminal\") return { result: \"terminal\" as const };\n\t\t\tconst invocation = this.#invocations.get(id);\n\t\t\tif (invocation === undefined && current.state.status !== \"completing\") {\n\t\t\t\tawait this.#loadScopes(false);\n\t\t\t\tif (!this.#ownedLive().has(id)) {\n\t\t\t\t\tconst resolution = this.#resolve(current as RunnableTaskRecord, this.#registry.snapshot());\n\t\t\t\t\tif (resolution.kind === \"blocked\") {\n\t\t\t\t\t\tawait this.#terminate(tx, current, { status: \"orphaned\", reason: resolution.reason });\n\t\t\t\t\t\treturn { result: \"marked\" as const };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!current.abortRequested) tx.setTask({ ...current, abortRequested: true });\n\t\t\treturn { result: \"marked\" as const, run: invocation?.mode === \"run\" ? invocation : undefined };\n\t\t}, context);\n\t\t// The commit listener signalled the run; join it.\n\t\tif (marked.run !== undefined) await awaitWithContext(marked.run.done, context);\n\t\treturn marked.result;\n\t}\n\n\tasync waitForTask(id: TaskId, context: Context): Promise<SettledTask<JsonValue>> {\n\t\t// Check and register on the line so no terminal publication falls between them.\n\t\tconst found = await this.#session.readOnLine(async () => {\n\t\t\tif (this.#closing) throw closedError();\n\t\t\tif (this.#live.has(id)) return { promise: this.#taskWaiters.add(id, context) };\n\t\t\tconst record = await this.#storage.task(id, context);\n\t\t\tif (record === undefined) throw new Error(`Task ${id} does not exist`);\n\t\t\treturn { promise: Promise.resolve(record as SettledTask<JsonValue>) };\n\t\t});\n\t\treturn found.promise;\n\t}\n\n\t/**\n\t * Resolve when ordinary traversal from the conversation, or from every ownerless conversation, reaches no live\n\t * non-background task.\n\t */\n\twaitForIdle(conversationId: ConversationId | undefined, context: Context): Promise<void> {\n\t\tif (this.#closing) return Promise.reject(closedError());\n\t\tif (this.#idle(conversationId)) return Promise.resolve();\n\t\tthis.#scheduleReconcile();\n\t\treturn this.#idleWaiters.add(conversationId, context);\n\t}\n\n\t/**\n\t * `Conversation.abort()`: in one commit, withdraw the queued inputs and mark every live non-background task that\n\t * ordinary traversal from the conversation reaches; resolves once the scope is idle. With `background`, traversal\n\t * crosses background boundaries, and the wait also covers every task it reached.\n\t */\n\tasync abortConversation(conversationId: ConversationId, background: boolean, context: Context): Promise<void> {\n\t\tconst reached = await this.#session.commitWith(async (tx) => {\n\t\t\tconst queued = await this.#loadScopes(true);\n\t\t\tconst scope = { conversation: conversationId };\n\t\t\tconst reached: TaskId[] = [];\n\t\t\tfor (const record of this.#live.values()) {\n\t\t\t\tif (record.background && !background) continue;\n\t\t\t\tif (this.#inScope(parentOf(record), scope, background) !== true) continue;\n\t\t\t\treached.push(record.id);\n\t\t\t\tif (!record.abortRequested) tx.setTask({ ...record, abortRequested: true });\n\t\t\t}\n\t\t\tfor (const id of queued) {\n\t\t\t\tif (this.#inScope({ conversation: id }, scope, background) === true) await this.#withdrawInputs(tx, id);\n\t\t\t}\n\t\t\treturn reached;\n\t\t}, context);\n\t\tif (background) for (const id of reached) await this.waitForTask(id, context);\n\t\tawait this.waitForIdle(conversationId, context);\n\t}\n\n\t// ─── Scheduling ────────────────────────────────────────────────────────\n\n\t#observe(publication: CommitPublication): void {\n\t\tconst updated: AnyTaskRecord[] = [];\n\t\tconst failed: TaskId[] = [];\n\t\tlet changed = false;\n\t\tfor (const change of publication.changes) {\n\t\t\tif (change.type !== \"task\") continue;\n\t\t\tchanged = true;\n\t\t\tconst record = change.value;\n\t\t\tconst previous = this.#live.get(record.id);\n\t\t\tif (failedOutcome(record) && (previous === undefined || !failedOutcome(previous))) failed.push(record.id);\n\t\t\tif (record.state.status === \"terminal\") {\n\t\t\t\tthis.#live.delete(record.id);\n\t\t\t\tthis.#failedMigrations.delete(record.id);\n\t\t\t\tthis.#failFastChecks.delete(record.id);\n\t\t\t\tif (this.#conversationOwners.has(record.id)) this.#settled.set(record.id, nodeOf(record));\n\t\t\t\tthis.#taskWaiters.resolve(record.id, record as SettledTask<JsonValue>);\n\t\t\t\t// Its owner may finalize now.\n\t\t\t\tthis.#scheduleReconcile();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (record.abortRequested && previous?.abortRequested !== true) {\n\t\t\t\tthis.#cascadePending = true;\n\t\t\t\t// Signal a run invocation of the newly marked task; its next step ends it.\n\t\t\t\tconst invocation = this.#invocations.get(record.id);\n\t\t\t\tif (invocation?.mode === \"run\") invocation.controller.abort();\n\t\t\t}\n\t\t\tconst status = record.state.status;\n\t\t\tif (status === \"completing\" && previous?.state.status !== \"completing\") {\n\t\t\t\tif (cancellationIntent(record)) this.#cascadePending = true;\n\t\t\t\tthis.#scheduleReconcile();\n\t\t\t}\n\t\t\tif (status === \"waiting\" && record.state.policy === \"failFast\" && previous?.state.status !== \"waiting\") {\n\t\t\t\tthis.#failFastChecks.add(record.id);\n\t\t\t\tthis.#scheduleReconcile();\n\t\t\t}\n\t\t\tthis.#live.set(record.id, record);\n\t\t\tupdated.push(record);\n\t\t}\n\t\tfor (const id of failed) {\n\t\t\tfor (const record of this.#live.values()) {\n\t\t\t\tconst state = record.state;\n\t\t\t\tif (state.status === \"waiting\" && state.policy === \"failFast\" && state.on.includes(id)) {\n\t\t\t\t\tthis.#failFastChecks.add(record.id);\n\t\t\t\t\tthis.#scheduleReconcile();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const change of publication.changes) {\n\t\t\tif (change.type === \"conversation\" && !this.#edges.has(change.value.id)) {\n\t\t\t\tthis.#setEdge(change.value.id, change.value.owner?.taskId ?? null);\n\t\t\t}\n\t\t}\n\t\tfor (const change of publication.changes) {\n\t\t\t// A queued input below a cancelled owner is withdrawn, even after its cascade.\n\t\t\tif (change.type !== \"submission\" || change.value.status !== \"queued\" || change.value.type !== \"input\")\n\t\t\t\tcontinue;\n\t\t\tconst up = { conversation: change.value.conversationId };\n\t\t\tif (!this.#chainKnown(up) || this.#belowCancelled(up)) this.#cascadePending = true;\n\t\t}\n\t\tfor (const record of updated) {\n\t\t\t// Work created below a cancelled owner, even after its cascade, is aborted too.\n\t\t\tif (!this.#chainKnown(parentOf(record))) this.#scheduleReconcile();\n\t\t\telse if (!record.background && !record.abortRequested && this.#belowCancelled(parentOf(record))) {\n\t\t\t\tthis.#cascadePending = true;\n\t\t\t}\n\t\t}\n\t\t// Also retries, with the next commit of any kind, a cascade whose commit failed.\n\t\tif (this.#cascadePending) this.#scheduleReconcile();\n\t\tif (!changed) return;\n\t\tthis.#resolveIdleWaiters();\n\t\tthis.#kick();\n\t}\n\n\t#resolveIdleWaiters(): void {\n\t\tfor (const conversationId of this.#idleWaiters.keys()) {\n\t\t\tif (this.#idle(conversationId)) this.#idleWaiters.resolve(conversationId);\n\t\t}\n\t}\n\n\t// ─── Ownership ───────────────────────────────────────────────────────────\n\n\t#scheduleReconcile(): void {\n\t\tif (this.#reconcileScheduled || this.#closing) return;\n\t\tthis.#reconcileScheduled = true;\n\t\tqueueMicrotask(() => void this.#reconcile());\n\t}\n\n\t/**\n\t * One commit that applies what committed records imply: abort marks below live owners with cancellation intent\n\t * (spec §5.4), `failFast` marks (spec §5.5), withdrawn queued inputs below cancelled owners, and the final terminal\n\t * record of every `completing` task whose ordinary owned work is gone. The durable records are the intent, so this\n\t * also repairs whatever a crash left unapplied. Resolves idle waiters that the loaded edges decide.\n\t */\n\tasync #reconcile(): Promise<void> {\n\t\tthis.#reconcileScheduled = false;\n\t\tconst cascade = this.#cascadePending;\n\t\tthis.#cascadePending = false;\n\t\tconst checks = [...this.#failFastChecks];\n\t\tthis.#failFastChecks.clear();\n\t\ttry {\n\t\t\tawait this.#session.commitWith(async (tx) => {\n\t\t\t\tif (this.#closing) return;\n\t\t\t\tconst queued = await this.#loadScopes(cascade);\n\t\t\t\tconst marked = new Set<TaskId>();\n\t\t\t\tconst mark = (record: AnyTaskRecord): void => {\n\t\t\t\t\tif (record.abortRequested || marked.has(record.id)) return;\n\t\t\t\t\tmarked.add(record.id);\n\t\t\t\t\ttx.setTask({ ...record, abortRequested: true });\n\t\t\t\t};\n\t\t\t\t// Loading edges can reveal a cancelled owner, so marks are derived on every pass.\n\t\t\t\tfor (const record of this.#live.values()) {\n\t\t\t\t\tif (!record.background && this.#belowCancelled(parentOf(record))) mark(record);\n\t\t\t\t}\n\t\t\t\tfor (const id of checks) {\n\t\t\t\t\tconst waiter = this.#live.get(id);\n\t\t\t\t\tif (waiter?.state.status !== \"waiting\" || !(await this.#anyFailed(waiter.state.on))) continue;\n\t\t\t\t\t// Every other live task: the failed one keeps its own outcome.\n\t\t\t\t\tfor (const member of waiter.state.on) {\n\t\t\t\t\t\tconst record = this.#live.get(member);\n\t\t\t\t\t\tif (record !== undefined && !failedOutcome(record)) mark(record);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const id of queued) if (this.#belowCancelled({ conversation: id })) await this.#withdrawInputs(tx, id);\n\t\t\t\tawait this.#finalize(tx);\n\t\t\t}, this.#context);\n\t\t} catch (error) {\n\t\t\t// Any pass may have staged marks, so a failed one is retried with the next commit.\n\t\t\tthis.#cascadePending = true;\n\t\t\tfor (const id of checks) this.#failFastChecks.add(id);\n\t\t\tif (!this.#closing) this.#report(error);\n\t\t}\n\t\tthis.#resolveIdleWaiters();\n\t}\n\n\t/** Whether any of `ids` holds or ended with an outcome other than `completed`. */\n\tasync #anyFailed(ids: readonly TaskId[]): Promise<boolean> {\n\t\tfor (const id of ids) {\n\t\t\tconst record = this.#live.get(id) ?? (await this.#storage.task(id, this.#context));\n\t\t\tif (record !== undefined && failedOutcome(record)) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Write the terminal record of every `completing` task without live ordinary owned work. Finalizing one can free its\n\t * owner, so this repeats over the commit's candidates until nothing changes. A held scheduler outcome gets its\n\t * Harness cleanup here.\n\t */\n\tasync #finalize(tx: Transaction): Promise<void> {\n\t\tfor (;;) {\n\t\t\tconst overlay = overlayOf(tx);\n\t\t\tconst owned = this.#ownedLive(overlay);\n\t\t\tconst done = [...this.#liveRecords(overlay)].filter(\n\t\t\t\t(record) => record.state.status === \"completing\" && !owned.has(record.id),\n\t\t\t);\n\t\t\tif (done.length === 0) return;\n\t\t\tfor (const record of done) {\n\t\t\t\tconst outcome = (record.state as { readonly outcome: TaskOutcome<JsonValue> }).outcome;\n\t\t\t\ttx.setTask(withState(record, { status: \"terminal\", outcome }));\n\t\t\t\t// REMINDER: only the scheduler writes `faulted` and `orphaned` (spec §5.4); their cleanup waits for this commit.\n\t\t\t\tif (outcome.status === \"faulted\" || outcome.status === \"orphaned\") {\n\t\t\t\t\tawait this.#settleOutcome(tx, record, outcome);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Load the owner chains of every live task and, with `queued`, of every conversation with queued submissions, on the\n\t * Session line; returns the latter. Reads committed Storage directly, so it may run inside a commit callback.\n\t */\n\tasync #loadScopes(queued: boolean): Promise<ConversationId[]> {\n\t\tfor (const record of [...this.#live.values()]) {\n\t\t\tif (!this.#chainKnown(parentOf(record))) await this.#loadChain(parentOf(record));\n\t\t}\n\t\tif (!queued) return [];\n\t\tconst submissions = await scanAll((cursor) =>\n\t\t\tthis.#storage.scanSubmissions({ status: \"queued\" }, SCAN_PAGE_SIZE, cursor, this.#context),\n\t\t);\n\t\tconst conversations = [...new Set(submissions.map((submission) => submission.conversationId))];\n\t\tfor (const id of conversations) await this.#loadChain({ conversation: id });\n\t\treturn conversations;\n\t}\n\n\t/** Load the owner edges and task nodes from `start` up to its ownerless root. */\n\tasync #loadChain(start: Up, overlay?: Overlay): Promise<void> {\n\t\tlet at: Up | undefined = start;\n\t\twhile (at !== undefined) {\n\t\t\tif (\"task\" in at) {\n\t\t\t\tlet node = this.#node(at.task, overlay);\n\t\t\t\tif (node === undefined) {\n\t\t\t\t\tconst record = await this.#storage.task(at.task, this.#context);\n\t\t\t\t\tif (record === undefined) return;\n\t\t\t\t\tnode = nodeOf(record);\n\t\t\t\t\tif (record.state.status === \"terminal\") this.#settled.set(record.id, node);\n\t\t\t\t}\n\t\t\t\tat = parentOf(node);\n\t\t\t} else {\n\t\t\t\tlet edge = this.#edge(at.conversation, overlay);\n\t\t\t\tif (edge === undefined) {\n\t\t\t\t\tconst record = await this.#storage.conversation(at.conversation, this.#context);\n\t\t\t\t\tedge = record?.owner?.taskId ?? null;\n\t\t\t\t\tthis.#setEdge(at.conversation, edge);\n\t\t\t\t}\n\t\t\t\tat = edge === null ? undefined : { task: edge };\n\t\t\t}\n\t\t}\n\t}\n\n\t#setEdge(conversationId: ConversationId, owner: TaskId | null): void {\n\t\tthis.#edges.set(conversationId, owner);\n\t\tif (owner !== null) this.#conversationOwners.add(owner);\n\t}\n\n\t/** Owner task of a conversation, `null` when ownerless, `undefined` while not loaded. */\n\t#edge(id: ConversationId, overlay?: Overlay): TaskId | null | undefined {\n\t\treturn overlay?.edges.has(id) === true ? overlay.edges.get(id) : this.#edges.get(id);\n\t}\n\n\t#node(id: TaskId, overlay?: Overlay): TaskNode | undefined {\n\t\treturn overlay?.tasks.get(id) ?? this.#live.get(id) ?? this.#settled.get(id);\n\t}\n\n\t/** Walk up from `start`: owner tasks and conversations, ending at an ownerless root or an edge not loaded yet. */\n\t*#above(start: Up, overlay?: Overlay): Generator<Step> {\n\t\tlet at: Up | undefined = start;\n\t\twhile (at !== undefined) {\n\t\t\tif (\"task\" in at) {\n\t\t\t\tconst node = this.#node(at.task, overlay);\n\t\t\t\tif (node === undefined) {\n\t\t\t\t\tyield { unknown: true };\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tyield { task: at.task, node };\n\t\t\t\tat = parentOf(node);\n\t\t\t} else {\n\t\t\t\tyield { conversation: at.conversation };\n\t\t\t\tconst edge = this.#edge(at.conversation, overlay);\n\t\t\t\tif (edge === undefined) {\n\t\t\t\t\tyield { unknown: true };\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tat = edge === null ? undefined : { task: edge };\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Whether every owner above `start` is loaded. */\n\t#chainKnown(start: Up, overlay?: Overlay): boolean {\n\t\tfor (const step of this.#above(start, overlay)) if (\"unknown\" in step) return false;\n\t\treturn true;\n\t}\n\n\t/** Live records, with the overlay's candidates replacing committed ones; terminal candidates are gone. */\n\t*#liveRecords(overlay?: Overlay): Generator<AnyTaskRecord> {\n\t\tfor (const record of this.#live.values()) {\n\t\t\tconst candidate = overlay?.tasks.get(record.id) ?? record;\n\t\t\tif (candidate.state.status !== \"terminal\") yield candidate;\n\t\t}\n\t\tif (overlay === undefined) return;\n\t\tfor (const record of overlay.tasks.values()) {\n\t\t\tif (!this.#live.has(record.id) && record.state.status !== \"terminal\") yield record;\n\t\t}\n\t}\n\n\t/**\n\t * Every task with live ordinary owned work (spec §5.5), mapped to that work: each live non-background task counts for\n\t * every owner task above it up to and including the first background one. Owner chains must be loaded.\n\t */\n\t#ownedLive(overlay?: Overlay): Map<TaskId, TaskId[]> {\n\t\tconst owned = new Map<TaskId, TaskId[]>();\n\t\tfor (const record of this.#liveRecords(overlay)) {\n\t\t\tif (record.background) continue;\n\t\t\tfor (const step of this.#above(parentOf(record), overlay)) {\n\t\t\t\tif (\"unknown\" in step) break;\n\t\t\t\tif (!(\"task\" in step)) continue;\n\t\t\t\tconst below = owned.get(step.task);\n\t\t\t\tif (below === undefined) owned.set(step.task, [record.id]);\n\t\t\t\telse below.push(record.id);\n\t\t\t\tif (step.node.background) break;\n\t\t\t}\n\t\t}\n\t\treturn owned;\n\t}\n\n\t/**\n\t * Whether ordinary traversal from `scope` reaches `start`: walking up reaches the scope's conversation, or an\n\t * ownerless one for `roots`, without crossing a background owner, unless `crossBackground`. `undefined` while an\n\t * edge is not loaded.\n\t */\n\t#inScope(start: Up, scope: Scope, crossBackground = false): boolean | undefined {\n\t\tfor (const step of this.#above(start)) {\n\t\t\tif (\"unknown\" in step) return undefined;\n\t\t\tif (\"conversation\" in step) {\n\t\t\t\tif (\"conversation\" in scope && step.conversation === scope.conversation) return true;\n\t\t\t} else if (step.node.background && !crossBackground) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn \"roots\" in scope;\n\t}\n\n\t/**\n\t * Whether a live owner's cancellation intent reaches `start`: walking up finds an owner with intent before a\n\t * background owner without it. Terminal owners never cascade (spec §5.4).\n\t */\n\t#belowCancelled(start: Up): boolean {\n\t\tfor (const step of this.#above(start)) {\n\t\t\tif (\"unknown\" in step) return false;\n\t\t\tif (!(\"task\" in step)) continue;\n\t\t\tconst live = this.#live.get(step.task);\n\t\t\tif (live !== undefined && cancellationIntent(live)) return true;\n\t\t\tif (step.node.background) return false;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Close listener: runs synchronously once admission is sealed, before `join()`. */\n\t#seal(): void {\n\t\tthis.#closing = true;\n\t\tthis.#unsubscribeRegistry();\n\t\tconst error = closedError();\n\t\tthis.#taskWaiters.rejectAll(error);\n\t\tthis.#idleWaiters.rejectAll(error);\n\t\tfor (const invocation of this.#invocations.values()) invocation.controller.abort();\n\t}\n\n\t#kick(): void {\n\t\tthis.#dirty = true;\n\t\tif (this.#draining || !this.#enabled || this.#closing) return;\n\t\tthis.#draining = true;\n\t\t// Never commit synchronously from a commit or registry listener.\n\t\tqueueMicrotask(() => void this.#drain());\n\t}\n\n\tasync #drain(): Promise<void> {\n\t\ttry {\n\t\t\twhile (this.#dirty && this.#enabled && !this.#closing) {\n\t\t\t\tthis.#dirty = false;\n\t\t\t\tfor (const reservation of await this.#reserve()) this.#start(reservation);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (!this.#closing) this.#report(error);\n\t\t} finally {\n\t\t\tthis.#draining = false;\n\t\t\t// A wakeup that arrived during a failed pass still needs its pass.\n\t\t\tif (this.#dirty) this.#kick();\n\t\t}\n\t}\n\n\t/** Reserve every eligible task in one commit; orphan abort-marked tasks no definition can take. */\n\tasync #reserve(): Promise<Reservation[]> {\n\t\tconst reservations: Reservation[] = [];\n\t\ttry {\n\t\t\tawait this.#session.commitWith(async (tx) => {\n\t\t\t\tif (!this.#enabled || this.#closing) return;\n\t\t\t\tawait this.#loadScopes(false);\n\t\t\t\tconst owned = this.#ownedLive();\n\t\t\t\t// Taken once per pass, and only when some task is a candidate.\n\t\t\t\tlet snapshot: RegistrySnapshot | undefined;\n\t\t\t\tfor (const record of [...this.#live.values()]) {\n\t\t\t\t\tif (this.#invocations.has(record.id) || this.#waitingOn(record, owned).length > 0) continue;\n\t\t\t\t\tif (record.state.status === \"completing\") continue;\n\t\t\t\t\tconst runnable = record as RunnableTaskRecord;\n\t\t\t\t\tconst mode = record.abortRequested ? \"abort\" : \"run\";\n\t\t\t\t\tsnapshot ??= this.#registry.snapshot();\n\t\t\t\t\tconst resolution = this.#resolve(runnable, snapshot);\n\t\t\t\t\tif (resolution.kind === \"blocked\") {\n\t\t\t\t\t\tif (mode === \"abort\") {\n\t\t\t\t\t\t\tawait this.#terminate(tx, record, { status: \"orphaned\", reason: resolution.reason });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (resolution.record !== runnable || record.state.status !== \"running\") {\n\t\t\t\t\t\ttx.setTask(\n\t\t\t\t\t\t\twithState(resolution.record, {\n\t\t\t\t\t\t\t\tstatus: \"running\",\n\t\t\t\t\t\t\t\tcheckpoint: resolution.record.state.checkpoint,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\t// Registered on the line, so marks and later reservations see it and close joins it.\n\t\t\t\t\tconst invocation = this.#createInvocation(record, mode);\n\t\t\t\t\treservations.push({ invocation, task: resolution.task, snapshot });\n\t\t\t\t}\n\t\t\t}, this.#context);\n\t\t} catch (error) {\n\t\t\tfor (const { invocation } of reservations) {\n\t\t\t\tthis.#invocations.delete(invocation.taskId);\n\t\t\t\tinvocation.finish();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\treturn reservations;\n\t}\n\n\t/**\n\t * Live tasks a task waits for before its next invocation: its live ordinary owned work when abort-marked, since\n\t * abort runs bottom-up, otherwise the live part of the `on` of a wait.\n\t */\n\t#waitingOn(record: AnyTaskRecord, owned: ReadonlyMap<TaskId, readonly TaskId[]>): readonly TaskId[] {\n\t\tif (record.abortRequested) return owned.get(record.id) ?? [];\n\t\tif (record.state.status !== \"waiting\") return [];\n\t\treturn record.state.on.filter((id) => this.#live.has(id));\n\t}\n\n\t/** Resolve the record's definition by kind, migrating an older stored version. */\n\t#resolve(record: RunnableTaskRecord, snapshot: RegistrySnapshot): Resolution {\n\t\tconst fit = this.#fit(record, snapshot.task(record.kind));\n\t\tif (\"reason\" in fit) return { kind: \"blocked\", reason: fit.reason };\n\t\tif (!fit.migrates) return { kind: \"ready\", task: fit.task, record };\n\t\tconst definition = erased(fit.task);\n\t\ttry {\n\t\t\tif (definition.migrate === undefined) throw missingMigration(record, definition);\n\t\t\tconst migrated = definition.migrate(record.input, record.state.checkpoint, record.version);\n\t\t\tconst state = { ...record.state, checkpoint: copyJson(migrated.checkpoint) };\n\t\t\tconst migratedRecord = { ...record, version: definition.version, input: copyJson(migrated.input), state };\n\t\t\treturn { kind: \"ready\", task: fit.task, record: migratedRecord as RunnableTaskRecord };\n\t\t} catch (error) {\n\t\t\tthis.#failedMigrations.set(record.id, { task: fit.task, error });\n\t\t\tthis.#report(error);\n\t\t\treturn { kind: \"blocked\", reason: \"migration_failed\" };\n\t\t}\n\t}\n\n\t#fit(record: AnyTaskRecord, task: AnyTask | undefined): Fit {\n\t\tif (task === undefined) return { reason: \"missing_task\" };\n\t\tconst version = task.definition.version;\n\t\tif (version === record.version) return { task, migrates: false };\n\t\tif (version < record.version) return { reason: \"task_too_old\" };\n\t\tconst failed = this.#failedMigrations.get(record.id);\n\t\tif (failed?.task === task) return { reason: \"migration_failed\", error: failed.error };\n\t\treturn { task, migrates: true };\n\t}\n\n\t/**\n\t * Scheduling state and every live task with its derived state, read on the Session line. Runs no task code: a\n\t * pending migration shows as `ready` with `migrates`, and only a migration the scheduler already tried, or one that\n\t * cannot exist, shows as failed.\n\t */\n\tasync inspect(\n\t\tsnapshot: RegistrySnapshot,\n\t): Promise<{ scheduling: HarnessInspection[\"scheduling\"]; tasks: TaskInspection[] }> {\n\t\tawait this.#loadScopes(false);\n\t\tconst owned = this.#ownedLive();\n\t\tconst tasks: TaskInspection[] = [];\n\t\tfor (const record of this.#live.values()) {\n\t\t\ttasks.push({ record, state: this.#inspectTask(record, snapshot, owned) });\n\t\t}\n\t\tconst scheduling = this.#closing ? \"closing\" : this.#enabled ? \"running\" : \"paused\";\n\t\treturn { scheduling, tasks };\n\t}\n\n\t#inspectTask(\n\t\trecord: AnyTaskRecord,\n\t\tsnapshot: RegistrySnapshot,\n\t\towned: ReadonlyMap<TaskId, readonly TaskId[]>,\n\t): TaskInspection[\"state\"] {\n\t\tif (this.#invocations.has(record.id)) return { kind: \"running\" };\n\t\tif (record.state.status === \"completing\") return { kind: \"completing\" };\n\t\tconst on = this.#waitingOn(record, owned);\n\t\tif (on.length > 0) return { kind: \"waiting\", on };\n\t\tconst fit = this.#fit(record, snapshot.task(record.kind));\n\t\tif (\"reason\" in fit) return { kind: \"blocked\", ...fit };\n\t\tif (fit.migrates && fit.task.definition.migrate === undefined) {\n\t\t\treturn { kind: \"blocked\", reason: \"migration_failed\", error: missingMigration(record, erased(fit.task)) };\n\t\t}\n\t\treturn { kind: \"ready\", migrates: fit.migrates };\n\t}\n\n\t#createInvocation(record: AnyTaskRecord, mode: \"run\" | \"abort\"): Invocation {\n\t\tconst controller = new AbortController();\n\t\tconst { promise: done, resolve: finish } = Promise.withResolvers<void>();\n\t\tconst invocation: Invocation = {\n\t\t\ttaskId: record.id,\n\t\t\tconversationId: record.conversationId,\n\t\t\tmode,\n\t\t\tcontroller,\n\t\t\tcontext: withAbortSignal(controller.signal, this.#context),\n\t\t\twatches: new Set(),\n\t\t\tended: false,\n\t\t\tdone,\n\t\t\tfinish: () => finish(),\n\t\t};\n\t\tthis.#invocations.set(record.id, invocation);\n\t\treturn invocation;\n\t}\n\n\t#start(reservation: Reservation): void {\n\t\tconst invocation = reservation.invocation;\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tif (invocation.mode === \"run\") await this.#run(reservation);\n\t\t\t\telse await this.#runAbort(reservation);\n\t\t\t} catch (error) {\n\t\t\t\tthis.#report(error);\n\t\t\t} finally {\n\t\t\t\tthis.#end(invocation);\n\t\t\t\tinvocation.finish();\n\t\t\t\tthis.#kick();\n\t\t\t}\n\t\t})();\n\t}\n\n\t/** Run phase handlers, each preceded by a step that decides on the line whether the invocation continues. */\n\tasync #run(reservation: Reservation): Promise<void> {\n\t\tconst invocation = reservation.invocation;\n\t\tconst state = { task: reservation.task, snapshot: reservation.snapshot, reported: undefined as ReportedTask };\n\t\tconst phase: Phase = { snapshot: () => state.snapshot, task: () => state.task, agent: undefined };\n\t\tconst runtime = this.#runtime(invocation, phase);\n\t\tlet previous: PhaseResult | undefined;\n\t\tfor (;;) {\n\t\t\tconst current = await this.#step(invocation, (tx, current) => this.#decide(tx, current, previous, state));\n\t\t\t// Close may seal between the decision and dispatch.\n\t\t\tif (current === undefined || this.#closing) return;\n\t\t\tconst checkpoint = current.state.checkpoint;\n\t\t\t// Each phase handler resolves its agent afresh, at first use.\n\t\t\tphase.agent = undefined;\n\t\t\ttry {\n\t\t\t\tawait erased(state.task).phases[checkpoint.phase]!(current, runtime, invocation.context);\n\t\t\t\tprevious = { checkpoint };\n\t\t\t} catch (error) {\n\t\t\t\tprevious = { checkpoint, failure: { error } };\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Precedence rules for a run invocation, on the line. Rules 1 (terminal, `completing`, or `waiting`) and 2 (closing)\n\t * are applied by `#step`. Returns whether the invocation continues with the next phase.\n\t */\n\t#decide(\n\t\ttx: Transaction,\n\t\tcurrent: ErasedRunningTask,\n\t\tprevious: PhaseResult | undefined,\n\t\tstate: { task: AnyTask; snapshot: RegistrySnapshot; reported: ReportedTask },\n\t): Decision {\n\t\t// 3. abort mark: end; a fresh abort invocation starts once the task's ordinary owned work is gone.\n\t\tif (current.abortRequested) return false;\n\t\tif (previous === undefined) return true;\n\t\t// 4. uncaught error.\n\t\tif (previous.failure !== undefined) return { fault: previous.failure.error };\n\t\t// 6. no durable progress.\n\t\tif (jsonEqual(current.state.checkpoint, previous.checkpoint)) {\n\t\t\tconst message = `Task ${current.kind} phase ${previous.checkpoint.phase} returned without durable progress`;\n\t\t\treturn { fault: new Error(message) };\n\t\t}\n\t\t// 5. progress: refresh the snapshot; hand over to a replacement definition that can take the task.\n\t\tstate.snapshot = this.#registry.snapshot();\n\t\tconst next = state.snapshot.task(current.kind);\n\t\tif (next !== state.task) {\n\t\t\tif (next !== undefined && canReserve(next, current)) {\n\t\t\t\ttx.setTask(withState(current, { status: \"pending\", checkpoint: current.state.checkpoint }));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (state.reported === undefined || state.reported.task !== next) {\n\t\t\t\tstate.reported = { task: next };\n\t\t\t\tconst cause = next === undefined ? \"missing_task\" : \"incompatible_task\";\n\t\t\t\tthis.#report(\n\t\t\t\t\tnew Error(`Task ${current.id} keeps running under its old ${current.kind} definition`, { cause }),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t/** Run the abort handler once; rules 1, 2, and 4 apply, and returning without an outcome faults. */\n\tasync #runAbort(reservation: Reservation): Promise<void> {\n\t\tconst invocation = reservation.invocation;\n\t\tconst current = this.#live.get(invocation.taskId) as ErasedRunningTask | undefined;\n\t\tif (current === undefined || this.#closing) return;\n\t\tlet failure: { readonly error: unknown } | undefined;\n\t\ttry {\n\t\t\tconst phase: Phase = { snapshot: () => reservation.snapshot, task: () => reservation.task, agent: undefined };\n\t\t\tconst runtime = this.#runtime(invocation, phase);\n\t\t\tawait erased(reservation.task).abort(current, runtime, invocation.context);\n\t\t} catch (error) {\n\t\t\tfailure = { error };\n\t\t}\n\t\tconst message = `Abort handler of task ${invocation.taskId} returned without a terminal outcome`;\n\t\tawait this.#step(invocation, () => ({ fault: failure?.error ?? new Error(message) }));\n\t}\n\n\t/**\n\t * One synchronous decision on the Session line. A task that is no longer running (rule 1: terminal, `completing`, or\n\t * `waiting`) or a closing Harness (rule 2) ends the invocation without a write; otherwise `decide` may stage a write\n\t * and returns whether the invocation continues. Ending happens inside the callback, before a fault's Harness\n\t * cleanup. A rejected step, such as admission after close, also ends the invocation.\n\t */\n\tasync #step(\n\t\tinvocation: Invocation,\n\t\tdecide: (tx: Transaction, current: ErasedRunningTask) => Decision,\n\t): Promise<ErasedRunningTask | undefined> {\n\t\ttry {\n\t\t\treturn await this.#session.commitWith(async (tx) => {\n\t\t\t\tconst found = this.#live.get(invocation.taskId);\n\t\t\t\tconst current = found?.state.status === \"running\" ? (found as ErasedRunningTask) : undefined;\n\t\t\t\tconst decision = current !== undefined && !this.#closing ? decide(tx, current) : false;\n\t\t\t\tif (decision === true) return current;\n\t\t\t\tthis.#end(invocation);\n\t\t\t\tif (decision !== false) {\n\t\t\t\t\tconst message = decision.fault instanceof Error ? decision.fault.message : String(decision.fault);\n\t\t\t\t\tawait this.#terminate(tx, current!, { status: \"faulted\", error: { message } });\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t}, this.#context);\n\t\t} catch (error) {\n\t\t\tthis.#end(invocation);\n\t\t\tif (!this.#closing) this.#report(error);\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Write an outcome the scheduler decided. While the task's ordinary owned work is live it holds as `completing` and\n\t * its Harness cleanup waits for the final commit (spec §5.5, rule 4); otherwise it is terminal with its cleanup.\n\t */\n\tasync #terminate(tx: Transaction, record: AnyTaskRecord, outcome: SchedulerOutcome): Promise<void> {\n\t\tawait this.#loadScopes(false);\n\t\tif (this.#ownedLive(overlayOf(tx)).has(record.id)) {\n\t\t\ttx.setTask(withState(record, { status: \"completing\", outcome }));\n\t\t\treturn;\n\t\t}\n\t\ttx.setTask(withState(record, { status: \"terminal\", outcome }));\n\t\tawait this.#settleOutcome(tx, record, outcome);\n\t}\n\n\t/**\n\t * Replace a running task's state with what it committed. A terminal state holds as `completing` while ordinary owned\n\t * work is live, judged on the commit's candidates, so work the same commit creates below the task counts. A wait is\n\t * validated first.\n\t */\n\tasync #commitState(\n\t\ttx: Transaction,\n\t\tinvocation: Invocation,\n\t\tcurrent: ErasedRunningTask,\n\t\tnext: NextTaskState<Checkpoint, JsonValue>,\n\t): Promise<void> {\n\t\tif (next.status === \"waiting\") await this.#validateWait(tx, invocation, current, next.on, next.policy);\n\t\tif (next.status === \"terminal\") {\n\t\t\tconst overlay = overlayOf(tx);\n\t\t\tawait this.#loadScopes(false);\n\t\t\tfor (const record of overlay.tasks.values()) await this.#loadChain(parentOf(record), overlay);\n\t\t\tif (this.#ownedLive(overlay).has(current.id)) {\n\t\t\t\ttx.setTask(withState(current, { status: \"completing\", outcome: next.outcome }));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\ttx.setTask(withState(current, next));\n\t}\n\n\t/**\n\t * A wait names existing tasks other than the waiter and its owners, which could never finish first; `failFast` only\n\t * tasks the waiter owns. An abort handler cannot wait.\n\t */\n\tasync #validateWait(\n\t\ttx: Transaction,\n\t\tinvocation: Invocation,\n\t\tcurrent: ErasedRunningTask,\n\t\ton: readonly TaskId[],\n\t\tpolicy: string,\n\t): Promise<void> {\n\t\tif (invocation.mode === \"abort\") throw new Error(`Abort handler of task ${current.id} cannot wait`);\n\t\tconst overlay = overlayOf(tx);\n\t\tawait this.#loadChain(parentOf(current));\n\t\tconst owners = new Set<TaskId>();\n\t\tfor (const step of this.#above(parentOf(current))) if (\"task\" in step) owners.add(step.task);\n\t\tfor (const id of on) {\n\t\t\tif (id === current.id || owners.has(id)) {\n\t\t\t\tthrow new Error(`Task ${current.id} cannot wait on itself or its owner ${id}`);\n\t\t\t}\n\t\t\tconst member = overlay.tasks.get(id) ?? this.#live.get(id) ?? (await this.#storage.task(id, this.#context));\n\t\t\tif (member === undefined) throw new Error(`Task ${id} does not exist`);\n\t\t\tif (policy === \"failFast\" && member.owner !== current.id) {\n\t\t\t\tthrow new Error(`Task ${current.id} can wait failFast only on tasks it owns; ${id} is not one`);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** End an invocation: its runtime operations reject from now on, its signal aborts, its watches stop, and its task is free. */\n\t#end(invocation: Invocation): void {\n\t\tif (invocation.ended) return;\n\t\tinvocation.ended = true;\n\t\tif (this.#invocations.get(invocation.taskId) === invocation) this.#invocations.delete(invocation.taskId);\n\t\tfor (const watch of invocation.watches) void watch.stop();\n\t\t// Pending waits bound to the invocation, such as a tool's waitForTask(), reject with it.\n\t\tinvocation.controller.abort(endedError(invocation));\n\t}\n\n\t/** No live non-background task in the scope; a task whose owner edges are not loaded yet counts as inside. */\n\t#idle(conversationId: ConversationId | undefined): boolean {\n\t\tconst scope: Scope = conversationId === undefined ? { roots: true } : { conversation: conversationId };\n\t\tfor (const record of this.#live.values()) {\n\t\t\tif (!record.background && this.#inScope(parentOf(record), scope) !== false) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t// ─── Invocation runtime ──────────────────────────────────────────────────\n\n\t#runtime(invocation: Invocation, phase: Phase): ErasedRuntime {\n\t\t// Resolved at most once per phase handler, at first use, with the invocation's context; fixed for the phase.\n\t\tconst agent = (): Promise<Agent> => {\n\t\t\tif (invocation.ended) return Promise.reject(endedError(invocation));\n\t\t\tif (phase.agent === undefined) {\n\t\t\t\tphase.agent = this.#agent(invocation.conversationId, phase.snapshot(), invocation.context);\n\t\t\t\t// A caller that stops waiting must not leave the shared resolution's failure unobserved.\n\t\t\t\tphase.agent.catch(() => {});\n\t\t\t}\n\t\t\treturn phase.agent;\n\t\t};\n\t\tconst hooks: HookRunner<Record<string, unknown>> = {\n\t\t\teach: async (name, invoke) => {\n\t\t\t\tfor (const handlers of agentHooks(await agent(), phase.task().definition.name)) {\n\t\t\t\t\tconst handler = (handlers as Record<string, unknown>)[name];\n\t\t\t\t\tif (typeof handler !== \"function\") continue;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait invoke(handler.bind(handlers));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (invocation.controller.signal.aborted) throw error;\n\t\t\t\t\t\tthis.#report(error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t\tconst settings = this.#settings;\n\t\treturn {\n\t\t\ttaskId: invocation.taskId as TaskId<JsonValue>,\n\t\t\tconversationId: invocation.conversationId,\n\t\t\tsignal: invocation.controller.signal,\n\t\t\tmodels: this.#models,\n\t\t\tagent: (context) =>\n\t\t\t\tinvocation.ended ? Promise.reject(endedError(invocation)) : awaitWithContext(agent(), context),\n\t\t\tget settings() {\n\t\t\t\treturn settings();\n\t\t\t},\n\t\t\tenv: (context) => this.#read(invocation, () => this.#env(invocation.conversationId, context)),\n\t\t\thooks: hooks as ErasedRuntime[\"hooks\"],\n\t\t\tget registry() {\n\t\t\t\treturn phase.snapshot();\n\t\t\t},\n\t\t\tcommit: (change, context) =>\n\t\t\t\tthis.#gated(\n\t\t\t\t\tinvocation,\n\t\t\t\t\tasync (tx, current) => {\n\t\t\t\t\t\tconst next = await change(tx, current);\n\t\t\t\t\t\tif (next !== undefined) await this.#commitState(tx, invocation, current, next);\n\t\t\t\t\t},\n\t\t\t\t\tcontext,\n\t\t\t\t),\n\t\t\tmemo: ((name: string, ...rest: readonly unknown[]) => {\n\t\t\t\tif (rest.length === 1) {\n\t\t\t\t\treturn this.#read(invocation, async () => memoOf(this.#live.get(invocation.taskId), name));\n\t\t\t\t}\n\t\t\t\tconst candidate = rest[0] as JsonValue;\n\t\t\t\treturn this.#gated(\n\t\t\t\t\tinvocation,\n\t\t\t\t\t(tx, current) => {\n\t\t\t\t\t\tconst winner = memoOf(current, name);\n\t\t\t\t\t\tif (winner !== undefined) return winner;\n\t\t\t\t\t\ttx.setTask({ ...current, memos: { ...current.memos, [name]: candidate } } as AnyTaskRecord);\n\t\t\t\t\t\treturn candidate;\n\t\t\t\t\t},\n\t\t\t\t\trest[1] as Context,\n\t\t\t\t);\n\t\t\t}) as ErasedRuntime[\"memo\"],\n\t\t\tsleep: (until, context) => this.#sleep(invocation, until, context),\n\t\t\twatchDoc: ((...args: readonly unknown[]) => this.#watchDoc(invocation, args)) as ErasedRuntime[\"watchDoc\"],\n\t\t\tsnapshot: ((...args: readonly unknown[]) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tsessionMethod(this.#session, \"snapshot\")(...args),\n\t\t\t\t)) as ErasedRuntime[\"snapshot\"],\n\t\t\tsnapshotAsOf: ((...args: readonly unknown[]) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tsessionMethod(this.#session, \"snapshotAsOf\")(...args),\n\t\t\t\t)) as ErasedRuntime[\"snapshotAsOf\"],\n\t\t\tgetTask: ((id: TaskId, context: Context) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tthis.#session.readOnLine(() => this.#storage.task(id, context)),\n\t\t\t\t)) as ErasedRuntime[\"getTask\"],\n\t\t\twaitForTask: ((id: TaskId, context: Context) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tthis.waitForTask(id, withAbortSignal(invocation.controller.signal, context)),\n\t\t\t\t)) as ErasedRuntime[\"waitForTask\"],\n\t\t\toutcomes: ((ids: readonly TaskId[], context: Context) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tthis.#session.readOnLine(async () => {\n\t\t\t\t\t\tconst outcomes: TaskOutcome<JsonValue>[] = [];\n\t\t\t\t\t\tfor (const id of ids) {\n\t\t\t\t\t\t\tconst state = (await this.#storage.task(id, context))?.state;\n\t\t\t\t\t\t\tif (state?.status !== \"terminal\") throw new Error(`Task ${id} is not terminal`);\n\t\t\t\t\t\t\toutcomes.push(state.outcome);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn outcomes;\n\t\t\t\t\t}),\n\t\t\t\t)) as ErasedRuntime[\"outcomes\"],\n\t\t\tconversation: (id, context) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tthis.#conversation(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsignal: invocation.controller.signal,\n\t\t\t\t\t\t\tcheck: () => {\n\t\t\t\t\t\t\t\tif (invocation.ended) throw endedError(invocation);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\tentry: ((...args: readonly unknown[]) => {\n\t\t\t\tconst [token, id, context] =\n\t\t\t\t\targs.length === 2\n\t\t\t\t\t\t? [undefined, args[0] as EntryId, args[1] as Context]\n\t\t\t\t\t\t: [args[0] as { readonly kind: string }, args[1] as EntryId, args[2] as Context];\n\t\t\t\treturn this.#read(invocation, async () => {\n\t\t\t\t\tconst found = await this.#session.readOnLine(() =>\n\t\t\t\t\t\tthis.#storage.entry(invocation.conversationId, id, context),\n\t\t\t\t\t);\n\t\t\t\t\tconst entry: EntryRecord | undefined = found?.entry;\n\t\t\t\t\treturn token === undefined || entry?.kind === token.kind ? entry : undefined;\n\t\t\t\t});\n\t\t\t}) as ErasedRuntime[\"entry\"],\n\t\t\tcontext: (conversationId, context, at) =>\n\t\t\t\tthis.#read(invocation, () => readContext(this.#session, this.#storage, conversationId, context, at)),\n\t\t\tnow: () => {\n\t\t\t\tif (invocation.ended) throw endedError(invocation);\n\t\t\t\treturn this.#now();\n\t\t\t},\n\t\t\treport: (error) => {\n\t\t\t\tif (invocation.ended) throw endedError(invocation);\n\t\t\t\tthis.#report(error);\n\t\t\t},\n\t\t};\n\t}\n\n\t/** Run a committed-state read unless the invocation has ended. */\n\tasync #read<T>(invocation: Invocation, read: () => Promise<T>): Promise<T> {\n\t\tif (invocation.ended) throw endedError(invocation);\n\t\treturn read();\n\t}\n\n\t/** Commit after rereading the task on the line and gating the invocation. */\n\t#gated<T>(\n\t\tinvocation: Invocation,\n\t\tchange: (tx: Transaction, current: ErasedRunningTask) => T | Promise<T>,\n\t\tcontext: Context,\n\t): Promise<T> {\n\t\tif (invocation.ended) return Promise.reject(endedError(invocation));\n\t\treturn this.#session.commitWith(\n\t\t\tasync (tx) => {\n\t\t\t\tif (invocation.ended) throw endedError(invocation);\n\t\t\t\tif (this.#closing) throw closedError();\n\t\t\t\tconst found = this.#live.get(invocation.taskId);\n\t\t\t\tif (found === undefined) throw new Error(`Task ${invocation.taskId} is terminal`);\n\t\t\t\tif (found.state.status !== \"running\") throw new Error(`Task ${invocation.taskId} is ${found.state.status}`);\n\t\t\t\tconst current = found as ErasedRunningTask;\n\t\t\t\tif (invocation.mode === \"run\" && current.abortRequested) {\n\t\t\t\t\tthrow new Error(`Task ${invocation.taskId} has a durable abort mark`);\n\t\t\t\t}\n\t\t\t\treturn change(tx, current);\n\t\t\t},\n\t\t\tcontext,\n\t\t\t{ conversationId: invocation.conversationId, taskId: invocation.taskId },\n\t\t);\n\t}\n\n\t/** Wait until the Harness clock reaches `until`, rechecking it after every timer. */\n\tasync #sleep(invocation: Invocation, until: number, context: Context): Promise<void> {\n\t\tif (invocation.ended) throw endedError(invocation);\n\t\tconst signals = [invocation.controller.signal];\n\t\tif (context.abortSignal !== undefined) signals.push(context.abortSignal);\n\t\tconst signal = AbortSignal.any(signals);\n\t\tfor (;;) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst remaining = until - this.#now();\n\t\t\tif (remaining <= 0) return;\n\t\t\tawait delay(Math.min(remaining, MAX_TIMER_DELAY), signal);\n\t\t}\n\t}\n\n\tasync #watchDoc(invocation: Invocation, args: readonly unknown[]): Promise<DocumentWatch<JsonObject> | undefined> {\n\t\tif (invocation.ended) throw endedError(invocation);\n\t\tconst watch = (await sessionMethod(this.#session, \"watchDoc\")(...args)) as DocumentWatch<JsonObject> | undefined;\n\t\tif (watch === undefined) return undefined;\n\t\tif (invocation.ended) {\n\t\t\tvoid watch.stop();\n\t\t\tthrow endedError(invocation);\n\t\t}\n\t\tinvocation.watches.add(watch);\n\t\tvoid watch.closed.then(() => invocation.watches.delete(watch));\n\t\treturn watch;\n\t}\n}\n\n/** A live owner's durable cancellation intent: its abort mark, or a held outcome other than `completed`. */\nfunction cancellationIntent(record: AnyTaskRecord): boolean {\n\treturn record.state.status !== \"terminal\" && (record.abortRequested || failedOutcome(record));\n}\n\n/** Whether the record holds or ends with an outcome other than `completed`. */\nfunction failedOutcome(record: AnyTaskRecord): boolean {\n\tconst state = record.state;\n\treturn (state.status === \"completing\" || state.status === \"terminal\") && state.outcome.status !== \"completed\";\n}\n\nfunction parentOf(node: TaskNode): Up {\n\treturn node.owner !== undefined ? { task: node.owner } : { conversation: node.conversationId };\n}\n\nfunction nodeOf(record: AnyTaskRecord): TaskNode {\n\treturn {\n\t\tconversationId: record.conversationId,\n\t\t...(record.owner === undefined ? {} : { owner: record.owner }),\n\t\tbackground: record.background,\n\t};\n}\n\nfunction overlayOf(tx: Transaction): Overlay {\n\tconst tasks = new Map(tx.stagedTasks().map((record) => [record.id, record]));\n\tconst edges = new Map(tx.stagedConversations().map((record) => [record.id, record.owner?.taskId ?? null]));\n\treturn { tasks, edges };\n}\n\n/** Own memo entry only; memo names such as `toString` must not resolve to inherited properties. */\nfunction memoOf(record: AnyTaskRecord | undefined, name: string): JsonValue | undefined {\n\tconst memos = record?.memos;\n\treturn memos !== undefined && Object.hasOwn(memos, name) ? memos[name] : undefined;\n}\n\n/** Overloaded Session method bound for forwarding an argument list unchanged. */\nfunction sessionMethod(\n\tsession: SessionImpl,\n\tname: \"snapshot\" | \"snapshotAsOf\" | \"watchDoc\",\n): (...args: readonly unknown[]) => Promise<unknown> {\n\treturn (session[name] as (...args: readonly unknown[]) => Promise<unknown>).bind(session);\n}\n\nfunction missingMigration(record: AnyTaskRecord, definition: ErasedDefinition): Error {\n\treturn new Error(`Task ${record.kind} version ${definition.version} has no migration from ${record.version}`);\n}\n\nfunction erased(task: AnyTask): ErasedDefinition {\n\treturn task.definition as unknown as ErasedDefinition;\n}\n\nfunction endedError(invocation: Invocation): Error {\n\treturn new Error(`Task ${invocation.taskId} invocation has ended`);\n}\n\n/** Replace a live record's state; memos disappear once an outcome is decided. */\nfunction withState(record: AnyTaskRecord, state: TaskState<JsonValue, JsonValue>): AnyTaskRecord {\n\tif (state.status !== \"terminal\" && state.status !== \"completing\") return { ...record, state } as AnyTaskRecord;\n\tconst { memos: _memos, ...rest } = record;\n\treturn { ...rest, state };\n}\n\n/** Whether a definition can take the task at reservation: same version, or newer with a migration. */\nfunction canReserve(task: AnyTask, record: AnyTaskRecord): boolean {\n\tconst definition = task.definition;\n\treturn (\n\t\tdefinition.version === record.version || (definition.version > record.version && definition.migrate !== undefined)\n\t);\n}\n\nfunction delay(ms: number, signal: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst onAbort = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\treject(signal.reason);\n\t\t};\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\n/** Structural equality of two JSON values; object key order is ignored. */\nfunction jsonEqual(left: JsonValue | undefined, right: JsonValue | undefined): boolean {\n\tif (left === right) return true;\n\tif (typeof left !== \"object\" || typeof right !== \"object\" || left === null || right === null) return false;\n\tif (Array.isArray(left) || Array.isArray(right)) {\n\t\tif (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;\n\t\treturn left.every((value, index) => jsonEqual(value, right[index]));\n\t}\n\tconst keys = Object.keys(left);\n\tif (keys.length !== Object.keys(right).length) return false;\n\treturn keys.every((key) => Object.hasOwn(right, key) && jsonEqual(left[key], right[key]));\n}\n", "import { type AttachedReplicatedState, type Context, type JsonValue, replicatedState } from \"@earendil-works/chord\";\nimport { withoutAbortSignal } from \"@earendil-works/chord/context\";\nimport { applyImmutable, type Op } from \"@earendil-works/chord/delta\";\nimport { CommittedStateSource, CommittedWatch } from \"../session/observation.ts\";\nimport type { SessionImpl } from \"../session/session.ts\";\nimport type {\n\tCommitPublication,\n\tConversationId,\n\tJoinPolicy,\n\tStorage,\n\tTaskId,\n\tTaskOutcome,\n\tTaskRecord,\n\tWatchHandle,\n} from \"../types.ts\";\nimport { closedError, scanAll } from \"./util.ts\";\n\n/** A live task's durable status without its checkpoint and outcome payloads (spec §9.5). */\nexport type TaskGraphState =\n\t| { readonly status: \"pending\" | \"running\"; readonly phase: string }\n\t| {\n\t\t\treadonly status: \"waiting\";\n\t\t\treadonly phase: string;\n\t\t\treadonly on: readonly TaskId[];\n\t\t\treadonly policy: JoinPolicy;\n\t }\n\t/** Outcome held until its ordinary owned work drains. */\n\t| { readonly status: \"completing\"; readonly outcome: TaskOutcome<JsonValue>[\"status\"] };\n\nexport type TaskGraphNode = {\n\treadonly id: TaskId;\n\treadonly kind: string;\n\treadonly conversationId: ConversationId;\n\t/** Owner task; absent for a conversation-owned task. */\n\treadonly owner?: TaskId;\n\treadonly background: boolean;\n\treadonly abortRequested: boolean;\n\treadonly state: TaskGraphState;\n\t/** Conversations this task owns, in ID order. */\n\treadonly conversations: readonly ConversationId[];\n};\n\n/** Every live task of the Session (spec §9.5). */\nexport type TaskGraph = {\n\t/** Every live task, keyed by its decimal ID. */\n\treadonly tasks: Readonly<Record<string, TaskGraphNode>>;\n};\n\nexport type TaskGraphWatch = WatchHandle<TaskGraph>;\n\ntype AnyTaskRecord = TaskRecord<JsonValue, JsonValue, JsonValue>;\ntype Observer = CommittedStateSource<TaskGraph> | CommittedWatch<TaskGraph>;\ntype Mount = { value: TaskGraph; readonly observers: Set<Observer> };\n\nconst LIVE_STATUSES = [\"pending\", \"running\", \"waiting\", \"completing\"] as const;\nconst SCAN_PAGE_SIZE = 256;\n\n/**\n * The Harness's task graph mount: built on the Session line by its first observer and dropped with its last. It\n * advances from the Session's commit publications, which are durable.\n */\nexport class TaskGraphView {\n\treadonly #session: SessionImpl;\n\treadonly #storage: Storage;\n\t#mount: Mount | undefined;\n\t#closed = false;\n\n\tconstructor(session: SessionImpl, storage: Storage) {\n\t\tthis.#session = session;\n\t\tthis.#storage = storage;\n\t\tsession.subscribeCommits((publication, context) => {\n\t\t\tif (this.#mount !== undefined) advance(this.#mount, publication, context);\n\t\t});\n\t\tsession.subscribeClose(() => {\n\t\t\tthis.#closed = true;\n\t\t\tfor (const observer of [...(this.#mount?.observers ?? [])]) observer.closeSession();\n\t\t\tthis.#mount = undefined;\n\t\t});\n\t}\n\n\t/** A disposable read-only Chord state of the graph. */\n\tasync state(context: Context): Promise<AttachedReplicatedState<TaskGraph>> {\n\t\tconst { observer, detach } = await this.#attach(\n\t\t\t(value, release) => new CommittedStateSource<TaskGraph>(value, release),\n\t\t\tcontext,\n\t\t);\n\t\ttry {\n\t\t\treturn replicatedState(observer);\n\t\t} catch (error) {\n\t\t\tdetach();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/** A serialized exact-frame watch of the graph; cancelling `context` stops it. */\n\tasync watch(context: Context): Promise<TaskGraphWatch> {\n\t\tconst { observer } = await this.#attach(\n\t\t\t(value, release) => new CommittedWatch<TaskGraph>(value, release),\n\t\t\tcontext,\n\t\t);\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) {\n\t\t\tobserver.cancel();\n\t\t\tthrow signal.reason;\n\t\t}\n\t\tif (signal !== undefined) observer.observeCancellation(signal);\n\t\treturn observer;\n\t}\n\n\t/** Register an observer created from the current revision, atomically on the Session line. */\n\t#attach<O extends Observer>(\n\t\tcreate: (value: TaskGraph, release: () => void) => O,\n\t\tcontext: Context,\n\t): Promise<{ observer: O; detach: () => void }> {\n\t\treturn this.#session.readOnLine(async () => {\n\t\t\tconst mount = this.#mount ?? { value: await this.#build(context), observers: new Set<Observer>() };\n\t\t\tconst detach = (): void => {\n\t\t\t\tmount.observers.delete(observer);\n\t\t\t\tif (mount.observers.size === 0 && this.#mount === mount) this.#mount = undefined;\n\t\t\t};\n\t\t\tconst observer = create(mount.value, detach);\n\t\t\t// Close or cancellation may begin while the mount builds; register nothing then.\n\t\t\tif (this.#closed) throw closedError();\n\t\t\tcontext.abortSignal?.throwIfAborted();\n\t\t\tthis.#mount = mount;\n\t\t\tmount.observers.add(observer);\n\t\t\treturn { observer, detach };\n\t\t});\n\t}\n\n\tasync #build(context: Context): Promise<TaskGraph> {\n\t\tconst tasks: Record<string, TaskGraphNode> = {};\n\t\tconst records: AnyTaskRecord[] = [];\n\t\tfor (const status of LIVE_STATUSES) {\n\t\t\trecords.push(\n\t\t\t\t...(await scanAll((cursor) => this.#storage.scanTasks({ status }, SCAN_PAGE_SIZE, cursor, context))),\n\t\t\t);\n\t\t}\n\t\trecords.sort((a, b) => a.id - b.id);\n\t\tfor (const record of records) {\n\t\t\tconst owned = await scanAll((cursor) =>\n\t\t\t\tthis.#storage.scanConversations({ ownerTaskId: record.id }, SCAN_PAGE_SIZE, cursor, context),\n\t\t\t);\n\t\t\tconst conversations = owned.map((conversation) => conversation.id).sort((a, b) => a - b);\n\t\t\ttasks[String(record.id)] = nodeOf(record, conversations);\n\t\t}\n\t\treturn { tasks };\n\t}\n}\n\n/** Derive the mount's operations from one publication, apply them, and hand the revision to every observer. */\nfunction advance(mount: Mount, publication: CommitPublication, context: Context): void {\n\tconst ops: Op[] = [];\n\t// Nodes this publication set or deleted, over the mount's value.\n\tconst changed = new Map<string, TaskGraphNode | undefined>();\n\tconst node = (key: string): TaskGraphNode | undefined =>\n\t\tchanged.has(key) ? changed.get(key) : mount.value.tasks[key];\n\tfor (const change of publication.changes) {\n\t\tif (change.type !== \"task\") continue;\n\t\tconst record = change.value;\n\t\tconst key = String(record.id);\n\t\tconst previous = node(key);\n\t\tif (record.state.status === \"terminal\") {\n\t\t\tif (previous === undefined) continue;\n\t\t\tops.push([\"d\", [\"tasks\", key]]);\n\t\t\tchanged.set(key, undefined);\n\t\t\tcontinue;\n\t\t}\n\t\tconst next = nodeOf(record, previous?.conversations ?? []);\n\t\tif (previous !== undefined && JSON.stringify(next) === JSON.stringify(previous)) continue;\n\t\tops.push([\"s\", [\"tasks\", key], next as unknown as JsonValue]);\n\t\tchanged.set(key, next);\n\t}\n\t// After the tasks, so a conversation created with its owner task in one commit finds the owner's node. Change order\n\t// within a publication is unspecified, so each owner's list is sorted again.\n\tconst created = new Map<string, ConversationId[]>();\n\tfor (const change of publication.changes) {\n\t\tif (change.type !== \"conversation\" || change.value.owner === undefined) continue;\n\t\tconst key = String(change.value.owner.taskId);\n\t\tif (node(key) !== undefined) created.set(key, [...(created.get(key) ?? []), change.value.id]);\n\t}\n\tfor (const [key, ids] of created) {\n\t\tconst conversations = [...node(key)!.conversations, ...ids].sort((a, b) => a - b);\n\t\tops.push([\"s\", [\"tasks\", key, \"conversations\"], conversations]);\n\t}\n\tif (ops.length === 0) return;\n\tmount.value = applyImmutable(mount.value, ops);\n\tconst frameContext = withoutAbortSignal(context);\n\tfor (const observer of [...mount.observers]) observer.advance(mount.value, ops, frameContext);\n}\n\nfunction nodeOf(record: AnyTaskRecord, conversations: readonly ConversationId[]): TaskGraphNode {\n\treturn {\n\t\tid: record.id,\n\t\tkind: record.kind,\n\t\tconversationId: record.conversationId,\n\t\t...(record.owner === undefined ? {} : { owner: record.owner }),\n\t\tbackground: record.background,\n\t\tabortRequested: record.abortRequested,\n\t\tstate: stateOf(record),\n\t\tconversations,\n\t};\n}\n\nfunction stateOf(record: AnyTaskRecord): TaskGraphState {\n\tconst state = record.state;\n\tswitch (state.status) {\n\t\tcase \"pending\":\n\t\tcase \"running\":\n\t\t\treturn { status: state.status, phase: phaseOf(state.checkpoint) };\n\t\tcase \"waiting\":\n\t\t\treturn { status: \"waiting\", phase: phaseOf(state.checkpoint), on: [...state.on], policy: state.policy };\n\t\t// Terminal records never reach here: they leave the graph.\n\t\tcase \"completing\":\n\t\tcase \"terminal\":\n\t\t\treturn { status: \"completing\", outcome: state.outcome.status };\n\t}\n}\n\nfunction phaseOf(checkpoint: JsonValue): string {\n\treturn (checkpoint as { readonly phase: string }).phase;\n}\n", "import type { AttachedReplicatedState, Context, JsonValue } from \"@earendil-works/chord\";\nimport { withAbortSignal, withoutAbortSignal } from \"@earendil-works/chord/context\";\nimport { ResetEntry } from \"../entries.ts\";\nimport type { ExecutionEnv } from \"../env/index.ts\";\nimport { SessionImpl } from \"../session/session.ts\";\nimport type { Transaction } from \"../session/transaction.ts\";\nimport type {\n\tConversationId,\n\tConversationOwnership,\n\tConversationRecord,\n\tCursor,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tPage,\n\tStorage,\n\tSubmissionId,\n\tTaskId,\n\tTaskRecord,\n\tTx,\n} from \"../types.ts\";\nimport { ROOT_CONVERSATION_ID } from \"../types.ts\";\nimport { AgentDoc, configure, createAgent, resolveAgent, resolveSettings } from \"./agent.ts\";\nimport { createCompaction } from \"./compaction.ts\";\nimport { readContext } from \"./context.ts\";\nimport { InboxDoc, withdrawQueuedInputs } from \"./inbox.ts\";\nimport { LiveDoc, settleSchedulerOutcome } from \"./live.ts\";\nimport { ProviderDoc } from \"./provider.ts\";\nimport { BUILTIN_TASKS } from \"./registry.ts\";\nimport { type InvocationBinding, TaskScheduler } from \"./scheduler.ts\";\nimport { Submissions } from \"./submissions.ts\";\nimport { type TaskGraph, TaskGraphView, type TaskGraphWatch } from \"./task-graph.ts\";\nimport type {\n\tAgent,\n\tAgentChange,\n\tCompactionResult,\n\tContextView,\n\tConversation,\n\tConversationAbortOptions,\n\tConversationCreateOptions,\n\tConversationHandle,\n\tConversationInit,\n\tConversationWatch,\n\tHarnessInspection,\n\tHarnessOptions,\n\tHarness as HarnessType,\n\tRegistrySnapshot,\n\tSettledTask,\n\tSubmission,\n\tSubmissionDraft,\n\tToolRegistration,\n} from \"./types.ts\";\nimport { addUsageState, UsageDoc, type UsageState } from \"./usage.ts\";\nimport { scanAll } from \"./util.ts\";\nimport { type ConversationView, ConversationViews } from \"./view.ts\";\n\nconst SCAN_PAGE_SIZE = 256;\n\ntype CreateTarget =\n\t| { readonly kind: \"root\" }\n\t| { readonly kind: \"independent\"; readonly ownership: ConversationOwnership }\n\t| {\n\t\t\treadonly kind: \"fork\";\n\t\t\treadonly parentId: ConversationId;\n\t\t\treadonly at: EntryId;\n\t\t\treadonly ownership: ConversationOwnership;\n\t };\n\n/** What the conveniences apply in the creating commit, after the creation hook. */\ntype CreateOptions = { readonly agent?: AgentChange; readonly init?: ConversationInit };\n\n/** Harness-private services used by Conversation handles. */\ntype ConversationHost<Tool extends ToolRegistration> = {\n\treadonly harness: HarnessImpl<Tool>;\n\treadonly storage: Storage;\n\treadonly tasks: TaskScheduler;\n\treadonly submissions: Submissions;\n\treadonly views: ConversationViews;\n\treadonly now: () => number;\n\tcreate(target: CreateTarget, options: CreateOptions, context: Context): Promise<Conversation>;\n};\n\nclass ConversationImpl<Tool extends ToolRegistration> implements Conversation {\n\treadonly id: ConversationId;\n\treadonly #host: ConversationHost<Tool>;\n\n\tconstructor(id: ConversationId, host: ConversationHost<Tool>) {\n\t\tthis.id = id;\n\t\tthis.#host = host;\n\t}\n\n\tagent(context: Context): Promise<Agent> {\n\t\treturn this.#host.harness.resolveAgent(this.id, undefined, context);\n\t}\n\n\tconfigure(change: AgentChange, context: Context): Promise<void> {\n\t\treturn this.#host.harness.commitWith((tx) => configure(tx, this.id, change), context);\n\t}\n\n\tsubmit(submission: SubmissionDraft, context: Context): Promise<Submission> {\n\t\treturn this.#host.submissions.submit(this.id, submission, context);\n\t}\n\n\tcompact(instructions: string | undefined, context: Context): Promise<TaskId<CompactionResult>> {\n\t\tthis.#host.tasks.resume();\n\t\tconst input = { reason: \"manual\", ...(instructions === undefined ? {} : { instructions }) } as const;\n\t\treturn this.#host.harness.commitWith((tx) => createCompaction(tx, this.id, input), context);\n\t}\n\n\tasync reset(handoff: string | undefined, context: Context): Promise<void> {\n\t\tconst model =\n\t\t\thandoff === undefined\n\t\t\t\t? {}\n\t\t\t\t: { model: [{ role: \"user\", content: handoff, timestamp: this.#host.now() } as const] };\n\t\tconst entry = { kind: ResetEntry.kind, head: \"self\", ...model } as const;\n\t\tawait this.#host.submissions.submit(this.id, { type: \"write\", entry }, context);\n\t}\n\n\tcommit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T> {\n\t\treturn this.#host.harness.commitWith(change, context, { conversationId: this.id });\n\t}\n\n\tcontext(context: Context): Promise<ContextView> {\n\t\treturn readContext(this.#host.harness, this.#host.storage, this.id, context);\n\t}\n\n\tentries(\n\t\tquery: Omit<EntryQuery, \"conversationId\">,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\tcontext: Context,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\tconst bounded: EntryQuery = {\n\t\t\tconversationId: this.id,\n\t\t\t...(query.minEntryId === undefined ? {} : { minEntryId: query.minEntryId }),\n\t\t\t...(query.maxEntryId === undefined ? {} : { maxEntryId: query.maxEntryId }),\n\t\t};\n\t\treturn this.#host.harness.readOnLine(() => this.#host.storage.scanEntries(bounded, limit, cursor, context));\n\t}\n\n\tfork(at: EntryId, options: ConversationCreateOptions, context: Context): Promise<Conversation> {\n\t\treturn this.#host.create({ kind: \"fork\", parentId: this.id, at, ownership: options.ownership }, options, context);\n\t}\n\n\tabort(context: Context, options?: ConversationAbortOptions): Promise<void> {\n\t\tthis.#host.tasks.resume();\n\t\treturn this.#host.tasks.abortConversation(this.id, options?.background === true, context);\n\t}\n\n\twaitForIdle(context: Context): Promise<void> {\n\t\tthis.#host.tasks.resume();\n\t\treturn this.#host.tasks.waitForIdle(this.id, context);\n\t}\n\n\tviewState(context: Context): Promise<AttachedReplicatedState<ConversationView>> {\n\t\treturn this.#host.views.state(this.id, context);\n\t}\n\n\twatch(context: Context): Promise<ConversationWatch> {\n\t\treturn this.#host.views.watch(this.id, context);\n\t}\n}\n\n/** Session kernel extended with conversation handles and a registry. */\nclass HarnessImpl<Tool extends ToolRegistration> extends SessionImpl implements HarnessType {\n\treadonly #storage: Storage;\n\treadonly #options: HarnessOptions<Tool>;\n\treadonly #report: (error: unknown) => void;\n\treadonly #host: ConversationHost<Tool>;\n\treadonly #tasks: TaskScheduler;\n\treadonly #submissions: Submissions;\n\treadonly #taskGraph: TaskGraphView;\n\t#closed = false;\n\n\tconstructor(storage: Storage, options: HarnessOptions<Tool>, context: Context) {\n\t\tsuper(storage);\n\t\tthis.#storage = storage;\n\t\tthis.#options = options;\n\t\tthis.#report = options.onReport ?? (() => {});\n\t\tconst now = options.now ?? Date.now;\n\t\tconst settings = () => resolveSettings(options.settings);\n\t\tthis.#tasks = new TaskScheduler({\n\t\t\tsession: this,\n\t\t\tstorage,\n\t\t\tregistry: options.registry,\n\t\t\tmodels: options.models,\n\t\t\tagent: (id, snapshot, callContext) => this.resolveAgent(id, snapshot as RegistrySnapshot<Tool>, callContext),\n\t\t\tsettings,\n\t\t\tenv: (id, callContext) => this.buildEnv(id, callContext),\n\t\t\tnow,\n\t\t\treport: this.#report,\n\t\t\tsettleOutcome: settleSchedulerOutcome,\n\t\t\twithdrawInputs: withdrawQueuedInputs,\n\t\t\tconversation: async (id, binding, callContext) => {\n\t\t\t\tconst record = await this.readOnLine(() => storage.conversation(id, callContext));\n\t\t\t\treturn record === undefined ? undefined : boundConversation(id, binding, this.#submissions, this.#tasks);\n\t\t\t},\n\t\t\tcontext: withoutAbortSignal(context),\n\t\t});\n\t\tthis.#submissions = new Submissions(this, storage, now, settings, () => this.#tasks.resume());\n\t\tthis.#taskGraph = new TaskGraphView(this, storage);\n\t\tthis.#host = {\n\t\t\tharness: this,\n\t\t\tstorage,\n\t\t\ttasks: this.#tasks,\n\t\t\tsubmissions: this.#submissions,\n\t\t\tviews: new ConversationViews(this, storage),\n\t\t\tnow,\n\t\t\tcreate: (target, createOptions, context) => this.#create(target, createOptions, context),\n\t\t};\n\t}\n\n\t/** Resolve a conversation's committed `pi.agent` against `snapshot`, or the current one, and the current settings. */\n\tasync resolveAgent(\n\t\tid: ConversationId,\n\t\tsnapshot: RegistrySnapshot<Tool> | undefined,\n\t\tcontext: Context,\n\t): Promise<Agent<Tool>> {\n\t\tconst registry = snapshot ?? this.#options.registry.snapshot();\n\t\tconst state = await this.snapshot(AgentDoc, id, context);\n\t\treturn resolveAgent(state, registry, resolveSettings(this.#options.settings), this.#report);\n\t}\n\n\t/** Build a conversation's environment from its current `cwd`; `undefined` without an `env` option. */\n\tasync buildEnv(id: ConversationId, context: Context): Promise<ExecutionEnv | undefined> {\n\t\tconst build = this.#options.env;\n\t\tif (build === undefined) return undefined;\n\t\tconst cwd = (await this.snapshot(AgentDoc, id, context))?.cwd;\n\t\treturn build({ conversationId: id, ...(cwd === undefined ? {} : { cwd }), read: this }, context);\n\t}\n\n\t/** Reconcile surviving `running` tasks to `pending`; part of open. */\n\topenTasks(context: Context): Promise<void> {\n\t\treturn this.#tasks.open(context);\n\t}\n\n\tresume(): void {\n\t\tthis.#assertOpen();\n\t\tthis.#tasks.resume();\n\t}\n\n\tgetTask<R>(id: TaskId<R>, context: Context): Promise<TaskRecord<JsonValue, JsonValue, R> | undefined> {\n\t\treturn this.readOnLine(() => this.#storage.task(id, context)) as Promise<\n\t\t\tTaskRecord<JsonValue, JsonValue, R> | undefined\n\t\t>;\n\t}\n\n\tinspect(context: Context): Promise<HarnessInspection> {\n\t\treturn this.readOnLine(async () => {\n\t\t\tconst { scheduling, tasks } = await this.#tasks.inspect(this.#options.registry.snapshot());\n\t\t\tconst scan = (status: \"queued\" | \"placed\") =>\n\t\t\t\tscanAll((cursor) => this.#storage.scanSubmissions({ status }, SCAN_PAGE_SIZE, cursor, context));\n\t\t\tconst submissions = [...(await scan(\"queued\")), ...(await scan(\"placed\"))].sort((a, b) => a.id - b.id);\n\t\t\treturn { scheduling, tasks, submissions };\n\t\t});\n\t}\n\n\tsubmission(id: SubmissionId, context: Context): Promise<Submission | undefined> {\n\t\treturn this.#submissions.get(id, context);\n\t}\n\n\tabortSubmission(\n\t\tid: SubmissionId,\n\t\tcontext: Context,\n\t\tconversationId?: ConversationId,\n\t): Promise<\"aborted\" | \"already_placed\" | \"settled\" | \"not_found\"> {\n\t\treturn this.#submissions.abort(id, context, conversationId);\n\t}\n\n\tabortTask(id: TaskId, context: Context): Promise<\"marked\" | \"terminal\"> {\n\t\treturn this.#tasks.abort(id, context);\n\t}\n\n\twaitForTask<R>(id: TaskId<R>, context: Context): Promise<SettledTask<R>> {\n\t\tthis.#tasks.resume();\n\t\treturn this.#tasks.waitForTask(id, context) as Promise<SettledTask<R>>;\n\t}\n\n\twaitForIdle(context: Context): Promise<void> {\n\t\tthis.#tasks.resume();\n\t\treturn this.#tasks.waitForIdle(undefined, context);\n\t}\n\n\t/** Sum every conversation's committed `pi.usage`. Each document is read at its own point; totals only grow. */\n\tasync usage(context: Context): Promise<UsageState> {\n\t\tconst conversations = await this.readOnLine(() =>\n\t\t\tscanAll((cursor) => this.#storage.scanConversations({}, SCAN_PAGE_SIZE, cursor, context)),\n\t\t);\n\t\tconst total = UsageDoc.definition.initial();\n\t\tfor (const { id } of conversations) {\n\t\t\tconst state = await this.snapshot(UsageDoc, id, context);\n\t\t\tif (state !== undefined) addUsageState(total, state);\n\t\t}\n\t\treturn total;\n\t}\n\n\ttaskGraph(context: Context): Promise<AttachedReplicatedState<TaskGraph>> {\n\t\treturn this.#taskGraph.state(context);\n\t}\n\n\twatchTaskGraph(context: Context): Promise<TaskGraphWatch> {\n\t\treturn this.#taskGraph.watch(context);\n\t}\n\n\troot(\n\t\tcontext: Context,\n\t\toptions?: { readonly agent?: AgentChange; readonly init?: ConversationInit },\n\t): Promise<Conversation> {\n\t\treturn this.#create({ kind: \"root\" }, options ?? {}, context);\n\t}\n\n\tasync conversation(id: ConversationId, context: Context): Promise<Conversation | undefined> {\n\t\tthis.#assertOpen();\n\t\tconst record = await this.readOnLine(() => this.#storage.conversation(id, context));\n\t\treturn record === undefined ? undefined : new ConversationImpl(record.id, this.#host);\n\t}\n\n\tcreateConversation(options: ConversationCreateOptions, context: Context): Promise<Conversation> {\n\t\treturn this.#create({ kind: \"independent\", ownership: options.ownership }, options, context);\n\t}\n\n\toverride close(context: Context): Promise<void> {\n\t\tthis.#closed = true;\n\t\treturn super.close(context);\n\t}\n\n\t/** Join task invocations after admission is sealed and before Storage closes; writes no task outcome. */\n\tprotected override beforeClose(): Promise<void> {\n\t\treturn this.#tasks.join();\n\t}\n\n\tasync #create(target: CreateTarget, options: CreateOptions, context: Context): Promise<Conversation> {\n\t\tthis.#assertOpen();\n\t\tconst id = await this.commitWith(async (tx) => {\n\t\t\tif (target.kind === \"root\" && (await tx.conversation(ROOT_CONVERSATION_ID)) !== undefined) {\n\t\t\t\treturn ROOT_CONVERSATION_ID;\n\t\t\t}\n\t\t\tconst record =\n\t\t\t\ttarget.kind === \"root\"\n\t\t\t\t\t? await tx.createRootConversation()\n\t\t\t\t\t: target.kind === \"fork\"\n\t\t\t\t\t\t? await tx.forkConversation(target.parentId, target.at, { ownership: target.ownership })\n\t\t\t\t\t\t: await tx.createConversation({ ownership: target.ownership });\n\t\t\tif (options.agent !== undefined) await configure(tx, record.id, options.agent);\n\t\t\tif (options.init !== undefined) await options.init(tx, record.id);\n\t\t\treturn record.id;\n\t\t}, context);\n\t\treturn new ConversationImpl(id, this.#host);\n\t}\n\n\t/**\n\t * The built-in creation hook, in every commit that creates or forks a conversation: empty `pi.live`, `pi.inbox`, and\n\t * `pi.usage`, a fresh `pi.provider`, the conversation's `pi.agent` (see `createAgent()`), then\n\t * `HarnessOptions.conversationCreated`.\n\t */\n\tprotected override async conversationCreated(tx: Transaction, record: ConversationRecord): Promise<void> {\n\t\tawait tx.doc(LiveDoc, record.id);\n\t\tawait tx.doc(InboxDoc, record.id);\n\t\tawait tx.doc(UsageDoc, record.id);\n\t\tawait tx.doc(ProviderDoc, record.id);\n\t\tawait createAgent(tx, record);\n\t\tawait this.#options.conversationCreated?.(tx, record);\n\t}\n\n\t#assertOpen(): void {\n\t\tif (this.#closed) throw new Error(\"Harness is closed\");\n\t}\n}\n\n/**\n * Invocation-bound handle for tasks and tools. Every operation, and every operation of a submission it returns, first\n * checks the invocation and runs under its signal, so it rejects once the invocation ends; admitted work stays durable.\n */\nfunction boundConversation(\n\tid: ConversationId,\n\tbinding: InvocationBinding,\n\tsubmissions: Submissions,\n\ttasks: TaskScheduler,\n): ConversationHandle {\n\tconst bind = (context: Context): Context => withAbortSignal(binding.signal, context);\n\tconst bound = <T>(operation: (context: Context) => Promise<T>) => {\n\t\treturn async (context: Context): Promise<T> => {\n\t\t\tbinding.check();\n\t\t\treturn operation(bind(context));\n\t\t};\n\t};\n\treturn {\n\t\tid,\n\t\tsubmit: async (draft, context) => {\n\t\t\tbinding.check();\n\t\t\tconst submission = await submissions.submit(id, draft, bind(context));\n\t\t\treturn {\n\t\t\t\tid: submission.id,\n\t\t\t\tstatus: bound((callContext) => submission.status(callContext)),\n\t\t\t\twait: bound((callContext) => submission.wait(callContext)),\n\t\t\t\tabort: bound((callContext) => submission.abort(callContext)),\n\t\t\t};\n\t\t},\n\t\tabort: async (context, options) => {\n\t\t\tbinding.check();\n\t\t\treturn tasks.abortConversation(id, options?.background === true, bind(context));\n\t\t},\n\t\twaitForIdle: bound((callContext) => tasks.waitForIdle(id, callContext)),\n\t};\n}\n\n/** Durable agent harness over one Session. */\nexport type Harness = HarnessType;\n\nexport const Harness = {\n\t/** Open a Harness over storage. The registry may keep changing while the Harness runs. */\n\tasync open<Tool extends ToolRegistration>(\n\t\tstorage: Storage,\n\t\toptions: HarnessOptions<Tool>,\n\t\tcontext: Context,\n\t): Promise<Harness> {\n\t\tcontext.abortSignal?.throwIfAborted();\n\t\tconst snapshot = options.registry.snapshot();\n\t\tconst missing = BUILTIN_TASKS.filter((task) => snapshot.task(task.definition.name) === undefined);\n\t\tif (missing.length > 0) {\n\t\t\tconst names = missing.map((task) => task.definition.name).join(\", \");\n\t\t\tthrow new Error(`Registry lacks built-in tasks ${names}; create it with createRegistry()`);\n\t\t}\n\t\tconst harness = new HarnessImpl(storage, options, context);\n\t\ttry {\n\t\t\tawait harness.openTasks(context);\n\t\t} catch (error) {\n\t\t\t// The caller's context may be what failed open: close without it, and rethrow the open error.\n\t\t\tawait harness\n\t\t\t\t.close(withoutAbortSignal(context))\n\t\t\t\t.catch((closeError: unknown) => options.onReport?.(closeError));\n\t\t\tthrow error;\n\t\t}\n\t\treturn harness;\n\t},\n};\n", "import type { SqliteDatabase } from \"./database.ts\";\n\nexport type SqliteMigration = {\n\treadonly version: number;\n\treadonly statements: readonly string[];\n};\n\n// next_id is TEXT because node:sqlite rejects INTEGER results outside JavaScript's safe integer range.\nconst INITIAL_SCHEMA: readonly string[] = [\n\t`CREATE TABLE durable_metadata (\n\t\tsingleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n\t\tnext_id TEXT NOT NULL,\n\t\tnext_seq INTEGER NOT NULL\n\t) STRICT`,\n\t`INSERT INTO durable_metadata (singleton, next_id, next_seq) VALUES (1, '2', 1)`,\n\t`CREATE TABLE record_ids (\n\t\tid INTEGER PRIMARY KEY,\n\t\trecord_type TEXT NOT NULL CHECK (record_type IN ('conversation', 'entry', 'task', 'submission', 'document'))\n\t) STRICT`,\n\t`CREATE TABLE conversations (\n\t\tid INTEGER PRIMARY KEY,\n\t\towner_conversation_id INTEGER,\n\t\towner_task_id INTEGER,\n\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t) STRICT`,\n\t\"CREATE INDEX conversations_by_owner_conversation ON conversations (owner_conversation_id, id)\",\n\t\"CREATE INDEX conversations_by_owner_task ON conversations (owner_task_id, id)\",\n\t`CREATE TABLE entries (\n\t\tid INTEGER PRIMARY KEY,\n\t\tconversation_id INTEGER NOT NULL,\n\t\thead INTEGER,\n\t\tcommit_seq INTEGER NOT NULL,\n\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t) STRICT`,\n\t\"CREATE INDEX entries_by_conversation ON entries (conversation_id, id DESC)\",\n\t\"CREATE INDEX entry_heads_by_conversation ON entries (conversation_id, id DESC) WHERE head IS NOT NULL\",\n\t`CREATE TABLE tasks (\n\t\tid INTEGER PRIMARY KEY,\n\t\tconversation_id INTEGER NOT NULL,\n\t\tkind TEXT NOT NULL,\n\t\tstatus TEXT NOT NULL CHECK (status IN ('pending', 'running', 'waiting', 'completing', 'terminal')),\n\t\tabort_requested INTEGER NOT NULL CHECK (abort_requested IN (0, 1)),\n\t\tbackground INTEGER NOT NULL CHECK (background IN (0, 1)),\n\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t) STRICT`,\n\t\"CREATE INDEX tasks_by_status ON tasks (status, id)\",\n\t\"CREATE INDEX tasks_by_conversation ON tasks (conversation_id, id)\",\n\t\"CREATE INDEX tasks_by_kind ON tasks (kind, id)\",\n\t\"CREATE INDEX tasks_by_abort_requested ON tasks (abort_requested, id)\",\n\t\"CREATE INDEX tasks_by_background ON tasks (background, id)\",\n\t`CREATE TABLE submissions (\n\t\tid INTEGER PRIMARY KEY,\n\t\tconversation_id INTEGER NOT NULL,\n\t\trequest_id TEXT,\n\t\tstatus TEXT NOT NULL CHECK (status IN ('queued', 'placed', 'done', 'unanswered')),\n\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t) STRICT`,\n\t\"CREATE INDEX submissions_by_request ON submissions (conversation_id, request_id)\",\n\t\"CREATE INDEX submissions_by_conversation ON submissions (conversation_id, id)\",\n\t\"CREATE INDEX submissions_by_status ON submissions (status, id)\",\n\t`CREATE TABLE documents (\n\t\tid INTEGER PRIMARY KEY,\n\t\tkind TEXT NOT NULL,\n\t\tfamily INTEGER NOT NULL CHECK (family IN (0, 1)),\n\t\tkey_value TEXT NOT NULL,\n\t\tscope_kind TEXT NOT NULL CHECK (scope_kind IN ('session', 'conversation', 'task')),\n\t\towner_id INTEGER NOT NULL,\n\t\tcreated_at INTEGER NOT NULL,\n\t\tretired_at INTEGER,\n\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t) STRICT`,\n\t`CREATE INDEX documents_by_address\n\t\tON documents (kind, scope_kind, owner_id, family, key_value, created_at DESC, retired_at)`,\n\t\"CREATE INDEX documents_by_scope ON documents (scope_kind, owner_id, id)\",\n\t\"CREATE INDEX documents_by_scope_kind ON documents (scope_kind, owner_id, kind, id)\",\n\t`CREATE TABLE document_revisions (\n\t\tdocument_id INTEGER NOT NULL,\n\t\tseq INTEGER NOT NULL,\n\t\tkind TEXT NOT NULL CHECK (kind IN ('base', 'delta')),\n\t\tversion INTEGER NOT NULL,\n\t\tcontent TEXT NOT NULL CHECK (json_valid(content)),\n\t\tPRIMARY KEY (document_id, seq)\n\t) STRICT`,\n\t\"CREATE INDEX document_revisions_by_kind ON document_revisions (document_id, kind, seq DESC)\",\n];\n\n/** Immutable, ordered schema history. Append new migrations after the initial schema ships. */\nexport const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [{ version: 1, statements: INITIAL_SCHEMA }];\n\nexport const CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0;\n\ntype SchemaRow = { readonly version: number };\n\n/** Apply all pending schema migrations atomically. */\nexport async function applySqliteMigrations(\n\tdatabase: SqliteDatabase,\n\tmigrations: readonly SqliteMigration[] = SQLITE_MIGRATIONS,\n): Promise<void> {\n\tfor (let index = 0; index < migrations.length; index++) {\n\t\tif (migrations[index]?.version !== index + 1) {\n\t\t\tthrow new Error(\"Durable SQLite migrations must have contiguous versions starting at 1\");\n\t\t}\n\t}\n\n\tawait database.transaction(async (transaction) => {\n\t\tawait transaction.exec(`CREATE TABLE IF NOT EXISTS durable_schema (\n\t\t\tsingleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n\t\t\tversion INTEGER NOT NULL CHECK (version >= 0)\n\t\t) STRICT`);\n\t\tawait transaction.run(\"INSERT OR IGNORE INTO durable_schema (singleton, version) VALUES (1, 0)\");\n\t\tconst row = await transaction.get<SchemaRow>(\"SELECT version FROM durable_schema WHERE singleton = 1\");\n\t\tif (row === undefined) throw new Error(\"Durable SQLite schema metadata is missing\");\n\t\tconst currentVersion = migrations.at(-1)?.version ?? 0;\n\t\tif (row.version > currentVersion) {\n\t\t\tthrow new Error(\n\t\t\t\t`Durable SQLite schema version ${row.version} is newer than supported version ${currentVersion}`,\n\t\t\t);\n\t\t}\n\t\tfor (const migration of migrations) {\n\t\t\tif (migration.version <= row.version) continue;\n\t\t\tfor (const statement of migration.statements) await transaction.exec(statement);\n\t\t\tawait transaction.run(\"UPDATE durable_schema SET version = ? WHERE singleton = 1\", migration.version);\n\t\t}\n\t});\n}\n", "import type { Context, JsonValue } from \"@earendil-works/chord\";\nimport { apply, type Op } from \"@earendil-works/chord/delta\";\nimport { StorageRejected } from \"../../errors.ts\";\nimport { idFromNumber, seqFromNumber } from \"../../ids.ts\";\nimport type {\n\tConversationId,\n\tConversationQuery,\n\tConversationRecord,\n\tCursor,\n\tDocumentAddress,\n\tDocumentContent,\n\tDocumentCreate,\n\tDocumentId,\n\tDocumentPoint,\n\tDocumentQuery,\n\tDocumentRecord,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tId,\n\tJsonObject,\n\tPage,\n\tSeq,\n\tStorage,\n\tStorageWrite,\n\tStoredDocument,\n\tSubmissionId,\n\tSubmissionQuery,\n\tSubmissionRecord,\n\tTaskId,\n\tTaskQuery,\n\tTaskRecord,\n} from \"../../types.ts\";\nimport type { SqliteDatabase, SqliteExecutor, SqliteValue } from \"./database.ts\";\nimport { applySqliteMigrations } from \"./migrations.ts\";\n\ntype StoredTask = TaskRecord<JsonValue, JsonValue, JsonValue>;\ntype TableName = \"conversation\" | \"entry\" | \"task\" | \"submission\" | \"document\";\ntype RecordIdRow = { readonly record_type: TableName };\ntype JsonRow = { readonly record: string };\ntype EntryJsonRow = { readonly record: string; readonly commit_seq: number };\ntype RevisionRow = {\n\treadonly seq: number;\n\treadonly kind: DocumentContent[\"kind\"];\n\treadonly version: number;\n\treadonly content: string;\n};\ntype IdRow = { readonly id: number };\ntype MetadataRow = { readonly next_id: string; readonly next_seq: number };\ntype DocumentAction = {\n\tcreate?: DocumentCreate;\n\tcopy?: Extract<StorageWrite, { readonly type: \"document.copy\" }>[\"source\"];\n\tcontent?: DocumentContent;\n\tretire: boolean;\n};\ntype ScopeColumns = {\n\treadonly scopeKind: DocumentRecord[\"scope\"][\"kind\"];\n\treadonly ownerId: number;\n};\n\nconst parseJson = <T>(value: string): T => JSON.parse(value) as T;\nconst encodeJson = (value: unknown): string => JSON.stringify(value) as string;\n// Some SQLite bindings replace lone UTF-16 surrogates. JSON encoding keeps indexed identities lossless.\nconst encodeIndexedString = (value: string): string => JSON.stringify(value);\n\nconst cursorId = <I extends Id<string>>(cursor: Cursor | undefined): I | undefined => {\n\tconst after = cursor?.after;\n\tif (after === undefined) return undefined;\n\tif (typeof after !== \"number\" || !Number.isSafeInteger(after)) throw new TypeError(\"Invalid storage cursor\");\n\treturn idFromNumber<I>(after);\n};\n\nconst page = <T extends { readonly id: Id<string> }>(values: readonly T[], limit: number): Page<T, Cursor> => {\n\tconst items = values.slice(0, limit);\n\tif (values.length <= limit) return { items };\n\treturn { items, next: { after: items.at(-1)!.id } };\n};\n\nconst scopeColumns = (scope: DocumentRecord[\"scope\"]): ScopeColumns => {\n\tswitch (scope.kind) {\n\t\tcase \"session\":\n\t\t\treturn { scopeKind: \"session\", ownerId: 0 };\n\t\tcase \"conversation\":\n\t\t\treturn { scopeKind: \"conversation\", ownerId: scope.conversationId };\n\t\tcase \"task\":\n\t\t\treturn { scopeKind: \"task\", ownerId: scope.taskId };\n\t}\n};\n\nconst addressParts = (address: DocumentAddress | DocumentCreate | DocumentRecord) => {\n\tconst scope = scopeColumns(address.scope);\n\treturn {\n\t\tkind: encodeIndexedString(address.kind),\n\t\t...scope,\n\t\tfamily: address.key === undefined ? 0 : 1,\n\t\tkeyValue: encodeIndexedString(address.key ?? \"\"),\n\t};\n};\n\nconst addressKey = (address: DocumentAddress | DocumentCreate | DocumentRecord): string => {\n\tconst parts = addressParts(address);\n\treturn JSON.stringify([parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue]);\n};\n\nconst isAliveAt = (record: DocumentRecord, at: DocumentPoint): boolean => {\n\tif (at === \"current\") return record.retiredAt === undefined;\n\treturn record.createdAt <= at && (record.retiredAt === undefined || at < record.retiredAt);\n};\n\nconst isCurrentOnly = (record: DocumentRecord): boolean =>\n\trecord.scope.kind !== \"conversation\" || record.history === \"latest\";\n\nconst writeId = (write: StorageWrite): Id<string> | undefined => {\n\tswitch (write.type) {\n\t\tcase \"conversation\":\n\t\tcase \"entry\":\n\t\tcase \"task\":\n\t\tcase \"submission\":\n\t\t\treturn write.value.id;\n\t\tcase \"document.create\":\n\t\tcase \"document.copy\":\n\t\t\treturn write.record.id;\n\t\tcase \"document.change\":\n\t\tcase \"document.retire\":\n\t\t\treturn undefined;\n\t}\n};\n\n/** Portable SQLite implementation of the Pico storage contract. */\nexport class SqliteStorage implements Storage {\n\tprivate readonly db: SqliteDatabase;\n\tprivate nextId: number;\n\tprivate closed = false;\n\tprivate closing: Promise<void> | undefined;\n\tprivate admittedReads = 0;\n\tprivate readsDrained: (() => void) | undefined;\n\n\tprivate constructor(db: SqliteDatabase, nextId: number) {\n\t\tthis.db = db;\n\t\tthis.nextId = nextId;\n\t}\n\n\t/** Initialize storage over an owned SQLite database facade. */\n\tstatic async open(db: SqliteDatabase): Promise<SqliteStorage> {\n\t\ttry {\n\t\t\tawait applySqliteMigrations(db);\n\t\t\tconst metadata = await db.get<MetadataRow>(\n\t\t\t\t\"SELECT next_id, next_seq FROM durable_metadata WHERE singleton = 1\",\n\t\t\t);\n\t\t\tif (metadata === undefined) throw new Error(\"Durable SQLite metadata is missing\");\n\t\t\treturn new SqliteStorage(db, Number(metadata.next_id));\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait db.close();\n\t\t\t} catch {\n\t\t\t\t// Preserve the initialization failure.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync commit(writes: readonly StorageWrite[], _context: Context): Promise<Seq> {\n\t\tthis.assertOpen();\n\t\tconst documentActions = this.prepareDocumentActions(writes);\n\t\tconst candidateNextId = this.candidateNextId(writes);\n\t\tconst seq = await this.db.transaction(async (transaction) => {\n\t\t\tconst metadata = await transaction.get<MetadataRow>(\n\t\t\t\t\"SELECT next_id, next_seq FROM durable_metadata WHERE singleton = 1\",\n\t\t\t);\n\t\t\tif (metadata === undefined) throw new Error(\"Durable SQLite metadata is missing\");\n\t\t\tconst committedSeq = seqFromNumber(metadata.next_seq);\n\t\t\tawait this.checkGlobalIds(transaction, writes);\n\t\t\tawait this.checkDocumentActions(transaction, documentActions);\n\t\t\tfor (const write of writes) await this.applyTableWrite(transaction, write, committedSeq);\n\t\t\tawait this.applyDocumentActions(transaction, documentActions, committedSeq);\n\t\t\tawait transaction.run(\n\t\t\t\t\"UPDATE durable_metadata SET next_id = ?, next_seq = ? WHERE singleton = 1\",\n\t\t\t\tString(Math.max(Number(metadata.next_id), candidateNextId)),\n\t\t\t\tcommittedSeq + 1,\n\t\t\t);\n\t\t\treturn committedSeq;\n\t\t});\n\t\tthis.nextId = Math.max(this.nextId, candidateNextId);\n\t\treturn seq;\n\t}\n\n\tasync mintId<I extends Id<string>>(): Promise<I> {\n\t\tthis.assertOpen();\n\t\tif (!Number.isSafeInteger(this.nextId)) throw new Error(\"ID space is exhausted\");\n\t\treturn idFromNumber<I>(this.nextId++);\n\t}\n\n\tasync conversation(id: ConversationId, _context: Context): Promise<ConversationRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(\"SELECT record FROM conversations WHERE id = ?\", id);\n\t\treturn row === undefined ? undefined : parseJson<ConversationRecord>(row.record);\n\t}\n\n\tasync scanConversations(\n\t\tquery: ConversationQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<ConversationRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst clauses = [\"id > ?\"];\n\t\tconst params: SqliteValue[] = [cursorId(cursor) ?? -1];\n\t\tif (query.ownerConversationId !== undefined) {\n\t\t\tclauses.push(\"owner_conversation_id = ?\");\n\t\t\tparams.push(query.ownerConversationId);\n\t\t}\n\t\tif (query.ownerTaskId !== undefined) {\n\t\t\tclauses.push(\"owner_task_id = ?\");\n\t\t\tparams.push(query.ownerTaskId);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM conversations WHERE ${clauses.join(\" AND \")} ORDER BY id LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<ConversationRecord>(row.record)),\n\t\t\tlimit,\n\t\t);\n\t}\n\n\tentry(id: EntryId, context: Context): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\tentry(\n\t\tconversationId: ConversationId,\n\t\tid: EntryId,\n\t\tcontext: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\tentry(\n\t\tidOrConversationId: EntryId | ConversationId,\n\t\tidOrContext: EntryId | Context,\n\t\tcontext?: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined> {\n\t\treturn this.admitRead(() => this.readEntry(idOrConversationId, idOrContext, context));\n\t}\n\n\tfindLatestHeadMarker(\n\t\tconversationId: ConversationId,\n\t\tatOrBeforeEntryId: EntryId | undefined,\n\t\t_context: Context,\n\t): Promise<(EntryRecord & { readonly head: EntryId }) | undefined> {\n\t\treturn this.admitRead(() => this.readLatestHeadMarker(conversationId, atOrBeforeEntryId));\n\t}\n\n\tscanEntries(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\treturn this.admitRead(() => this.readEntries(query, limit, cursor));\n\t}\n\n\tprivate async readEntry(\n\t\tidOrConversationId: EntryId | ConversationId,\n\t\tidOrContext: EntryId | Context,\n\t\tcontext?: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined> {\n\t\tconst id =\n\t\t\tcontext === undefined\n\t\t\t\t? idFromNumber<EntryId>(idOrConversationId)\n\t\t\t\t: typeof idOrContext === \"number\"\n\t\t\t\t\t? idFromNumber<EntryId>(idOrContext)\n\t\t\t\t\t: undefined;\n\t\tif (id === undefined) throw new TypeError(\"Storage.entry() requires an entry ID\");\n\t\tlet conversation: ConversationRecord | undefined;\n\t\tif (context !== undefined) {\n\t\t\tconst conversationId = idFromNumber<ConversationId>(idOrConversationId);\n\t\t\tconversation = await this.readConversation(conversationId);\n\t\t\tif (conversation === undefined) throw new Error(`Unknown conversation: ${conversationId}`);\n\t\t}\n\t\tconst row = await this.db.get<EntryJsonRow>(\"SELECT record, commit_seq FROM entries WHERE id = ?\", id);\n\t\tif (row === undefined) return undefined;\n\t\tconst entry = parseJson<EntryRecord>(row.record);\n\t\tif (conversation !== undefined) {\n\t\t\tlet upperEntryId = Number.POSITIVE_INFINITY;\n\t\t\twhile (conversation.id !== entry.conversationId) {\n\t\t\t\tif (conversation.parent === undefined) return undefined;\n\t\t\t\tupperEntryId = Math.min(upperEntryId, conversation.parent.at);\n\t\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t\t}\n\t\t\tif (entry.id > upperEntryId) return undefined;\n\t\t}\n\t\treturn { entry, commitSeq: seqFromNumber(row.commit_seq) };\n\t}\n\n\tprivate async readLatestHeadMarker(\n\t\tconversationId: ConversationId,\n\t\tatOrBeforeEntryId: EntryId | undefined,\n\t): Promise<(EntryRecord & { readonly head: EntryId }) | undefined> {\n\t\tlet conversation = await this.readConversation(conversationId);\n\t\tif (conversation === undefined) throw new Error(`Unknown conversation: ${conversationId}`);\n\t\tlet upper: number | undefined = atOrBeforeEntryId;\n\t\twhile (true) {\n\t\t\tconst row =\n\t\t\t\tupper === undefined\n\t\t\t\t\t? await this.db.get<JsonRow>(\n\t\t\t\t\t\t\t\"SELECT record FROM entries WHERE conversation_id = ? AND head IS NOT NULL ORDER BY id DESC LIMIT 1\",\n\t\t\t\t\t\t\tconversation.id,\n\t\t\t\t\t\t)\n\t\t\t\t\t: await this.db.get<JsonRow>(\n\t\t\t\t\t\t\t\"SELECT record FROM entries WHERE conversation_id = ? AND head IS NOT NULL AND id <= ? ORDER BY id DESC LIMIT 1\",\n\t\t\t\t\t\t\tconversation.id,\n\t\t\t\t\t\t\tupper,\n\t\t\t\t\t\t);\n\t\t\tif (row !== undefined) return parseJson<EntryRecord & { readonly head: EntryId }>(row.record);\n\t\t\tif (conversation.parent === undefined) return undefined;\n\t\t\tupper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);\n\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t}\n\t}\n\n\tprivate async readEntries(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\tlet conversation = await this.readConversation(query.conversationId);\n\t\tif (conversation === undefined) throw new Error(`Unknown conversation: ${query.conversationId}`);\n\t\tconst after = cursorId(cursor);\n\t\tlet upper: number | undefined = query.maxEntryId;\n\t\tif (after !== undefined) upper = Math.min(upper ?? Number.MAX_SAFE_INTEGER, after - 1);\n\t\tconst values: EntryRecord[] = [];\n\t\twhile (true) {\n\t\t\tconst clauses = [\"conversation_id = ?\"];\n\t\t\tconst params: SqliteValue[] = [conversation.id];\n\t\t\tif (query.minEntryId !== undefined) {\n\t\t\t\tclauses.push(\"id >= ?\");\n\t\t\t\tparams.push(query.minEntryId);\n\t\t\t}\n\t\t\tif (upper !== undefined) {\n\t\t\t\tclauses.push(\"id <= ?\");\n\t\t\t\tparams.push(upper);\n\t\t\t}\n\t\t\tparams.push(limit + 1 - values.length);\n\t\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t\t`SELECT record FROM entries WHERE ${clauses.join(\" AND \")} ORDER BY id DESC LIMIT ?`,\n\t\t\t\t...params,\n\t\t\t);\n\t\t\tvalues.push(...rows.map((row) => parseJson<EntryRecord>(row.record)));\n\t\t\tif (values.length > limit || conversation.parent === undefined) break;\n\t\t\tupper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);\n\t\t\tif (query.minEntryId !== undefined && upper < query.minEntryId) break;\n\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t}\n\t\treturn page(values, limit);\n\t}\n\n\tasync task(id: TaskId, _context: Context): Promise<StoredTask | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(\"SELECT record FROM tasks WHERE id = ?\", id);\n\t\treturn row === undefined ? undefined : parseJson<StoredTask>(row.record);\n\t}\n\n\tasync scanTasks(\n\t\tquery: TaskQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<StoredTask, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst clauses = [\"id > ?\"];\n\t\tconst params: SqliteValue[] = [cursorId(cursor) ?? -1];\n\t\tif (query.conversationId !== undefined) {\n\t\t\tclauses.push(\"conversation_id = ?\");\n\t\t\tparams.push(query.conversationId);\n\t\t}\n\t\tif (query.kind !== undefined) {\n\t\t\tclauses.push(\"kind = ?\");\n\t\t\tparams.push(encodeIndexedString(query.kind));\n\t\t}\n\t\tif (query.status !== undefined) {\n\t\t\tclauses.push(\"status = ?\");\n\t\t\tparams.push(query.status);\n\t\t}\n\t\tif (query.abortRequested !== undefined) {\n\t\t\tclauses.push(\"abort_requested = ?\");\n\t\t\tparams.push(query.abortRequested ? 1 : 0);\n\t\t}\n\t\tif (query.background !== undefined) {\n\t\t\tclauses.push(\"background = ?\");\n\t\t\tparams.push(query.background ? 1 : 0);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM tasks WHERE ${clauses.join(\" AND \")} ORDER BY id LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<StoredTask>(row.record)),\n\t\t\tlimit,\n\t\t);\n\t}\n\n\tasync submission(id: SubmissionId, _context: Context): Promise<SubmissionRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(\"SELECT record FROM submissions WHERE id = ?\", id);\n\t\treturn row === undefined ? undefined : parseJson<SubmissionRecord>(row.record);\n\t}\n\n\tasync scanSubmissions(\n\t\tquery: SubmissionQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<SubmissionRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst clauses = [\"id > ?\"];\n\t\tconst params: SqliteValue[] = [cursorId(cursor) ?? -1];\n\t\tif (query.conversationId !== undefined) {\n\t\t\tclauses.push(\"conversation_id = ?\");\n\t\t\tparams.push(query.conversationId);\n\t\t}\n\t\tif (query.status !== undefined) {\n\t\t\tclauses.push(\"status = ?\");\n\t\t\tparams.push(query.status);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM submissions WHERE ${clauses.join(\" AND \")} ORDER BY id LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<SubmissionRecord>(row.record)),\n\t\t\tlimit,\n\t\t);\n\t}\n\n\tasync submissionByRequest(\n\t\tconversationId: ConversationId,\n\t\trequestId: string,\n\t\t_context: Context,\n\t): Promise<SubmissionRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(\n\t\t\t\"SELECT record FROM submissions WHERE conversation_id = ? AND request_id = ?\",\n\t\t\tconversationId,\n\t\t\tencodeIndexedString(requestId),\n\t\t);\n\t\treturn row === undefined ? undefined : parseJson<SubmissionRecord>(row.record);\n\t}\n\n\tasync findDocument(\n\t\taddress: DocumentAddress,\n\t\tat: DocumentPoint,\n\t\t_context: Context,\n\t): Promise<DocumentRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst parts = addressParts(address);\n\t\tconst sql =\n\t\t\tat === \"current\"\n\t\t\t\t? `SELECT record FROM documents\n\t\t\t\t\tWHERE kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ?\n\t\t\t\t\tAND retired_at IS NULL ORDER BY created_at DESC LIMIT 1`\n\t\t\t\t: `SELECT record FROM documents\n\t\t\t\t\tWHERE kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ?\n\t\t\t\t\tAND created_at <= ? AND (retired_at IS NULL OR retired_at > ?)\n\t\t\t\t\tORDER BY created_at DESC LIMIT 1`;\n\t\tconst params: SqliteValue[] = [parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue];\n\t\tif (at !== \"current\") params.push(at, at);\n\t\tconst row = await this.db.get<JsonRow>(sql, ...params);\n\t\treturn row === undefined ? undefined : parseJson<DocumentRecord>(row.record);\n\t}\n\n\tasync document(id: DocumentId, at: DocumentPoint, _context: Context): Promise<StoredDocument | undefined> {\n\t\tthis.assertOpen();\n\t\t// The record and revision queries must observe one committed state; a commit between them can replace the base.\n\t\treturn this.db.transaction((transaction) => this.materializeDocument(transaction, id, at));\n\t}\n\n\tasync scanDocuments(\n\t\tquery: DocumentQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<DocumentRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst scope = scopeColumns(query.scope);\n\t\tconst clauses = [\"scope_kind = ?\", \"owner_id = ?\", \"id > ?\"];\n\t\tconst params: SqliteValue[] = [scope.scopeKind, scope.ownerId, cursorId(cursor) ?? -1];\n\t\tif (query.kind !== undefined) {\n\t\t\tclauses.push(\"kind = ?\");\n\t\t\tparams.push(encodeIndexedString(query.kind));\n\t\t}\n\t\tif (query.at === \"current\") {\n\t\t\tclauses.push(\"retired_at IS NULL\");\n\t\t} else {\n\t\t\tclauses.push(\"created_at <= ?\", \"(retired_at IS NULL OR retired_at > ?)\");\n\t\t\tparams.push(query.at, query.at);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM documents WHERE ${clauses.join(\" AND \")} ORDER BY id LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<DocumentRecord>(row.record)),\n\t\t\tlimit,\n\t\t);\n\t}\n\n\tclose(_context: Context): Promise<void> {\n\t\tif (this.closing === undefined) {\n\t\t\tthis.closed = true;\n\t\t\tthis.closing = this.closeDatabase();\n\t\t}\n\t\treturn this.closing;\n\t}\n\n\tprivate async closeDatabase(): Promise<void> {\n\t\tif (this.admittedReads > 0) {\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tthis.readsDrained = resolve;\n\t\t\t});\n\t\t}\n\t\tawait this.db.close();\n\t}\n\n\t/**\n\t * Run a read that issues several queries. Close waits for admitted reads, so their later queries never reach a\n\t * closed database. Single-query reads and transactions are already ordered before close by the database.\n\t */\n\tprivate async admitRead<T>(read: () => Promise<T>): Promise<T> {\n\t\tthis.assertOpen();\n\t\tthis.admittedReads++;\n\t\ttry {\n\t\t\treturn await read();\n\t\t} finally {\n\t\t\tif (--this.admittedReads === 0) this.readsDrained?.();\n\t\t}\n\t}\n\n\tprivate async readConversation(id: ConversationId): Promise<ConversationRecord | undefined> {\n\t\tconst row = await this.db.get<JsonRow>(\"SELECT record FROM conversations WHERE id = ?\", id);\n\t\treturn row === undefined ? undefined : parseJson<ConversationRecord>(row.record);\n\t}\n\n\tprivate async materializeDocument(\n\t\texecutor: SqliteExecutor,\n\t\tid: DocumentId,\n\t\tat: DocumentPoint,\n\t): Promise<StoredDocument | undefined> {\n\t\tconst row = await executor.get<JsonRow>(\"SELECT record FROM documents WHERE id = ?\", id);\n\t\tif (row === undefined) return undefined;\n\t\tconst record = parseJson<DocumentRecord>(row.record);\n\t\tif (at !== \"current\" && isCurrentOnly(record)) {\n\t\t\tthrow new Error(`Document ${id} does not retain historical content`);\n\t\t}\n\t\tif (!isAliveAt(record, at)) return undefined;\n\t\tconst upper = at === \"current\" ? Number.MAX_SAFE_INTEGER : at;\n\t\tconst base = await executor.get<RevisionRow>(\n\t\t\t`SELECT seq, kind, version, content FROM document_revisions\n\t\t\t\tWHERE document_id = ? AND kind = 'base' AND seq <= ? ORDER BY seq DESC LIMIT 1`,\n\t\t\tid,\n\t\t\tupper,\n\t\t);\n\t\tif (base === undefined) throw new Error(`Document ${id} is missing a required base`);\n\t\tlet value = parseJson<JsonObject>(base.content);\n\t\tconst tail = await executor.all<RevisionRow>(\n\t\t\t`SELECT seq, kind, version, content FROM document_revisions\n\t\t\t\tWHERE document_id = ? AND seq > ? AND seq <= ? ORDER BY seq`,\n\t\t\tid,\n\t\t\tbase.seq,\n\t\t\tupper,\n\t\t);\n\t\tfor (const revision of tail) {\n\t\t\tif (revision.kind !== \"delta\" || revision.version !== base.version) {\n\t\t\t\tthrow new Error(`Document ${id} crosses a stored version boundary without a base`);\n\t\t\t}\n\t\t\tvalue = apply(value, parseJson<readonly Op[]>(revision.content)) as JsonObject;\n\t\t}\n\t\treturn { record, version: base.version, value, deltasSinceBase: tail.length };\n\t}\n\n\tprivate candidateNextId(writes: readonly StorageWrite[]): number {\n\t\tlet nextId = this.nextId;\n\t\tfor (const write of writes) {\n\t\t\tconst id = writeId(write);\n\t\t\tif (id !== undefined) nextId = Math.max(nextId, id + 1);\n\t\t}\n\t\treturn nextId;\n\t}\n\n\tprivate async checkGlobalIds(executor: SqliteExecutor, writes: readonly StorageWrite[]): Promise<void> {\n\t\tconst claimed = new Map<Id<string>, TableName>();\n\t\tfor (const write of writes) {\n\t\t\tif (write.type === \"document.change\" || write.type === \"document.retire\") continue;\n\t\t\tconst document = write.type === \"document.create\" || write.type === \"document.copy\";\n\t\t\tconst table: TableName = document ? \"document\" : write.type;\n\t\t\tconst id = document ? write.record.id : write.value.id;\n\t\t\tconst existing = (await executor.get<RecordIdRow>(\"SELECT record_type FROM record_ids WHERE id = ?\", id))\n\t\t\t\t?.record_type;\n\t\t\tconst earlier = claimed.get(id);\n\t\t\tif (table === \"conversation\" || table === \"entry\" || table === \"document\") {\n\t\t\t\tif (existing !== undefined) throw new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined) throw new Error(`ID ${id} is written more than once`);\n\t\t\t} else {\n\t\t\t\tif (existing !== undefined && existing !== table)\n\t\t\t\t\tthrow new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined && earlier !== table) throw new Error(`ID ${id} is written as two record types`);\n\t\t\t}\n\t\t\tclaimed.set(id, table);\n\t\t}\n\t}\n\n\tprivate prepareDocumentActions(writes: readonly StorageWrite[]): Map<DocumentId, DocumentAction> {\n\t\tconst actions = new Map<DocumentId, DocumentAction>();\n\t\tfor (const write of writes) {\n\t\t\tif (\n\t\t\t\twrite.type !== \"document.create\" &&\n\t\t\t\twrite.type !== \"document.copy\" &&\n\t\t\t\twrite.type !== \"document.change\" &&\n\t\t\t\twrite.type !== \"document.retire\"\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst id = write.type === \"document.create\" || write.type === \"document.copy\" ? write.record.id : write.id;\n\t\t\tlet action = actions.get(id);\n\t\t\tif (action === undefined) {\n\t\t\t\taction = { retire: false };\n\t\t\t\tactions.set(id, action);\n\t\t\t}\n\t\t\tswitch (write.type) {\n\t\t\t\tcase \"document.create\":\n\t\t\t\t\tif (action.create !== undefined || action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t\t}\n\t\t\t\t\taction.create = write.record;\n\t\t\t\t\taction.content = write.content;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"document.copy\":\n\t\t\t\t\tif (action.create !== undefined || action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t\t}\n\t\t\t\t\taction.create = write.record;\n\t\t\t\t\taction.copy = write.source;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"document.change\":\n\t\t\t\t\tif (action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t\t}\n\t\t\t\t\taction.content = write.content;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"document.retire\":\n\t\t\t\t\tif (action.retire) throw new Error(`Document ${id} is retired more than once`);\n\t\t\t\t\taction.retire = true;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn actions;\n\t}\n\n\tprivate async checkDocumentActions(\n\t\texecutor: SqliteExecutor,\n\t\tactions: ReadonlyMap<DocumentId, DocumentAction>,\n\t): Promise<void> {\n\t\tconst liveCounts = new Map<string, number>();\n\t\tfor (const [id, action] of actions) {\n\t\t\tif (action.copy !== undefined && actions.has(action.copy.id)) {\n\t\t\t\tthrow new StorageRejected(`Document copy ${id} source is changed in the copy batch`);\n\t\t\t}\n\t\t\tconst row = await executor.get<JsonRow>(\"SELECT record FROM documents WHERE id = ?\", id);\n\t\t\tconst existing = row === undefined ? undefined : parseJson<DocumentRecord>(row.record);\n\t\t\tif (action.create === undefined && existing === undefined) throw new Error(`Unknown document: ${id}`);\n\t\t\tif (action.create !== undefined && existing !== undefined) throw new Error(`Document ${id} already exists`);\n\t\t\tif (existing?.retiredAt !== undefined) throw new Error(`Document ${id} is retired`);\n\t\t\tif (action.content?.kind === \"delta\") {\n\t\t\t\tconst previous = await executor.get<{ readonly version: number }>(\n\t\t\t\t\t\"SELECT version FROM document_revisions WHERE document_id = ? ORDER BY seq DESC LIMIT 1\",\n\t\t\t\t\tid,\n\t\t\t\t);\n\t\t\t\tif (previous === undefined) throw new Error(`Document ${id} delta has no base`);\n\t\t\t\tif (previous.version !== action.content.version) {\n\t\t\t\t\tthrow new Error(`Document ${id} version transition requires a base`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst record = action.create ?? existing!;\n\t\t\tconst key = addressKey(record);\n\t\t\tlet live = liveCounts.get(key);\n\t\t\tif (live === undefined) live = (await this.currentDocumentId(executor, record)) === undefined ? 0 : 1;\n\t\t\tif (action.retire && existing !== undefined) live--;\n\t\t\tif (action.create !== undefined && !action.retire) live++;\n\t\t\tliveCounts.set(key, live);\n\t\t}\n\t\tfor (const live of liveCounts.values()) {\n\t\t\tif (live > 1) throw new Error(\"Document address already has a current incarnation\");\n\t\t}\n\t}\n\n\tprivate async currentDocumentId(\n\t\texecutor: SqliteExecutor,\n\t\taddress: DocumentAddress | DocumentCreate | DocumentRecord,\n\t): Promise<DocumentId | undefined> {\n\t\tconst parts = addressParts(address);\n\t\tconst id = (\n\t\t\tawait executor.get<IdRow>(\n\t\t\t\t`SELECT id FROM documents\n\t\t\t\tWHERE kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ? AND retired_at IS NULL\n\t\t\t\tLIMIT 1`,\n\t\t\t\tparts.kind,\n\t\t\t\tparts.scopeKind,\n\t\t\t\tparts.ownerId,\n\t\t\t\tparts.family,\n\t\t\t\tparts.keyValue,\n\t\t\t)\n\t\t)?.id;\n\t\treturn id === undefined ? undefined : idFromNumber<DocumentId>(id);\n\t}\n\n\tprivate async applyTableWrite(executor: SqliteExecutor, write: StorageWrite, seq: Seq): Promise<void> {\n\t\tswitch (write.type) {\n\t\t\tcase \"conversation\":\n\t\t\t\tawait this.claimId(executor, write.value.id, \"conversation\");\n\t\t\t\tawait executor.run(\n\t\t\t\t\t\"INSERT INTO conversations (id, owner_conversation_id, owner_task_id, record) VALUES (?, ?, ?, ?)\",\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.owner?.conversationId ?? null,\n\t\t\t\t\twrite.value.owner?.taskId ?? null,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase \"entry\":\n\t\t\t\tawait this.claimId(executor, write.value.id, \"entry\");\n\t\t\t\tawait executor.run(\n\t\t\t\t\t\"INSERT INTO entries (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)\",\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.conversationId,\n\t\t\t\t\twrite.value.head ?? null,\n\t\t\t\t\tseq,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase \"task\":\n\t\t\t\tawait this.claimId(executor, write.value.id, \"task\");\n\t\t\t\tawait executor.run(\n\t\t\t\t\t`INSERT INTO tasks (id, conversation_id, kind, status, abort_requested, background, record)\n\t\t\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?)\n\t\t\t\t\t\tON CONFLICT(id) DO UPDATE SET conversation_id = excluded.conversation_id, kind = excluded.kind,\n\t\t\t\t\t\tstatus = excluded.status, abort_requested = excluded.abort_requested,\n\t\t\t\t\t\tbackground = excluded.background, record = excluded.record`,\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.conversationId,\n\t\t\t\t\tencodeIndexedString(write.value.kind),\n\t\t\t\t\twrite.value.state.status,\n\t\t\t\t\twrite.value.abortRequested ? 1 : 0,\n\t\t\t\t\twrite.value.background ? 1 : 0,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase \"submission\":\n\t\t\t\tawait this.claimId(executor, write.value.id, \"submission\");\n\t\t\t\tawait executor.run(\n\t\t\t\t\t`INSERT INTO submissions (id, conversation_id, request_id, status, record) VALUES (?, ?, ?, ?, ?)\n\t\t\t\t\t\tON CONFLICT(id) DO UPDATE SET conversation_id = excluded.conversation_id,\n\t\t\t\t\t\trequest_id = excluded.request_id, status = excluded.status, record = excluded.record`,\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.conversationId,\n\t\t\t\t\twrite.value.requestId === undefined ? null : encodeIndexedString(write.value.requestId),\n\t\t\t\t\twrite.value.status,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase \"document.create\":\n\t\t\tcase \"document.copy\":\n\t\t\tcase \"document.change\":\n\t\t\tcase \"document.retire\":\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate async claimId(executor: SqliteExecutor, id: Id<string>, table: TableName): Promise<void> {\n\t\tawait executor.run(\"INSERT OR IGNORE INTO record_ids (id, record_type) VALUES (?, ?)\", id, table);\n\t}\n\n\tprivate async applyDocumentActions(\n\t\texecutor: SqliteExecutor,\n\t\tactions: ReadonlyMap<DocumentId, DocumentAction>,\n\t\tseq: Seq,\n\t): Promise<void> {\n\t\tfor (const [id, action] of actions) {\n\t\t\tlet content = action.content;\n\t\t\tif (action.copy !== undefined) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stored = await this.materializeDocument(executor, action.copy.id, action.copy.at);\n\t\t\t\t\tif (stored === undefined) throw new Error(`Fork source document ${action.copy.id} cannot be read`);\n\t\t\t\t\tconst create = action.create!;\n\t\t\t\t\tif (\n\t\t\t\t\t\tstored.record.scope.kind !== \"conversation\" ||\n\t\t\t\t\t\tcreate.scope.kind !== \"conversation\" ||\n\t\t\t\t\t\tstored.record.kind !== create.kind ||\n\t\t\t\t\t\tstored.record.key !== create.key ||\n\t\t\t\t\t\tstored.record.history !== create.history ||\n\t\t\t\t\t\tstored.record.fork !== create.fork\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(`Fork source document ${action.copy.id} does not match the copied record`);\n\t\t\t\t\t}\n\t\t\t\t\tcontent = { kind: \"base\", version: stored.version, value: stored.value };\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof StorageRejected) throw error;\n\t\t\t\t\tthrow new StorageRejected(`Document copy ${id} was rejected`, { cause: error });\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet record: DocumentRecord;\n\t\t\tif (action.create !== undefined) {\n\t\t\t\trecord = {\n\t\t\t\t\t...action.create,\n\t\t\t\t\tcreatedAt: seq,\n\t\t\t\t\t...(action.retire ? { retiredAt: seq } : {}),\n\t\t\t\t};\n\t\t\t\tconst parts = addressParts(record);\n\t\t\t\tawait this.claimId(executor, id, \"document\");\n\t\t\t\tawait executor.run(\n\t\t\t\t\t`INSERT INTO documents\n\t\t\t\t\t\t(id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record)\n\t\t\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t\t\tid,\n\t\t\t\t\tparts.kind,\n\t\t\t\t\tparts.family,\n\t\t\t\t\tparts.keyValue,\n\t\t\t\t\tparts.scopeKind,\n\t\t\t\t\tparts.ownerId,\n\t\t\t\t\tseq,\n\t\t\t\t\taction.retire ? seq : null,\n\t\t\t\t\tencodeJson(record),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst row = (await executor.get<JsonRow>(\"SELECT record FROM documents WHERE id = ?\", id))!;\n\t\t\t\trecord = parseJson<DocumentRecord>(row.record);\n\t\t\t}\n\n\t\t\tif (content !== undefined) {\n\t\t\t\tif (content.kind === \"base\" && isCurrentOnly(record)) {\n\t\t\t\t\tawait executor.run(\"DELETE FROM document_revisions WHERE document_id = ?\", id);\n\t\t\t\t}\n\t\t\t\tconst encodedContent = content.kind === \"base\" ? encodeJson(content.value) : encodeJson(content.ops);\n\t\t\t\tawait executor.run(\n\t\t\t\t\t\"INSERT INTO document_revisions (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)\",\n\t\t\t\t\tid,\n\t\t\t\t\tseq,\n\t\t\t\t\tcontent.kind,\n\t\t\t\t\tcontent.version,\n\t\t\t\t\tencodedContent,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (action.retire) {\n\t\t\t\tif (action.create === undefined) {\n\t\t\t\t\trecord = { ...record, retiredAt: seq };\n\t\t\t\t\tawait executor.run(\n\t\t\t\t\t\t\"UPDATE documents SET retired_at = ?, record = ? WHERE id = ?\",\n\t\t\t\t\t\tseq,\n\t\t\t\t\t\tencodeJson(record),\n\t\t\t\t\t\tid,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (isCurrentOnly(record)) {\n\t\t\t\t\tawait executor.run(\"DELETE FROM document_revisions WHERE document_id = ?\", id);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate assertOpen(): void {\n\t\tif (this.closed) throw new Error(\"SqliteStorage is closed\");\n\t}\n}\n", "/**\n * The Relay harness: one durable session per product object, a model turn on the user's own CLI login,\n * capabilities behind one permission gate, and one event stream for the dock.\n *\n * **Mental model**\n *\n * - **Pi Durable owns the loop and the store.** Every input, model turn and tool call is committed\n * before it is shown; a process killed mid-run continues from its last checkpoint on the next start,\n * and a write that was interrupted is never repeated.\n * - **This service is the only door.** Products and the dock call {@link RelayHarnessService}; nothing\n * outside this package imports Pi. Replacing Pi with an Effect-native store changes this module only.\n * - **One process owns a store.** The SQLite connection runs in exclusive locking mode, so a second\n * process fails to open the same store with {@link RelayStoreLocked}, and the OS releases the lock if\n * the owner dies, even on `kill -9`.\n * - **A run is named by the `requestId`s it answers.** `send` takes the dock's `requestId`; events that\n * end a run, and the Snapshot of a run in flight, list them, and `cancel` stops a run only by one of them.\n * - **Backend status is observed, not assumed.** A backend starts `Unverified` when its CLI answers\n * `--version`, turns `Ready` when a turn answers, and `Unavailable` with `SignedOut` when the CLI refuses\n * the login. Nothing about it is persisted.\n *\n * @module\n */\nimport { BACKGROUND_CONTEXT } from \"@earendil-works/chord/context\"\nimport type { Message } from \"@earendil-works/pi-ai\"\nimport { createRegistry, defineDoc, Harness, watchEvents } from \"@earendil-works/pi-durable\"\nimport type {\n AgentEvent,\n Conversation,\n ConversationId,\n SubmissionId,\n SubmissionRecord\n} from \"@earendil-works/pi-durable\"\nimport { SqliteStorage } from \"@earendil-works/pi-durable/storage/sqlite\"\nimport * as Capability from \"@knpkv/capability\"\nimport { createClient } from \"@libsql/client\"\nimport {\n Clock,\n Context,\n Crypto,\n Deferred,\n Effect,\n Exit,\n FileSystem,\n Layer,\n Path,\n Predicate,\n PubSub,\n Queue,\n Ref,\n Schema,\n Semaphore,\n Stream\n} from \"effect\"\nimport { AiError } from \"effect/ai\"\nimport type { LanguageModel } from \"effect/ai\"\nimport type { PlatformError } from \"effect/PlatformError\"\nimport { libsqlDatabase } from \"./libsqlDatabase.js\"\nimport { BackendUnavailableCause, DecisionState, objectRefKey, RelayBackendId, WriteReceipt } from \"./model.js\"\nimport type { BackendStatus, ObjectRef, RelayEvent, SessionInfo, SessionTool } from \"./model.js\"\nimport { relayModels, relayProvider } from \"./piProvider.js\"\nimport type { TurnRunner } from \"./piProvider.js\"\nimport { relayExtension } from \"./piTools.js\"\nimport type { ConfirmationBroker, EffectRunner } from \"./piTools.js\"\nimport type { RegisteredCapability } from \"./registry.js\"\nimport { runTurn } from \"./turn.js\"\n\n/** Another process already owns this Relay store. */\nexport class RelayStoreLocked extends Schema.TaggedError<RelayStoreLocked>()(\"RelayStoreLocked\", {\n path: Schema.String,\n message: Schema.String\n}) {}\n\n/**\n * The store directory or database is a symbolic link. Relay refuses it rather than re-permission and\n * write conversation content wherever the link points.\n */\nexport class RelayStoreLinked extends Schema.TaggedError<RelayStoreLinked>()(\"RelayStoreLinked\", {\n path: Schema.String,\n message: Schema.String\n}) {}\n\n/** The Relay store could not be opened or read. `message` names the operation and the fix. */\nexport class RelayStoreFailed extends Schema.TaggedError<RelayStoreFailed>()(\"RelayStoreFailed\", {\n operation: Schema.String,\n message: Schema.String\n}) {}\n\n/** No confirmation is waiting for this call; `state` says whether it was answered, withdrawn, or never asked. */\nexport class RelayDecisionNotPending extends Schema.TaggedError<RelayDecisionNotPending>()(\n \"RelayDecisionNotPending\",\n { callId: Schema.String, state: DecisionState }\n) {}\n\n/** No run of this session answers `runId`: it finished, or never started. */\nexport class RelayRunNotActive extends Schema.TaggedError<RelayRunNotActive>()(\"RelayRunNotActive\", {\n runId: Schema.String\n}) {}\n\n/** The session asked for a backend this product did not configure. */\nexport class RelayBackendNotConfigured extends Schema.TaggedError<RelayBackendNotConfigured>()(\n \"RelayBackendNotConfigured\",\n { backend: RelayBackendId }\n) {}\n\n/** A backend's CLI can't be used. `fix` is the one action that makes it usable. */\nexport class RelayBackendUnavailable extends Schema.TaggedError<RelayBackendUnavailable>()(\n \"RelayBackendUnavailable\",\n { cause: BackendUnavailableCause, fix: Schema.String }\n) {}\n\n/** One backend the harness can run turns on, with the `LanguageModel` that reaches it. */\nexport interface RelayBackend {\n readonly id: RelayBackendId\n readonly name: string\n readonly model: Layer.Layer<LanguageModel.LanguageModel>\n /** The CLI's version, read without a model call; fails when it is missing or unusable. */\n readonly probe: Effect.Effect<string, RelayBackendUnavailable>\n /** The one line that signs the CLI back in, shown when a turn is refused for its login. */\n readonly signInFix: string\n}\n\nexport interface RelayHarnessOptions<Requirements> {\n /** SQLite file of this product's Relay sessions. Owner-only; never on a shared path. */\n readonly storePath: string\n /** The product's standing instructions for Relay. */\n readonly instructions: string\n readonly capabilities: ReadonlyArray<RegisteredCapability<Requirements>>\n /** The first backend is the default for new sessions. */\n readonly backends: readonly [RelayBackend, ...ReadonlyArray<RelayBackend>]\n}\n\n/**\n * Context the person attached to one message, as the product renders it for the model: `label` names\n * what it is, `body` is the text the model reads. It reaches the model's context, never the transcript.\n */\nexport interface MessageContext {\n readonly label: string\n readonly body: string\n}\n\nexport interface SendOptions {\n /** Switch the session to this backend from its next turn on. */\n readonly backend?: RelayBackendId | undefined\n /** Attached context, placed just before the message. */\n readonly context?: ReadonlyArray<MessageContext> | undefined\n}\n\nexport interface RelayHarnessService {\n /**\n * Send a message to the session about `ref`. `requestId` makes a retried send land once and names the run\n * that answers it. `backend` switches the session to that backend from its next turn on.\n */\n readonly send: (\n ref: ObjectRef,\n text: string,\n requestId: string,\n options?: SendOptions\n ) => Effect.Effect<void, RelayStoreFailed | RelayBackendNotConfigured>\n /** The session's events: a `Snapshot` first, then every change. Ends when the scope closes. */\n readonly events: (ref: ObjectRef) => Stream.Stream<RelayEvent, RelayStoreFailed>\n /**\n * Answer a confirmation pending in `ref`'s session. A call raised in another session is `Unknown` here and\n * stays pending. Outcomes are remembered for the harness's lifetime, not across restarts.\n */\n readonly decide: (\n ref: ObjectRef,\n callId: string,\n allow: boolean\n ) => Effect.Effect<void, RelayDecisionNotPending | RelayStoreFailed>\n /**\n * Stop the run answering `runId`. A message still queued is withdrawn alone; a run in flight stops whole,\n * with every message it took. Nothing already committed is undone.\n */\n readonly cancel: (ref: ObjectRef, runId: string) => Effect.Effect<void, RelayStoreFailed | RelayRunNotActive>\n /** The tools the dock lists for a session, and the backend its next turn runs on. */\n readonly session: (ref: ObjectRef) => Effect.Effect<SessionInfo, RelayStoreFailed>\n /** Every configured backend's status, in configuration order. */\n readonly backends: Effect.Effect<ReadonlyArray<BackendStatus>>\n /** The tools the dock lists for a session. */\n readonly tools: ReadonlyArray<SessionTool>\n}\n\nexport class RelayHarness extends Context.Service<RelayHarness, RelayHarnessService>()(\"@knpkv/relay/RelayHarness\") {}\n\n/** Which conversation is about which object. Lives on the root conversation. */\nconst SessionIndex = defineDoc<{ readonly sessions: Record<string, ConversationId> }>({\n kind: \"relay.sessions\",\n version: 1,\n scope: \"conversation\",\n history: \"latest\",\n fork: \"initial\",\n initial: () => ({ sessions: {} })\n})\n\nconst promise = <A>(operation: string, run: () => Promise<A>) =>\n Effect.tryPromise({\n try: run,\n catch: (cause) => new RelayStoreFailed({ operation, message: `${operation} failed: ${String(cause)}` })\n })\n\n/** `readLink` fails with NotFound for a missing path and EINVAL for a path that exists but is not a link. */\nconst notALink = (error: PlatformError): boolean =>\n error.reason._tag === \"NotFound\" ||\n (error.reason._tag !== \"BadArgument\" && Predicate.hasProperty(error.reason.cause, \"code\") &&\n error.reason.cause.code === \"EINVAL\")\n\nconst openStore = (path: string) =>\n Effect.acquireRelease(\n Effect.gen(function*() {\n // Sessions hold conversation content: the directory and the database are owner-only.\n const fs = yield* FileSystem.FileSystem\n const paths = yield* Path.Path\n const ownerOnly = (operation: string) =>\n Effect.mapError((cause: PlatformError) =>\n new RelayStoreFailed({ operation, message: `${operation} failed: ${cause.message}` })\n )\n const directory = paths.dirname(path)\n // chmod and SQLite follow links, so neither the directory, the database nor SQLite's sidecar files may\n // be one: a link would have Relay re-permission and write conversation content wherever it points.\n // Parent components may be links (a linked home directory is common); only the store's own names are\n // checked, the directory before it is created so a dangling link is reported as a link.\n const refuseLink = (target: string, what: string) =>\n fs.readLink(target).pipe(\n Effect.matchEffect({\n onFailure: (error) =>\n notALink(error)\n ? Effect.void\n : Effect.fail(\n new RelayStoreFailed({\n operation: \"check the Relay store\",\n message: `check the Relay store failed: ${error.message}`\n })\n ),\n onSuccess: (destination) =>\n Effect.fail(\n new RelayStoreLinked({\n path: target,\n message: `The Relay ${what} ${target} is a link to ${destination}. Replace it with a real ${what}.`\n })\n )\n })\n )\n yield* refuseLink(directory, \"store directory\")\n yield* fs.makeDirectory(directory, { recursive: true, mode: 0o700 }).pipe(\n ownerOnly(\"create the Relay store directory\")\n )\n yield* Effect.forEach([path, `${path}-wal`, `${path}-shm`], (file) => refuseLink(file, \"store\"), {\n discard: true\n })\n yield* fs.chmod(directory, 0o700).pipe(ownerOnly(\"restrict the Relay store directory\"))\n const client = createClient({ url: `file:${path}` })\n const database = libsqlDatabase(client)\n yield* promise(\"open the Relay store\", async () => {\n // Exclusive locking: the first write takes a lock this connection keeps until it closes or dies.\n await database.exec(\"PRAGMA locking_mode = EXCLUSIVE\")\n await database.exec(\"PRAGMA journal_mode = WAL\")\n await database.exec(\"PRAGMA synchronous = NORMAL\")\n await database.exec(\"BEGIN IMMEDIATE; COMMIT\")\n }).pipe(\n Effect.andThen(fs.chmod(path, 0o600).pipe(ownerOnly(\"restrict the Relay store\"))),\n Effect.catchTag(\"RelayStoreFailed\", (failure): Effect.Effect<never, RelayStoreFailed | RelayStoreLocked> =>\n /SQLITE_BUSY|database is locked/u.test(failure.message)\n ? Effect.fail(\n new RelayStoreLocked({\n path,\n message: `Another process owns the Relay store at ${path}. Stop it, then retry.`\n })\n )\n : Effect.fail(failure))\n )\n return database\n }),\n (database) =>\n Effect.promise(() =>\n database.close()\n )\n )\n\n/** Build the harness for one product. */\nexport const make = Effect.fn(\"RelayHarness.make\")(function*<Requirements>(options: RelayHarnessOptions<Requirements>) {\n const services = yield* Effect.context<Requirements>()\n const runEffect: EffectRunner<Requirements> = (effect, signal) =>\n Effect.runPromiseExitWith(services)(effect, signal === undefined ? undefined : { signal })\n const runPromise = Effect.runPromiseWith(services)\n const cryptoService = yield* Crypto.Crypto\n // Pi sleeps until `now()` reaches persisted deadlines (retry backoff, deferred polls), so it reads the\n // live clock on every call, never a cached value.\n const clockService = yield* Clock.Clock\n const now = () => clockService.currentTimeMillisUnsafe()\n\n const probed = (backend: RelayBackend): Effect.Effect<BackendStatus> =>\n backend.probe.pipe(\n Effect.match({\n onSuccess: (version): BackendStatus => ({\n _tag: \"Unverified\",\n backend: backend.id,\n label: backend.name,\n version\n }),\n onFailure: (failure): BackendStatus => ({\n _tag: \"Unavailable\",\n backend: backend.id,\n label: backend.name,\n cause: failure.cause,\n fix: failure.fix\n })\n })\n )\n const statuses = yield* Ref.make<ReadonlyArray<BackendStatus>>(\n yield* Effect.forEach(options.backends, probed, { concurrency: \"unbounded\" })\n )\n const setStatus = (status: BackendStatus) =>\n Ref.update(statuses, (all) => all.map((current) => (current.backend === status.backend ? status : current)))\n const statusOf = (backend: RelayBackend) =>\n Effect.map(Ref.get(statuses), (all) => all.find((status) => status.backend === backend.id))\n // A turn that answered proves the CLI works. One refused for its login is the only failure that says\n // something about the backend rather than the request; the rest stay on the run.\n const observed = (backend: RelayBackend, exit: Exit.Exit<unknown, unknown>) =>\n Effect.gen(function*() {\n const current = yield* statusOf(backend)\n const version = current?.version\n if (Exit.isSuccess(exit)) {\n if (version !== undefined) {\n return yield* setStatus({ _tag: \"Ready\", backend: backend.id, label: backend.name, version })\n }\n const reprobed = yield* probed(backend)\n return yield* setStatus(\n reprobed._tag === \"Unverified\" ? { ...reprobed, _tag: \"Ready\" } : reprobed\n )\n }\n const error = Exit.findErrorOption(exit)\n if (\n error._tag === \"Some\" && AiError.isAiError(error.value) && error.value.reason._tag === \"AuthenticationError\"\n ) {\n yield* setStatus({\n _tag: \"Unavailable\",\n backend: backend.id,\n label: backend.name,\n ...(version !== undefined && { version }),\n cause: \"SignedOut\",\n fix: backend.signInFix\n })\n }\n })\n\n // Each backend's model is built once, with the harness, and reused by every turn.\n const providers = yield* Effect.forEach(\n options.backends,\n (backend) =>\n Effect.map(Layer.build(backend.model), (modelContext) => {\n const runner: TurnRunner = (request, signal) =>\n runPromise(\n Effect.gen(function*() {\n const turn = yield* runTurn(request).pipe(Effect.provideContext(modelContext))\n const callIds = yield* Effect.forEach(turn.toolCalls, () => cryptoService.randomUUIDv4)\n return { turn, callIds }\n }).pipe(Effect.onExit((exit) => observed(backend, exit))),\n signal === undefined ? undefined : { signal }\n )\n return relayProvider(backend.id, backend.name, runner, now)\n })\n )\n const models = relayModels(providers)\n\n // Confirmations waiting for a person, with the event that shows them, so a dock that reconnects\n // mid-confirmation sees the card again after its Snapshot.\n const pending = new Map<string, { readonly decision: Deferred.Deferred<boolean>; readonly event: Unsequenced }>()\n // How each confirmation this process asked for ended, so a late or repeated answer learns why it is refused.\n const outcomes = new Map<string, DecisionState>()\n const pendingFor = (session: string): ReadonlyArray<Unsequenced> =>\n [...pending.values()].flatMap(({ event }) => (event.session === session ? [event] : []))\n const confirmations = yield* PubSub.unbounded<{ readonly conversationId: string; readonly event: Unsequenced }>()\n const broker: ConfirmationBroker = {\n ask: (request, signal) =>\n runPromise(\n Effect.gen(function*() {\n const decision = yield* Deferred.make<boolean>()\n const event: Unsequenced = {\n _tag: \"ConfirmationRequired\",\n session: request.conversationId,\n call: request.callId,\n action: request.action,\n reversible: request.reversible\n }\n pending.set(request.callId, { decision, event })\n yield* PubSub.publish(confirmations, { conversationId: request.conversationId, event })\n return yield* Deferred.await(decision)\n }).pipe(\n // A cancelled run aborts the call: the card goes away with it, answered or not, and the dock\n // hears how it ended.\n Effect.ensuring(Effect.suspend(() => {\n pending.delete(request.callId)\n const outcome = outcomes.get(request.callId) ?? { _tag: \"Expired\" }\n outcomes.set(request.callId, outcome)\n const event: Unsequenced = {\n _tag: \"ConfirmationResolved\",\n session: request.conversationId,\n call: request.callId,\n decision: outcome._tag === \"Decided\" ? (outcome.allow ? \"confirmed\" : \"declined\") : \"expired\"\n }\n return PubSub.publish(confirmations, { conversationId: request.conversationId, event })\n }))\n ),\n signal === undefined ? undefined : { signal }\n )\n }\n\n const registry = createRegistry()\n registry.install(relayExtension(options.capabilities, runEffect, broker))\n const database = yield* openStore(options.storePath)\n const storage = yield* promise(\"read the Relay store\", () => SqliteStorage.open(database))\n const harness = yield* Effect.acquireRelease(\n promise(\n \"start the Relay harness\",\n () => Harness.open(storage, { models, registry, now }, BACKGROUND_CONTEXT)\n ),\n (opened) => Effect.promise(() => opened.close(BACKGROUND_CONTEXT))\n )\n const defaultBackend = options.backends[0].id\n const root = yield* promise(\n \"open the Relay index\",\n () => harness.root(BACKGROUND_CONTEXT, { agent: { model: { provider: defaultBackend, modelId: \"default\" } } })\n )\n harness.resume()\n\n // One process owns the store, so one lock here is enough to create each object's session once.\n const sessionLock = yield* Semaphore.make(1)\n const conversationFor = (ref: ObjectRef): Effect.Effect<Conversation, RelayStoreFailed> =>\n sessionLock.withPermits(1)(promise(\"open the session\", async () => {\n const key = objectRefKey(ref)\n const index = await harness.snapshot(SessionIndex, root.id, BACKGROUND_CONTEXT)\n const known = index?.sessions[key]\n if (known !== undefined) {\n const existing = await harness.conversation(known, BACKGROUND_CONTEXT)\n if (existing !== undefined) return existing\n }\n const created = await harness.createConversation({\n ownership: { kind: \"ownerless\" },\n agent: { model: { provider: defaultBackend, modelId: \"default\" }, instructions: options.instructions }\n }, BACKGROUND_CONTEXT)\n await root.commit(async (tx) => {\n const sessions = await tx.doc(SessionIndex, root.id)\n sessions.sessions[key] = created.id\n }, BACKGROUND_CONTEXT)\n return created\n }))\n\n // The session an object already has, without creating one: deciding never opens a session.\n const existingSession = (ref: ObjectRef): Effect.Effect<ConversationId | undefined, RelayStoreFailed> =>\n promise(\"find the session\", async () => {\n const index = await harness.snapshot(SessionIndex, root.id, BACKGROUND_CONTEXT)\n return index?.sessions[objectRefKey(ref)]\n })\n\n const byName = new Map(options.capabilities.map((capability) => [capability.name, capability]))\n const display: Display = (capability) => byName.get(capability)\n const tools = options.capabilities.map((capability): SessionTool => ({\n name: capability.name,\n access: capability.gate?.access ?? \"read\",\n available: true\n }))\n\n return RelayHarness.of({\n tools,\n send: (ref, text, requestId, { backend, context = [] } = {}) =>\n Effect.gen(function*() {\n if (backend !== undefined && !options.backends.some((configured) => configured.id === backend)) {\n return yield* new RelayBackendNotConfigured({ backend })\n }\n const conversation = yield* conversationFor(ref)\n if (backend !== undefined) {\n yield* promise(\"switch the backend\", () =>\n conversation.configure({ model: { provider: backend, modelId: \"default\" } }, BACKGROUND_CONTEXT))\n }\n // Context goes in as its own entry: the model reads it, the transcript and Snapshot do not. Each entry\n // is keyed by the message's requestId, so a retried send places it once.\n yield* Effect.forEach(context, (item, index) =>\n promise(\"attach the context\", () =>\n conversation.submit({\n type: \"write\",\n requestId: `${requestId}#context-${index}`,\n entry: {\n kind: \"relay.context\",\n model: [{\n role: \"user\",\n content: `Context the person attached to their next message: ${item.label}\\n${item.body}`,\n timestamp: now()\n }]\n }\n }, BACKGROUND_CONTEXT)))\n yield* promise(\"send the message\", () =>\n conversation.submit({ type: \"input\", content: text, requestId }, BACKGROUND_CONTEXT))\n }),\n events: (ref) =>\n Stream.unwrap(\n Effect.map(conversationFor(ref), (conversation) =>\n sessionEvents(harness, conversation, confirmations, pendingFor, display))\n ),\n decide: (ref, callId, allow) =>\n Effect.gen(function*() {\n const session = yield* existingSession(ref)\n const waiting = pending.get(callId)\n if (waiting === undefined || session === undefined || waiting.event.session !== String(session)) {\n const outcome = waiting === undefined ? outcomes.get(callId) : undefined\n return yield* new RelayDecisionNotPending({ callId, state: outcome ?? { _tag: \"Unknown\" } })\n }\n outcomes.set(callId, { _tag: \"Decided\", allow })\n pending.delete(callId)\n yield* Deferred.succeed(waiting.decision, allow)\n }),\n cancel: (ref, runId) =>\n Effect.gen(function*() {\n const conversation = yield* conversationFor(ref)\n const submission = yield* promise(\n \"find the run\",\n () => storage.submissionByRequest(conversation.id, runId, BACKGROUND_CONTEXT)\n )\n if (submission?.type !== \"input\") return yield* new RelayRunNotActive({ runId })\n if (submission.status === \"queued\") {\n const withdrawn = yield* promise(\n \"withdraw the message\",\n () => harness.abortSubmission(submission.id, BACKGROUND_CONTEXT, conversation.id)\n )\n // Placed between the read and the withdrawal: it is the run in flight now.\n if (withdrawn !== \"already_placed\") return\n } else if (submission.status !== \"placed\") {\n return yield* new RelayRunNotActive({ runId })\n }\n yield* promise(\"cancel the run\", () => conversation.abort(BACKGROUND_CONTEXT))\n }),\n session: (ref) =>\n Effect.gen(function*() {\n const conversation = yield* conversationFor(ref)\n const agent = yield* promise(\"read the session\", () => conversation.agent(BACKGROUND_CONTEXT))\n const backend = Schema.decodeUnknownOption(RelayBackendId)(agent.model?.provider)\n return { tools, backend: backend._tag === \"Some\" ? backend.value : defaultBackend, cancel: true }\n }),\n backends: Ref.get(statuses)\n })\n})\n\n/** Build the harness as a scoped layer: the store closes, and the lock is released, with the scope. */\nexport const layer = <Requirements>(options: RelayHarnessOptions<Requirements>) =>\n Layer.effect(RelayHarness, make(options))\n\n/** The visible text of a stored user or assistant entry. */\nconst entryText = (messages: ReadonlyArray<Message> | undefined): string =>\n (messages ?? [])\n .flatMap((message) =>\n message.role === \"user\" || message.role === \"assistant\"\n ? Predicate.isString(message.content)\n ? [message.content]\n : message.content.flatMap((block) => (block.type === \"text\" ? [block.text] : []))\n : []\n )\n .join(\"\\n\")\n\n/** The citations a capability call records in its Pi tool details. */\n/** What a capability call records in its Pi tool details: citations, and a write's receipt. */\nconst decodeDetails = Schema.decodeUnknownOption(\n Schema.Struct({ cites: Schema.Array(Capability.ObjectRef), receipt: Schema.optionalKey(WriteReceipt) })\n)\n\n/** How the dock shows one capability's calls. */\ntype Display = (capability: string) => Pick<RegisteredCapability<unknown>, \"label\" | \"summarize\"> | undefined\n\n/** A Relay event before the stream numbers it. */\ntype Unsequenced = RelayEvent extends infer Event ? Event extends RelayEvent ? Omit<Event, \"seq\"> : never : never\n\nconst sessionEvents = (\n harness: Harness,\n conversation: Conversation,\n confirmations: PubSub.PubSub<{ readonly conversationId: string; readonly event: Unsequenced }>,\n pendingFor: (session: string) => ReadonlyArray<Unsequenced>,\n display: Display\n): Stream.Stream<RelayEvent, RelayStoreFailed> => {\n const summarize = (capability: string, args: Schema.Json) => display(capability)?.summarize(args) ?? capability\n const labelOf = (capability: string) => display(capability)?.label ?? capability\n const session = String(conversation.id)\n const fromPi = Stream.callback<AgentEvent, RelayStoreFailed>((queue) =>\n Effect.acquireRelease(\n promise(\"watch the session\", async () => {\n const watch = await watchEvents(harness, conversation.id, BACKGROUND_CONTEXT)\n Queue.offerUnsafe(queue, watch.snapshot)\n watch.start(async (events) => {\n for (const event of events) Queue.offerUnsafe(queue, event)\n })\n return watch\n }),\n (watch) => Effect.promise(() => watch.stop())\n )\n )\n const details = new Map<\n string,\n { readonly cites: ReadonlyArray<Capability.ObjectRef>; readonly receipt?: WriteReceipt }\n >()\n // Text already shown per content block of the in-flight message, so each change emits only what's new.\n const sent = new Map<number, string>()\n const textFrom = (index: number, full: string): ReadonlyArray<Unsequenced> => {\n const before = sent.get(index) ?? \"\"\n sent.set(index, full)\n return full.length > before.length && full.startsWith(before)\n ? [{ _tag: \"TextDelta\", session, text: full.slice(before.length) }]\n : []\n }\n // A dock that attaches mid-run sees the run as it stands: the partial answer so far, then the tools\n // still running, with their arguments from the call that started them.\n const inFlight = (snapshot: Extract<AgentEvent, { readonly type: \"snapshot\" }>): ReadonlyArray<Unsequenced> => {\n const calls = new Map<string, Schema.Json>()\n for (const entry of snapshot.entries) {\n for (const message of entry.model ?? []) {\n if (message.role !== \"assistant\") continue\n for (const block of message.content) if (block.type === \"toolCall\") calls.set(block.id, block.arguments)\n }\n }\n const partial =\n snapshot.generation?.message?.content.flatMap((block, index) =>\n block.type === \"text\" ? textFrom(index, block.text) : []\n ) ?? []\n const running = snapshot.tools.flatMap((slot): ReadonlyArray<Unsequenced> =>\n slot.status === \"done\"\n ? []\n : [{\n _tag: \"ToolStarted\",\n session,\n call: slot.callId,\n capability: slot.name,\n summary: summarize(slot.name, calls.get(slot.callId) ?? {}),\n input: calls.get(slot.callId) ?? {}\n }]\n )\n return [...partial, ...running]\n }\n const toRelay = (event: AgentEvent, runIds: ReadonlyArray<string>): ReadonlyArray<Unsequenced> => {\n switch (event.type) {\n case \"snapshot\":\n return [\n {\n _tag: \"Snapshot\",\n session,\n runIds,\n messages: event.entries.flatMap((\n entry\n ): ReadonlyArray<{ readonly id: string; readonly role: \"user\" | \"relay\"; readonly text: string }> =>\n entry.kind === \"pi.user\"\n ? [{ id: String(entry.id), role: \"user\", text: entryText(entry.model) }]\n : entry.kind === \"pi.assistant\"\n ? [{ id: String(entry.id), role: \"relay\", text: entryText(entry.model) }]\n : []\n )\n },\n ...inFlight(event),\n ...pendingFor(session)\n ]\n case \"message_start\":\n sent.clear()\n // A turn that finished before its first commit arrives whole here, with no updates after it.\n return event.message.role === \"assistant\"\n ? event.message.content.flatMap((block, index) => (block.type === \"text\" ? textFrom(index, block.text) : []))\n : []\n case \"message_update\":\n return event.changes.flatMap((change): ReadonlyArray<Unsequenced> => {\n // Pi coalesces commits, so text arrives as deltas, as a whole block, or as the whole message.\n if (change.type === \"text_delta\") {\n return textFrom(change.contentIndex, (sent.get(change.contentIndex) ?? \"\") + change.delta)\n }\n if (change.type === \"block\") {\n return change.block.type === \"text\"\n ? textFrom(change.contentIndex, change.block.text)\n : []\n }\n if (change.type === \"message\") {\n return change.message.content.flatMap((\n block,\n index\n ) => (block.type === \"text\" ? textFrom(index, block.text) : []))\n }\n return []\n })\n case \"tool_execution_start\":\n return [{\n _tag: \"ToolStarted\",\n session,\n call: event.toolCallId,\n capability: event.toolName,\n summary: summarize(event.toolName, event.args),\n input: event.args\n }]\n case \"tool_execution_update\": {\n const decoded = decodeDetails(event.details)\n if (decoded._tag === \"Some\") details.set(event.toolCallId, decoded.value)\n return []\n }\n case \"tool_execution_end\": {\n const recorded = details.get(event.toolCallId)\n details.delete(event.toolCallId)\n // Pi writes a result entry for blocked, declined, failed and interrupted calls too; only a result\n // that is not an error is a success.\n const failed = (event.entry?.model ?? []).some((message) =>\n message.role === \"toolResult\" && message.isError === true\n )\n return [{\n _tag: \"ToolFinished\",\n session,\n call: event.toolCallId,\n ok: event.entry !== undefined && !failed,\n summary: recorded?.receipt?.summary ?? labelOf(event.toolName),\n cites: recorded?.cites ?? [],\n ...(recorded?.receipt !== undefined && { receipt: recorded.receipt })\n }]\n }\n case \"task_failed\":\n return [{\n _tag: \"RunFailed\",\n session,\n runIds,\n cause: \"The run stopped on an error\",\n fix: \"Retry the message; if it fails again, check the backend in setup.\"\n }]\n default:\n return []\n }\n }\n const records = (inputs: ReadonlyArray<SubmissionId>) =>\n Promise.all(\n inputs.map(async (id) => (await harness.submission(id, BACKGROUND_CONTEXT))?.status(BACKGROUND_CONTEXT))\n )\n // Every input Relay submits carries the dock's requestId; an id is the fallback for one that doesn't.\n const runIdsOf = (inputs: ReadonlyArray<SubmissionId>, read: ReadonlyArray<SubmissionRecord | undefined>) =>\n inputs.map((id, index) => read[index]?.requestId ?? String(id))\n // The run in flight as this subscription last saw it: the Snapshot names it, so a cancel can address it.\n let active: ReadonlyArray<string> = []\n const track = (inputs: ReadonlyArray<SubmissionId>): Effect.Effect<ReadonlyArray<string>, RelayStoreFailed> =>\n (inputs.length === 0\n ? Effect.succeed([])\n : promise(\"read the run in flight\", async () => runIdsOf(inputs, await records(inputs)))).pipe(\n Effect.tap((runIds) => Effect.sync(() => (active = runIds)))\n )\n // A run's end says only which inputs it ran; each input's submission record says how it ended.\n const runEnded = (inputs: ReadonlyArray<SubmissionId>): Effect.Effect<Unsequenced, RelayStoreFailed> =>\n promise(\"read how the run ended\", async () => {\n const read = await records(inputs)\n const runIds = runIdsOf(inputs, read)\n const unanswered = read.find((record) => record?.status === \"unanswered\")\n if (unanswered === undefined || unanswered.status !== \"unanswered\") {\n return { _tag: \"RunFinished\", session, runIds }\n }\n // An abort is the person's cancellation; any other reason is a failure the dock must explain.\n return /abort/iu.test(unanswered.reason)\n ? { _tag: \"Cancelled\", session, runIds }\n : {\n _tag: \"RunFailed\",\n session,\n runIds,\n // `reason` is Pi's code (`model_error`); `detail` carries the backend's own message when there is one.\n cause: Predicate.isString(unanswered.detail) ? unanswered.detail : unanswered.reason,\n fix: \"Check the backend in Relay setup (installed and signed in), then send the message again.\"\n }\n })\n const gate = Stream.fromPubSub(confirmations).pipe(\n Stream.filter(({ conversationId }) => conversationId === session),\n Stream.map(({ event }) => event)\n )\n let seq = 0\n const relayed = Stream.flatMap(\n fromPi,\n (event) =>\n event.type === \"run_end\"\n ? Stream.fromEffect(runEnded(event.inputs).pipe(Effect.tap(() => Effect.sync(() => (active = [])))))\n : event.type === \"run_start\"\n ? Stream.fromEffect(track(event.inputs)).pipe(\n Stream.map((runIds): Unsequenced => ({ _tag: \"RunStarted\", session, runIds }))\n )\n : event.type === \"snapshot\"\n ? Stream.fromEffect(track(event.run?.inputs ?? [])).pipe(\n Stream.flatMap((runIds) => Stream.fromIterable(toRelay(event, runIds)))\n )\n : Stream.fromIterable(toRelay(event, active))\n )\n return Stream.merge(relayed, gate).pipe(\n Stream.map((event): RelayEvent => ({ ...event, seq: seq++ }))\n )\n}\n", "/**\n * Pi Durable's portable SQLite core over `@libsql/client`, so Relay sessions use the same SQLite\n * driver as codecommit-core and run under both Node and Bun.\n *\n * **Mental model**\n *\n * - **One queue per connection.** Pi requires that unrelated operations wait while a transaction is\n * open. Every operation and every transaction runs through one promise queue, in call order.\n * - **Rows are plain objects.** libsql rows also carry positional keys; Pi reads columns by name, so each\n * row is rebuilt from the result's column list.\n *\n * This module is a Promise boundary by design: Pi calls it, not Effect.\n *\n * @module\n */\nimport type { SqliteDatabase, SqliteExecutor, SqliteValue } from \"@earendil-works/pi-durable/storage/sqlite\"\nimport type { Client, InStatement, ResultSet, Transaction } from \"@libsql/client\"\nimport { Predicate } from \"effect\"\n\nconst toObjects = <T extends object>(result: ResultSet): Array<T> =>\n result.rows.map((row) =>\n // SAFETY: Pi's `get<T>`/`all<T>` contract names the row shape its own SQL selects; this adapter only\n // rebuilds each row by column name and cannot check `T`.\n // ast-grep-ignore: no-type-assertion\n Object.fromEntries(result.columns.map((column, index) => [column, row[index]])) as T\n )\n\nconst statement = (sql: string, params: ReadonlyArray<SqliteValue>): InStatement => ({\n sql,\n args: params.map((value) => (Predicate.isUint8Array(value) ? value.slice().buffer : value))\n})\n\nconst executorOver = (\n execute: (sql: string, params: ReadonlyArray<SqliteValue>) => Promise<ResultSet>,\n multiple: (sql: string) => Promise<void>\n): SqliteExecutor => ({\n exec: multiple,\n run: async (sql, ...params) => {\n await execute(sql, params)\n },\n get: async <T extends object>(sql: string, ...params: Array<SqliteValue>) =>\n toObjects<T>(await execute(sql, params))[0],\n all: async <T extends object>(sql: string, ...params: Array<SqliteValue>) => toObjects<T>(await execute(sql, params))\n})\n\n/** Wrap an open libsql client as Pi's `SqliteDatabase`. The client is closed with it. */\nexport const libsqlDatabase = (client: Client): SqliteDatabase => {\n let tail: Promise<void> = Promise.resolve()\n const queued = <T>(operation: () => Promise<T>): Promise<T> => {\n const result = tail.then(operation)\n tail = result.then(() => undefined, () => undefined)\n return result\n }\n const direct = executorOver(\n (sql, params) => queued(() => client.execute(statement(sql, params))),\n (sql) => queued(() => client.executeMultiple(sql))\n )\n const inside = (transaction: Transaction): SqliteExecutor =>\n executorOver(\n (sql, params) => transaction.execute(statement(sql, params)),\n (sql) => transaction.executeMultiple(sql)\n )\n return {\n ...direct,\n transaction: <T>(callback: (transaction: SqliteExecutor) => Promise<T>) =>\n queued(async () => {\n const transaction = await client.transaction(\"write\")\n try {\n const value = await callback(inside(transaction))\n await transaction.commit()\n return value\n } catch (error) {\n try {\n await transaction.rollback()\n } catch (rollbackError) {\n throw new AggregateError([error, rollbackError], \"Relay session transaction failed and did not roll back\", {\n cause: rollbackError\n })\n }\n throw error\n } finally {\n transaction.close()\n }\n }),\n close: () => queued(async () => client.close())\n }\n}\n", "/**\n * The Relay contracts every product and the dock share.\n *\n * **Mental model**\n *\n * - **An {@link ObjectRef} is what a conversation is about.** A pull request, a jcf week, a herdr\n * goal. Relay keeps one durable session per ref, so the same question about the same object finds\n * its history again.\n * - **A capability (`@knpkv/capability`) is the only way Relay touches a product.** Its contract declares\n * input, output and failure as Schema, and its access: `read` runs, `write` waits for the person to\n * confirm the exact action in the dock, `host` waits for a herdr Approval. The harness enforces it; the\n * product never sees an unconfirmed write.\n * - **A {@link RelayEvent} is the only thing the dock renders.** Every event carries the session and a\n * `seq` that counts up within one subscription. A dock that reconnects starts a new subscription: a\n * `Snapshot` first (with any run in flight and any pending confirmation), then live events. `seq` is not\n * comparable across subscriptions; render the Snapshot rather than deduplicating by `seq`.\n *\n * @module\n */\nimport * as Capability from \"@knpkv/capability\"\nimport { Schema } from \"effect\"\n\nconst Name = Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(200))\n\n/** The products Relay can be about. */\nexport const RelayProduct = Schema.Literals([\"codecommit\", \"jcf\", \"agent-usage\", \"control-center\", \"herdr\"])\nexport type RelayProduct = typeof RelayProduct.Type\n\n/** A product object a Relay session is about. Relay keeps sessions only for the products it knows. */\nexport const ObjectRef = Schema.Struct({\n product: RelayProduct,\n kind: Name,\n id: Name\n})\nexport interface ObjectRef extends Schema.Schema.Type<typeof ObjectRef> {}\n\n/** The key a session is stored under. Unique per product, kind and id: JSON-encoded, so no field can contain the separator. */\nexport const objectRefKey = (ref: ObjectRef): string => JSON.stringify([ref.product, ref.kind, ref.id])\n\n/** Who must agree before a capability runs, as the dock lists it. */\nexport const CapabilityAccess = Schema.Literals([\"read\", \"write\", \"host\"])\nexport type CapabilityAccess = typeof CapabilityAccess.Type\n\n/** Why a backend can't answer yet, and the one action that fixes it. */\nexport const BackendUnavailableCause = Schema.Literals([\"NotInstalled\", \"SignedOut\", \"Misconfigured\", \"NoCapability\"])\nexport type BackendUnavailableCause = typeof BackendUnavailableCause.Type\n\n/** The backends Relay supports: each runs on the user's own CLI login, never on a token Relay holds. */\nexport const RelayBackendId = Schema.Literals([\"claude-code\", \"codex-cli\"])\nexport type RelayBackendId = typeof RelayBackendId.Type\n\nconst backendFields = { backend: RelayBackendId, label: Schema.String }\n\n/**\n * What setup shows for one backend. `Unverified` (installed, version known, never answered yet) until a turn\n * answers (`Ready`) or is refused for sign-in (`Unavailable` with `SignedOut`). Not persisted: every start is\n * `Unverified` or `Unavailable` again. `fix` is one line the person can act on.\n */\nexport const BackendStatus = Schema.TaggedUnion({\n Unverified: { ...backendFields, version: Schema.String },\n Ready: { ...backendFields, version: Schema.String },\n Unavailable: {\n ...backendFields,\n version: Schema.optionalKey(Schema.String),\n cause: BackendUnavailableCause,\n fix: Schema.String\n }\n})\nexport type BackendStatus = typeof BackendStatus.Type\n\n/** Why a confirmation can't be answered: answered already, withdrawn with its run, or never asked. */\nexport const DecisionState = Schema.TaggedUnion({\n Decided: { allow: Schema.Boolean },\n Expired: {},\n Unknown: {}\n})\nexport type DecisionState = typeof DecisionState.Type\n\n/** One tool as the dock lists it for a session. */\nexport const SessionTool = Schema.Struct({\n name: Name,\n access: CapabilityAccess,\n available: Schema.Boolean,\n unavailableReason: Schema.optional(Schema.String)\n})\nexport interface SessionTool extends Schema.Schema.Type<typeof SessionTool> {}\n\n/**\n * What the dock shows for a session: its tools, the backend its next turn runs on, and whether a run can\n * be stopped (the dock offers Stop only when `cancel` is true).\n */\nexport const SessionInfo = Schema.Struct({\n tools: Schema.Array(SessionTool),\n backend: RelayBackendId,\n cancel: Schema.Boolean\n})\nexport interface SessionInfo extends Schema.Schema.Type<typeof SessionInfo> {}\n\n/**\n * What a confirmed write did, as the product projects it: a display-safe line, the provider's id for what\n * was made, and where to see it.\n */\nexport const WriteReceipt = Schema.Struct({\n summary: Schema.String,\n providerId: Schema.String,\n link: Schema.optionalKey(Schema.String)\n})\nexport interface WriteReceipt extends Schema.Schema.Type<typeof WriteReceipt> {}\n\nconst Seq = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))\n\nconst eventFields = { session: Name, seq: Seq }\n\n/** The `requestId`s of the messages a run answers: one run can take several queued messages. */\nconst RunIds = Schema.Array(Name)\n\n/** Everything the dock renders. `seq` counts up within one subscription; a reconnect starts from a `Snapshot`. */\nexport const RelayEvent = Schema.TaggedUnion({\n Snapshot: {\n ...eventFields,\n messages: Schema.Array(\n Schema.Struct({ id: Name, role: Schema.Literals([\"user\", \"relay\"]), text: Schema.String })\n ),\n /** The run in flight, empty when idle. */\n runIds: RunIds\n },\n RunStarted: { ...eventFields, runIds: RunIds },\n TextDelta: { ...eventFields, text: Schema.String },\n /** `summary` is a server-built, display-safe line; `input` is the call's typed arguments. */\n ToolStarted: { ...eventFields, call: Name, capability: Name, summary: Schema.String, input: Schema.Json },\n /** `receipt` is set when a write completed and its capability projects one. */\n ToolFinished: {\n ...eventFields,\n call: Name,\n ok: Schema.Boolean,\n summary: Schema.String,\n cites: Schema.Array(Capability.ObjectRef),\n receipt: Schema.optionalKey(WriteReceipt)\n },\n ConfirmationRequired: { ...eventFields, call: Name, action: Capability.PendingAction, reversible: Schema.Boolean },\n /** The server's outcome for a confirmation: the card turns to past tense only on this. */\n ConfirmationResolved: {\n ...eventFields,\n call: Name,\n decision: Schema.Literals([\"confirmed\", \"declined\", \"expired\"])\n },\n ApprovalPending: { ...eventFields, call: Name, approvalId: Name },\n Cancelled: { ...eventFields, runIds: RunIds },\n RunFinished: { ...eventFields, runIds: RunIds },\n RunFailed: { ...eventFields, runIds: RunIds, cause: Schema.String, fix: Schema.String }\n})\nexport type RelayEvent = typeof RelayEvent.Type\n", "export type { Static, TSchema } from \"typebox\";\nexport { Type } from \"typebox\";\n\n// Core only, side-effect free: no generated catalogs, no provider factories,\n// no api-registry, no OAuth implementations, no compat. Provider factories\n// live under \"@earendil-works/pi-ai/providers/*\", API implementations under\n// \"@earendil-works/pi-ai/api/*\", the old global API under\n// \"@earendil-works/pi-ai/compat\".\nexport type { AnthropicEffort, AnthropicOptions, AnthropicThinkingDisplay } from \"./api/anthropic-messages.ts\";\nexport type { AzureOpenAIResponsesOptions } from \"./api/azure-openai-responses.ts\";\nexport type { BedrockOptions, BedrockThinkingDisplay } from \"./api/bedrock-converse-stream.ts\";\nexport type { GoogleOptions } from \"./api/google-generative-ai.ts\";\nexport type { GoogleApiThinkingLevel, ResolvedGoogleThinkingLevel } from \"./api/google-shared.ts\";\nexport type { GoogleVertexOptions } from \"./api/google-vertex.ts\";\nexport * from \"./api/lazy.ts\";\nexport type { MistralOptions } from \"./api/mistral-conversations.ts\";\nexport type { OpenAICodexResponsesOptions, OpenAICodexWebSocketDebugStats } from \"./api/openai-codex-responses.ts\";\nexport type { OpenAICompletionsOptions } from \"./api/openai-completions.ts\";\nexport type { OpenAIResponsesOptions } from \"./api/openai-responses.ts\";\nexport type { PiMessagesEvent, PiMessagesOptions, PiMessagesRewriteImpact } from \"./api/pi-messages.ts\";\nexport * from \"./auth/context.ts\";\nexport * from \"./auth/credential-store.ts\";\nexport * from \"./auth/helpers.ts\";\nexport * from \"./auth/types.ts\";\nexport type {\n\tOAuthAuthInfo,\n\tOAuthDeviceCodeInfo,\n\tOAuthLoginCallbacks,\n\tOAuthPrompt,\n\tOAuthSelectOption,\n\tOAuthSelectPrompt,\n} from \"./compat/extension-oauth-types.ts\";\nexport * from \"./models.ts\";\nexport * from \"./models-store.ts\";\nexport * from \"./providers/faux.ts\";\nexport * from \"./session-resources.ts\";\nexport * from \"./types.ts\";\nexport * from \"./utils/assistant-message-frame.ts\";\nexport * from \"./utils/diagnostics.ts\";\nexport * from \"./utils/event-stream.ts\";\nexport * from \"./utils/json-parse.ts\";\nexport * from \"./utils/overflow.ts\";\nexport * from \"./utils/retry.ts\";\nexport { contentText, getSystemMessageText, renderSystemMessageUpdate } from \"./utils/text.ts\";\nexport * from \"./utils/transcript.ts\";\nexport * from \"./utils/typebox-helpers.ts\";\nexport { uuidv7 } from \"./utils/uuid.ts\";\nexport * from \"./utils/validation.ts\";\n", "import type { AssistantMessage, AssistantMessageEvent } from \"../types.ts\";\n\nclass FifoQueue<T> {\n\tprivate incoming: T[] = [];\n\tprivate outgoing: T[] = [];\n\n\tget length(): number {\n\t\treturn this.incoming.length + this.outgoing.length;\n\t}\n\n\tenqueue(value: T): void {\n\t\tthis.incoming.push(value);\n\t}\n\n\tdequeue(): T | undefined {\n\t\tif (this.outgoing.length === 0) {\n\t\t\twhile (this.incoming.length > 0) {\n\t\t\t\tthis.outgoing.push(this.incoming.pop()!);\n\t\t\t}\n\t\t}\n\t\treturn this.outgoing.pop();\n\t}\n}\n\n// Generic event stream class for async iteration\nexport class EventStream<T, R = T> implements AsyncIterable<T> {\n\tprivate queue = new FifoQueue<T>();\n\tprivate waiting = new FifoQueue<(value: IteratorResult<T>) => void>();\n\tprivate done = false;\n\tprivate finalResultPromise: Promise<R>;\n\tprivate resolveFinalResult!: (result: R) => void;\n\tprivate isComplete: (event: T) => boolean;\n\tprivate extractResult: (event: T) => R;\n\n\tconstructor(isComplete: (event: T) => boolean, extractResult: (event: T) => R) {\n\t\tthis.isComplete = isComplete;\n\t\tthis.extractResult = extractResult;\n\t\tthis.finalResultPromise = new Promise((resolve) => {\n\t\t\tthis.resolveFinalResult = resolve;\n\t\t});\n\t}\n\n\tpush(event: T): void {\n\t\tif (this.done) return;\n\n\t\tif (this.isComplete(event)) {\n\t\t\tthis.done = true;\n\t\t\tthis.resolveFinalResult(this.extractResult(event));\n\t\t}\n\n\t\t// Deliver to waiting consumer or queue it\n\t\tconst waiter = this.waiting.dequeue();\n\t\tif (waiter) {\n\t\t\twaiter({ value: event, done: false });\n\t\t} else {\n\t\t\tthis.queue.enqueue(event);\n\t\t}\n\t}\n\n\tend(result?: R): void {\n\t\tthis.done = true;\n\t\tif (result !== undefined) {\n\t\t\tthis.resolveFinalResult(result);\n\t\t}\n\t\t// Notify all waiting consumers that we're done\n\t\twhile (this.waiting.length > 0) {\n\t\t\tconst waiter = this.waiting.dequeue()!;\n\t\t\twaiter({ value: undefined as any, done: true });\n\t\t}\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncIterator<T> {\n\t\twhile (true) {\n\t\t\tif (this.queue.length > 0) {\n\t\t\t\tyield this.queue.dequeue()!;\n\t\t\t} else if (this.done) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tconst result = await new Promise<IteratorResult<T>>((resolve) => this.waiting.enqueue(resolve));\n\t\t\t\tif (result.done) return;\n\t\t\t\tyield result.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tresult(): Promise<R> {\n\t\treturn this.finalResultPromise;\n\t}\n}\n\nexport class AssistantMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.message;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/** Factory function for AssistantMessageEventStream (for use in extensions) */\nexport function createAssistantMessageEventStream(): AssistantMessageEventStream {\n\treturn new AssistantMessageEventStream();\n}\n", "import type { Api, AssistantMessage, AssistantMessageEvent, Model, ProviderStreams } from \"../types.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\n\nfunction createSetupErrorMessage(model: Model<Api>, error: unknown): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction hasResult(\n\tsource: AsyncIterable<AssistantMessageEvent>,\n): source is AsyncIterable<AssistantMessageEvent> & { result(): Promise<AssistantMessage> } {\n\treturn typeof (source as { result?: unknown }).result === \"function\";\n}\n\nasync function forwardStream(\n\ttarget: AssistantMessageEventStream,\n\tsource: AsyncIterable<AssistantMessageEvent>,\n): Promise<void> {\n\tfor await (const event of source) {\n\t\ttarget.push(event);\n\t}\n\ttarget.end(hasResult(source) ? await source.result() : undefined);\n}\n\n/**\n * Returns a stream synchronously while running async setup (auth resolution,\n * lazy module loading) behind it. Setup failures terminate the stream with an\n * error event.\n */\nexport function lazyStream(\n\tmodel: Model<Api>,\n\tsetup: () => Promise<AsyncIterable<AssistantMessageEvent>>,\n): AssistantMessageEventStream {\n\tconst outer = new AssistantMessageEventStream();\n\n\tsetup()\n\t\t.then((inner) => forwardStream(outer, inner))\n\t\t.catch((error) => {\n\t\t\tconst message = createSetupErrorMessage(model, error);\n\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\touter.end(message);\n\t\t});\n\n\treturn outer;\n}\n\n/**\n * Wraps a dynamically imported API implementation module as `ProviderStreams`.\n * The module loads on first stream call; the host's import cache deduplicates\n * loads. Load failures terminate the returned stream with an error event.\n */\nexport interface LazyApiCapabilities {\n\tfetchDeferred?: boolean;\n\tcancelDeferred?: boolean;\n}\n\nexport function lazyApi(load: () => Promise<ProviderStreams>, capabilities?: LazyApiCapabilities): ProviderStreams {\n\tconst api: ProviderStreams = {\n\t\tstream: (model, context, options) =>\n\t\t\tlazyStream(model, async () => (await load()).stream(model, context, options)),\n\t\tstreamSimple: (model, context, options) =>\n\t\t\tlazyStream(model, async () => (await load()).streamSimple(model, context, options)),\n\t};\n\n\tif (capabilities?.fetchDeferred) {\n\t\tapi.fetchDeferred = (model, handle, options) =>\n\t\t\tlazyStream(model, async () => {\n\t\t\t\tconst implementation = await load();\n\t\t\t\tif (!implementation.fetchDeferred) throw new Error(\"API does not support deferred responses\");\n\t\t\t\treturn implementation.fetchDeferred(model, handle, options);\n\t\t\t});\n\t}\n\tif (capabilities?.cancelDeferred) {\n\t\tapi.cancelDeferred = async (model, handle, options) => {\n\t\t\tconst implementation = await load();\n\t\t\tif (!implementation.cancelDeferred) throw new Error(\"API cannot cancel deferred responses\");\n\t\t\tawait implementation.cancelDeferred(model, handle, options);\n\t\t};\n\t}\n\n\treturn api;\n}\n", "import type { AuthContext } from \"./types.ts\";\n\ninterface NodeFsModule {\n\taccess(path: string): Promise<void>;\n}\n\ninterface NodeOsModule {\n\thomedir(): string;\n}\n\n// Variable specifier so browser bundlers do not try to resolve node builtins.\nconst importNodeModule = (specifier: string): Promise<unknown> => import(specifier);\n\nfunction getProcessEnv(): Record<string, string | undefined> | undefined {\n\tconst proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;\n\treturn proc?.env;\n}\n\n/**\n * Default auth context: env vars from `process.env` (undefined in browsers),\n * file existence via node:fs (always false in browsers).\n */\nexport function defaultProviderAuthContext(): AuthContext {\n\treturn {\n\t\tasync env(name: string): Promise<string | undefined> {\n\t\t\tconst value = getProcessEnv()?.[name];\n\t\t\treturn typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n\t\t},\n\n\t\tasync fileExists(path: string): Promise<boolean> {\n\t\t\ttry {\n\t\t\t\tconst fs = (await importNodeModule(\"node:fs/promises\")) as NodeFsModule;\n\t\t\t\tlet resolved = path;\n\t\t\t\tif (resolved.startsWith(\"~\")) {\n\t\t\t\t\tconst os = (await importNodeModule(\"node:os\")) as NodeOsModule;\n\t\t\t\t\tresolved = os.homedir() + resolved.slice(1);\n\t\t\t\t}\n\t\t\t\tawait fs.access(resolved);\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\t};\n}\n", "function abortReason(signal: AbortSignal): unknown {\n\tif (signal.reason !== undefined) return signal.reason;\n\tconst error = new Error(\"The operation was aborted\");\n\terror.name = \"AbortError\";\n\treturn error;\n}\n\n/** Create an operation-local signal for public APIs whose signal is optional. */\nexport function operationSignal(signal?: AbortSignal): AbortSignal {\n\treturn signal ?? new AbortController().signal;\n}\n\n/**\n * Stop waiting for an operation when its signal aborts while continuing to\n * observe the abandoned promise so a later rejection is always handled.\n */\nexport function raceWithAbortSignal<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {\n\tif (signal.aborted) {\n\t\tvoid operation.catch(() => {});\n\t\treturn Promise.reject(abortReason(signal));\n\t}\n\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst cleanup = () => signal.removeEventListener(\"abort\", onAbort);\n\t\tconst onAbort = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(abortReason(signal));\n\t\t};\n\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid operation.then(\n\t\t\t(value) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t\tif (signal.aborted) onAbort();\n\t});\n}\n", "import { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport type { AuthOperationOptions, Credential, CredentialInfo, CredentialStore } from \"./types.ts\";\n\n/**\n * Default in-memory credential store. Apps inject persistent stores.\n * Keyed by `Provider.id`, one credential per provider; see `CredentialStore`.\n * Writes are serialized per provider through a promise chain.\n */\nexport class InMemoryCredentialStore implements CredentialStore {\n\tprivate credentials = new Map<string, Credential>();\n\tprivate chains = new Map<string, Promise<unknown>>();\n\n\t/** Serialize tasks per provider id without releasing the chain before active work settles. */\n\tprivate enqueue<T>(providerId: string, task: () => Promise<T>, options?: AuthOperationOptions): Promise<T> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tconst previous = this.chains.get(providerId) ?? Promise.resolve();\n\t\tconst queued = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tsignal.throwIfAborted();\n\t\t\treturn task();\n\t\t})();\n\t\tconst tail = queued.catch(() => {});\n\t\tthis.chains.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.chains.get(providerId) === tail) this.chains.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(queued, signal);\n\t}\n\n\tasync read(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined> {\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn this.credentials.get(providerId);\n\t}\n\n\tasync list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn [...this.credentials].map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined> {\n\t\treturn this.enqueue(\n\t\t\tproviderId,\n\t\t\tasync () => {\n\t\t\t\tconst current = this.credentials.get(providerId);\n\t\t\t\tconst next = await fn(current);\n\t\t\t\toptions?.signal?.throwIfAborted();\n\t\t\t\tif (next !== undefined) this.credentials.set(providerId, next);\n\t\t\t\treturn next ?? current;\n\t\t\t},\n\t\t\toptions,\n\t\t);\n\t}\n\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void> {\n\t\treturn this.enqueue(\n\t\t\tproviderId,\n\t\t\tasync () => {\n\t\t\t\tthis.credentials.delete(providerId);\n\t\t\t},\n\t\t\toptions,\n\t\t);\n\t}\n}\n", "import type { JsonObject } from \"../types.ts\";\n\nexport interface DiagnosticErrorInfo {\n\tname?: string;\n\tmessage: string;\n\tstack?: string;\n\tcode?: string | number;\n}\n\nexport interface AssistantMessageDiagnostic {\n\ttype: string;\n\ttimestamp: number;\n\terror?: DiagnosticErrorInfo;\n\tdetails?: JsonObject;\n}\n\nexport function formatThrownValue(value: unknown): string {\n\tif (value instanceof Error) return value.message || value.name;\n\tif (typeof value === \"string\") return value;\n\treturn String(value);\n}\n\nexport function extractDiagnosticError(error: unknown): DiagnosticErrorInfo {\n\tif (!(error instanceof Error)) return { name: \"ThrownValue\", message: formatThrownValue(error) };\n\tconst code = (error as Error & { code?: unknown }).code;\n\treturn {\n\t\tname: error.name || undefined,\n\t\tmessage: error.message || error.name,\n\t\tstack: error.stack,\n\t\tcode: typeof code === \"string\" || typeof code === \"number\" ? code : undefined,\n\t};\n}\n\nexport function createAssistantMessageDiagnostic(\n\ttype: string,\n\terror: unknown,\n\tdetails?: JsonObject,\n): AssistantMessageDiagnostic {\n\treturn { type, timestamp: Date.now(), error: extractDiagnosticError(error), details };\n}\n\nexport function appendAssistantMessageDiagnostic<T extends { diagnostics?: AssistantMessageDiagnostic[] }>(\n\tmessage: T,\n\tdiagnostic: AssistantMessageDiagnostic,\n): void {\n\tmessage.diagnostics = [...(message.diagnostics ?? []), diagnostic];\n}\n", "import { formatThrownValue } from \"./diagnostics.ts\";\n\nexport type ModelsErrorCode = \"model_source\" | \"model_validation\" | \"provider\" | \"stream\" | \"auth\" | \"oauth\";\n\nexport class ModelsError extends Error {\n\treadonly code: ModelsErrorCode;\n\n\tconstructor(code: ModelsErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(withCauseDetail(message, options?.cause), options);\n\t\tthis.name = \"ModelsError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Callers surface `error.message` only, so keep the underlying reason in it. */\nfunction withCauseDetail(message: string, cause: unknown): string {\n\tif (cause === undefined || cause === null) return message;\n\tconst detail = formatThrownValue(cause).trim();\n\tif (!detail || message.includes(detail)) return message;\n\treturn `${message}: ${detail}`;\n}\n", "import type { ProviderEnv } from \"../types.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { ModelsError } from \"../utils/models-error.ts\";\n\nexport { ModelsError, type ModelsErrorCode } from \"../utils/models-error.ts\";\n\nimport type {\n\tApiKeyAuth,\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tCredential,\n\tCredentialStore,\n\tOAuthAuth,\n\tOAuthCredential,\n\tProviderAuth,\n} from \"./types.ts\";\n\nexport interface AuthResolutionOverrides {\n\tapiKey?: string;\n\tenv?: ProviderEnv;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n\tsignal?: AbortSignal;\n}\n\n/**\n * Auth resolution shared by all operations in a `Models` collection.\n * A stored credential owns the provider: ambient/env is consulted only when\n * nothing is stored. No silent env fallback after a failed refresh or for a\n * credential type without a matching handler.\n */\nexport function resolveProviderAuth(\n\tprovider: { id: string; auth: ProviderAuth },\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides?: AuthResolutionOverrides,\n): Promise<AuthResult | undefined> {\n\tconst signal = operationSignal(overrides?.signal);\n\treturn raceWithAbortSignal(\n\t\tresolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal),\n\t\tsignal,\n\t);\n}\n\nasync function resolveProviderAuthWithSignal(\n\tprovider: { id: string; auth: ProviderAuth },\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides: AuthResolutionOverrides | undefined,\n\tsignal: AbortSignal,\n): Promise<AuthResult | undefined> {\n\tsignal.throwIfAborted();\n\tconst requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;\n\n\tif (overrides?.apiKey !== undefined && provider.auth.apiKey) {\n\t\treturn resolveApiKey(\n\t\t\trequestAuthContext,\n\t\t\tprovider.auth.apiKey,\n\t\t\tprovider.id,\n\t\t\t{\n\t\t\t\ttype: \"api_key\",\n\t\t\t\tkey: overrides.apiKey,\n\t\t\t\tenv: overrides.env,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t}\n\n\tconst stored = await readCredential(credentials, provider.id, signal);\n\tif (stored) {\n\t\tif (stored.type === \"oauth\" && provider.auth.oauth) {\n\t\t\treturn resolveStoredOAuth(\n\t\t\t\tcredentials,\n\t\t\t\tprovider.id,\n\t\t\t\tprovider.auth.oauth,\n\t\t\t\tstored,\n\t\t\t\tsignal,\n\t\t\t\toverrides?.minOAuthValidityMs,\n\t\t\t);\n\t\t}\n\t\tif (stored.type === \"api_key\" && provider.auth.apiKey) {\n\t\t\tconst credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;\n\t\t\treturn resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, credential, signal);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Ambient (env vars, AWS profiles, ADC files).\n\treturn provider.auth.apiKey\n\t\t? resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, undefined, signal)\n\t\t: undefined;\n}\n\nfunction overlayEnvAuthContext(base: AuthContext, env: ProviderEnv): AuthContext {\n\treturn {\n\t\tenv: async (name) => env[name] || (await base.env(name)),\n\t\tfileExists: (path) => base.fileExists(path),\n\t};\n}\n\nconst DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 5 * 60 * 1000;\nconst DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 15_000;\n\n/**\n * Refresh a stored OAuth credential under the credential-store lock and persist\n * the result before the lock is released. `needsRefresh` is re-checked under\n * the lock, so concurrent callers and processes refresh only once.\n *\n * `signal` cancels only the wait for the lock. Once a refresh starts, the\n * provider may already have rotated the refresh token, so the refresh and its\n * persistence ignore `signal` and are bounded only by a timeout. Otherwise a\n * cancelled caller could discard the only valid refresh token. Callers that\n * must return promptly on cancellation race this promise with their signal.\n *\n * Resolves with the stored OAuth credential after the operation, or undefined\n * when the provider no longer has an OAuth credential.\n */\nexport async function refreshStoredOAuthCredential(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\toauth: OAuthAuth,\n\tneedsRefresh: (credential: OAuthCredential) => boolean,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential | undefined> {\n\tlet post: Credential | undefined;\n\tconst lockWait = new AbortController();\n\tconst cancelLockWait = () => lockWait.abort(signal.reason);\n\tsignal.addEventListener(\"abort\", cancelLockWait, { once: true });\n\tif (signal.aborted) cancelLockWait();\n\ttry {\n\t\tpost = await credentials.modify(\n\t\t\tproviderId,\n\t\t\tasync (current) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", cancelLockWait);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (current?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\t\t\tif (!needsRefresh(current)) return undefined; // another process/request refreshed\n\t\t\t\ttry {\n\t\t\t\t\treturn await oauth.refresh(current, AbortSignal.timeout(DEFAULT_OAUTH_REFRESH_TIMEOUT_MS));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh failed for ${providerId}`, { cause: error });\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ signal: lockWait.signal },\n\t\t);\n\t} catch (error) {\n\t\tif (error instanceof ModelsError) throw error;\n\t\tsignal.throwIfAborted();\n\t\tthrow new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", cancelLockWait);\n\t}\n\treturn post?.type === \"oauth\" ? post : undefined;\n}\n\n/**\n * OAuth resolution with double-checked locking: tokens with less than five\n * minutes remaining are refreshed through `refreshStoredOAuthCredential`.\n */\nasync function resolveStoredOAuth(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\toauth: OAuthAuth,\n\tstored: OAuthCredential,\n\tsignal: AbortSignal,\n\tminOAuthValidityMs?: number,\n): Promise<AuthResult | undefined> {\n\tconst minimumValidityMs = Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, minOAuthValidityMs ?? 0);\n\tconst expiresSoon = (credential: OAuthCredential) => Date.now() + minimumValidityMs >= credential.expires;\n\tlet credential = stored;\n\n\tif (expiresSoon(credential)) {\n\t\t// Optimistic check said expired; the authoritative check runs under the lock.\n\t\tconst post = await refreshStoredOAuthCredential(credentials, providerId, oauth, expiresSoon, signal);\n\t\tif (!post) return undefined; // logged out meanwhile\n\t\tcredential = post;\n\t\t// The normal five-minute window triggers a refresh but does not impose a\n\t\t// provider contract. Explicit callers (such as bearer-token export) do\n\t\t// require the requested minimum after the refresh.\n\t\tif (minOAuthValidityMs !== undefined && expiresSoon(credential)) {\n\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh returned a token that expires too soon for ${providerId}`);\n\t\t}\n\t}\n\n\ttry {\n\t\treturn { auth: await oauth.toAuth(credential), source: \"OAuth\" };\n\t} catch (error) {\n\t\tthrow new ModelsError(\"oauth\", `OAuth auth derivation failed for ${providerId}`, { cause: error });\n\t}\n}\n\nasync function resolveApiKey(\n\tauthContext: AuthContext,\n\tapiKey: ApiKeyAuth,\n\tproviderId: string,\n\tcredential: ApiKeyCredential | undefined,\n\tsignal: AbortSignal,\n): Promise<AuthResult | undefined> {\n\ttry {\n\t\treturn await apiKey.resolve({ ctx: authContext, credential, signal });\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `API key auth failed for provider ${providerId}`, { cause: error });\n\t}\n}\n\nasync function readCredential(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\tsignal: AbortSignal,\n): Promise<Credential | undefined> {\n\ttry {\n\t\treturn await credentials.read(providerId, { signal });\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n\t}\n}\n", "import type { AnyModel } from \"./types.ts\";\n\nexport interface ModelsStoreEntry {\n\t/** Persisted models of every type. */\n\tmodels: readonly AnyModel[];\n\t/** Unix timestamp from the remote catalog's Last-Modified header. */\n\tlastModified?: number;\n\t/** Unix timestamp of the last completed remote check. */\n\tcheckedAt?: number;\n\t/**\n\t * Opaque validator from the remote catalog's ETag header, stored verbatim\n\t * (quotes included) and echoed back as If-None-Match.\n\t */\n\tetag?: string;\n}\n\nexport interface ModelsStoreOperationOptions {\n\tsignal?: AbortSignal;\n}\n\n/** Persistent model catalogs keyed by provider ID. */\nexport interface ModelsStore {\n\tread(providerId: string, options?: ModelsStoreOperationOptions): Promise<ModelsStoreEntry | undefined>;\n\twrite(providerId: string, entry: ModelsStoreEntry, options?: ModelsStoreOperationOptions): Promise<void>;\n\tdelete(providerId: string, options?: ModelsStoreOperationOptions): Promise<void>;\n}\n\nexport class InMemoryModelsStore implements ModelsStore {\n\tprivate readonly entries = new Map<string, ModelsStoreEntry>();\n\n\tasync read(providerId: string, options?: ModelsStoreOperationOptions): Promise<ModelsStoreEntry | undefined> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tconst entry = this.entries.get(providerId);\n\t\treturn entry ? structuredClone(entry) : undefined;\n\t}\n\n\tasync write(providerId: string, entry: ModelsStoreEntry, options?: ModelsStoreOperationOptions): Promise<void> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tthis.entries.set(providerId, structuredClone(entry));\n\t}\n\n\tasync delete(providerId: string, options?: ModelsStoreOperationOptions): Promise<void> {\n\t\toptions?.signal?.throwIfAborted();\n\t\tthis.entries.delete(providerId);\n\t}\n}\n", "import type {\n\tAnyModel,\n\tApi,\n\tAssistantImages,\n\tClassifierApi,\n\tClassifierModel,\n\tClassifierResult,\n\tImageApi,\n\tImageModel,\n\tModel,\n\tModelType,\n\tModelTypeMap,\n} from \"../types.ts\";\nimport { ModelsError } from \"./models-error.ts\";\n\n/** The type of a model. Models without `type` are chat models. */\nexport function getModelType(model: AnyModel): ModelType {\n\treturn model.type ?? \"chat\";\n}\n\n/** Runtime-checked model type narrowing, including legacy chat models without `type`. */\nexport function isModelType<TType extends ModelType>(model: AnyModel, type: TType): model is ModelTypeMap[TType] {\n\treturn getModelType(model) === type;\n}\n\nexport function assertChatModel(model: AnyModel): asserts model is Model<Api> {\n\tif (!isModelType(model, \"chat\")) {\n\t\tthrow new ModelsError(\"provider\", `Model ${model.provider}/${model.id} is not a chat model`);\n\t}\n}\n\nexport function assertImageModel(model: AnyModel): asserts model is ImageModel<ImageApi> {\n\tif (!isModelType(model, \"image\")) {\n\t\tthrow new ModelsError(\"provider\", `Model ${model.provider}/${model.id} is not an image model`);\n\t}\n}\n\nexport function assertClassifierModel(model: AnyModel): asserts model is ClassifierModel<ClassifierApi> {\n\tif (!isModelType(model, \"classifier\")) {\n\t\tthrow new ModelsError(\"provider\", `Model ${model.provider}/${model.id} is not a classifier model`);\n\t}\n}\n\nexport function imageErrorResult(model: ImageModel<ImageApi>, error: unknown, aborted = false): AssistantImages {\n\treturn {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\toutput: [],\n\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nexport function classifierErrorResult(\n\tmodel: ClassifierModel<ClassifierApi>,\n\terror: unknown,\n\taborted = false,\n): ClassifierResult {\n\treturn {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tanswers: {},\n\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n", "import { lazyStream } from \"./api/lazy.ts\";\nimport { defaultProviderAuthContext as defaultAuthContext } from \"./auth/context.ts\";\nimport { InMemoryCredentialStore } from \"./auth/credential-store.ts\";\nimport {\n\ttype AuthResolutionOverrides,\n\tModelsError,\n\trefreshStoredOAuthCredential,\n\tresolveProviderAuth,\n} from \"./auth/resolve.ts\";\nimport type {\n\tAuthCheck,\n\tAuthContext,\n\tAuthInteraction,\n\tAuthOperationOptions,\n\tAuthResult,\n\tAuthType,\n\tCredential,\n\tCredentialStore,\n\tLoginOptions,\n\tProviderAuth,\n} from \"./auth/types.ts\";\nimport { InMemoryModelsStore, type ModelsStore, type ModelsStoreEntry } from \"./models-store.ts\";\nimport type {\n\tAnyModel,\n\tApi,\n\tApiStreamOptions,\n\tAssistantImages,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tClassifierApi,\n\tClassifierContext,\n\tClassifierModel,\n\tClassifierOptions,\n\tClassifierResult,\n\tContext,\n\tDeferredCancelOptions,\n\tDeferredFetchOptions,\n\tDeferredHandle,\n\tImageApi,\n\tImageModel,\n\tImagesContext,\n\tImagesOptions,\n\tModel,\n\tModelCostRates,\n\tModelThinkingLevel,\n\tModelType,\n\tModelTypeMap,\n\tProviderClassifier,\n\tProviderHeaders,\n\tProviderImages,\n\tProviderRequestOptions,\n\tProviderStreams,\n\tSimpleStreamOptions,\n\tTranscriptContext,\n\tUsage,\n} from \"./types.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"./utils/abort.ts\";\nimport {\n\tassertChatModel,\n\tassertClassifierModel,\n\tassertImageModel,\n\tclassifierErrorResult,\n\tgetModelType,\n\timageErrorResult,\n\tisModelType,\n} from \"./utils/model-operations.ts\";\nimport { normalizeContext } from \"./utils/transcript.ts\";\n\nexport { ModelsError, type ModelsErrorCode } from \"./auth/resolve.ts\";\nexport { getModelType, isModelType } from \"./utils/model-operations.ts\";\n\nexport interface ModelsPublication {\n\t/** Provider-selected persisted catalog. Omit to leave storage unchanged; null deletes it. */\n\tpersist?: ModelsStoreEntry | null;\n\t/** Optional synchronous update of provider-private in-memory catalog state. */\n\tupdate?: () => void;\n}\n\nexport interface RefreshModelsContext {\n\t/** Effective configured credential. OAuth credentials are refreshed before network access. */\n\tcredential?: Credential;\n\t/** Immutable provider-scoped catalog snapshot captured before this refresh phase. */\n\tstored?: Readonly<ModelsStoreEntry>;\n\t/**\n\t * Generation-checked publication. Persistence policy remains provider-owned;\n\t * the update runs synchronously only after the selected persistence mutation.\n\t */\n\tpublish(publication: ModelsPublication): Promise<boolean>;\n\t/** False during offline/cache-only initialization. */\n\tallowNetwork: boolean;\n\t/** Bypass provider freshness checks and fetch immediately when network access is allowed. */\n\tforce?: boolean;\n\t/** Always present, including when the public refresh caller omits its optional signal. */\n\tsignal: AbortSignal;\n}\n\nexport interface ModelsRefreshOptions {\n\tallowNetwork?: boolean;\n\t/** Restrict refresh to these provider IDs. Unknown and static providers are ignored. */\n\tproviders?: readonly string[];\n\t/** Bypass provider freshness checks and fetch immediately when network access is allowed. */\n\tforce?: boolean;\n\tsignal?: AbortSignal;\n}\n\nexport interface ModelsRefreshResult {\n\taborted: boolean;\n\terrors: ReadonlyMap<string, Error>;\n}\n\nexport interface ModelsRequestTransforms {\n\t/** Transform fully assembled model/auth/request headers before provider dispatch. */\n\ttransformHeaders?: (headers: ProviderHeaders) => ProviderHeaders | Promise<ProviderHeaders>;\n}\n\nexport type ModelsApiStreamOptions<TApi extends Api> = ApiStreamOptions<TApi> & ModelsRequestTransforms;\nexport type ModelsSimpleStreamOptions = SimpleStreamOptions & ModelsRequestTransforms;\nexport type ModelsDeferredFetchOptions = DeferredFetchOptions & ModelsRequestTransforms;\nexport type ModelsDeferredCancelOptions = DeferredCancelOptions & ModelsRequestTransforms;\nexport type ModelsImagesOptions = ImagesOptions & ModelsRequestTransforms;\nexport type ModelsClassifierOptions = ClassifierOptions & ModelsRequestTransforms;\n\nconst KNOWN_MODEL_TYPES: Record<ModelType, true> = { chat: true, image: true, classifier: true };\n\n/** Models from stores and remote sources may have types that only newer versions know. */\nfunction hasKnownModelType(model: AnyModel): boolean {\n\treturn Object.hasOwn(KNOWN_MODEL_TYPES, getModelType(model));\n}\n\n/** Drops stored models whose type this version does not know. */\nfunction withKnownModelTypes(entry: ModelsStoreEntry): ModelsStoreEntry {\n\treturn { ...entry, models: entry.models.filter(hasKnownModelType) };\n}\n\n/** Any model a provider with chat APIs `TApi` can list. */\ntype ProviderModel<TApi extends Api> = Model<TApi> | ImageModel<ImageApi> | ClassifierModel<ClassifierApi>;\n\n/**\n * A provider is the concrete runtime unit. It owns id/name/base metadata,\n * auth methods, model listing, and the operations its models support\n * (streaming, image generation, classification).\n *\n * `TApi` lets concrete provider factories declare which chat APIs their models\n * use (e.g. `openaiProvider(): Provider<\"openai-responses\" | \"openai-completions\">`),\n * giving typed chat model lists to direct factory users. Other model types use\n * their operation-specific API unions. Inside a `Models` collection providers\n * are held as `Provider<Api>`.\n */\nexport interface Provider<TApi extends Api = Api> {\n\treadonly id: string;\n\treadonly name: string;\n\n\treadonly baseUrl?: string;\n\treadonly headers?: ProviderHeaders;\n\n\t/**\n\t * Required: at least one of `apiKey`/`oauth`. Every provider has auth\n\t * semantics — even providers with only ambient credentials (env vars, AWS\n\t * profiles, ADC files) and keyless local servers provide `apiKey` auth\n\t * whose `resolve()` reports whether the provider is configured.\n\t * `Models.getAuth()` returns undefined when the provider is unconfigured.\n\t */\n\treadonly auth: ProviderAuth;\n\n\t/**\n\t * Current known chat models, sync. Static providers return their catalog;\n\t * dynamic providers return the list as of the last `refreshModels()` (empty\n\t * before the first). Must not throw; `Models` treats a throwing\n\t * implementation as having no models.\n\t */\n\tgetModels(): readonly Model<TApi>[];\n\n\t/**\n\t * Current known models of every type, sync, with the same contract as\n\t * `getModels()`. Providers with only chat models may omit it; `Models` then\n\t * uses `getModels()`. Model ids are unique within each type; one upstream\n\t * model may have separate entries for different operations.\n\t */\n\tgetAllModels?(): readonly ProviderModel<TApi>[];\n\n\t/**\n\t * Dynamic providers only: restore `context.stored` and optionally fetch a newer list using\n\t * the effective credential. Implementations retain their previous list on failure, publish\n\t * persistence and synchronous state changes through `context.publish()`, and honor the\n\t * shared abort signal for blocking work.\n\t */\n\trefreshModels?(context: RefreshModelsContext): Promise<void>;\n\n\t/**\n\t * Optional provider policy for credential-specific model availability.\n\t * `getModels()` remains the complete synchronous chat catalog; `Models.getAvailable()`\n\t * applies this filter after confirming that provider auth is configured.\n\t */\n\tfilterModels?(models: readonly Model<TApi>[], credential: Credential | undefined): readonly Model<TApi>[];\n\n\t/**\n\t * Optional credential-specific availability policy across every model type.\n\t * Without it, `Models.getAllAvailable()` applies `filterModels` to chat models\n\t * and keeps every other model.\n\t */\n\tfilterAllModels?(\n\t\tmodels: readonly ProviderModel<TApi>[],\n\t\tcredential: Credential | undefined,\n\t): readonly ProviderModel<TApi>[];\n\n\t/** Stream a normalized transcript. `Models` normalizes the caller's `Context` before dispatching here. */\n\tstream<T extends TApi>(\n\t\tmodel: Model<T>,\n\t\tcontext: TranscriptContext,\n\t\toptions?: ApiStreamOptions<T>,\n\t): AssistantMessageEventStream;\n\n\tstreamSimple(\n\t\tmodel: Model<TApi>,\n\t\tcontext: TranscriptContext,\n\t\toptions?: SimpleStreamOptions,\n\t): AssistantMessageEventStream;\n\tfetchDeferred?(\n\t\tmodel: Model<TApi>,\n\t\thandle: DeferredHandle,\n\t\toptions?: DeferredFetchOptions,\n\t): AssistantMessageEventStream;\n\tcancelDeferred?(model: Model<TApi>, handle: DeferredHandle, options?: DeferredCancelOptions): Promise<void>;\n\n\t/** Present when the provider supports dedicated image models. Never rejects. */\n\tgenerateImages?(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ImagesOptions,\n\t): Promise<AssistantImages>;\n\n\t/** Present when the provider supports structured classifier models. Never rejects. */\n\tclassify?(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ClassifierOptions,\n\t): Promise<ClassifierResult>;\n}\n\n/**\n * Runtime collection of providers plus auth application and request\n * convenience. Providers own request behavior; `Models` resolves auth and\n * delegates each request to the provider that owns the model.\n *\n * Read accessors come in three flavors: the unqualified ones (`getModels`,\n * `getModel`, `getAvailable`) return chat models, the `*OfType` accessors\n * return one model type, and `getAllModels`/`getAllAvailable` return every type.\n */\nexport interface Models {\n\tgetProviders(): readonly Provider[];\n\tgetProvider(id: string): Provider | undefined;\n\n\t/**\n\t * Sync read of last-known chat models from one provider or all providers.\n\t * Best-effort: a provider whose `getModels()` throws yields no models.\n\t */\n\tgetModels(provider?: string): readonly Model<Api>[];\n\n\t/**\n\t * Sync runtime chat model lookup against last-known lists. Dynamic model lists\n\t * are typed as `Model<Api>`; narrow with the `hasApi()` type guard.\n\t */\n\tgetModel(provider: string, id: string): Model<Api> | undefined;\n\n\t/** Sync read of last-known models of one type from one provider or all providers. */\n\tgetModelsOfType<TType extends ModelType>(type: TType, provider?: string): readonly ModelTypeMap[TType][];\n\n\t/** Sync runtime lookup of a model of one type against last-known lists. */\n\tgetModelOfType<TType extends ModelType>(type: TType, provider: string, id: string): ModelTypeMap[TType] | undefined;\n\n\t/** Sync read of last-known models of every type from one provider or all providers. */\n\tgetAllModels(provider?: string): readonly AnyModel[];\n\n\t/**\n\t * Refresh selected configured dynamic providers concurrently (all when `providers` is omitted).\n\t * Provider errors and cancellation are returned without rejecting; static, unknown, and\n\t * unconfigured providers are skipped.\n\t */\n\trefresh(options?: ModelsRefreshOptions): Promise<ModelsRefreshResult>;\n\n\t/** Check whether a provider has complete auth configuration without refreshing OAuth. */\n\tcheckAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined>;\n\n\t/** Return chat models whose providers have complete auth configuration. */\n\tgetAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]>;\n\n\t/** Return models of one type whose providers have complete auth configuration. */\n\tgetAvailableOfType<TType extends ModelType>(\n\t\ttype: TType,\n\t\tproviderId?: string,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<readonly ModelTypeMap[TType][]>;\n\n\t/** Return models of every type whose providers have complete auth configuration. */\n\tgetAllAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly AnyModel[]>;\n\n\t/**\n\t * Resolve provider-scoped auth by provider id, or provider auth plus static\n\t * model headers when passed a model. Includes a source label for status UI.\n\t * Resolves `undefined` when the provider is unknown or unconfigured.\n\t * Rejects with `ModelsError`: code \"oauth\" when a token refresh fails (the\n\t * stored credential is preserved for retry; re-login fixes it), code \"auth\"\n\t * when api-key resolution or the credential store fails. Request paths\n\t * surface rejections as stream errors.\n\t */\n\tgetAuth(providerId: string, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: AnyModel, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\n\t/** Run a provider-owned login flow and persist its returned credential. */\n\tlogin(providerId: string, type: AuthType, interaction: AuthInteraction, options?: LoginOptions): Promise<Credential>;\n\n\t/** Remove the stored credential for a provider. */\n\tlogout(providerId: string, options?: AuthOperationOptions): Promise<void>;\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream;\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage>;\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream;\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage>;\n\tstreamDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): AssistantMessageEventStream;\n\tfetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage>;\n\tcancelDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredCancelOptions): Promise<void>;\n\n\t/**\n\t * Generate images through the owning provider with auth resolved like\n\t * `stream()`. Never rejects: unknown providers, unconfigured auth, and\n\t * providers without `generateImages` return an error `AssistantImages`.\n\t */\n\tgenerateImages(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ModelsImagesOptions,\n\t): Promise<AssistantImages>;\n\n\t/** Classify structured state through the owning provider. Never rejects. */\n\tclassify(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ModelsClassifierOptions,\n\t): Promise<ClassifierResult>;\n}\n\nexport interface MutableModels extends Models {\n\t/** Upsert/replace by provider.id. Provider ids are unique. */\n\tsetProvider(provider: Provider): void;\n\tdeleteProvider(id: string): void;\n\tclearProviders(): void;\n}\n\nexport interface CreateModelsOptions {\n\tcredentials?: CredentialStore;\n\tmodelsStore?: ModelsStore;\n\tauthContext?: AuthContext;\n}\n\nfunction mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\nclass ModelsImpl implements MutableModels {\n\tprivate providers = new Map<string, Provider>();\n\tprivate credentials: CredentialStore;\n\tprivate modelsStore: ModelsStore;\n\tprivate authContext: AuthContext;\n\tprivate refreshGenerations = new Map<string, number>();\n\tprivate refreshControllers = new Map<string, AbortController>();\n\tprivate publicationChains = new Map<string, Promise<unknown>>();\n\n\tconstructor(options?: CreateModelsOptions) {\n\t\tthis.credentials = options?.credentials ?? new InMemoryCredentialStore();\n\t\tthis.modelsStore = options?.modelsStore ?? new InMemoryModelsStore();\n\t\tthis.authContext = options?.authContext ?? defaultAuthContext();\n\t}\n\n\tsetProvider(provider: Provider): void {\n\t\tthis.supersedeProviderRefresh(provider.id);\n\t\tthis.providers.set(provider.id, provider);\n\t}\n\n\tdeleteProvider(id: string): void {\n\t\tthis.supersedeProviderRefresh(id);\n\t\tthis.providers.delete(id);\n\t}\n\n\tclearProviders(): void {\n\t\tfor (const id of new Set([...this.providers.keys(), ...this.refreshControllers.keys()])) {\n\t\t\tthis.supersedeProviderRefresh(id);\n\t\t}\n\t\tthis.providers.clear();\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn Array.from(this.providers.values());\n\t}\n\n\tgetProvider(id: string): Provider | undefined {\n\t\treturn this.providers.get(id);\n\t}\n\n\tgetModels(provider?: string): readonly Model<Api>[] {\n\t\tif (provider !== undefined) {\n\t\t\tconst entry = this.providers.get(provider);\n\t\t\tif (!entry) return [];\n\t\t\ttry {\n\t\t\t\treturn entry.getModels();\n\t\t\t} catch {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t}\n\n\t\tconst models: Model<Api>[] = [];\n\t\tfor (const entry of this.providers.values()) {\n\t\t\ttry {\n\t\t\t\tmodels.push(...entry.getModels());\n\t\t\t} catch {\n\t\t\t\t// Best-effort: ill-behaved providers yield no models.\n\t\t\t}\n\t\t}\n\t\treturn models;\n\t}\n\n\tgetAllModels(provider?: string): readonly AnyModel[] {\n\t\tif (provider !== undefined) {\n\t\t\tconst entry = this.providers.get(provider);\n\t\t\tif (!entry) return [];\n\t\t\ttry {\n\t\t\t\treturn entry.getAllModels?.() ?? entry.getModels();\n\t\t\t} catch {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t}\n\n\t\tconst models: AnyModel[] = [];\n\t\tfor (const entry of this.providers.values()) {\n\t\t\ttry {\n\t\t\t\tmodels.push(...(entry.getAllModels?.() ?? entry.getModels()));\n\t\t\t} catch {\n\t\t\t\t// Best-effort: ill-behaved providers yield no models.\n\t\t\t}\n\t\t}\n\t\treturn models;\n\t}\n\n\tgetModelsOfType<TType extends ModelType>(type: TType, provider?: string): readonly ModelTypeMap[TType][] {\n\t\treturn this.getAllModels(provider).filter((model): model is ModelTypeMap[TType] => isModelType(model, type));\n\t}\n\n\tgetModel(provider: string, id: string): Model<Api> | undefined {\n\t\treturn this.getModels(provider).find((model) => model.id === id);\n\t}\n\n\tgetModelOfType<TType extends ModelType>(type: TType, provider: string, id: string): ModelTypeMap[TType] | undefined {\n\t\treturn this.getModelsOfType(type, provider).find((model) => model.id === id);\n\t}\n\n\tprivate supersedeProviderRefresh(providerId: string): number {\n\t\tconst generation = (this.refreshGenerations.get(providerId) ?? 0) + 1;\n\t\tthis.refreshGenerations.set(providerId, generation);\n\t\tconst previous = this.refreshControllers.get(providerId);\n\t\tif (previous) {\n\t\t\tthis.refreshControllers.delete(providerId);\n\t\t\tprevious.abort();\n\t\t}\n\t\treturn generation;\n\t}\n\n\tprivate beginProviderRefresh(providerId: string): { generation: number; controller: AbortController } {\n\t\tconst generation = this.supersedeProviderRefresh(providerId);\n\t\tconst controller = new AbortController();\n\t\tthis.refreshControllers.set(providerId, controller);\n\t\treturn { generation, controller };\n\t}\n\n\tprivate publishProviderModels(\n\t\tproviderId: string,\n\t\tgeneration: number,\n\t\tsignal: AbortSignal,\n\t\tpublication: ModelsPublication,\n\t): Promise<boolean> {\n\t\tconst previous = this.publicationChains.get(providerId) ?? Promise.resolve();\n\t\tconst queued = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tif (signal.aborted || this.refreshGenerations.get(providerId) !== generation) return false;\n\n\t\t\tif (publication.persist === null) {\n\t\t\t\tawait this.modelsStore.delete(providerId, { signal });\n\t\t\t} else if (publication.persist !== undefined) {\n\t\t\t\tawait this.modelsStore.write(providerId, structuredClone(publication.persist), { signal });\n\t\t\t}\n\n\t\t\tif (signal.aborted || this.refreshGenerations.get(providerId) !== generation) return false;\n\t\t\tpublication.update?.();\n\t\t\treturn true;\n\t\t})();\n\t\tconst tail = queued.catch(() => {});\n\t\tthis.publicationChains.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.publicationChains.get(providerId) === tail) this.publicationChains.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(queued, signal);\n\t}\n\n\tprivate async runProviderRefreshPhase(\n\t\tprovider: Provider & Required<Pick<Provider, \"refreshModels\">>,\n\t\tcredential: Credential | undefined,\n\t\tallowNetwork: boolean,\n\t\tforce: boolean | undefined,\n\t\tgeneration: number,\n\t\tsignal: AbortSignal,\n\t): Promise<void> {\n\t\tconst stored = await this.modelsStore.read(provider.id, { signal });\n\t\tawait provider.refreshModels({\n\t\t\tcredential,\n\t\t\tstored: stored ? withKnownModelTypes(structuredClone(stored)) : undefined,\n\t\t\tpublish: (publication) => this.publishProviderModels(provider.id, generation, signal, publication),\n\t\t\tallowNetwork,\n\t\t\tforce: allowNetwork ? force : undefined,\n\t\t\tsignal,\n\t\t});\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tconst allowNetwork = options.allowNetwork ?? true;\n\t\tconst callerSignal = operationSignal(options.signal);\n\t\tconst errors = new Map<string, Error>();\n\t\tif (callerSignal.aborted) return { aborted: true, errors };\n\t\tconst selected = options.providers ? new Set(options.providers) : undefined;\n\t\tconst refreshable = Array.from(this.providers.values()).filter(\n\t\t\t(provider): provider is Provider & Required<Pick<Provider, \"refreshModels\">> =>\n\t\t\t\tprovider.refreshModels !== undefined && (!selected || selected.has(provider.id)),\n\t\t);\n\n\t\tconst refresh = Promise.all(\n\t\t\trefreshable.map(async (provider) => {\n\t\t\t\tconst { generation, controller } = this.beginProviderRefresh(provider.id);\n\t\t\t\tconst signal = AbortSignal.any([callerSignal, controller.signal]);\n\t\t\t\tconst operation = (async () => {\n\t\t\t\t\tlet storedCredential: Credential | undefined;\n\t\t\t\t\tlet credentialError: unknown;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tstoredCredential = await this.readCredential(provider.id, signal);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tcredentialError = error;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Restore cached provider state before auth resolution or network access.\n\t\t\t\t\tawait this.runProviderRefreshPhase(provider, storedCredential, false, undefined, generation, signal);\n\t\t\t\t\tif (credentialError !== undefined) throw credentialError;\n\t\t\t\t\tif (!allowNetwork || signal.aborted) return;\n\n\t\t\t\t\tconst credential = await this.resolveRefreshCredential(provider, storedCredential, signal);\n\t\t\t\t\tif (!credential) return;\n\t\t\t\t\tawait this.runProviderRefreshPhase(provider, credential, true, options.force, generation, signal);\n\t\t\t\t})();\n\n\t\t\t\ttry {\n\t\t\t\t\tawait raceWithAbortSignal(operation, signal);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!signal.aborted) {\n\t\t\t\t\t\terrors.set(\n\t\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t? error\n\t\t\t\t\t\t\t\t: new ModelsError(\"model_source\", `Model refresh failed for ${provider.id}`, { cause: error }),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (this.refreshControllers.get(provider.id) === controller) {\n\t\t\t\t\t\tthis.refreshControllers.delete(provider.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\n\t\ttry {\n\t\t\tawait raceWithAbortSignal(refresh, callerSignal);\n\t\t} catch (error) {\n\t\t\tif (!callerSignal.aborted) throw error;\n\t\t}\n\n\t\treturn { aborted: callerSignal.aborted, errors: new Map(errors) };\n\t}\n\n\tprivate async resolveRefreshCredential(\n\t\tprovider: Provider,\n\t\tstored: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<Credential | undefined> {\n\t\tif (stored?.type === \"oauth\") {\n\t\t\tconst oauth = provider.auth.oauth;\n\t\t\tif (!oauth) return undefined;\n\t\t\tif (Date.now() < stored.expires) return stored;\n\t\t\tif (signal.aborted) return undefined;\n\t\t\t// A refresh that has started survives cancellation or a superseding model refresh, so a\n\t\t\t// rotated refresh token is always persisted. A newer refresh then sees the fresh credential.\n\t\t\treturn refreshStoredOAuthCredential(\n\t\t\t\tthis.credentials,\n\t\t\t\tprovider.id,\n\t\t\t\toauth,\n\t\t\t\t(current) => Date.now() >= current.expires,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\n\t\tconst apiKey = provider.auth.apiKey;\n\t\tif (!apiKey) return undefined;\n\t\tconst credential = stored?.type === \"api_key\" ? stored : undefined;\n\t\tconst result = await apiKey.resolve({ ctx: this.authContext, credential, signal });\n\t\tif (!result) return undefined;\n\t\treturn { type: \"api_key\", key: result.auth.apiKey, env: result.env };\n\t}\n\n\tprivate async readCredential(providerId: string, signal: AbortSignal): Promise<Credential | undefined> {\n\t\ttry {\n\t\t\treturn await this.credentials.read(providerId, { signal });\n\t\t} catch (error) {\n\t\t\tthrow new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n\t\t}\n\t}\n\n\tprivate async checkProviderAuth(\n\t\tprovider: Provider,\n\t\tcredential: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<AuthCheck | undefined> {\n\t\tif (credential?.type === \"oauth\") {\n\t\t\treturn provider.auth.oauth ? { source: \"OAuth\", type: \"oauth\" } : undefined;\n\t\t}\n\t\tconst apiKey = provider.auth.apiKey;\n\t\tif (!apiKey) return undefined;\n\t\tif (apiKey.check) {\n\t\t\ttry {\n\t\t\t\treturn await apiKey.check({\n\t\t\t\t\tctx: this.authContext,\n\t\t\t\t\tcredential: credential?.type === \"api_key\" ? credential : undefined,\n\t\t\t\t\tsignal,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new ModelsError(\"auth\", `API key auth check failed for provider ${provider.id}`, { cause: error });\n\t\t\t}\n\t\t}\n\n\t\tconst resolution = await resolveProviderAuth(provider, this.credentials, this.authContext, { signal });\n\t\treturn resolution ? { source: resolution.source, type: \"api_key\" } : undefined;\n\t}\n\n\tcheckAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tconst check = (async () => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst provider = this.providers.get(providerId);\n\t\t\tif (!provider) return undefined;\n\t\t\treturn this.checkProviderAuth(provider, await this.readCredential(providerId, signal), signal);\n\t\t})();\n\t\treturn raceWithAbortSignal(check, signal);\n\t}\n\n\tprivate async getAuthenticatedProviders(providerId: string | undefined, signal: AbortSignal) {\n\t\tsignal.throwIfAborted();\n\t\tconst providers = providerId\n\t\t\t? [this.providers.get(providerId)].filter((entry) => entry !== undefined)\n\t\t\t: this.getProviders();\n\t\tconst checks = await Promise.all(\n\t\t\tproviders.map(async (provider) => {\n\t\t\t\tconst credential = await this.readCredential(provider.id, signal);\n\t\t\t\treturn { provider, credential, auth: await this.checkProviderAuth(provider, credential, signal) };\n\t\t\t}),\n\t\t);\n\t\treturn checks.filter((entry) => entry.auth !== undefined);\n\t}\n\n\tgetAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tconst available = (async () => {\n\t\t\tconst providers = await this.getAuthenticatedProviders(providerId, signal);\n\t\t\treturn providers.flatMap(({ provider, credential }) => {\n\t\t\t\tconst models = provider.getModels();\n\t\t\t\treturn provider.filterModels?.(models, credential) ?? models;\n\t\t\t});\n\t\t})();\n\t\treturn raceWithAbortSignal(available, signal);\n\t}\n\n\tasync getAvailableOfType<TType extends ModelType>(\n\t\ttype: TType,\n\t\tproviderId?: string,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<readonly ModelTypeMap[TType][]> {\n\t\treturn (await this.getAllAvailable(providerId, options)).filter((model): model is ModelTypeMap[TType] =>\n\t\t\tisModelType(model, type),\n\t\t);\n\t}\n\n\tgetAllAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly AnyModel[]> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tconst available = (async () => {\n\t\t\tconst providers = await this.getAuthenticatedProviders(providerId, signal);\n\t\t\treturn providers.flatMap(({ provider, credential }) => {\n\t\t\t\tconst models = provider.getAllModels?.() ?? provider.getModels();\n\t\t\t\tif (provider.filterAllModels) return provider.filterAllModels(models, credential);\n\t\t\t\tif (!provider.filterModels) return models;\n\t\t\t\tconst availableChatIds = new Set(\n\t\t\t\t\tprovider.filterModels(provider.getModels(), credential).map((model) => model.id),\n\t\t\t\t);\n\t\t\t\treturn models.filter((model) => !isModelType(model, \"chat\") || availableChatIds.has(model.id));\n\t\t\t});\n\t\t})();\n\t\treturn raceWithAbortSignal(available, signal);\n\t}\n\n\tgetAuth(providerId: string, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: AnyModel, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | AnyModel,\n\t\toverrides?: AuthResolutionOverrides,\n\t): Promise<AuthResult | undefined> {\n\t\tconst signal = operationSignal(overrides?.signal);\n\t\tconst providerId = typeof providerOrModel === \"string\" ? providerOrModel : providerOrModel.provider;\n\t\tconst provider = this.providers.get(providerId);\n\t\tif (!provider) return undefined;\n\t\tconst result = await resolveProviderAuth(provider, this.credentials, this.authContext, { ...overrides, signal });\n\t\tif (!result || typeof providerOrModel === \"string\" || !providerOrModel.headers) return result;\n\t\treturn {\n\t\t\t...result,\n\t\t\tauth: {\n\t\t\t\t...result.auth,\n\t\t\t\theaders: mergeHeaders(result.auth.headers, providerOrModel.headers),\n\t\t\t},\n\t\t};\n\t}\n\n\tasync login(\n\t\tproviderId: string,\n\t\ttype: AuthType,\n\t\tinteraction: AuthInteraction,\n\t\toptions?: LoginOptions,\n\t): Promise<Credential> {\n\t\tconst signal = operationSignal(interaction.signal);\n\t\tsignal.throwIfAborted();\n\t\tconst provider = this.providers.get(providerId);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${providerId}`);\n\t\tconst method = type === \"oauth\" ? provider.auth.oauth : provider.auth.apiKey;\n\t\tif (!method?.login) {\n\t\t\tthrow new ModelsError(\"auth\", `${provider.name} does not support ${type} login`);\n\t\t}\n\t\tconst loginOperation: Promise<Credential> = method.login({ ...interaction, signal }, options);\n\t\tconst credential = await raceWithAbortSignal(loginOperation, signal);\n\t\tlet mutationStarted = false;\n\t\tlet markMutationStarted: (() => void) | undefined;\n\t\tconst started = new Promise<void>((resolve) => {\n\t\t\tmarkMutationStarted = resolve;\n\t\t});\n\t\tconst mutation = this.credentials.modify(\n\t\t\tproviderId,\n\t\t\tasync () => {\n\t\t\t\tmutationStarted = true;\n\t\t\t\tmarkMutationStarted?.();\n\t\t\t\treturn credential;\n\t\t\t},\n\t\t\t{ signal },\n\t\t);\n\t\tvoid mutation.catch(() => {});\n\t\ttry {\n\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\tconst onAbort = () => {\n\t\t\t\t\tif (!mutationStarted) reject(signal.reason);\n\t\t\t\t};\n\t\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\tvoid Promise.race([started, mutation]).then(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t});\n\t\t\tawait mutation;\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n\t\t}\n\t\treturn credential;\n\t}\n\n\tasync logout(providerId: string, options?: AuthOperationOptions): Promise<void> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tsignal.throwIfAborted();\n\t\ttry {\n\t\t\tawait this.credentials.delete(providerId, { signal });\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow new ModelsError(\"auth\", `Credential store delete failed for ${providerId}`, { cause: error });\n\t\t}\n\t}\n\n\tprivate requireProvider(model: AnyModel): Provider {\n\t\tconst provider = this.providers.get(model.provider);\n\t\tif (!provider) {\n\t\t\tthrow new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\t}\n\t\treturn provider;\n\t}\n\n\tprivate requireChatProvider(model: Model<Api>): Provider {\n\t\tassertChatModel(model);\n\t\treturn this.requireProvider(model);\n\t}\n\n\tprivate async applyAuth<\n\t\tTModel extends AnyModel,\n\t\tTOptions extends ProviderRequestOptions<TModel> & ModelsRequestTransforms,\n\t>(\n\t\tmodel: TModel,\n\t\toptions: TOptions | undefined,\n\t): Promise<{\n\t\trequestModel: TModel;\n\t\trequestOptions: Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions<TModel>;\n\t}> {\n\t\tthis.requireProvider(model);\n\t\tconst resolution = await this.getAuth(model, {\n\t\t\tapiKey: options?.apiKey,\n\t\t\tenv: options?.env,\n\t\t\tsignal: options?.signal,\n\t\t});\n\t\tif (!resolution) {\n\t\t\tthrow new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\t\t}\n\t\tconst auth = resolution.auth;\n\n\t\t// Explicit request options win per-field; the Models-only transform runs last.\n\t\tconst apiKey = options?.apiKey ?? auth.apiKey;\n\t\tlet headers = mergeHeaders(auth.headers, options?.headers);\n\t\tif (options?.transformHeaders) headers = await options.transformHeaders(headers ?? {});\n\t\tconst env = resolution.env || options?.env ? { ...(resolution.env ?? {}), ...(options?.env ?? {}) } : undefined;\n\t\tconst requestModel: TModel = auth.baseUrl ? { ...model, baseUrl: auth.baseUrl } : model;\n\t\tconst { transformHeaders: _transformHeaders, ...providerOptions } = options ?? {};\n\t\tconst requestOptions = { ...providerOptions, apiKey, headers, env } as Omit<TOptions, \"transformHeaders\"> &\n\t\t\tProviderRequestOptions<TModel>;\n\n\t\treturn { requestModel, requestOptions };\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst provider = this.requireChatProvider(model);\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(\n\t\t\t\tmodel,\n\t\t\t\toptions as ModelsApiStreamOptions<Api> | undefined,\n\t\t\t);\n\t\t\treturn provider.stream(requestModel, transcript, requestOptions as ApiStreamOptions<TApi>);\n\t\t});\n\t}\n\n\tasync complete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst provider = this.requireChatProvider(model);\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\t\treturn provider.streamSimple(requestModel, transcript, requestOptions as SimpleStreamOptions);\n\t\t});\n\t}\n\n\tasync completeSimple(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions?: ModelsSimpleStreamOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tstreamDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst provider = this.requireChatProvider(model);\n\t\t\tif (!provider.fetchDeferred) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t\t}\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\t\treturn provider.fetchDeferred(requestModel, handle, requestOptions as DeferredFetchOptions);\n\t\t});\n\t}\n\n\tasync fetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn this.streamDeferred(model, handle, options).result();\n\t}\n\n\tasync cancelDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredCancelOptions,\n\t): Promise<void> {\n\t\tconst provider = this.requireChatProvider(model);\n\t\tif (!provider.cancelDeferred) {\n\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t}\n\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\tawait provider.cancelDeferred(requestModel, handle, requestOptions);\n\t}\n\n\tasync generateImages(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ModelsImagesOptions,\n\t): Promise<AssistantImages> {\n\t\ttry {\n\t\t\tassertImageModel(model);\n\t\t\tconst provider = this.requireProvider(model);\n\t\t\tif (!provider.generateImages) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support image generation`);\n\t\t\t}\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\t\treturn await provider.generateImages(requestModel, context, requestOptions);\n\t\t} catch (error) {\n\t\t\treturn imageErrorResult(model, error, options?.signal?.aborted);\n\t\t}\n\t}\n\n\tasync classify(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ModelsClassifierOptions,\n\t): Promise<ClassifierResult> {\n\t\ttry {\n\t\t\tassertClassifierModel(model);\n\t\t\tconst provider = this.requireProvider(model);\n\t\t\tif (!provider.classify) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support classification`);\n\t\t\t}\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\t\treturn await provider.classify(requestModel, context, requestOptions);\n\t\t} catch (error) {\n\t\t\treturn classifierErrorResult(model, error, options?.signal?.aborted);\n\t\t}\n\t}\n}\n\nexport function createModels(options?: CreateModelsOptions): MutableModels {\n\treturn new ModelsImpl(options);\n}\n\nexport interface CreateProviderOptions<TApi extends Api = Api> {\n\tid: string;\n\t/** Display name. Default: `id`. */\n\tname?: string;\n\tbaseUrl?: string;\n\theaders?: ProviderHeaders;\n\t/** Required — every provider has auth semantics, even ambient/keyless ones. */\n\tauth: ProviderAuth;\n\t/**\n\t * Static baseline models of every type (empty for purely dynamic providers).\n\t * Models without `type` are chat models.\n\t */\n\tmodels: readonly ProviderModel<TApi>[];\n\t/**\n\t * Fetch a dynamic model overlay of every type. createProvider restores and\n\t * publishes it transactionally and drops models of unknown types.\n\t */\n\tfetchModels?: (context: RefreshModelsContext) => Promise<readonly ProviderModel<TApi>[]>;\n\t/** Credential-specific chat model availability. See `Provider.filterModels`. */\n\tfilterModels?: (models: readonly Model<TApi>[], credential: Credential | undefined) => readonly Model<TApi>[];\n\t/** Credential-specific availability across every model type. See `Provider.filterAllModels`. */\n\tfilterAllModels?: (\n\t\tmodels: readonly ProviderModel<TApi>[],\n\t\tcredential: Credential | undefined,\n\t) => readonly ProviderModel<TApi>[];\n\t/**\n\t * Chat implementation: a single one for all chat models, or a map keyed by\n\t * `model.api` for mixed-API providers. Optional when `images` or\n\t * `classifiers` is given.\n\t */\n\tapi?: ProviderStreams | Partial<Record<TApi, ProviderStreams>>;\n\t/** Image-generation implementations keyed by `model.api`. */\n\timages?: Partial<Record<ImageApi, ProviderImages>>;\n\t/** Classifier implementations keyed by `model.api`. */\n\tclassifiers?: Partial<Record<ClassifierApi, ProviderClassifier>>;\n}\n\n/**\n * Builds a provider from parts. Built-in provider factories and models.json\n * custom providers both go through this. A single `api` streams all chat\n * models; an `api` map dispatches on `model.api`, and a model whose api has\n * no entry produces a stream error. One-shot operation maps dispatch on\n * `model.api` the same way. At least one concrete implementation across\n * `api`/`images`/`classifiers` is required; empty maps are rejected.\n */\nexport function createProvider<TApi extends Api = Api>(input: CreateProviderOptions<TApi>): Provider<TApi> {\n\tconst single =\n\t\tinput.api && typeof (input.api as ProviderStreams).stream === \"function\"\n\t\t\t? (input.api as ProviderStreams)\n\t\t\t: undefined;\n\tconst byApi = single || !input.api ? undefined : (input.api as Partial<Record<string, ProviderStreams>>);\n\tconst images = input.images as Partial<Record<string, ProviderImages>> | undefined;\n\tconst classifiers = input.classifiers as Partial<Record<string, ProviderClassifier>> | undefined;\n\tconst streams = single ? [single] : Object.values(byApi ?? {}).filter((entry) => entry !== undefined);\n\tconst imageImplementations = Object.values(images ?? {}).filter((entry) => entry !== undefined);\n\tconst classifierImplementations = Object.values(classifiers ?? {}).filter((entry) => entry !== undefined);\n\tif (streams.length === 0 && imageImplementations.length === 0 && classifierImplementations.length === 0) {\n\t\tthrow new Error(`Provider ${input.id}: at least one of \"api\", \"images\", or \"classifiers\" is required.`);\n\t}\n\n\tconst baselineModels = input.models;\n\tlet dynamicModels: readonly ProviderModel<TApi>[] = [];\n\tconst fetchModels = input.fetchModels;\n\tconst currentModels = (): readonly ProviderModel<TApi>[] => {\n\t\tconst merged = [...baselineModels];\n\t\tfor (const model of dynamicModels) {\n\t\t\tconst index = merged.findIndex(\n\t\t\t\t(entry) => getModelType(entry) === getModelType(model) && entry.id === model.id,\n\t\t\t);\n\t\t\tif (index >= 0) merged[index] = model;\n\t\t\telse merged.push(model);\n\t\t}\n\t\treturn merged;\n\t};\n\tconst apiFor = (model: Model<Api>): ProviderStreams | undefined => single ?? byApi?.[model.api];\n\n\tconst dispatch = (\n\t\tmodel: Model<Api>,\n\t\trun: (streams: ProviderStreams) => AssistantMessageEventStream,\n\t): AssistantMessageEventStream => {\n\t\tconst streams = apiFor(model);\n\t\tif (!streams) {\n\t\t\treturn lazyStream(model, async () => {\n\t\t\t\tthrow new ModelsError(\"stream\", `Provider ${input.id} has no API implementation for \"${model.api}\"`);\n\t\t\t});\n\t\t}\n\t\treturn run(streams);\n\t};\n\n\tconst provider: Provider<TApi> = {\n\t\tid: input.id,\n\t\tname: input.name ?? input.id,\n\t\tbaseUrl: input.baseUrl,\n\t\theaders: input.headers,\n\t\tauth: input.auth,\n\t\tgetModels: () => currentModels().filter((model): model is Model<TApi> => isModelType(model, \"chat\")),\n\t\tgetAllModels: currentModels,\n\t\trefreshModels: fetchModels\n\t\t\t? async (context) => {\n\t\t\t\t\tif (context.stored) {\n\t\t\t\t\t\tconst restored = context.stored.models\n\t\t\t\t\t\t\t.filter((model) => model.provider === input.id)\n\t\t\t\t\t\t\t.map((model) => model as ProviderModel<TApi>);\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!(await context.publish({\n\t\t\t\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\t\t\t\tdynamicModels = restored;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}))\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\t\t\tconst fetched = await fetchModels(context);\n\t\t\t\t\tif (context.signal.aborted) return;\n\t\t\t\t\tconst refreshed = fetched.filter(hasKnownModelType);\n\t\t\t\t\tawait context.publish({\n\t\t\t\t\t\tpersist: { models: refreshed, checkedAt: Date.now() },\n\t\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\t\tdynamicModels = refreshed;\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t: undefined,\n\t\tfilterModels: input.filterModels,\n\t\tfilterAllModels: input.filterAllModels,\n\t\tstream: (model, context, options) => dispatch(model, (streams) => streams.stream(model, context, options)),\n\t\tstreamSimple: (model, context, options) =>\n\t\t\tdispatch(model, (streams) => streams.streamSimple(model, context, options)),\n\t};\n\n\tif (streams.some((entry) => entry.fetchDeferred !== undefined)) {\n\t\tprovider.fetchDeferred = (model, handle, options) =>\n\t\t\tlazyStream(model, async () => {\n\t\t\t\tconst implementation = apiFor(model);\n\t\t\t\tif (!implementation?.fetchDeferred) {\n\t\t\t\t\tthrow new ModelsError(\n\t\t\t\t\t\t\"provider\",\n\t\t\t\t\t\t`Provider ${input.id} does not support deferred responses for \"${model.api}\"`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn implementation.fetchDeferred(model, handle, options);\n\t\t\t});\n\t}\n\tif (streams.some((entry) => entry.cancelDeferred !== undefined)) {\n\t\tprovider.cancelDeferred = async (model, handle, options) => {\n\t\t\tconst implementation = apiFor(model);\n\t\t\tif (!implementation?.cancelDeferred) {\n\t\t\t\tthrow new ModelsError(\n\t\t\t\t\t\"provider\",\n\t\t\t\t\t`Provider ${input.id} cannot cancel deferred responses for \"${model.api}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait implementation.cancelDeferred(model, handle, options);\n\t\t};\n\t}\n\tif (images && imageImplementations.length > 0) {\n\t\tprovider.generateImages = async (model, context, options) => {\n\t\t\tconst implementation = images[model.api];\n\t\t\tif (!implementation) {\n\t\t\t\treturn imageErrorResult(\n\t\t\t\t\tmodel,\n\t\t\t\t\tnew ModelsError(\n\t\t\t\t\t\t\"provider\",\n\t\t\t\t\t\t`Provider ${input.id} has no image generation implementation for \"${model.api}\"`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn implementation.generateImages(model, context, options);\n\t\t};\n\t}\n\tif (classifiers && classifierImplementations.length > 0) {\n\t\tprovider.classify = async (model, context, options) => {\n\t\t\tconst implementation = classifiers[model.api];\n\t\t\tif (!implementation) {\n\t\t\t\treturn classifierErrorResult(\n\t\t\t\t\tmodel,\n\t\t\t\t\tnew ModelsError(\"provider\", `Provider ${input.id} has no classifier implementation for \"${model.api}\"`),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn implementation.classify(model, context, options);\n\t\t};\n\t}\n\n\treturn provider;\n}\n\n/**\n * Runtime-checked narrowing for dynamically looked-up models:\n *\n * ```ts\n * const model = models.getModel(\"anthropic\", \"claude-opus-4-7\");\n * if (model && hasApi(model, \"anthropic-messages\")) {\n * // model: Model<\"anthropic-messages\">, stream options fully typed\n * }\n * ```\n *\n * Non-chat models never match, even when their api id equals `api`.\n */\nexport function hasApi<TApi extends Api>(model: AnyModel, api: TApi): model is Model<TApi> {\n\treturn isModelType(model, \"chat\") && model.api === api;\n}\n\nexport function calculateCost(model: AnyModel, usage: Usage): Usage[\"cost\"] {\n\tconst inputTokens = usage.input + usage.cacheRead + usage.cacheWrite;\n\tlet rates: ModelCostRates = model.cost;\n\tlet matchedThreshold = -1;\n\tfor (const tier of model.cost.tiers ?? []) {\n\t\tif (inputTokens > tier.inputTokensAbove && tier.inputTokensAbove > matchedThreshold) {\n\t\t\trates = tier;\n\t\t\tmatchedThreshold = tier.inputTokensAbove;\n\t\t}\n\t}\n\n\t// Anthropic charges 2x base input for 1h cache writes.\n\tconst longWrite = usage.cacheWrite1h ?? 0;\n\tconst shortWrite = usage.cacheWrite - longWrite;\n\tusage.cost.input = (rates.input / 1000000) * usage.input;\n\tusage.cost.output = (rates.output / 1000000) * usage.output;\n\tusage.cost.cacheRead = (rates.cacheRead / 1000000) * usage.cacheRead;\n\tusage.cost.cacheWrite = (rates.cacheWrite * shortWrite + rates.input * 2 * longWrite) / 1000000;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n\treturn usage.cost;\n}\n\nconst EXTENDED_THINKING_LEVELS: ModelThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\nexport function getSupportedThinkingLevels<TApi extends Api>(model: Model<TApi>): ModelThinkingLevel[] {\n\tif (!model.reasoning) return [\"off\"];\n\n\treturn EXTENDED_THINKING_LEVELS.filter((level) => {\n\t\tconst mapped = model.thinkingLevelMap?.[level];\n\t\tif (mapped === null) return false;\n\t\tif (level === \"xhigh\" || level === \"max\") return mapped !== undefined;\n\t\treturn true;\n\t});\n}\n\nexport function clampThinkingLevel<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tlevel: ModelThinkingLevel,\n): ModelThinkingLevel {\n\tconst availableLevels = getSupportedThinkingLevels(model);\n\tif (availableLevels.includes(level)) return level;\n\n\tconst requestedIndex = EXTENDED_THINKING_LEVELS.indexOf(level);\n\tif (requestedIndex === -1) return availableLevels[0] ?? \"off\";\n\n\tfor (let i = requestedIndex; i < EXTENDED_THINKING_LEVELS.length; i++) {\n\t\tconst candidate = EXTENDED_THINKING_LEVELS[i];\n\t\tif (availableLevels.includes(candidate)) return candidate;\n\t}\n\tfor (let i = requestedIndex - 1; i >= 0; i--) {\n\t\tconst candidate = EXTENDED_THINKING_LEVELS[i];\n\t\tif (availableLevels.includes(candidate)) return candidate;\n\t}\n\treturn availableLevels[0] ?? \"off\";\n}\n\n/**\n * Check if two models are equal by comparing their type, id, and provider.\n * Returns false if either model is null or undefined.\n */\nexport function modelsAreEqual(a: AnyModel | null | undefined, b: AnyModel | null | undefined): boolean {\n\tif (!a || !b) return false;\n\treturn getModelType(a) === getModelType(b) && a.id === b.id && a.provider === b.provider;\n}\n", "/**\n * The pi-ai providers Relay registers: `claude-code` and `codex-cli`, each a model turn delegated to\n * the user's own CLI login through {@link runTurn}. Pi's own providers (including its claude.ai and\n * ChatGPT OAuth flows) are never registered; {@link relayModels} is the only way Relay builds its\n * model registry, and it accepts only these ids.\n *\n * This module is the Promise boundary between Pi's generation task and Effect.\n *\n * @module\n */\nimport {\n type AssistantMessage,\n type AssistantMessageEventStream,\n createAssistantMessageEventStream,\n createModels,\n createProvider,\n type Message,\n type Model,\n type Models,\n type SimpleStreamOptions,\n type TextContent,\n type Tool,\n type ToolCall,\n type TranscriptContext\n} from \"@earendil-works/pi-ai\"\nimport { Predicate, Schema } from \"effect\"\nimport type { RelayBackendId } from \"./model.js\"\nimport type { Turn, TurnLine, TurnRequest, TurnTool } from \"./turn.js\"\n\n/** Runs one turn for the provider; the harness supplies it with its Effect runtime and the CLI layer. */\nexport type TurnRunner = (request: TurnRequest, signal: AbortSignal | undefined) => Promise<{\n readonly turn: Turn\n readonly callIds: ReadonlyArray<string>\n}>\n\nconst API = \"relay-cli-turn\"\nconst decodeJson = Schema.decodeUnknownOption(Schema.Json)\nconst MODEL_ID = \"default\"\n\nconst textOf = (content: string | ReadonlyArray<{ readonly type: string; readonly text?: string }>): string =>\n Predicate.isString(content)\n ? content\n : content.flatMap((block) => (block.type === \"text\" && block.text !== undefined ? [block.text] : [])).join(\"\\n\")\n\n/** Fold Pi's transcript into instructions, the current tool set, and the visible lines. */\nexport const turnRequestOf = (messages: ReadonlyArray<Message>): TurnRequest => {\n const instructions: Array<string> = []\n const tools = new Map<string, TurnTool>()\n const transcript: Array<TurnLine> = []\n for (const message of messages) {\n switch (message.role) {\n case \"system\": {\n const text = textOf(message.content)\n if (text !== \"\") instructions.push(text)\n for (const section of Object.values(message.sections ?? {})) if (section !== null) instructions.push(section)\n for (const tool of message.toolsAdded ?? []) {\n // Pi's TypeBox schema is plain JSON Schema at runtime; parse it rather than trust the type.\n const parameters = decodeJson(tool.parameters)\n if (parameters._tag === \"Some\") {\n tools.set(tool.name, { name: tool.name, description: tool.description, parameters: parameters.value })\n }\n }\n for (const removed of message.toolsRemoved ?? []) tools.delete(removed.name)\n break\n }\n case \"user\":\n transcript.push({ _tag: \"User\", text: textOf(message.content) })\n break\n case \"assistant\":\n for (const block of message.content) {\n if (block.type === \"text\" && block.text !== \"\") transcript.push({ _tag: \"Relay\", text: block.text })\n if (block.type === \"toolCall\") {\n transcript.push({ _tag: \"ToolCall\", id: block.id, name: block.name, arguments: block.arguments })\n }\n }\n break\n case \"toolResult\":\n transcript.push({\n _tag: \"ToolResult\",\n id: message.toolCallId,\n name: message.toolName,\n text: textOf(message.content),\n isError: message.isError === true\n })\n break\n }\n }\n return { instructions: instructions.join(\"\\n\\n\"), tools: [...tools.values()], transcript }\n}\n\nconst emptyUsage = () => ({\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }\n})\n\nconst messageOf = (model: Model<string>, turn: Turn, callIds: ReadonlyArray<string>, now: number): AssistantMessage => {\n const calls = turn.toolCalls.map((call, index): ToolCall => ({\n type: \"toolCall\",\n id: callIds[index] ?? `call-${index}`,\n name: call.name,\n arguments: call.arguments\n }))\n const reply: ReadonlyArray<TextContent> = turn.reply === \"\" ? [] : [{ type: \"text\", text: turn.reply }]\n return {\n role: \"assistant\",\n content: [...reply, ...calls],\n api: model.api,\n provider: model.provider,\n model: model.id,\n usage: emptyUsage(),\n stopReason: calls.length > 0 ? \"toolUse\" : \"stop\",\n timestamp: now\n }\n}\n\nconst emit = (stream: AssistantMessageEventStream, message: AssistantMessage): void => {\n const partial: AssistantMessage = { ...message, content: [], stopReason: \"pending\" }\n stream.push({ type: \"start\", partial: { ...partial } })\n message.content.forEach((block, index) => {\n if (block.type === \"text\") {\n partial.content.push({ type: \"text\", text: \"\" })\n stream.push({ type: \"text_start\", contentIndex: index, partial: { ...partial } })\n partial.content[index] = block\n stream.push({ type: \"text_delta\", contentIndex: index, delta: block.text, partial: { ...partial } })\n stream.push({ type: \"text_end\", contentIndex: index, content: block.text, partial: { ...partial } })\n } else if (block.type === \"toolCall\") {\n partial.content.push(block)\n stream.push({ type: \"toolcall_start\", contentIndex: index, partial: { ...partial } })\n stream.push({ type: \"toolcall_end\", contentIndex: index, toolCall: block, partial: { ...partial } })\n }\n })\n stream.push({\n type: \"done\",\n reason: message.content.some((block) => block.type === \"toolCall\") ? \"toolUse\" : \"stop\",\n message\n })\n stream.end(message)\n}\n\nconst failed = (model: Model<string>, reason: \"error\" | \"aborted\", detail: string, now: number): AssistantMessage => ({\n role: \"assistant\",\n content: [],\n api: model.api,\n provider: model.provider,\n model: model.id,\n usage: emptyUsage(),\n stopReason: reason,\n errorMessage: detail,\n timestamp: now\n})\n\n/** A Relay provider: one model, every turn handed to `run`. */\nexport const relayProvider = (id: RelayBackendId, name: string, run: TurnRunner, now: () => number) =>\n createProvider({\n id,\n name,\n // The CLI holds the user's login; Relay holds no credential, so auth always resolves empty.\n auth: { apiKey: { name, resolve: async () => ({ auth: {} }) } },\n models: [{\n id: MODEL_ID,\n name,\n api: API,\n provider: id,\n baseUrl: \"cli:\",\n reasoning: false,\n input: [\"text\"],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: 200_000,\n maxTokens: 32_000\n }],\n api: {\n stream: (model, context, options) => streamTurn(model, context, options, run, now),\n streamSimple: (model, context, options) => streamTurn(model, context, options, run, now)\n }\n })\n\nconst streamTurn = (\n model: Model<string>,\n context: TranscriptContext,\n options: SimpleStreamOptions | undefined,\n run: TurnRunner,\n now: () => number\n): AssistantMessageEventStream => {\n const stream = createAssistantMessageEventStream()\n const signal = options?.signal\n run(turnRequestOf(context.messages), signal).then(\n ({ callIds, turn }) => emit(stream, messageOf(model, turn, callIds, now())),\n (cause: unknown) => {\n const message = failed(model, signal?.aborted === true ? \"aborted\" : \"error\", String(cause), now())\n stream.push({ type: \"error\", reason: message.stopReason === \"aborted\" ? \"aborted\" : \"error\", error: message })\n stream.end(message)\n }\n )\n return stream\n}\n\n/** The only model registry Relay builds: exactly the given Relay providers, nothing from pi-ai's catalog. */\nexport const relayModels = (providers: ReadonlyArray<ReturnType<typeof relayProvider>>): Models => {\n const models = createModels()\n for (const provider of providers) models.setProvider(provider)\n return models\n}\n\n/** The tool declarations Pi reports for a capability, as JSON Schema. */\nexport type RelayToolDeclaration = Pick<Tool, \"name\" | \"description\" | \"parameters\">\n", "/**\n * Relay's Pi extension: every registered capability as a Pi tool, and the permission gate as the one\n * `beforeTool` hook in front of all of them.\n *\n * **Mental model**\n *\n * - **Reads replay, writes never do.** A `read` capability is `replay: \"safe\"`, so a crash mid-call\n * reruns it. A `write` or `host` capability is not, so Pi gives the model an `interrupted` result\n * instead of running it twice.\n * - **The gate decides once per call, durably.** For `write`, the hook asks the person through\n * {@link ConfirmationBroker} and memoises the answer under the call id, so a restart neither asks again\n * after a decision nor runs a declined action. `host` is refused until herdr Approvals are wired (H3).\n *\n * This module is a Promise boundary: Pi runs the hook and the tools.\n *\n * @module\n */\nimport type { Context as ChordContext } from \"@earendil-works/chord\"\nimport { Type } from \"@earendil-works/pi-ai\"\nimport { defineExtension, defineTool, hook, ToolTask } from \"@earendil-works/pi-durable\"\nimport type { Extension } from \"@earendil-works/pi-durable\"\nimport type {\n CapabilityEncodingFailed,\n CapabilityFailed,\n CapabilityInputInvalid,\n InvocationResult,\n PendingAction\n} from \"@knpkv/capability\"\nimport { Cause, Data, Effect, Schema } from \"effect\"\nimport type { Exit, Option } from \"effect\"\nimport type { RegisteredCapability } from \"./registry.js\"\n\n/** Runs an Effect from inside Pi with the harness's services. */\nexport type EffectRunner<Requirements> = <A, E>(\n effect: Effect.Effect<A, E, Requirements>,\n signal: AbortSignal | undefined\n) => Promise<Exit.Exit<A, E>>\n\n/** The dock-facing side of the gate: ask a person about one call and wait for the answer. */\nexport interface ConfirmationBroker {\n /** Resolves with the person's answer; rejects when `signal` aborts (the run was cancelled). */\n readonly ask: (request: {\n readonly conversationId: string\n readonly callId: string\n readonly action: PendingAction\n readonly reversible: boolean\n }, signal: AbortSignal | undefined) => Promise<boolean>\n}\n\nconst decodeJson = Schema.decodeUnknownOption(Schema.Json)\n\n/** Reads rerun after a crash; writes and host actions never do. */\nconst replaySafe = { replay: \"safe\" } satisfies { readonly replay: \"safe\" }\n\nconst declined = (verb: string): string => `The user declined: ${verb}. Do not retry it unless they ask again.`\n\n/** Arguments that passed Pi's JSON Schema but not the capability's own decode; the person is never asked. */\nconst invalidArguments = (verb: string, cause: string): string =>\n `${verb} got invalid arguments, so nobody was asked: ${cause}`\n\nconst resultText = (result: InvocationResult): string => JSON.stringify(result.output)\n\n/** What the model reads when a call fails: the declared reason and fix, never a defect's internals. */\nconst modelVisibleFailure = (\n name: string,\n failure: Option.Option<CapabilityFailed | CapabilityInputInvalid | CapabilityEncodingFailed>\n): string => {\n if (failure._tag === \"None\") return `${name} failed unexpectedly. Tell the user it did not complete.`\n switch (failure.value._tag) {\n case \"CapabilityFailed\":\n return `${failure.value.reason} \u2014 ${failure.value.fix}`\n case \"CapabilityInputInvalid\":\n return `${name} got invalid arguments: ${failure.value.issue}`\n case \"CapabilityEncodingFailed\":\n return `${name} failed unexpectedly. Tell the user it did not complete.`\n }\n}\n\n/** Build the `relay` Pi extension for one product's capabilities. */\nexport const relayExtension = <Requirements>(\n capabilities: ReadonlyArray<RegisteredCapability<Requirements>>,\n runEffect: EffectRunner<Requirements>,\n broker: ConfirmationBroker\n): Extension => {\n const byName = new Map(capabilities.map((capability) => [capability.name, capability]))\n const tools = capabilities.map((capability) =>\n defineTool({\n name: capability.name,\n description: capability.description,\n parameters: Type.Unsafe(capability.parameters),\n ...(capability.gate === undefined && replaySafe),\n execute: async (args, api, context: ChordContext) => {\n // Pi validated `args` against the capability's JSON Schema; decode it to JSON for the capability.\n const json = decodeJson(args)\n if (json._tag === \"None\") {\n throw new RelayToolFailure({\n capability: capability.name,\n message: `${capability.name} got non-JSON arguments`\n })\n }\n const exit = await runEffect(capability.run(json.value), context.abortSignal)\n if (exit._tag === \"Failure\") {\n const failure = Cause.findErrorOption(exit.cause)\n if (failure._tag === \"None\") {\n // A defect or an undeclared error: logged here, never shown to the model.\n await runEffect(\n Effect.logError(`Relay capability ${capability.name} failed unexpectedly`, exit.cause),\n undefined\n )\n }\n throw new RelayToolFailure({\n capability: capability.name,\n message: modelVisibleFailure(capability.name, failure)\n })\n }\n const receipt = capability.receipt(exit.value)\n await api.details({\n cites: exit.value.cites.map((ref) => ({ ...ref })),\n ...(receipt !== undefined && { receipt: { ...receipt } })\n }, context)\n return { content: [{ type: \"text\", text: resultText(exit.value) }] }\n }\n })\n )\n const gate = hook(ToolTask, {\n beforeTool: async (call, api, context) => {\n const capability = byName.get(call.name)\n // Pi refuses unregistered tools before this hook, but another extension's tools would reach it.\n if (capability === undefined) return { block: `${call.name} is not a Relay capability.` }\n const gate = capability.gate\n if (gate === undefined) return undefined\n if (gate.access === \"host\") {\n return { block: `${call.name} needs a herdr Approval, which Relay cannot request yet.` }\n }\n const memoKey = `relay.decision.${call.id}`\n const remembered = await api.memo<boolean>(memoKey, context)\n if (remembered !== undefined) return remembered ? undefined : { block: declined(call.name) }\n // Arguments the confirmation can't show are refused with their reason, never asked about or read as a decline.\n const action = await runEffect(gate.describe(call.arguments), context.abortSignal)\n if (action._tag === \"Failure\") {\n const failure = Cause.findErrorOption(action.cause)\n return {\n block: failure._tag === \"Some\" && failure.value._tag === \"CapabilityInputInvalid\"\n ? invalidArguments(call.name, failure.value.issue)\n : modelVisibleFailure(call.name, failure)\n }\n }\n const allowed = await broker.ask({\n conversationId: String(api.conversationId),\n callId: call.id,\n action: action.value,\n reversible: gate.reversible\n }, context.abortSignal)\n const decision = await api.memo(memoKey, allowed, context)\n return decision ? undefined : { block: declined(call.name) }\n }\n })\n return defineExtension({ name: \"relay\", tools, hooks: [gate] })\n}\n\n/**\n * A capability failed. Pi turns a thrown error into an error tool result for the model; the message is\n * what the model reads, so it names the capability and the failure.\n */\nexport class RelayToolFailure extends Data.TaggedError(\"RelayToolFailure\")<{\n readonly capability: string\n readonly message: string\n}> {}\n", "/**\n * One model turn over a CLI-backed `LanguageModel`, with tool calls carried in a JSON schema.\n *\n * **Mental model**\n *\n * - **The CLI never runs tools.** `claude --print` and `codex exec` are asked for one structured\n * answer: either tool calls or a final reply. The harness runs the tools, behind its gate, and the\n * next turn sees their results. That keeps the user's own CLI login as the only credential and the\n * permission gate as the only path to a product.\n * - **The transcript is rendered, not replayed into provider sessions.** Each turn gets the whole\n * visible transcript, so switching backends mid-session needs no provider state.\n *\n * @module\n */\nimport { Effect, Schema } from \"effect\"\nimport { LanguageModel } from \"effect/ai\"\n\n/** A tool as the model is told about it. */\nexport interface TurnTool {\n readonly name: string\n readonly description: string\n readonly parameters: Schema.Json\n}\n\n/** One transcript line as the model reads it. */\nexport type TurnLine =\n | { readonly _tag: \"User\"; readonly text: string }\n | { readonly _tag: \"Relay\"; readonly text: string }\n | { readonly _tag: \"ToolCall\"; readonly id: string; readonly name: string; readonly arguments: Schema.Json }\n | {\n readonly _tag: \"ToolResult\"\n readonly id: string\n readonly name: string\n readonly text: string\n readonly isError: boolean\n }\n\nexport interface TurnRequest {\n readonly instructions: string\n readonly tools: ReadonlyArray<TurnTool>\n readonly transcript: ReadonlyArray<TurnLine>\n}\n\n/** What the model returns for one turn. An empty `toolCalls` means `reply` is the final answer. */\nexport const Turn = Schema.Struct({\n reply: Schema.String,\n toolCalls: Schema.Array(Schema.Struct({ name: Schema.String, arguments: Schema.Record(Schema.String, Schema.Json) }))\n})\nexport type Turn = typeof Turn.Type\n\nconst renderLine = (line: TurnLine): string => {\n switch (line._tag) {\n case \"User\":\n return `USER: ${line.text}`\n case \"Relay\":\n return `RELAY: ${line.text}`\n case \"ToolCall\":\n return `RELAY CALLED ${line.name} (${line.id}) WITH ${JSON.stringify(line.arguments)}`\n case \"ToolResult\":\n return `${line.isError ? \"TOOL ERROR\" : \"TOOL RESULT\"} ${line.name} (${line.id}): ${line.text}`\n }\n}\n\n/** The prompt one turn sends: instructions, the tool list with schemas, the transcript, the answer rule. */\nexport const renderTurnPrompt = (request: TurnRequest): string =>\n [\n request.instructions,\n \"\",\n request.tools.length === 0\n ? \"You have no tools in this session.\"\n : [\n \"Tools you may call (arguments must match the JSON Schema):\",\n ...request.tools.map((tool) =>\n `- ${tool.name}: ${tool.description}\\n schema: ${JSON.stringify(tool.parameters)}`\n )\n ].join(\"\\n\"),\n \"\",\n \"Conversation so far:\",\n ...request.transcript.map(renderLine),\n \"\",\n \"Answer with one JSON object. To call tools, list them in toolCalls and keep reply short or empty.\",\n \"To answer the user, leave toolCalls empty and put the whole answer in reply.\",\n \"Never claim an action happened unless a TOOL RESULT says so.\"\n ].join(\"\\n\")\n\n/** Run one turn on whatever `LanguageModel` is provided: the user's Claude Code or Codex CLI. */\nexport const runTurn = Effect.fn(\"Relay.runTurn\")(function*(request: TurnRequest) {\n const response = yield* LanguageModel.generateObject({\n prompt: renderTurnPrompt(request),\n schema: Turn,\n objectName: \"relay_turn\"\n })\n return response.value\n})\n", "/**\n * Capabilities as the harness holds them: one list of `@knpkv/capability` capabilities with their\n * types closed over, so the harness can run any of them from the model's JSON without `any`.\n *\n * Decoding, encoding and failure handling are the capability package's (`invoke`, `describeCall`);\n * this module only erases types and records what the gate needs.\n *\n * @module\n */\nimport {\n type Capability,\n type CapabilityEncodingFailed,\n type CapabilityFailed,\n type CapabilityInputInvalid,\n describeCall,\n type FailureSchema,\n inputJsonSchema,\n type InputSchema,\n type InvocationResult,\n invoke,\n type PendingAction,\n type PlainSchema\n} from \"@knpkv/capability\"\nimport { Option, Schema } from \"effect\"\nimport type { Effect } from \"effect\"\nimport type * as JsonSchema from \"effect/JsonSchema\"\nimport type { WriteReceipt } from \"./model.js\"\n\n/** What a person must agree to before a gated capability runs. */\nexport interface Gate {\n readonly access: \"write\" | \"host\"\n readonly reversible: boolean\n readonly describe: (\n args: Schema.Json\n ) => Effect.Effect<PendingAction, CapabilityInputInvalid | CapabilityEncodingFailed>\n}\n\n/** One registered capability, its types erased behind closures. */\nexport interface RegisteredCapability<Requirements> {\n readonly name: string\n readonly description: string\n /** `undefined` for a read: it runs without anyone agreeing first. */\n readonly gate: Gate | undefined\n /** A short display name, for activity rows. */\n readonly label: string\n /** A display-safe line for one call: a write's action verb, or the label. */\n readonly summarize: (args: Schema.Json) => string\n /** What a completed call made, for writes whose product projects a receipt. */\n readonly receipt: (result: InvocationResult) => WriteReceipt | undefined\n /** JSON Schema of the input, for the model's tool list and argument validation. */\n readonly parameters: JsonSchema.JsonSchema\n /** `args` is the model's JSON for this call; the capability decodes it at the boundary. */\n readonly run: (\n args: Schema.Json\n ) => Effect.Effect<\n InvocationResult,\n CapabilityInputInvalid | CapabilityFailed | CapabilityEncodingFailed,\n Requirements\n >\n}\n\n/** How the dock shows a capability's calls. Every field has a default. */\nexport interface DisplayOptions<Output extends PlainSchema> {\n /** Defaults to the capability name with spaces: `get_pull_request` is \"get pull request\". */\n readonly label?: string\n /** A write's receipt, from its decoded output: a display-safe line, the provider's id, a link. */\n readonly receipt?: (output: Output[\"Type\"]) => WriteReceipt\n}\n\n/** Register a capability for Relay, with how the dock shows its calls. */\nexport const register = <\n Name extends string,\n Input extends InputSchema,\n Output extends PlainSchema,\n Failure extends FailureSchema,\n Requirements\n>(\n capability: Capability<Name, Input, Output, Failure, Requirements>,\n display: DisplayOptions<Output> = {}\n): RegisteredCapability<Requirements> => {\n const { contract } = capability\n const label = display.label ?? contract.name.replaceAll(\"_\", \" \")\n const decodeInput = Schema.decodeUnknownOption(contract.input)\n const decodeOutput = Schema.decodeUnknownOption(contract.output)\n const project = display.receipt\n return {\n name: contract.name,\n description: contract.description,\n label,\n summarize: (args) =>\n contract.access === \"read\"\n ? label\n : Option.match(decodeInput(args), { onNone: () => label, onSome: (input) => contract.describe(input).verb }),\n receipt: (result) =>\n project === undefined ? undefined : Option.getOrUndefined(Option.map(decodeOutput(result.output), project)),\n gate: contract.access === \"read\"\n ? undefined\n : {\n access: contract.access,\n reversible: contract.reversible,\n describe: (args) => describeCall(contract, args)\n },\n parameters: inputJsonSchema(contract),\n run: (args) => invoke(capability, args)\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAaA,YAAY,eAAe;AAC3B,YAAY,cAAc;AAC1B,SAAS,mCAAmC;AAC5C,SAAS,UAAAA,SAAQ,cAAAC,aAAY,SAAAC,cAAa;AAC1C,SAAS,2BAA2B;;;ACfpC,IAAM,2BAAgE,OAAO,OAAO;EACnF,OAAO,uBAAO,mBAAmB;CACjC;AAED,IAAe,cAAf,MAA0B;EAIzB,IAAI,cAAW;AACd,WAAO,KAAK,MAAM,wBAAwB;EAC3C;;AAGD,IAAM,eAAN,cAA2B,YAAW;EAC5B;EAET,YAAY,MAAY;AACvB,UAAK;AACL,SAAK,QAAQ;EACd;EAEA,MAAS,MAAmB;AAC3B,WAAO;EACR;EAEA,WAAQ;AACP,WAAO,KAAK;EACb;;AAGD,IAAM,eAAN,cAA8B,YAAW;EAC/B;EACA;EACA;EAET,YAAY,QAAiB,KAAoB,OAAQ;AACxD,UAAK;AACL,SAAK,UAAU;AACf,SAAK,OAAO;AACZ,SAAK,SAAS;EACf;EAEA,MAAa,KAAsB;AAClC,QAAI,IAAI,UAAU,KAAK,KAAK;AAAO,aAAO,KAAK;AAC/C,WAAO,KAAK,QAAQ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AAY,SAAS;MACrB,UAAU,CAAC,SAAS,aAAa,UAAU,IAAI;;IAEnD,YAAY,gBAAgB,QAAQ;IACpC,KAAK,CAAC,SAAS,OAAO,YAAY,IAAI;;AAE1C;",
|
|
6
|
+
"names": ["Effect", "FileSystem", "Layer", "promise", "resolve", "result", "DATA_DESCRIPTOR", "copied", "defineData", "copy", "DATA_DESCRIPTOR", "node", "isContainer", "keys", "sources", "existingIndex", "snapshotValue", "result", "defineData", "index", "run", "other", "probe", "read", "copy", "sequence", "hook", "section", "parts", "delay", "page", "section", "lines", "hook", "result", "model", "hook", "slot", "policy", "tools", "page", "id", "entry", "model", "failNoModel", "hook", "parts", "contentText", "resolve", "toError", "run", "SCAN_PAGE_SIZE", "page", "copy", "page", "settle", "read", "addressId", "run", "section", "SCAN_PAGE_SIZE", "queued", "reached", "failed", "current", "invoke", "read", "resolve", "LIVE_STATUSES", "SCAN_PAGE_SIZE", "advance", "nodeOf", "SCAN_PAGE_SIZE", "model", "context", "names", "statement", "parts", "resolve", "read", "Capability", "Effect", "Predicate", "Schema", "queued", "ObjectRef", "resolve", "model", "resolve", "queued", "credential", "model", "model", "queued", "resolve", "run", "streams", "Predicate", "Schema", "section", "model", "run", "Schema", "decodeJson", "gate", "Effect", "Schema", "Schema", "run", "Effect", "Predicate", "failed", "read", "track", "Effect", "Layer", "FileSystem", "Schema"]
|
|
7
|
+
}
|