diff --git a/AGENTS.md b/AGENTS.md index d6bd72d4b0..f6f3c970e8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,6 +27,7 @@ Never bypass Git hooks. Do not use `--no-verify` or otherwise disable, skip, or - Keep things in one function unless composable or reusable - Do not extract single-use helpers preemptively. Inline the logic at the call site unless the helper is reused, hides a genuinely complex boundary, or has a clear independent name that improves the caller. +- Before adding complexity for a speculative or vanishingly unlikely race or security edge case, explain the concrete failure mode, likelihood, and complexity cost to the user and get their buy-in. Do not silently expand scope for theoretical robustness. - Avoid `try`/`catch` where possible - Avoid using the `any` type - Use Bun APIs when possible, like `Bun.file()` @@ -154,14 +155,14 @@ const table = sqliteTable("session", { ## V2 Session Core - Keep durable events minimal: record irreducible new facts and do not repeat state derivable by folding the ordered aggregate history. Enrich projections and read models with previous or derived state when consumers need self-contained views. -- Keep durable prompt admission separate from model execution. `SessionV2.prompt(...)` admits one durable `session_input` row before scheduling advisory `SessionExecution.wake(sessionID)` unless `resume: false` requests admit-only behavior. The serialized runner promotes admitted inputs into visible user messages at safe boundaries. -- Reusing a Session ID adopts the existing Session. Reusing a prompt message ID reconciles an exact retry only when Session, prompt, and delivery mode match; conflicting reuse fails. Historical projected prompts lazily synthesize promoted inbox records during exact retry. -- Keep `SessionExecution` process-global and Session-ID based. Its local implementation owns the process-local Session coordinator and discovers placement through `SessionStore` plus `LocationServiceMap.get(session.location)` only when a drain starts; no layer should take a Session ID. V2 interruption targets the active process-local ownership chain for that Session; idle or missing interruption is a no-op. +- Keep durable prompt admission separate from model execution. `SessionV2.prompt(...)` admits one durable `session_pending` row before scheduling advisory `SessionExecution.wake(sessionID)` unless `resume: false` requests admit-only behavior. The serialized runner promotes admitted inputs into visible user messages at safe boundaries, consuming the pending row in the same event transaction; `session_pending` stores only unconsumed work. +- Reusing a Session ID adopts the existing Session. Reusing a prompt message ID reconciles an exact retry only when Session, prompt, and delivery mode match; conflicting reuse fails. Retry of an already-promoted input reconciles against the projected message and the durable admitted event rather than a retained row. +- Keep `SessionExecution` process-global and Session-ID based. Its local implementation owns the process-local Session coordinator and discovers placement through `SessionStore` plus `LocationServiceMap.get(session.location)` only when a drain starts; no layer should take a Session ID. V2 interruption targets the active process-local ownership chain for that Session; interruption of a known but idle or locally unowned Session is a no-op, while the public API rejects an unknown Session. - Keep `SessionRunner`, model resolution, tool registry, permissions, and filesystem Location-scoped. Omitted `Location.workspaceID` means implicit-local placement; explicit workspace identity remains reserved for future placement semantics. -- Preserve one explicit `llm.stream(request)` call per step and reload projected history before durable continuation. Do not bridge through legacy `SessionPrompt.loop(...)` or delegate orchestration to an in-memory tool loop. +- Preserve one explicit `llm.stream(request)` call per Physical Attempt and reload projected history before durable continuation. Most Steps have one Physical Attempt; overflow-triggered compaction recovery may rebuild one Step for a second attempt. Do not bridge through legacy `SessionPrompt.loop(...)` or delegate orchestration to an in-memory tool loop. - Keep local Session drains process-local until clustering is implemented. `SessionRunCoordinator` joins explicit same-Session resumes, coalesces prompt wakeups, and allows different Sessions to run concurrently. Advisory wakes drain eligible durable inbox rows only; post-crash continuation recovery requires a separate explicit design before it may retry provider work. A drain has no durable identity or transcript boundary. - Keep delivery vocabulary explicit. Prompts steer by default and promote at the next safe step boundary while the current drain requires continuation. An explicit `queue` input remains pending until the Session would otherwise become idle; promote one queued input at that boundary, then reevaluate continuation before promoting another. Promoting any new user input resets the selected agent's step allowance; a batch of steers resets it once. - One step is one logical LLM call; its durable record covers only the model-visible span. Do not write "provider turn", and do not use bare "turn" for a single call: "turn" is reserved for the future assistant-turn unit containing all steps from prompt promotion until the session would go idle. - Keep EventV2 replay owner claims separate from clustered Session execution ownership. -- Keep the Instructions algebra and built-ins in `src/instructions`; keep instruction producers with their observed domains, and keep Session History selection plus `InstructionCheckpoint` and `InstructionEntry` persistence Session-owned. `InstructionDiscovery` observes ambient global and upward-project instructions. The runner composes built-ins, discovery, guidance, and entries explicitly in `loadInstructions`; there is no instruction registry. -- The durable `Instructions.Applied` record is what the model was last told, per instruction source. Reconciliation narrates drift through `session.instructions.updated` and never rewrites the baseline; only completed compaction rebaselines, while Session movement or committed revert resets the `InstructionCheckpoint`. Unavailable sources keep the model's prior belief, blocking only a Session's first instruction baseline. +- Keep the Instructions algebra and built-ins in `src/instructions`; keep instruction producers with their observed domains, and keep Session History selection plus `InstructionState` and `InstructionEntry` persistence Session-owned. `InstructionDiscovery` observes ambient global and upward-project instructions. The runner composes built-ins, discovery, guidance, and entries explicitly in `loadInstructions`; there is no instruction registry. +- `session.instructions.updated` stores only changed source keys and content hashes. Blob values live once in `instruction_blob`; `instruction_state` is a rebuildable fold cache, never primary state. Render initial instructions and chronological updates from values during request assembly. Completed compaction moves the instruction epoch; Session movement and committed revert clear it. Unavailable sources retain the last value and block only the initial complete delta. diff --git a/CONTEXT.md b/CONTEXT.md index ce880380d1..79611f30f5 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -13,11 +13,11 @@ The opaque algebra of independently refreshable typed instruction sources that r _Avoid_: Model Context, System Context **Session History**: -The projected chronological conversation selected for a **Step** after applying the active compaction and **InstructionCheckpoint** baseline cutoffs. +The projected chronological conversation selected for a **Step** after applying the active compaction boundary and interleaving derived **Instruction Updates** from the current **Instruction Epoch**. _Avoid_: Session Context **Instruction Source**: -One independently observed typed value within **Instructions**, represented by a stable namespaced key, JSON codec, loader, pure baseline/update renderers, and an optional removal renderer. +One independently read typed value within **Instructions**, represented by a stable namespaced key, canonical JSON codec, pure first/changed renderers, and an optional removal renderer. _Avoid_: Prompt fragment **InstructionEntry**: @@ -26,22 +26,25 @@ One API-managed, durable, per-Session instruction value. Its slash-free client k **InstructionDiscovery**: The Location-scoped service that observes ambient global and upward-project `AGENTS.md` files as one ordered aggregate **Instruction Source**. -**InstructionCheckpoint**: -The Session-owned durable instruction baseline, baseline sequence, and `Instructions.Applied` record used to prepare later Steps. +**Instruction State**: +The Session-owned projection cache of one instruction log fold: epoch start, values at that start, current values, and the last folded sequence. It is rebuilt from durable events and never authors model-visible facts. **Instruction Update**: -A durable chronological System message published as `session.instructions.updated` that tells the model the newly effective state of one or more changed **Instruction Sources**. -_Avoid_: System notification, raw text diff +A durable `session.instructions.updated` value delta admitted at a **Safe Step Boundary**. Its model-visible System text is rendered from stored values at request assembly and is never persisted verbatim. +_Avoid_: Correction, stored prose, raw text diff -**Instruction Baseline**: -The exact joined instruction text stored by **InstructionCheckpoint** and sent as immutable provider-cache prefix state until completed compaction rebaselines it or Session movement or committed revert resets it. +**Initial Instructions**: +The deterministic instruction text rendered from values at the current **Instruction Epoch** start and sent as provider-cache prefix state until completed compaction moves the epoch or Session movement or committed revert resets it. _Avoid_: Live system prompt -**Applied Instructions**: -The overwriteable model-hidden `Instructions.Applied` record in **InstructionCheckpoint**, containing what the model was last told per **Instruction Source**. +**Instruction Epoch**: +The span between completed compactions. Its start is the last `session.compaction.ended` sequence, or the initial complete instruction delta when no prior epoch exists. + +**Instruction Values**: +The key-to-hash map produced by folding instruction deltas in durable sequence order. Hash bodies live once in the content-addressed instruction blob store. **Unavailable Instruction Source**: -An expected temporary inability to observe an **Instruction Source** value; the runtime retains its prior effective state and emits no update, while an unavailable source blocks creation of the first complete **Instruction Baseline**. +An expected temporary inability to read an **Instruction Source** value; the runtime retains its prior effective value and emits no update, while an unavailable source blocks the initial complete delta. **Safe Step Boundary**: The point during Step preparation, after prior tool settlement and before durable input promotion, where instruction changes may be admitted chronologically. @@ -53,7 +56,7 @@ A durable user input accepted into the Session inbox but not yet included in **S The durable transition that removes an **Admitted Prompt** from pending input and appends its user message to **Session History**. **Step**: -One logical LLM call spanning pre-flight instruction checkpoint preparation, input promotion, request build, and compaction check; the provider stream; and tool settlement. +One logical LLM call spanning pre-flight instruction synchronization, input promotion, request build, and compaction check; the provider stream; and tool settlement. _Avoid_: provider turn, turn (unqualified) **Physical Attempt**: @@ -108,18 +111,16 @@ _Avoid_: Response envelope ## Relationships - **Instructions** is an opaque carrier composed from zero or more **Instruction Sources**. -- **Model Context** is broader than **Instructions**. For each **Step**, the runner assembles the selected agent or provider system text, the **Instruction Baseline**, **Session History**, available tools, and step-local additions into one model request. -- **Session History** contains projected conversational messages and admitted **Instruction Updates**; the active **Instruction Baseline** remains separate provider-request state. +- **Model Context** is broader than **Instructions**. For each **Step**, the runner assembles the selected agent or provider system text, **Initial Instructions**, **Session History**, available tools, and step-local additions into one model request. +- **Session History** persists conversational messages. The runner derives model-facing **Instruction Update** messages from value deltas and interleaves them by durable sequence; **Initial Instructions** remain separate provider-request state. - The runner explicitly loads and combines instruction built-ins, **InstructionDiscovery**, selected-agent skill guidance, reference guidance, MCP guidance, and **InstructionEntry** values. There is no instruction registry. - `Instructions.combine(...)` preserves caller order and rejects duplicate stable namespaced source keys. The runner loads its producers concurrently, then combines them in its fixed declared order. -- Each **Instruction Source** loader returns one coherent typed value or explicitly reports unavailability. `Instructions.make(...)` hides the value type so differently typed sources compose uniformly; its codec compares and stores the value, while pure renderers produce baseline, update, and optional removal text. -- `Instructions.initialize(...)` observes composed **Instructions** once and produces a complete **Instruction Baseline** with **Applied Instructions**. -- `Instructions.reconcile(...)` observes composed **Instructions** once and returns either unchanged or one combined chronological update. It never rewrites the baseline. -- `Instructions.rebaseline(...)` renders a fresh baseline after completed compaction, recalling previously applied values for sources that are temporarily unavailable. -- A changed **Instruction Source** may contribute text to one **Instruction Update** containing the newly effective state. -- An **Instruction Update** persists the exact combined rendered text sent to the model through `session.instructions.updated`. -- **Applied Instructions** advances atomically with the corresponding durable **Instruction Update**. -- **Applied Instructions** stores one codec-encoded JSON value and, for removable sources, a pre-rendered removal message per stable **Instruction Source** key. +- Each **Instruction Source** read returns one coherent typed value, explicit removal, or temporary unavailability. `Instructions.make(...)` hides the value type so differently typed sources compose uniformly; its canonical codec defines storage and hash equivalence, while pure renderers produce first, changed, and optional removal text. +- `Instructions.read(...)` reads every composed source concurrently and exactly once at the boundary. `Instructions.diff(...)` compares encoded-value hashes with current **Instruction Values** and returns one delta plus new blob bodies. +- `Instructions.renderInitial(...)` renders values at the **Instruction Epoch** start. `Instructions.renderUpdate(...)` renders one hydrated delta against the values immediately before it. +- A changed **Instruction Source** contributes its hash to one **Instruction Update**; explicit removal contributes the `"removed"` sentinel. +- An **Instruction Update** persists only its value delta. Rendered text is derived during request assembly and excluded from compaction summaries. +- The instruction blob insert, durable delta, and **Instruction State** advance commit atomically. - Changes from multiple **Instruction Sources** admitted at one safe boundary combine into one **Instruction Update**. - Instruction changes are sampled and admitted lazily at a **Safe Step Boundary**, never pushed asynchronously when their source changes. - At a **Safe Step Boundary**, prior tool results are already settled; instruction preparation completes before newly admitted user input promotes. @@ -130,28 +131,27 @@ _Avoid_: Response envelope - A **Session Drain** is process-local coordination rather than a durable domain entity. Durable recovery must reason from prompts, projected history, physical attempts, and tool state rather than inventing an enclosing execution identity. - An **Execution** contains one or more **Session Drains**; a **Session Drain** contains one reserved assistant-turn span at a time; that span contains **Steps**; and each **Step** contains one or more **Physical Attempts** plus any tool calls it requires. - A **Step** record covers only the model-visible span from first assistant output through tool settlement; pre-flight leaves no record, and one Step settles at most one record. -- The first **Step** renders the latest complete **Instruction Baseline** and creates its **InstructionCheckpoint** without emitting a redundant **Instruction Update**; an unavailable initial source blocks the Step instead of persisting an incomplete baseline. +- The first **Step** admits one complete delta and renders **Initial Instructions** without narrating that delta in history; an unavailable initial source blocks the Step instead of persisting incomplete values. - Instruction preparation precedes durable input promotion on every Step so an unavailable first baseline leaves pending input untouched and later updates enter history before newly promoted input. -- Completed compaction rebaselines the **InstructionCheckpoint** from current **Instructions** and removes earlier **Instruction Updates** from active projected model history while preserving durable audit history. -- A newly composed **Instruction Source** absent from **Applied Instructions** emits its baseline rendering once at the next **Safe Step Boundary**. +- Completed compaction moves the **Instruction Epoch** to the exact `session.compaction.ended` sequence and copies current hashes to the epoch's initial values. Earlier updates leave active model history while durable deltas remain. +- A newly composed **Instruction Source** absent from current **Instruction Values** emits its first rendering once at the next **Safe Step Boundary**. - **Unavailable Instruction Source** uses stale-while-revalidate semantics and is distinct from a successfully loaded absence, which may emit removal text. - **InstructionDiscovery** observes ambient instructions as one ordered aggregate **Instruction Source**. - Ambient discovery reads global and upward-project `AGENTS.md` files and honors `OPENCODE_DISABLE_PROJECT_CONFIG` for project files. - After a successful internal file or directory read, nearby `AGENTS.md` files toward the Location root are injected once per Session as durable synthetic instruction messages. - **InstructionEntry** stores API-managed per-Session JSON values. Each entry contributes one `api/` **Instruction Source**, so adding, replacing, or removing an entry is reconciled at the next **Safe Step Boundary**. - Location-scoped instruction producers naturally re-resolve when a moved Session next runs in its destination Location. -- Moving a Session resets its **InstructionCheckpoint**, so the destination must initialize a complete baseline before another prompt can promote. Committed revert also resets the checkpoint. +- Moving a Session clears its **Instruction State**, so the destination must admit a complete delta before another prompt can promote. Committed revert does the same; replay derives both resets from their durable events. - Selected-agent available-skill guidance is an **Instruction Source** composed explicitly by the runner. It lists only names and descriptions permitted for that agent; skill bodies and locations are exposed only through the permission-checked `skill` tool. - The selected agent and model are sampled when a **Step** starts. Changes admitted after that boundary apply to the next Step and do not restart the current Step. - An agent switch that changes selected-agent guidance produces an **Instruction Update** while preserving the current baseline. - Local tool authorization and pending permission requests retain the effective agent of the **Step** that issued the call; a later agent switch cannot change that call's policy. - Instruction source changes never wake idle Sessions; the next naturally scheduled **Safe Step Boundary** loads and compares current values lazily. - Once admitted, an **Instruction Update** remains durable even if the following **Physical Attempt** fails and is replayed unchanged on retry. -- **Instruction Updates** remain durable Session-message history; normal user-facing transcript surfaces may hide them. +- **Instruction Updates** remain durable value history but are not `session_message` rows. Clients display changed keys rather than model-facing prose. - The date **Instruction Source** initially preserves host-local calendar-date behavior; a configured user timezone may replace that default later. -- An **Instruction Baseline** is stored durably and reused verbatim across process restarts until rebaseline or reset. -- An **Instruction Baseline** durably preserves the exact joined text used for its part of the active provider-cache prefix. -- A model/provider switch preserves the current **InstructionCheckpoint** and chronological conversation history; the new selection applies to the next **Step**. +- **Initial Instructions** are recomputed deterministically from durable values for every request; rendered bytes are not stored. +- A model/provider switch preserves current **Instruction Values**, the **Instruction Epoch**, and chronological conversation history; the new selection applies to the next **Step**. - **Native Continuation Metadata** remains in durable history. Step projection includes it only for a successful exact originating provider/model match; failed Steps and incompatible models omit opaque metadata, while non-empty visible reasoning lowers to ordinary assistant text after a model switch. This conservative relation may widen only when recorded provider tests establish compatibility. - **Model Request Options** remain provider-semantic through Catalog resolution. The Session runner maps them into the LLM package's provider-option namespace; the selected protocol adapter alone owns provider wire encoding. - **Generation Controls**, protocol-semantic **Model Request Options**, and compatibility request body fields are separate Catalog domains. A shared ingestion adapter partitions legacy and models.dev AI-SDK-shaped options before routing. @@ -182,12 +182,12 @@ _Avoid_: Response envelope - SDK executes Server's assembled `HttpRouter` in memory. It opens no listener and performs no network I/O, while preserving Server routing, middleware, codecs, handlers, and errors. - The Effect Client and SDK re-export their decoded datatype facade from Schema so callers do not depend on internal package locations or Core's versioned names. - A capability intended for both networked and **Embedded OpenCode** belongs in the authoritative public `HttpApi`; embedded-only same-process capabilities extend **Embedded OpenCode** separately. -- `sessions.events({ sessionID, after })` is a public durable Session event stream. It verifies the Session, replays durable events after the optional aggregate sequence, continues with newly committed durable events, excludes live-only fragments, and is transported as SSE in both networked and embedded modes. +- `sessions.log({ sessionID, after, follow })` is the public durable Session event stream. It verifies the Session, replays durable events after the optional aggregate sequence, optionally continues with newly committed durable events, excludes live-only fragments, and is transported as SSE in both networked and embedded modes. - `events.subscribe()` is a distinct public instance-wide live stream for Session and non-Session activity. It has no replay guarantee and includes connection, heartbeat, and instance-disposal lifecycle events; consumers recover from disconnection by refreshing authoritative state. - A Session ID is not an optional filter on `events.subscribe()`: instance-wide live events and durable Session events have different schemas, replay guarantees, cursors, lifecycle events, and failure behavior. - The initial common OpenCode Client does not expose server-global event aggregation. `events.subscribe()` is bounded to the connected OpenCode instance or workspace; any future cross-instance administrative stream requires a separately designed API. - `events.subscribe()` does not automatically reconnect after transport loss. The live-only stream fails with `ClientError`; consumers refresh authoritative state before explicitly opening a new subscription because events missed during disconnection cannot be replayed. -- `sessions.events({ sessionID, after })` returns the generated HTTP client's cold durable event stream and does not build reconnection policy into the endpoint or client constructor. Transport loss fails the stream with `ClientError`. Callers may compose an explicit resuming stream above it by retaining the last observed durable sequence and opening a new subscription with `after`; any reusable resume helper remains a separate API design question. +- `sessions.log({ sessionID, after, follow })` returns the generated HTTP client's cold durable event stream and does not build reconnection policy into the endpoint or client constructor. Transport loss fails the stream with `ClientError`. Callers may compose an explicit resuming stream above it by retaining the last observed durable sequence and opening a new subscription with `after`; any reusable resume helper remains a separate API design question. - The stable `sessions.list(...)` design returns a **Page** in both networked and **Embedded OpenCode**; embedded execution does not define a separate unbounded array-returning list operation. The beta client currently preserves the existing HTTP `{ data, cursor }` envelope until emitter-level Page projection is implemented. - Session list cursors are opaque branded values carrying continuation query and ordering state. Consumers pass them back unchanged and do not inspect storage anchors or encoded filter fields. - A Session list continuation accepts only its opaque cursor. Scope, filters, ordering, and page size are fixed by the initial query and carried by that cursor. @@ -195,10 +195,10 @@ _Avoid_: Response envelope - `sessions.message({ sessionID, messageID })` is a required resource lookup. An unknown Session fails with `SessionNotFoundError`; a known Session with an absent or differently owned message fails with `MessageNotFoundError` without disclosing cross-Session ownership. Absence is not represented as `undefined` across the public HTTP boundary. - `sessions.interrupt({ sessionID })` first verifies that the durable Session exists, failing with `SessionNotFoundError` otherwise. For a known Session, interruption is idempotent: idle, already-settled, or locally unowned execution is a no-op. - `sessions.active()` snapshots the current process's foreground Session drain registry as a record of Session IDs to `{ type: "running" }`. Missing IDs are inactive; background subagents and tasks do not make their parent Session active, and process restart clears the registry. -- `sessions.context({ sessionID })` preserves the existing message-only operation. It returns projected **Session History**; it does not include or represent the complete **Model Context**, whose system text, **Instruction Baseline**, tools, and step-local additions remain separate. +- `sessions.context({ sessionID })` preserves the existing message-only operation. It returns projected **Session History**; it does not include or represent the complete **Model Context**, whose agent system text, **Initial Instructions**, tools, and step-local additions remain separate. - **Open question**: Should a future, separately named operation expose complete **Model Context**, including the instruction baseline, applied instruction metadata, tools, and step-local additions? - `sessions.prompt(...)` exposes `resume?: boolean`. Omitting it preserves durable admission followed by an advisory execution wake; `resume: false` requests durable admit-only behavior. -- The public operation remains `sessions.prompt(...)`; `SessionInput.admit` is the internal primitive, while the public `Admission` result and `resume` option express its durable admission semantics. +- The public operation remains `sessions.prompt(...)`; `SessionPending.admit` is the internal primitive, while the public `Admission` result and `resume` option express its durable admission semantics. - `sessions.create(...)` accepts an optional `location`. Omission resolves through the connected OpenCode instance's default or current location; an explicit value selects a known location. Networked and embedded transports use the same handler semantics. - `sessions.switchAgent({ sessionID, agent })` is part of the common client alongside `sessions.switchModel(...)`. It affects subsequent Session activity and fails with `SessionNotFoundError` for an unknown Session. - The **Embedded OpenCode** Layer delegates to the same scoped creation path; it does not define a second implementation. @@ -209,13 +209,13 @@ _Avoid_: Response envelope - Oversized textual **Model Tool Output** retains a bounded preview in Session history while its complete text moves to managed tool-output storage. Arbitrary structured-result size is a separate concern. - One tool settlement receives one aggregate textual limit, using the configured maximum lines or UTF-8 bytes, whichever is reached first. The limit is provider-independent; token pressure belongs to context assembly and compaction. - Generic truncation preserves the beginning and end of textual output. Tools may apply a more meaningful strategy before the Tool Registry enforces the final limit. -- A truncated **Model Tool Output** identifies its complete text both in the bounded model-visible preview and as a typed managed output path. Managed output paths do not modify the tool's validated structured result. +- A truncated **Model Tool Output** identifies its complete text in the bounded model-visible preview. The Tool Registry also supplies managed paths as internal metadata to tool hooks; Session events do not expose a typed `outputPaths` field. - A **Managed Tool Output File** is temporary and may expire after its retention period. The bounded **Model Tool Output**, not the file, is the durable replayable record. -- Failure to retain a **Managed Tool Output File** does not change a successful tool operation into a failed one. The Session records an explicitly lossy bounded output without a path, while operators receive diagnostics for the storage failure. +- Failure to retain a **Managed Tool Output File** fails settlement operationally. The Session never publishes a successful result whose complete output was lost during generic bounding. - Once a tool operation succeeds, bounding its **Model Tool Output** and publishing its one durable settlement form an interruption-safe completion region. Raw oversized success is never published before a later correction. - When a structured-only result would exceed the **Model Tool Output** limit, its validated structured value remains unchanged for Session consumers while model replay uses a bounded textual JSON preview and optional managed output path. - Existing tool-managed output paths survive generic bounding. A fallback file retains exactly the complete projected text received by the Tool Registry and never claims to reconstruct output already discarded by tool-specific shaping. -- **Managed Tool Output Files** use globally unique names in one shared flat directory. Their absolute paths are readable and searchable by ordinary tools; other absolute paths remain outside Location-scoped filesystem authority. +- **Managed Tool Output Files** use globally unique names in one shared flat directory. They receive no special filesystem authority; each tool applies its ordinary external-path policy. - Provider-executed tool results remain provider-native transcript facts outside generic Tool Registry bounding. Their context control requires provider-aware pruning or compaction because some providers require exact structured round-trip payloads. ## Client contract architecture diff --git a/bun.lock b/bun.lock index 0e5369f703..6627771aca 100644 --- a/bun.lock +++ b/bun.lock @@ -716,8 +716,6 @@ "dependencies": { "@ai-sdk/provider": "3.0.8", "@opencode-ai/client": "workspace:*", - "@opencode-ai/llm": "workspace:*", - "@opencode-ai/protocol": "workspace:*", "@opencode-ai/schema": "workspace:*", "@opencode-ai/sdk": "workspace:*", "effect": "catalog:", @@ -792,6 +790,8 @@ "effect": "catalog:", }, "devDependencies": { + "@opencode-ai/httpapi-codegen": "workspace:*", + "@opencode-ai/protocol": "workspace:*", "@tsconfig/bun": "catalog:", "@types/bun": "catalog:", "@typescript/native-preview": "catalog:", diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index e358b181c4..75f798b0eb 100755 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -1,10 +1,10 @@ #!/usr/bin/env bun -import { NodeFileSystem, NodeRuntime, NodeServices } from "@effect/platform-node" -import { Effect, Layer, Logger, References } from "effect" +import { NodeRuntime, NodeServices } from "@effect/platform-node" +import { Effect } from "effect" import { Commands } from "./commands/commands" import { Runtime } from "./framework/runtime" -import { Logging } from "@opencode-ai/core/observability/logging" +import { Observability } from "@opencode-ai/core/observability" import { Updater } from "./services/updater" import { InstallationChannel, InstallationVersion, InstallationLocal } from "@opencode-ai/core/installation/version" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" @@ -12,12 +12,6 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { Global } from "@opencode-ai/core/global" import { AppProcess } from "@opencode-ai/core/process" -const LoggingLayer = Logger.layer(Logging.loggers(), { mergeWithExisting: false }).pipe( - Layer.provide(NodeFileSystem.layer), - Layer.orDie, - Layer.merge(Layer.succeed(References.MinimumLogLevel, Logging.minimumLogLevel())), -) - const Handlers = Runtime.handlers(Commands, { $: () => import("./commands/handlers/default"), api: () => import("./commands/handlers/api"), @@ -59,7 +53,7 @@ Effect.logInfo("cli starting", { Effect.annotateLogs({ role: "cli" }), Effect.provide(Updater.layer), Effect.provide(AppNodeBuilder.build(LayerNode.group([Global.node, AppProcess.node]))), - Effect.provide(LoggingLayer), + Effect.provide(Observability.layer), Effect.provide(NodeServices.layer), Effect.scoped, Effect.tap(() => Effect.sync(() => process.exit(process.exitCode ?? 0))), diff --git a/packages/client/package.json b/packages/client/package.json index 85b550779e..531e28caaa 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -16,6 +16,7 @@ "dist" ], "exports": { + ".": "./src/promise/index.ts", "./promise": "./src/promise/index.ts", "./promise/api": "./src/promise/api.ts", "./effect": "./src/effect/index.ts", diff --git a/packages/client/script/build.ts b/packages/client/script/build.ts index 70f1dcc587..8e432b0a17 100644 --- a/packages/client/script/build.ts +++ b/packages/client/script/build.ts @@ -17,12 +17,7 @@ await Effect.runPromise( [ write( emitPromise(promiseContract, { - outputTypes: { - "events.subscribe": { - name: "OpenCodeEventEncoded", - import: 'import type { OpenCodeEventEncoded } from "@opencode-ai/protocol/groups/event"', - }, - }, + mutableOutputs: true, }), fileURLToPath(new URL("../src/promise/generated", import.meta.url)), ), diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index d1f726d077..334c4b1f18 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -226,64 +226,69 @@ export type Endpoint5_20Input = { readonly sessionID: Endpoint5_20Request["param export type Endpoint5_20Output = EffectValue>["data"] export type SessionContextOperation = (input: Endpoint5_20Input) => Effect.Effect -type Endpoint5_21Request = Parameters[0] +type Endpoint5_21Request = Parameters[0] export type Endpoint5_21Input = { readonly sessionID: Endpoint5_21Request["params"]["sessionID"] } -export type Endpoint5_21Output = EffectValue< +export type Endpoint5_21Output = EffectValue>["data"] +export type SessionPendingListOperation = (input: Endpoint5_21Input) => Effect.Effect + +type Endpoint5_22Request = Parameters[0] +export type Endpoint5_22Input = { readonly sessionID: Endpoint5_22Request["params"]["sessionID"] } +export type Endpoint5_22Output = EffectValue< ReturnType >["data"] export type SessionInstructionsEntryListOperation = ( - input: Endpoint5_21Input, -) => Effect.Effect - -type Endpoint5_22Request = Parameters[0] -export type Endpoint5_22Input = { - readonly sessionID: Endpoint5_22Request["params"]["sessionID"] - readonly key: Endpoint5_22Request["params"]["key"] - readonly value: Endpoint5_22Request["payload"]["value"] -} -export type Endpoint5_22Output = EffectValue> -export type SessionInstructionsEntryPutOperation = ( input: Endpoint5_22Input, ) => Effect.Effect -type Endpoint5_23Request = Parameters[0] +type Endpoint5_23Request = Parameters[0] export type Endpoint5_23Input = { readonly sessionID: Endpoint5_23Request["params"]["sessionID"] readonly key: Endpoint5_23Request["params"]["key"] + readonly value: Endpoint5_23Request["payload"]["value"] } -export type Endpoint5_23Output = EffectValue< - ReturnType -> -export type SessionInstructionsEntryRemoveOperation = ( +export type Endpoint5_23Output = EffectValue> +export type SessionInstructionsEntryPutOperation = ( input: Endpoint5_23Input, ) => Effect.Effect -type Endpoint5_24Request = Parameters[0] +type Endpoint5_24Request = Parameters[0] export type Endpoint5_24Input = { readonly sessionID: Endpoint5_24Request["params"]["sessionID"] - readonly after?: Endpoint5_24Request["query"]["after"] - readonly follow?: Endpoint5_24Request["query"]["follow"] + readonly key: Endpoint5_24Request["params"]["key"] } -export type Endpoint5_24Output = StreamValue>> -export type SessionLogOperation = (input: Endpoint5_24Input) => Stream.Stream +export type Endpoint5_24Output = EffectValue< + ReturnType +> +export type SessionInstructionsEntryRemoveOperation = ( + input: Endpoint5_24Input, +) => Effect.Effect -type Endpoint5_25Request = Parameters[0] -export type Endpoint5_25Input = { readonly sessionID: Endpoint5_25Request["params"]["sessionID"] } -export type Endpoint5_25Output = EffectValue> -export type SessionInterruptOperation = (input: Endpoint5_25Input) => Effect.Effect +type Endpoint5_25Request = Parameters[0] +export type Endpoint5_25Input = { + readonly sessionID: Endpoint5_25Request["params"]["sessionID"] + readonly after?: Endpoint5_25Request["query"]["after"] + readonly follow?: Endpoint5_25Request["query"]["follow"] +} +export type Endpoint5_25Output = StreamValue>> +export type SessionLogOperation = (input: Endpoint5_25Input) => Stream.Stream -type Endpoint5_26Request = Parameters[0] +type Endpoint5_26Request = Parameters[0] export type Endpoint5_26Input = { readonly sessionID: Endpoint5_26Request["params"]["sessionID"] } -export type Endpoint5_26Output = EffectValue> -export type SessionBackgroundOperation = (input: Endpoint5_26Input) => Effect.Effect +export type Endpoint5_26Output = EffectValue> +export type SessionInterruptOperation = (input: Endpoint5_26Input) => Effect.Effect -type Endpoint5_27Request = Parameters[0] -export type Endpoint5_27Input = { - readonly sessionID: Endpoint5_27Request["params"]["sessionID"] - readonly messageID: Endpoint5_27Request["params"]["messageID"] +type Endpoint5_27Request = Parameters[0] +export type Endpoint5_27Input = { readonly sessionID: Endpoint5_27Request["params"]["sessionID"] } +export type Endpoint5_27Output = EffectValue> +export type SessionBackgroundOperation = (input: Endpoint5_27Input) => Effect.Effect + +type Endpoint5_28Request = Parameters[0] +export type Endpoint5_28Input = { + readonly sessionID: Endpoint5_28Request["params"]["sessionID"] + readonly messageID: Endpoint5_28Request["params"]["messageID"] } -export type Endpoint5_27Output = EffectValue>["data"] -export type SessionMessageOperation = (input: Endpoint5_27Input) => Effect.Effect +export type Endpoint5_28Output = EffectValue>["data"] +export type SessionMessageOperation = (input: Endpoint5_28Input) => Effect.Effect export interface SessionApi { readonly list: SessionListOperation @@ -309,6 +314,7 @@ export interface SessionApi { readonly commit: SessionRevertCommitOperation } readonly context: SessionContextOperation + readonly pending: { readonly list: SessionPendingListOperation } readonly instructions: { readonly entry: { readonly list: SessionInstructionsEntryListOperation @@ -544,9 +550,7 @@ export type Endpoint14_2Input = { readonly id?: Endpoint14_2Request["payload"]["id"] readonly title: Endpoint14_2Request["payload"]["title"] readonly metadata?: Endpoint14_2Request["payload"]["metadata"] - readonly mode: Endpoint14_2Request["payload"]["mode"] - readonly fields?: Endpoint14_2Request["payload"]["fields"] - readonly url?: Endpoint14_2Request["payload"]["url"] + readonly fields: Endpoint14_2Request["payload"]["fields"] } export type Endpoint14_2Output = EffectValue>["data"] export type FormCreateOperation = (input: Endpoint14_2Input) => Effect.Effect diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index 3b39da28a0..7e14e5151f 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -318,43 +318,51 @@ const Endpoint5_20 = (raw: RawClient["server.session"]) => (input: Endpoint5_20I Effect.map((value) => value.data), ) -type Endpoint5_21Request = Parameters[0] +type Endpoint5_21Request = Parameters[0] type Endpoint5_21Input = { readonly sessionID: Endpoint5_21Request["params"]["sessionID"] } const Endpoint5_21 = (raw: RawClient["server.session"]) => (input: Endpoint5_21Input) => + raw["session.pending.list"]({ params: { sessionID: input["sessionID"] } }).pipe( + Effect.mapError(mapClientError), + Effect.map((value) => value.data), + ) + +type Endpoint5_22Request = Parameters[0] +type Endpoint5_22Input = { readonly sessionID: Endpoint5_22Request["params"]["sessionID"] } +const Endpoint5_22 = (raw: RawClient["server.session"]) => (input: Endpoint5_22Input) => raw["session.instructions.entry.list"]({ params: { sessionID: input["sessionID"] } }).pipe( Effect.mapError(mapClientError), Effect.map((value) => value.data), ) -type Endpoint5_22Request = Parameters[0] -type Endpoint5_22Input = { - readonly sessionID: Endpoint5_22Request["params"]["sessionID"] - readonly key: Endpoint5_22Request["params"]["key"] - readonly value: Endpoint5_22Request["payload"]["value"] +type Endpoint5_23Request = Parameters[0] +type Endpoint5_23Input = { + readonly sessionID: Endpoint5_23Request["params"]["sessionID"] + readonly key: Endpoint5_23Request["params"]["key"] + readonly value: Endpoint5_23Request["payload"]["value"] } -const Endpoint5_22 = (raw: RawClient["server.session"]) => (input: Endpoint5_22Input) => +const Endpoint5_23 = (raw: RawClient["server.session"]) => (input: Endpoint5_23Input) => raw["session.instructions.entry.put"]({ params: { sessionID: input["sessionID"], key: input["key"] }, payload: { value: input["value"] }, }).pipe(Effect.mapError(mapClientError)) -type Endpoint5_23Request = Parameters[0] -type Endpoint5_23Input = { - readonly sessionID: Endpoint5_23Request["params"]["sessionID"] - readonly key: Endpoint5_23Request["params"]["key"] +type Endpoint5_24Request = Parameters[0] +type Endpoint5_24Input = { + readonly sessionID: Endpoint5_24Request["params"]["sessionID"] + readonly key: Endpoint5_24Request["params"]["key"] } -const Endpoint5_23 = (raw: RawClient["server.session"]) => (input: Endpoint5_23Input) => +const Endpoint5_24 = (raw: RawClient["server.session"]) => (input: Endpoint5_24Input) => raw["session.instructions.entry.remove"]({ params: { sessionID: input["sessionID"], key: input["key"] } }).pipe( Effect.mapError(mapClientError), ) -type Endpoint5_24Request = Parameters[0] -type Endpoint5_24Input = { - readonly sessionID: Endpoint5_24Request["params"]["sessionID"] - readonly after?: Endpoint5_24Request["query"]["after"] - readonly follow?: Endpoint5_24Request["query"]["follow"] +type Endpoint5_25Request = Parameters[0] +type Endpoint5_25Input = { + readonly sessionID: Endpoint5_25Request["params"]["sessionID"] + readonly after?: Endpoint5_25Request["query"]["after"] + readonly follow?: Endpoint5_25Request["query"]["follow"] } -const Endpoint5_24 = (raw: RawClient["server.session"]) => (input: Endpoint5_24Input) => +const Endpoint5_25 = (raw: RawClient["server.session"]) => (input: Endpoint5_25Input) => Stream.unwrap( raw["session.log"]({ params: { sessionID: input["sessionID"] }, @@ -365,22 +373,22 @@ const Endpoint5_24 = (raw: RawClient["server.session"]) => (input: Endpoint5_24I ), ) -type Endpoint5_25Request = Parameters[0] -type Endpoint5_25Input = { readonly sessionID: Endpoint5_25Request["params"]["sessionID"] } -const Endpoint5_25 = (raw: RawClient["server.session"]) => (input: Endpoint5_25Input) => - raw["session.interrupt"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)) - -type Endpoint5_26Request = Parameters[0] +type Endpoint5_26Request = Parameters[0] type Endpoint5_26Input = { readonly sessionID: Endpoint5_26Request["params"]["sessionID"] } const Endpoint5_26 = (raw: RawClient["server.session"]) => (input: Endpoint5_26Input) => + raw["session.interrupt"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)) + +type Endpoint5_27Request = Parameters[0] +type Endpoint5_27Input = { readonly sessionID: Endpoint5_27Request["params"]["sessionID"] } +const Endpoint5_27 = (raw: RawClient["server.session"]) => (input: Endpoint5_27Input) => raw["session.background"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)) -type Endpoint5_27Request = Parameters[0] -type Endpoint5_27Input = { - readonly sessionID: Endpoint5_27Request["params"]["sessionID"] - readonly messageID: Endpoint5_27Request["params"]["messageID"] +type Endpoint5_28Request = Parameters[0] +type Endpoint5_28Input = { + readonly sessionID: Endpoint5_28Request["params"]["sessionID"] + readonly messageID: Endpoint5_28Request["params"]["messageID"] } -const Endpoint5_27 = (raw: RawClient["server.session"]) => (input: Endpoint5_27Input) => +const Endpoint5_28 = (raw: RawClient["server.session"]) => (input: Endpoint5_28Input) => raw["session.message"]({ params: { sessionID: input["sessionID"], messageID: input["messageID"] } }).pipe( Effect.mapError(mapClientError), Effect.map((value) => value.data), @@ -406,11 +414,12 @@ const adaptGroup5 = (raw: RawClient["server.session"]) => ({ wait: Endpoint5_16(raw), revert: { stage: Endpoint5_17(raw), clear: Endpoint5_18(raw), commit: Endpoint5_19(raw) }, context: Endpoint5_20(raw), - instructions: { entry: { list: Endpoint5_21(raw), put: Endpoint5_22(raw), remove: Endpoint5_23(raw) } }, - log: Endpoint5_24(raw), - interrupt: Endpoint5_25(raw), - background: Endpoint5_26(raw), - message: Endpoint5_27(raw), + pending: { list: Endpoint5_21(raw) }, + instructions: { entry: { list: Endpoint5_22(raw), put: Endpoint5_23(raw), remove: Endpoint5_24(raw) } }, + log: Endpoint5_25(raw), + interrupt: Endpoint5_26(raw), + background: Endpoint5_27(raw), + message: Endpoint5_28(raw), }) type Endpoint6_0Request = Parameters[0] @@ -646,21 +655,12 @@ type Endpoint14_2Input = { readonly id?: Endpoint14_2Request["payload"]["id"] readonly title: Endpoint14_2Request["payload"]["title"] readonly metadata?: Endpoint14_2Request["payload"]["metadata"] - readonly mode: Endpoint14_2Request["payload"]["mode"] - readonly fields?: Endpoint14_2Request["payload"]["fields"] - readonly url?: Endpoint14_2Request["payload"]["url"] + readonly fields: Endpoint14_2Request["payload"]["fields"] } const Endpoint14_2 = (raw: RawClient["server.form"]) => (input: Endpoint14_2Input) => raw["session.form.create"]({ params: { sessionID: input["sessionID"] }, - payload: { - id: input["id"], - title: input["title"], - metadata: input["metadata"], - mode: input["mode"], - fields: input["fields"], - url: input["url"], - }, + payload: { id: input["id"], title: input["title"], metadata: input["metadata"], fields: input["fields"] }, }).pipe( Effect.mapError(mapClientError), Effect.map((value) => value.data), diff --git a/packages/client/src/effect/index.ts b/packages/client/src/effect/index.ts index 3e47320953..67c2c42142 100644 --- a/packages/client/src/effect/index.ts +++ b/packages/client/src/effect/index.ts @@ -38,7 +38,7 @@ export { Question } from "@opencode-ai/schema/question" export { Reference } from "@opencode-ai/schema/reference" export { AbsolutePath, RelativePath } from "@opencode-ai/schema/schema" export { Session } from "@opencode-ai/schema/session" -export { SessionInput } from "@opencode-ai/schema/session-input" +export { SessionPending } from "@opencode-ai/schema/session-pending" export { SessionMessage } from "@opencode-ai/schema/session-message" export { Skill } from "@opencode-ai/schema/skill" export { Prompt } from "@opencode-ai/schema/prompt" diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index 606673944c..28c223e6b5 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -48,6 +48,8 @@ import type { SessionRevertCommitOutput, SessionContextInput, SessionContextOutput, + SessionPendingListInput, + SessionPendingListOutput, SessionInstructionsEntryListInput, SessionInstructionsEntryListOutput, SessionInstructionsEntryPutInput, @@ -666,6 +668,19 @@ export function make(options: ClientOptions) { }, requestOptions, ).then((value) => value.data), + pending: { + list: (input: SessionPendingListInput, requestOptions?: RequestOptions) => + request<{ readonly data: SessionPendingListOutput }>( + { + method: "GET", + path: `/api/session/${encodeURIComponent(input.sessionID)}/pending`, + successStatus: 200, + declaredStatuses: [404, 400, 401], + empty: false, + }, + requestOptions, + ).then((value) => value.data), + }, instructions: { entry: { list: (input: SessionInstructionsEntryListInput, requestOptions?: RequestOptions) => @@ -686,7 +701,7 @@ export function make(options: ClientOptions) { path: `/api/session/${encodeURIComponent(input.sessionID)}/instructions/entries/${encodeURIComponent(input.key)}`, body: { value: input["value"] }, successStatus: 204, - declaredStatuses: [404, 400, 401], + declaredStatuses: [404, 413, 400, 401], empty: true, }, requestOptions, @@ -1041,14 +1056,7 @@ export function make(options: ClientOptions) { { method: "POST", path: `/api/session/${encodeURIComponent(input.sessionID)}/form`, - body: { - id: input["id"], - title: input["title"], - metadata: input["metadata"], - mode: input["mode"], - fields: input["fields"], - url: input["url"], - }, + body: { id: input["id"], title: input["title"], metadata: input["metadata"], fields: input["fields"] }, successStatus: 200, declaredStatuses: [404, 409, 400, 401], empty: false, diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index c61fdb5eea..c6a703c5fa 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -1,12 +1,4 @@ -import type { OpenCodeEventEncoded } from "@opencode-ai/protocol/groups/event" - -export type JsonValue = - | null - | boolean - | number - | string - | ReadonlyArray - | { readonly [key: string]: JsonValue } +export type JsonValue = null | boolean | number | string | Array | { [key: string]: JsonValue } export type UnauthorizedError = { readonly _tag: "UnauthorizedError"; readonly message: string } export const isUnauthorizedError = (value: unknown): value is UnauthorizedError => @@ -98,6 +90,18 @@ export type UnknownError = { export const isUnknownError = (value: unknown): value is UnknownError => typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "UnknownError" +export type InstructionEntryValueTooLargeError = { + readonly _tag: "InstructionEntryValueTooLargeError" + readonly actualBytes: number + readonly maxBytes: number + readonly message: string +} +export const isInstructionEntryValueTooLargeError = (value: unknown): value is InstructionEntryValueTooLargeError => + typeof value === "object" && + value !== null && + "_tag" in value && + value["_tag"] === "InstructionEntryValueTooLargeError" + export type ProviderNotFoundError = { readonly _tag: "ProviderNotFoundError" readonly providerID: string @@ -157,9 +161,9 @@ export type ProjectCopyError = { export const isProjectCopyError = (value: unknown): value is ProjectCopyError => typeof value === "object" && value !== null && "name" in value && value["name"] === "ProjectCopyError" -export type HealthGetOutput = { readonly healthy: true; readonly version: string; readonly pid: number } +export type HealthGetOutput = { healthy: true; version: string; pid: number } -export type ServerGetOutput = { readonly urls: ReadonlyArray } +export type ServerGetOutput = { urls: Array } export type LocationGetInput = { readonly location?: { @@ -167,11 +171,7 @@ export type LocationGetInput = { }["location"] } -export type LocationGetOutput = { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } -} +export type LocationGetOutput = { directory: string; workspaceID?: string; project: { id: string; directory: string } } export type AgentListInput = { readonly location?: { @@ -180,31 +180,23 @@ export type AgentListInput = { } export type AgentListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly id: string - readonly name: string - readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly request: { - readonly settings: { readonly [x: string]: JsonValue } - readonly headers: { readonly [x: string]: string } - readonly body: { readonly [x: string]: JsonValue } + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + id: string + name: string + model?: { id: string; providerID: string; variant?: string } + request: { + settings: { [x: string]: JsonValue } + headers: { [x: string]: string } + body: { [x: string]: JsonValue } } - readonly system?: string - readonly description?: string - readonly mode: "subagent" | "primary" | "all" - readonly hidden: boolean - readonly color?: string | "primary" | "secondary" | "accent" | "success" | "warning" | "error" | "info" - readonly steps?: number - readonly permissions: ReadonlyArray<{ - readonly action: string - readonly resource: string - readonly effect: "allow" | "deny" | "ask" - }> + system?: string + description?: string + mode: "subagent" | "primary" | "all" + hidden: boolean + color?: string | "primary" | "secondary" | "accent" | "success" | "warning" | "error" | "info" + steps?: number + permissions: Array<{ action: string; resource: string; effect: "allow" | "deny" | "ask" }> }> } @@ -215,12 +207,8 @@ export type PluginListInput = { } export type PluginListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ readonly id: string }> + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ id: string }> } export type SessionListInput = { @@ -326,38 +314,33 @@ export type SessionListInput = { } export type SessionListOutput = { - readonly data: ReadonlyArray<{ - readonly id: string - readonly parentID?: string - readonly fork?: { readonly sessionID: string; readonly messageID?: string } - readonly projectID: string - readonly agent?: string - readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly cost: number - readonly tokens: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } - readonly time: { readonly created: number; readonly updated: number; readonly archived?: number } - readonly title: string - readonly location: { readonly directory: string; readonly workspaceID?: string } - readonly subpath?: string - readonly revert?: { - readonly messageID: string - readonly partID?: string - readonly snapshot?: string - readonly files?: ReadonlyArray<{ - readonly file: string - readonly patch: string - readonly additions: number - readonly deletions: number - readonly status: "added" | "deleted" | "modified" + data: Array<{ + id: string + parentID?: string + fork?: { sessionID: string; messageID?: string } + projectID: string + agent?: string + model?: { id: string; providerID: string; variant?: string } + cost: number + tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } + time: { created: number; updated: number; archived?: number } + title: string + location: { directory: string; workspaceID?: string } + subpath?: string + revert?: { + messageID: string + partID?: string + snapshot?: string + files?: Array<{ + file: string + patch: string + additions: number + deletions: number + status: "added" | "deleted" | "modified" }> } }> - readonly cursor: { readonly previous?: string | null; readonly next?: string | null } + cursor: { previous?: string | null; next?: string | null } } export type SessionCreateInput = { @@ -388,72 +371,62 @@ export type SessionCreateInput = { } export type SessionCreateOutput = { - readonly data: { - readonly id: string - readonly parentID?: string - readonly fork?: { readonly sessionID: string; readonly messageID?: string } - readonly projectID: string - readonly agent?: string - readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly cost: number - readonly tokens: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } - readonly time: { readonly created: number; readonly updated: number; readonly archived?: number } - readonly title: string - readonly location: { readonly directory: string; readonly workspaceID?: string } - readonly subpath?: string - readonly revert?: { - readonly messageID: string - readonly partID?: string - readonly snapshot?: string - readonly files?: ReadonlyArray<{ - readonly file: string - readonly patch: string - readonly additions: number - readonly deletions: number - readonly status: "added" | "deleted" | "modified" + data: { + id: string + parentID?: string + fork?: { sessionID: string; messageID?: string } + projectID: string + agent?: string + model?: { id: string; providerID: string; variant?: string } + cost: number + tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } + time: { created: number; updated: number; archived?: number } + title: string + location: { directory: string; workspaceID?: string } + subpath?: string + revert?: { + messageID: string + partID?: string + snapshot?: string + files?: Array<{ + file: string + patch: string + additions: number + deletions: number + status: "added" | "deleted" | "modified" }> } } }["data"] -export type SessionActiveOutput = { readonly data: { readonly [x: string]: { readonly type: "running" } } }["data"] +export type SessionActiveOutput = { data: { [x: string]: { type: "running" } } }["data"] export type SessionGetInput = { readonly sessionID: { readonly sessionID: string }["sessionID"] } export type SessionGetOutput = { - readonly data: { - readonly id: string - readonly parentID?: string - readonly fork?: { readonly sessionID: string; readonly messageID?: string } - readonly projectID: string - readonly agent?: string - readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly cost: number - readonly tokens: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } - readonly time: { readonly created: number; readonly updated: number; readonly archived?: number } - readonly title: string - readonly location: { readonly directory: string; readonly workspaceID?: string } - readonly subpath?: string - readonly revert?: { - readonly messageID: string - readonly partID?: string - readonly snapshot?: string - readonly files?: ReadonlyArray<{ - readonly file: string - readonly patch: string - readonly additions: number - readonly deletions: number - readonly status: "added" | "deleted" | "modified" + data: { + id: string + parentID?: string + fork?: { sessionID: string; messageID?: string } + projectID: string + agent?: string + model?: { id: string; providerID: string; variant?: string } + cost: number + tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } + time: { created: number; updated: number; archived?: number } + title: string + location: { directory: string; workspaceID?: string } + subpath?: string + revert?: { + messageID: string + partID?: string + snapshot?: string + files?: Array<{ + file: string + patch: string + additions: number + deletions: number + status: "added" | "deleted" | "modified" }> } } @@ -469,34 +442,29 @@ export type SessionForkInput = { } export type SessionForkOutput = { - readonly data: { - readonly id: string - readonly parentID?: string - readonly fork?: { readonly sessionID: string; readonly messageID?: string } - readonly projectID: string - readonly agent?: string - readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly cost: number - readonly tokens: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } - readonly time: { readonly created: number; readonly updated: number; readonly archived?: number } - readonly title: string - readonly location: { readonly directory: string; readonly workspaceID?: string } - readonly subpath?: string - readonly revert?: { - readonly messageID: string - readonly partID?: string - readonly snapshot?: string - readonly files?: ReadonlyArray<{ - readonly file: string - readonly patch: string - readonly additions: number - readonly deletions: number - readonly status: "added" | "deleted" | "modified" + data: { + id: string + parentID?: string + fork?: { sessionID: string; messageID?: string } + projectID: string + agent?: string + model?: { id: string; providerID: string; variant?: string } + cost: number + tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } + time: { created: number; updated: number; archived?: number } + title: string + location: { directory: string; workspaceID?: string } + subpath?: string + revert?: { + messageID: string + partID?: string + snapshot?: string + files?: Array<{ + file: string + patch: string + additions: number + deletions: number + status: "added" | "deleted" | "modified" }> } } @@ -663,30 +631,26 @@ export type SessionPromptInput = { } export type SessionPromptOutput = { - readonly data: { - readonly admittedSeq: number - readonly id: string - readonly sessionID: string - readonly timeCreated: number - readonly promotedSeq?: number - readonly type: "user" - readonly data: { - readonly text: string - readonly files?: ReadonlyArray<{ - readonly data: string - readonly mime: string - readonly source: { readonly type: "inline" } | { readonly type: "uri"; readonly uri: string } - readonly name?: string - readonly description?: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } + data: { + admittedSeq: number + id: string + sessionID: string + timeCreated: number + type: "user" + data: { + text: string + files?: Array<{ + data: string + mime: string + source: { type: "inline" } | { type: "uri"; uri: string } + name?: string + description?: string + mention?: { start: number; end: number; text: string } }> - readonly agents?: ReadonlyArray<{ - readonly name: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } - }> - readonly metadata?: { readonly [x: string]: JsonValue } + agents?: Array<{ name: string; mention?: { start: number; end: number; text: string } }> + metadata?: { [x: string]: JsonValue } } - readonly delivery: "steer" | "queue" + delivery: "steer" | "queue" } }["data"] @@ -866,30 +830,26 @@ export type SessionCommandInput = { } export type SessionCommandOutput = { - readonly data: { - readonly admittedSeq: number - readonly id: string - readonly sessionID: string - readonly timeCreated: number - readonly promotedSeq?: number - readonly type: "user" - readonly data: { - readonly text: string - readonly files?: ReadonlyArray<{ - readonly data: string - readonly mime: string - readonly source: { readonly type: "inline" } | { readonly type: "uri"; readonly uri: string } - readonly name?: string - readonly description?: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } + data: { + admittedSeq: number + id: string + sessionID: string + timeCreated: number + type: "user" + data: { + text: string + files?: Array<{ + data: string + mime: string + source: { type: "inline" } | { type: "uri"; uri: string } + name?: string + description?: string + mention?: { start: number; end: number; text: string } }> - readonly agents?: ReadonlyArray<{ - readonly name: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } - }> - readonly metadata?: { readonly [x: string]: JsonValue } + agents?: Array<{ name: string; mention?: { start: number; end: number; text: string } }> + metadata?: { [x: string]: JsonValue } } - readonly delivery: "steer" | "queue" + delivery: "steer" | "queue" } }["data"] @@ -967,19 +927,14 @@ export type SessionSyntheticInput = { } export type SessionSyntheticOutput = { - readonly data: { - readonly admittedSeq: number - readonly id: string - readonly sessionID: string - readonly timeCreated: number - readonly promotedSeq?: number - readonly type: "synthetic" - readonly data: { - readonly text: string - readonly description?: string - readonly metadata?: { readonly [x: string]: JsonValue } - } - readonly delivery: "steer" | "queue" + data: { + admittedSeq: number + id: string + sessionID: string + timeCreated: number + type: "synthetic" + data: { text: string; description?: string; metadata?: { [x: string]: JsonValue } } + delivery: "steer" | "queue" } }["data"] @@ -997,14 +952,7 @@ export type SessionCompactInput = { } export type SessionCompactOutput = { - readonly data: { - readonly admittedSeq: number - readonly id: string - readonly sessionID: string - readonly timeCreated: number - readonly type: "compaction" - readonly handledSeq?: number - } + data: { admittedSeq: number; id: string; sessionID: string; timeCreated: number; type: "compaction" } }["data"] export type SessionWaitInput = { readonly sessionID: { readonly sessionID: string }["sessionID"] } @@ -1018,16 +966,16 @@ export type SessionRevertStageInput = { } export type SessionRevertStageOutput = { - readonly data: { - readonly messageID: string - readonly partID?: string - readonly snapshot?: string - readonly files?: ReadonlyArray<{ - readonly file: string - readonly patch: string - readonly additions: number - readonly deletions: number - readonly status: "added" | "deleted" | "modified" + data: { + messageID: string + partID?: string + snapshot?: string + files?: Array<{ + file: string + patch: string + additions: number + deletions: number + status: "added" | "deleted" | "modified" }> } }["data"] @@ -1043,193 +991,203 @@ export type SessionRevertCommitOutput = void export type SessionContextInput = { readonly sessionID: { readonly sessionID: string }["sessionID"] } export type SessionContextOutput = { - readonly data: ReadonlyArray< + data: Array< | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly type: "agent-switched" - readonly agent: string + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + type: "agent-switched" + agent: string } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly type: "model-switched" - readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly previous?: { readonly id: string; readonly providerID: string; readonly variant?: string } + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + type: "model-switched" + model: { id: string; providerID: string; variant?: string } + previous?: { id: string; providerID: string; variant?: string } } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly text: string - readonly files?: ReadonlyArray<{ - readonly data: string - readonly mime: string - readonly source: { readonly type: "inline" } | { readonly type: "uri"; readonly uri: string } - readonly name?: string - readonly description?: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + text: string + files?: Array<{ + data: string + mime: string + source: { type: "inline" } | { type: "uri"; uri: string } + name?: string + description?: string + mention?: { start: number; end: number; text: string } }> - readonly agents?: ReadonlyArray<{ - readonly name: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } - }> - readonly type: "user" + agents?: Array<{ name: string; mention?: { start: number; end: number; text: string } }> + type: "user" } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly text: string - readonly description?: string - readonly type: "synthetic" + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + text: string + description?: string + type: "synthetic" + } + | { id: string; metadata?: { [x: string]: JsonValue }; time: { created: number }; type: "system"; text: string } + | { + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + type: "skill" + skill: string + name: string + text: string } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly type: "system" - readonly text: string + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number; completed?: number } + type: "shell" + shellID: string + command: string + status: "running" | "exited" | "timeout" | "killed" + exit?: number | "Infinity" | "-Infinity" | "NaN" + output?: { output: string; cursor: number; size: number; truncated: boolean } } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly type: "skill" - readonly skill: string - readonly name: string - readonly text: string - } - | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number; readonly completed?: number } - readonly type: "shell" - readonly shellID: string - readonly command: string - readonly status: "running" | "exited" | "timeout" | "killed" - readonly exit?: number | "Infinity" | "-Infinity" | "NaN" - readonly output?: { - readonly output: string - readonly cursor: number - readonly size: number - readonly truncated: boolean - } - } - | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number; readonly completed?: number } - readonly type: "assistant" - readonly agent: string - readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number; completed?: number } + type: "assistant" + agent: string + model: { id: string; providerID: string; variant?: string } + content: Array< + | { type: "text"; text: string } | { - readonly type: "reasoning" - readonly text: string - readonly state?: { readonly [x: string]: JsonValue } - readonly time?: { readonly created: number; readonly completed?: number } + type: "reasoning" + text: string + state?: { [x: string]: JsonValue } + time?: { created: number; completed?: number } } | { - readonly type: "tool" - readonly id: string - readonly name: string - readonly executed?: boolean - readonly providerState?: { readonly [x: string]: JsonValue } - readonly providerResultState?: { readonly [x: string]: JsonValue } - readonly state: - | { readonly status: "streaming"; readonly input: string } + type: "tool" + id: string + name: string + executed?: boolean + providerState?: { [x: string]: JsonValue } + providerResultState?: { [x: string]: JsonValue } + state: + | { status: "streaming"; input: string } | { - readonly status: "running" - readonly input: { readonly [x: string]: JsonValue } - readonly structured: { readonly [x: string]: JsonValue } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } - | { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string } + status: "running" + input: { [x: string]: JsonValue } + structured: { [x: string]: JsonValue } + content: Array< + { type: "text"; text: string } | { type: "file"; uri: string; mime: string; name?: string } > } | { - readonly status: "completed" - readonly input: { readonly [x: string]: JsonValue } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } - | { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string } + status: "completed" + input: { [x: string]: JsonValue } + content: Array< + { type: "text"; text: string } | { type: "file"; uri: string; mime: string; name?: string } > - readonly structured: { readonly [x: string]: JsonValue } - readonly result?: JsonValue + structured: { [x: string]: JsonValue } + result?: JsonValue } | { - readonly status: "error" - readonly input: { readonly [x: string]: JsonValue } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } - | { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string } + status: "error" + input: { [x: string]: JsonValue } + content: Array< + { type: "text"; text: string } | { type: "file"; uri: string; mime: string; name?: string } > - readonly structured: { readonly [x: string]: JsonValue } - readonly error: { readonly type: string; readonly message: string } - readonly result?: JsonValue + structured: { [x: string]: JsonValue } + error: { type: string; message: string } + result?: JsonValue } - readonly time: { readonly created: number; readonly ran?: number; readonly completed?: number } + time: { created: number; ran?: number; completed?: number } } > - readonly snapshot?: { readonly start?: string; readonly end?: string; readonly files?: ReadonlyArray } - readonly finish?: "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown" - readonly cost?: number - readonly tokens?: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } - readonly error?: { readonly type: string; readonly message: string } - readonly retry?: { - readonly attempt: number - readonly at: number - readonly error: { readonly type: string; readonly message: string } - } + snapshot?: { start?: string; end?: string; files?: Array } + finish?: "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown" + cost?: number + tokens?: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } + error?: { type: string; message: string } + retry?: { attempt: number; at: number; error: { type: string; message: string } } } | ( | { - readonly type: "compaction" - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly status: "running" - readonly reason: "auto" | "manual" - readonly summary: string - readonly recent: string + type: "compaction" + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + status: "running" + reason: "auto" | "manual" + summary: string + recent: string } | { - readonly type: "compaction" - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly status: "completed" - readonly reason: "auto" | "manual" - readonly summary: string - readonly recent: string + type: "compaction" + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + status: "completed" + reason: "auto" | "manual" + summary: string + recent: string } | { - readonly type: "compaction" - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly status: "failed" - readonly reason: "auto" | "manual" - readonly error: { readonly type: string; readonly message: string } + type: "compaction" + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + status: "failed" + reason: "auto" | "manual" + error: { type: string; message: string } } ) > }["data"] +export type SessionPendingListInput = { readonly sessionID: { readonly sessionID: string }["sessionID"] } + +export type SessionPendingListOutput = { + data: Array< + | { + admittedSeq: number + id: string + sessionID: string + timeCreated: number + type: "user" + data: { + text: string + files?: Array<{ + data: string + mime: string + source: { type: "inline" } | { type: "uri"; uri: string } + name?: string + description?: string + mention?: { start: number; end: number; text: string } + }> + agents?: Array<{ name: string; mention?: { start: number; end: number; text: string } }> + metadata?: { [x: string]: JsonValue } + } + delivery: "steer" | "queue" + } + | { + admittedSeq: number + id: string + sessionID: string + timeCreated: number + type: "synthetic" + data: { text: string; description?: string; metadata?: { [x: string]: JsonValue } } + delivery: "steer" | "queue" + } + | { admittedSeq: number; id: string; sessionID: string; timeCreated: number; type: "compaction" } + > +}["data"] + export type SessionInstructionsEntryListInput = { readonly sessionID: { readonly sessionID: string }["sessionID"] } -export type SessionInstructionsEntryListOutput = { - readonly data: ReadonlyArray<{ readonly key: string; readonly value: JsonValue }> -}["data"] +export type SessionInstructionsEntryListOutput = { data: Array<{ key: string; value: JsonValue }> }["data"] export type SessionInstructionsEntryPutInput = { readonly sessionID: { readonly sessionID: string; readonly key: string }["sessionID"] @@ -1255,563 +1213,485 @@ export type SessionLogInput = { export type SessionLogOutput = | ( | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.agent.selected" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly agent: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.agent.selected" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; agent: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.model.selected" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.model.selected" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; model: { id: string; providerID: string; variant?: string } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.moved" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly location: { readonly directory: string; readonly workspaceID?: string } - readonly subpath?: string - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.moved" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; location: { directory: string; workspaceID?: string }; subpath?: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.renamed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly title: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.renamed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; title: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.deleted" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 2 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.deleted" + durable: { aggregateID: string; seq: number; version: 2 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.forked" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly parentID: string; readonly from?: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.forked" + durable: { aggregateID: string; seq: number; version: 2 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; parentID: string; parentSeq: number; from?: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.input.promoted" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly inputID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.input.promoted" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; inputID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.input.admitted" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly inputID: string - readonly input: + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.input.admitted" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + inputID: string + input: | { - readonly type: "user" - readonly data: { - readonly text: string - readonly files?: ReadonlyArray<{ - readonly data: string - readonly mime: string - readonly source: { readonly type: "inline" } | { readonly type: "uri"; readonly uri: string } - readonly name?: string - readonly description?: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } + type: "user" + data: { + text: string + files?: Array<{ + data: string + mime: string + source: { type: "inline" } | { type: "uri"; uri: string } + name?: string + description?: string + mention?: { start: number; end: number; text: string } }> - readonly agents?: ReadonlyArray<{ - readonly name: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } - }> - readonly metadata?: { readonly [x: string]: unknown } + agents?: Array<{ name: string; mention?: { start: number; end: number; text: string } }> + metadata?: { [x: string]: unknown } } - readonly delivery: "steer" | "queue" + delivery: "steer" | "queue" } | { - readonly type: "synthetic" - readonly data: { - readonly text: string - readonly description?: string - readonly metadata?: { readonly [x: string]: unknown } - } - readonly delivery: "steer" | "queue" + type: "synthetic" + data: { text: string; description?: string; metadata?: { [x: string]: unknown } } + delivery: "steer" | "queue" } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.execution.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.execution.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.execution.succeeded" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.execution.succeeded" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.execution.failed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly error: { readonly type: string; readonly message: string } - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.execution.failed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; error: { type: string; message: string } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.execution.interrupted" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly reason: "user" | "shutdown" | "superseded" } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.execution.interrupted" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; reason: "user" | "shutdown" | "superseded" } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.instructions.updated" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly text: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.instructions.updated" + durable: { aggregateID: string; seq: number; version: 2 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; delta: { [x: string]: string | "removed" } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.synthetic" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly text: string - readonly description?: string - readonly metadata?: { readonly [x: string]: unknown } - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.synthetic" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; text: string; description?: string; metadata?: { [x: string]: unknown } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.skill.activated" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly id: string - readonly name: string - readonly text: string - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.skill.activated" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; id: string; name: string; text: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.shell.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly shell: { - readonly id: string - readonly status: "running" | "exited" | "timeout" | "killed" - readonly command: string - readonly cwd: string - readonly shell: string - readonly file: string - readonly pid?: number - readonly exit?: number - readonly metadata: { readonly [x: string]: unknown } - readonly time: { readonly started: number; readonly completed?: number } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.shell.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + shell: { + id: string + status: "running" | "exited" | "timeout" | "killed" + command: string + cwd: string + shell: string + file: string + pid?: number + exit?: number + metadata: { [x: string]: unknown } + time: { started: number; completed?: number } } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.shell.ended" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly shell: { - readonly id: string - readonly status: "running" | "exited" | "timeout" | "killed" - readonly command: string - readonly cwd: string - readonly shell: string - readonly file: string - readonly pid?: number - readonly exit?: number - readonly metadata: { readonly [x: string]: unknown } - readonly time: { readonly started: number; readonly completed?: number } - } - readonly output: { - readonly output: string - readonly cursor: number - readonly size: number - readonly truncated: boolean + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.shell.ended" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + shell: { + id: string + status: "running" | "exited" | "timeout" | "killed" + command: string + cwd: string + shell: string + file: string + pid?: number + exit?: number + metadata: { [x: string]: unknown } + time: { started: number; completed?: number } } + output: { output: string; cursor: number; size: number; truncated: boolean } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.step.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly agent: string - readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly snapshot?: string + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.step.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + agent: string + model: { id: string; providerID: string; variant?: string } + snapshot?: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.step.ended" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly finish: "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown" - readonly cost: number - readonly tokens: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } - readonly snapshot?: string - readonly files?: ReadonlyArray + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.step.ended" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + finish: "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown" + cost: number + tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } + snapshot?: string + files?: Array } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.step.failed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly error: { readonly type: string; readonly message: string } - readonly cost?: number - readonly tokens?: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.step.failed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + error: { type: string; message: string } + cost?: number + tokens?: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.text.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly assistantMessageID: string; readonly ordinal: number } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.text.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; assistantMessageID: string; ordinal: number } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.text.ended" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly ordinal: number - readonly text: string + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.text.ended" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; assistantMessageID: string; ordinal: number; text: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.reasoning.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; assistantMessageID: string; ordinal: number; state?: { [x: string]: unknown } } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.reasoning.ended" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + ordinal: number + text: string + state?: { [x: string]: unknown } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.reasoning.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly ordinal: number - readonly state?: { readonly [x: string]: unknown } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.tool.input.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; assistantMessageID: string; callID: string; name: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.tool.input.ended" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; assistantMessageID: string; callID: string; text: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.tool.called" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + callID: string + input: { [x: string]: unknown } + executed: boolean + state?: { [x: string]: unknown } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.reasoning.ended" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly ordinal: number - readonly text: string - readonly state?: { readonly [x: string]: unknown } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.tool.progress" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + callID: string + structured: { [x: string]: unknown } + content: Array<{ type: "text"; text: string } | { type: "file"; uri: string; mime: string; name?: string }> } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.tool.input.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly callID: string - readonly name: string + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.tool.success" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + callID: string + structured: { [x: string]: unknown } + content: Array<{ type: "text"; text: string } | { type: "file"; uri: string; mime: string; name?: string }> + result?: unknown + executed: boolean + resultState?: { [x: string]: unknown } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.tool.input.ended" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly callID: string - readonly text: string + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.tool.failed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + callID: string + error: { type: string; message: string } + result?: unknown + executed: boolean + resultState?: { [x: string]: unknown } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.tool.called" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly callID: string - readonly input: { readonly [x: string]: unknown } - readonly executed: boolean - readonly state?: { readonly [x: string]: unknown } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.retry.scheduled" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + attempt: number + at: number + error: { type: string; message: string } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.tool.progress" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly callID: string - readonly structured: { readonly [x: string]: unknown } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } - | { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string } - > + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.compaction.admitted" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; inputID: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.compaction.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; reason: "auto" | "manual"; recent: string; inputID?: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.compaction.ended" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; reason: "auto" | "manual"; text: string; recent: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.compaction.failed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + reason: "auto" | "manual" + error: { type: string; message: string } + inputID?: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.tool.success" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly callID: string - readonly structured: { readonly [x: string]: unknown } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } - | { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string } - > - readonly result?: unknown - readonly executed: boolean - readonly resultState?: { readonly [x: string]: unknown } - } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.tool.failed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly callID: string - readonly error: { readonly type: string; readonly message: string } - readonly result?: unknown - readonly executed: boolean - readonly resultState?: { readonly [x: string]: unknown } - } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.retry.scheduled" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly attempt: number - readonly at: number - readonly error: { readonly type: string; readonly message: string } - } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.compaction.admitted" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly inputID: string } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.compaction.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly reason: "auto" | "manual" - readonly recent: string - readonly inputID?: string - } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.compaction.ended" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly reason: "auto" | "manual" - readonly text: string - readonly recent: string - } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.compaction.failed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly reason: "auto" | "manual" - readonly error: { readonly type: string; readonly message: string } - readonly inputID?: string - } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.revert.staged" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly revert: { - readonly messageID: string - readonly partID?: string - readonly snapshot?: string - readonly files?: ReadonlyArray<{ - readonly file: string - readonly patch: string - readonly additions: number - readonly deletions: number - readonly status: "added" | "deleted" | "modified" + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.revert.staged" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + revert: { + messageID: string + partID?: string + snapshot?: string + files?: Array<{ + file: string + patch: string + additions: number + deletions: number + status: "added" | "deleted" | "modified" }> } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.revert.cleared" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.revert.cleared" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.revert.committed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly to: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.revert.committed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; to: string } } ) - | { readonly type: "log.synced"; readonly aggregateID: string; readonly seq?: number } + | { type: "log.synced"; aggregateID: string; seq?: number } export type SessionInterruptInput = { readonly sessionID: { readonly sessionID: string }["sessionID"] } @@ -1827,183 +1707,157 @@ export type SessionMessageInput = { } export type SessionMessageOutput = { - readonly data: + data: | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly type: "agent-switched" - readonly agent: string + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + type: "agent-switched" + agent: string } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly type: "model-switched" - readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly previous?: { readonly id: string; readonly providerID: string; readonly variant?: string } + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + type: "model-switched" + model: { id: string; providerID: string; variant?: string } + previous?: { id: string; providerID: string; variant?: string } } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly text: string - readonly files?: ReadonlyArray<{ - readonly data: string - readonly mime: string - readonly source: { readonly type: "inline" } | { readonly type: "uri"; readonly uri: string } - readonly name?: string - readonly description?: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + text: string + files?: Array<{ + data: string + mime: string + source: { type: "inline" } | { type: "uri"; uri: string } + name?: string + description?: string + mention?: { start: number; end: number; text: string } }> - readonly agents?: ReadonlyArray<{ - readonly name: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } - }> - readonly type: "user" + agents?: Array<{ name: string; mention?: { start: number; end: number; text: string } }> + type: "user" } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly text: string - readonly description?: string - readonly type: "synthetic" + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + text: string + description?: string + type: "synthetic" + } + | { id: string; metadata?: { [x: string]: JsonValue }; time: { created: number }; type: "system"; text: string } + | { + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + type: "skill" + skill: string + name: string + text: string } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly type: "system" - readonly text: string + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number; completed?: number } + type: "shell" + shellID: string + command: string + status: "running" | "exited" | "timeout" | "killed" + exit?: number | "Infinity" | "-Infinity" | "NaN" + output?: { output: string; cursor: number; size: number; truncated: boolean } } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly type: "skill" - readonly skill: string - readonly name: string - readonly text: string - } - | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number; readonly completed?: number } - readonly type: "shell" - readonly shellID: string - readonly command: string - readonly status: "running" | "exited" | "timeout" | "killed" - readonly exit?: number | "Infinity" | "-Infinity" | "NaN" - readonly output?: { - readonly output: string - readonly cursor: number - readonly size: number - readonly truncated: boolean - } - } - | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number; readonly completed?: number } - readonly type: "assistant" - readonly agent: string - readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number; completed?: number } + type: "assistant" + agent: string + model: { id: string; providerID: string; variant?: string } + content: Array< + | { type: "text"; text: string } | { - readonly type: "reasoning" - readonly text: string - readonly state?: { readonly [x: string]: JsonValue } - readonly time?: { readonly created: number; readonly completed?: number } + type: "reasoning" + text: string + state?: { [x: string]: JsonValue } + time?: { created: number; completed?: number } } | { - readonly type: "tool" - readonly id: string - readonly name: string - readonly executed?: boolean - readonly providerState?: { readonly [x: string]: JsonValue } - readonly providerResultState?: { readonly [x: string]: JsonValue } - readonly state: - | { readonly status: "streaming"; readonly input: string } + type: "tool" + id: string + name: string + executed?: boolean + providerState?: { [x: string]: JsonValue } + providerResultState?: { [x: string]: JsonValue } + state: + | { status: "streaming"; input: string } | { - readonly status: "running" - readonly input: { readonly [x: string]: JsonValue } - readonly structured: { readonly [x: string]: JsonValue } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } - | { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string } + status: "running" + input: { [x: string]: JsonValue } + structured: { [x: string]: JsonValue } + content: Array< + { type: "text"; text: string } | { type: "file"; uri: string; mime: string; name?: string } > } | { - readonly status: "completed" - readonly input: { readonly [x: string]: JsonValue } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } - | { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string } + status: "completed" + input: { [x: string]: JsonValue } + content: Array< + { type: "text"; text: string } | { type: "file"; uri: string; mime: string; name?: string } > - readonly structured: { readonly [x: string]: JsonValue } - readonly result?: JsonValue + structured: { [x: string]: JsonValue } + result?: JsonValue } | { - readonly status: "error" - readonly input: { readonly [x: string]: JsonValue } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } - | { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string } + status: "error" + input: { [x: string]: JsonValue } + content: Array< + { type: "text"; text: string } | { type: "file"; uri: string; mime: string; name?: string } > - readonly structured: { readonly [x: string]: JsonValue } - readonly error: { readonly type: string; readonly message: string } - readonly result?: JsonValue + structured: { [x: string]: JsonValue } + error: { type: string; message: string } + result?: JsonValue } - readonly time: { readonly created: number; readonly ran?: number; readonly completed?: number } + time: { created: number; ran?: number; completed?: number } } > - readonly snapshot?: { readonly start?: string; readonly end?: string; readonly files?: ReadonlyArray } - readonly finish?: "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown" - readonly cost?: number - readonly tokens?: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } - readonly error?: { readonly type: string; readonly message: string } - readonly retry?: { - readonly attempt: number - readonly at: number - readonly error: { readonly type: string; readonly message: string } - } + snapshot?: { start?: string; end?: string; files?: Array } + finish?: "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown" + cost?: number + tokens?: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } + error?: { type: string; message: string } + retry?: { attempt: number; at: number; error: { type: string; message: string } } } | ( | { - readonly type: "compaction" - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly status: "running" - readonly reason: "auto" | "manual" - readonly summary: string - readonly recent: string + type: "compaction" + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + status: "running" + reason: "auto" | "manual" + summary: string + recent: string } | { - readonly type: "compaction" - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly status: "completed" - readonly reason: "auto" | "manual" - readonly summary: string - readonly recent: string + type: "compaction" + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + status: "completed" + reason: "auto" | "manual" + summary: string + recent: string } | { - readonly type: "compaction" - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly status: "failed" - readonly reason: "auto" | "manual" - readonly error: { readonly type: string; readonly message: string } + type: "compaction" + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + status: "failed" + reason: "auto" | "manual" + error: { type: string; message: string } } ) }["data"] @@ -2028,187 +1882,161 @@ export type MessageListInput = { } export type MessageListOutput = { - readonly data: ReadonlyArray< + data: Array< | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly type: "agent-switched" - readonly agent: string + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + type: "agent-switched" + agent: string } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly type: "model-switched" - readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly previous?: { readonly id: string; readonly providerID: string; readonly variant?: string } + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + type: "model-switched" + model: { id: string; providerID: string; variant?: string } + previous?: { id: string; providerID: string; variant?: string } } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly text: string - readonly files?: ReadonlyArray<{ - readonly data: string - readonly mime: string - readonly source: { readonly type: "inline" } | { readonly type: "uri"; readonly uri: string } - readonly name?: string - readonly description?: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + text: string + files?: Array<{ + data: string + mime: string + source: { type: "inline" } | { type: "uri"; uri: string } + name?: string + description?: string + mention?: { start: number; end: number; text: string } }> - readonly agents?: ReadonlyArray<{ - readonly name: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } - }> - readonly type: "user" + agents?: Array<{ name: string; mention?: { start: number; end: number; text: string } }> + type: "user" } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly text: string - readonly description?: string - readonly type: "synthetic" + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + text: string + description?: string + type: "synthetic" + } + | { id: string; metadata?: { [x: string]: JsonValue }; time: { created: number }; type: "system"; text: string } + | { + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + type: "skill" + skill: string + name: string + text: string } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly type: "system" - readonly text: string + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number; completed?: number } + type: "shell" + shellID: string + command: string + status: "running" | "exited" | "timeout" | "killed" + exit?: number | "Infinity" | "-Infinity" | "NaN" + output?: { output: string; cursor: number; size: number; truncated: boolean } } | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly type: "skill" - readonly skill: string - readonly name: string - readonly text: string - } - | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number; readonly completed?: number } - readonly type: "shell" - readonly shellID: string - readonly command: string - readonly status: "running" | "exited" | "timeout" | "killed" - readonly exit?: number | "Infinity" | "-Infinity" | "NaN" - readonly output?: { - readonly output: string - readonly cursor: number - readonly size: number - readonly truncated: boolean - } - } - | { - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number; readonly completed?: number } - readonly type: "assistant" - readonly agent: string - readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number; completed?: number } + type: "assistant" + agent: string + model: { id: string; providerID: string; variant?: string } + content: Array< + | { type: "text"; text: string } | { - readonly type: "reasoning" - readonly text: string - readonly state?: { readonly [x: string]: JsonValue } - readonly time?: { readonly created: number; readonly completed?: number } + type: "reasoning" + text: string + state?: { [x: string]: JsonValue } + time?: { created: number; completed?: number } } | { - readonly type: "tool" - readonly id: string - readonly name: string - readonly executed?: boolean - readonly providerState?: { readonly [x: string]: JsonValue } - readonly providerResultState?: { readonly [x: string]: JsonValue } - readonly state: - | { readonly status: "streaming"; readonly input: string } + type: "tool" + id: string + name: string + executed?: boolean + providerState?: { [x: string]: JsonValue } + providerResultState?: { [x: string]: JsonValue } + state: + | { status: "streaming"; input: string } | { - readonly status: "running" - readonly input: { readonly [x: string]: JsonValue } - readonly structured: { readonly [x: string]: JsonValue } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } - | { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string } + status: "running" + input: { [x: string]: JsonValue } + structured: { [x: string]: JsonValue } + content: Array< + { type: "text"; text: string } | { type: "file"; uri: string; mime: string; name?: string } > } | { - readonly status: "completed" - readonly input: { readonly [x: string]: JsonValue } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } - | { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string } + status: "completed" + input: { [x: string]: JsonValue } + content: Array< + { type: "text"; text: string } | { type: "file"; uri: string; mime: string; name?: string } > - readonly structured: { readonly [x: string]: JsonValue } - readonly result?: JsonValue + structured: { [x: string]: JsonValue } + result?: JsonValue } | { - readonly status: "error" - readonly input: { readonly [x: string]: JsonValue } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } - | { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string } + status: "error" + input: { [x: string]: JsonValue } + content: Array< + { type: "text"; text: string } | { type: "file"; uri: string; mime: string; name?: string } > - readonly structured: { readonly [x: string]: JsonValue } - readonly error: { readonly type: string; readonly message: string } - readonly result?: JsonValue + structured: { [x: string]: JsonValue } + error: { type: string; message: string } + result?: JsonValue } - readonly time: { readonly created: number; readonly ran?: number; readonly completed?: number } + time: { created: number; ran?: number; completed?: number } } > - readonly snapshot?: { readonly start?: string; readonly end?: string; readonly files?: ReadonlyArray } - readonly finish?: "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown" - readonly cost?: number - readonly tokens?: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } - readonly error?: { readonly type: string; readonly message: string } - readonly retry?: { - readonly attempt: number - readonly at: number - readonly error: { readonly type: string; readonly message: string } - } + snapshot?: { start?: string; end?: string; files?: Array } + finish?: "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown" + cost?: number + tokens?: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } + error?: { type: string; message: string } + retry?: { attempt: number; at: number; error: { type: string; message: string } } } | ( | { - readonly type: "compaction" - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly status: "running" - readonly reason: "auto" | "manual" - readonly summary: string - readonly recent: string + type: "compaction" + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + status: "running" + reason: "auto" | "manual" + summary: string + recent: string } | { - readonly type: "compaction" - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly status: "completed" - readonly reason: "auto" | "manual" - readonly summary: string - readonly recent: string + type: "compaction" + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + status: "completed" + reason: "auto" | "manual" + summary: string + recent: string } | { - readonly type: "compaction" - readonly id: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly time: { readonly created: number } - readonly status: "failed" - readonly reason: "auto" | "manual" - readonly error: { readonly type: string; readonly message: string } + type: "compaction" + id: string + metadata?: { [x: string]: JsonValue } + time: { created: number } + status: "failed" + reason: "auto" | "manual" + error: { type: string; message: string } } ) > - readonly cursor: { readonly previous?: string | null; readonly next?: string | null } + cursor: { previous?: string | null; next?: string | null } } export type ModelListInput = { @@ -2218,42 +2046,34 @@ export type ModelListInput = { } export type ModelListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly id: string - readonly modelID: string - readonly providerID: string - readonly family?: string - readonly name: string - readonly package?: string - readonly settings?: { readonly [x: string]: JsonValue } - readonly headers?: { readonly [x: string]: string } - readonly body?: { readonly [x: string]: JsonValue } - readonly capabilities: { - readonly tools: boolean - readonly input: ReadonlyArray - readonly output: ReadonlyArray - } - readonly variants: ReadonlyArray<{ - readonly id: string - readonly settings?: { readonly [x: string]: JsonValue } - readonly headers?: { readonly [x: string]: string } - readonly body?: { readonly [x: string]: JsonValue } + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + id: string + modelID: string + providerID: string + family?: string + name: string + package?: string + settings?: { [x: string]: JsonValue } + headers?: { [x: string]: string } + body?: { [x: string]: JsonValue } + capabilities: { tools: boolean; input: Array; output: Array } + variants: Array<{ + id: string + settings?: { [x: string]: JsonValue } + headers?: { [x: string]: string } + body?: { [x: string]: JsonValue } }> - readonly time: { readonly released: number } - readonly cost: ReadonlyArray<{ - readonly tier?: { readonly type: "context"; readonly size: number } - readonly input: number - readonly output: number - readonly cache: { readonly read: number; readonly write: number } + time: { released: number } + cost: Array<{ + tier?: { type: "context"; size: number } + input: number + output: number + cache: { read: number; write: number } }> - readonly status: "alpha" | "beta" | "deprecated" | "active" - readonly enabled: boolean - readonly limit: { readonly context: number; readonly input?: number; readonly output: number } + status: "alpha" | "beta" | "deprecated" | "active" + enabled: boolean + limit: { context: number; input?: number; output: number } }> } @@ -2264,42 +2084,34 @@ export type ModelDefaultInput = { } export type ModelDefaultOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: { - readonly id: string - readonly modelID: string - readonly providerID: string - readonly family?: string - readonly name: string - readonly package?: string - readonly settings?: { readonly [x: string]: JsonValue } - readonly headers?: { readonly [x: string]: string } - readonly body?: { readonly [x: string]: JsonValue } - readonly capabilities: { - readonly tools: boolean - readonly input: ReadonlyArray - readonly output: ReadonlyArray - } - readonly variants: ReadonlyArray<{ - readonly id: string - readonly settings?: { readonly [x: string]: JsonValue } - readonly headers?: { readonly [x: string]: string } - readonly body?: { readonly [x: string]: JsonValue } + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: { + id: string + modelID: string + providerID: string + family?: string + name: string + package?: string + settings?: { [x: string]: JsonValue } + headers?: { [x: string]: string } + body?: { [x: string]: JsonValue } + capabilities: { tools: boolean; input: Array; output: Array } + variants: Array<{ + id: string + settings?: { [x: string]: JsonValue } + headers?: { [x: string]: string } + body?: { [x: string]: JsonValue } }> - readonly time: { readonly released: number } - readonly cost: ReadonlyArray<{ - readonly tier?: { readonly type: "context"; readonly size: number } - readonly input: number - readonly output: number - readonly cache: { readonly read: number; readonly write: number } + time: { released: number } + cost: Array<{ + tier?: { type: "context"; size: number } + input: number + output: number + cache: { read: number; write: number } }> - readonly status: "alpha" | "beta" | "deprecated" | "active" - readonly enabled: boolean - readonly limit: { readonly context: number; readonly input?: number; readonly output: number } + status: "alpha" | "beta" | "deprecated" | "active" + enabled: boolean + limit: { context: number; input?: number; output: number } } | null } @@ -2317,7 +2129,7 @@ export type GenerateTextInput = { }["model"] } -export type GenerateTextOutput = { readonly data: { readonly text: string } }["data"] +export type GenerateTextOutput = { data: { text: string } }["data"] export type ProviderListInput = { readonly location?: { @@ -2326,20 +2138,16 @@ export type ProviderListInput = { } export type ProviderListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly id: string - readonly integrationID?: string - readonly name: string - readonly disabled?: boolean - readonly package: string - readonly settings?: { readonly [x: string]: JsonValue } - readonly headers?: { readonly [x: string]: string } - readonly body?: { readonly [x: string]: JsonValue } + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + id: string + integrationID?: string + name: string + disabled?: boolean + package: string + settings?: { [x: string]: JsonValue } + headers?: { [x: string]: string } + body?: { [x: string]: JsonValue } }> } @@ -2351,20 +2159,16 @@ export type ProviderGetInput = { } export type ProviderGetOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: { - readonly id: string - readonly integrationID?: string - readonly name: string - readonly disabled?: boolean - readonly package: string - readonly settings?: { readonly [x: string]: JsonValue } - readonly headers?: { readonly [x: string]: string } - readonly body?: { readonly [x: string]: JsonValue } + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: { + id: string + integrationID?: string + name: string + disabled?: boolean + package: string + settings?: { [x: string]: JsonValue } + headers?: { [x: string]: string } + body?: { [x: string]: JsonValue } } } @@ -2375,47 +2179,36 @@ export type IntegrationListInput = { } export type IntegrationListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly id: string - readonly name: string - readonly methods: ReadonlyArray< + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + id: string + name: string + methods: Array< | { - readonly id: string - readonly type: "oauth" - readonly label: string - readonly prompts?: ReadonlyArray< + id: string + type: "oauth" + label: string + prompts?: Array< | { - readonly type: "text" - readonly key: string - readonly message: string - readonly placeholder?: string - readonly when?: { readonly key: string; readonly op: "eq" | "neq"; readonly value: string } + type: "text" + key: string + message: string + placeholder?: string + when?: { key: string; op: "eq" | "neq"; value: string } } | { - readonly type: "select" - readonly key: string - readonly message: string - readonly options: ReadonlyArray<{ - readonly label: string - readonly value: string - readonly hint?: string - }> - readonly when?: { readonly key: string; readonly op: "eq" | "neq"; readonly value: string } + type: "select" + key: string + message: string + options: Array<{ label: string; value: string; hint?: string }> + when?: { key: string; op: "eq" | "neq"; value: string } } > } - | { readonly type: "key"; readonly label?: string } - | { readonly type: "env"; readonly names: ReadonlyArray } - > - readonly connections: ReadonlyArray< - | { readonly type: "credential"; readonly id: string; readonly label: string } - | { readonly type: "env"; readonly name: string } + | { type: "key"; label?: string } + | { type: "env"; names: Array } > + connections: Array<{ type: "credential"; id: string; label: string } | { type: "env"; name: string }> }> } @@ -2427,47 +2220,36 @@ export type IntegrationGetInput = { } export type IntegrationGetOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: { - readonly id: string - readonly name: string - readonly methods: ReadonlyArray< + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: { + id: string + name: string + methods: Array< | { - readonly id: string - readonly type: "oauth" - readonly label: string - readonly prompts?: ReadonlyArray< + id: string + type: "oauth" + label: string + prompts?: Array< | { - readonly type: "text" - readonly key: string - readonly message: string - readonly placeholder?: string - readonly when?: { readonly key: string; readonly op: "eq" | "neq"; readonly value: string } + type: "text" + key: string + message: string + placeholder?: string + when?: { key: string; op: "eq" | "neq"; value: string } } | { - readonly type: "select" - readonly key: string - readonly message: string - readonly options: ReadonlyArray<{ - readonly label: string - readonly value: string - readonly hint?: string - }> - readonly when?: { readonly key: string; readonly op: "eq" | "neq"; readonly value: string } + type: "select" + key: string + message: string + options: Array<{ label: string; value: string; hint?: string }> + when?: { key: string; op: "eq" | "neq"; value: string } } > } - | { readonly type: "key"; readonly label?: string } - | { readonly type: "env"; readonly names: ReadonlyArray } - > - readonly connections: ReadonlyArray< - | { readonly type: "credential"; readonly id: string; readonly label: string } - | { readonly type: "env"; readonly name: string } + | { type: "key"; label?: string } + | { type: "env"; names: Array } > + connections: Array<{ type: "credential"; id: string; label: string } | { type: "env"; name: string }> } | null } @@ -2505,20 +2287,13 @@ export type IntegrationConnectOauthInput = { } export type IntegrationConnectOauthOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: { - readonly attemptID: string - readonly url: string - readonly instructions: string - readonly mode: "auto" | "code" - readonly time: { - readonly created: number | "Infinity" | "-Infinity" | "NaN" - readonly expires: number | "Infinity" | "-Infinity" | "NaN" - } + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: { + attemptID: string + url: string + instructions: string + mode: "auto" | "code" + time: { created: number | "Infinity" | "-Infinity" | "NaN"; expires: number | "Infinity" | "-Infinity" | "NaN" } } } @@ -2530,40 +2305,24 @@ export type IntegrationAttemptStatusInput = { } export type IntegrationAttemptStatusOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: | { - readonly status: "pending" - readonly time: { - readonly created: number | "Infinity" | "-Infinity" | "NaN" - readonly expires: number | "Infinity" | "-Infinity" | "NaN" - } + status: "pending" + time: { created: number | "Infinity" | "-Infinity" | "NaN"; expires: number | "Infinity" | "-Infinity" | "NaN" } } | { - readonly status: "complete" - readonly time: { - readonly created: number | "Infinity" | "-Infinity" | "NaN" - readonly expires: number | "Infinity" | "-Infinity" | "NaN" - } + status: "complete" + time: { created: number | "Infinity" | "-Infinity" | "NaN"; expires: number | "Infinity" | "-Infinity" | "NaN" } } | { - readonly status: "failed" - readonly message: string - readonly time: { - readonly created: number | "Infinity" | "-Infinity" | "NaN" - readonly expires: number | "Infinity" | "-Infinity" | "NaN" - } + status: "failed" + message: string + time: { created: number | "Infinity" | "-Infinity" | "NaN"; expires: number | "Infinity" | "-Infinity" | "NaN" } } | { - readonly status: "expired" - readonly time: { - readonly created: number | "Infinity" | "-Infinity" | "NaN" - readonly expires: number | "Infinity" | "-Infinity" | "NaN" - } + status: "expired" + time: { created: number | "Infinity" | "-Infinity" | "NaN"; expires: number | "Infinity" | "-Infinity" | "NaN" } } } @@ -2593,21 +2352,17 @@ export type ServerMcpListInput = { } export type ServerMcpListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly name: string - readonly status: - | { readonly status: "connected" } - | { readonly status: "pending" } - | { readonly status: "disabled" } - | { readonly status: "failed"; readonly error: string } - | { readonly status: "needs_auth" } - | { readonly status: "needs_client_registration"; readonly error: string } - readonly integrationID?: string + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + name: string + status: + | { status: "connected" } + | { status: "pending" } + | { status: "disabled" } + | { status: "failed"; error: string } + | { status: "needs_auth" } + | { status: "needs_client_registration"; error: string } + integrationID?: string }> } @@ -2618,26 +2373,10 @@ export type ServerMcpResourceCatalogInput = { } export type ServerMcpResourceCatalogOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: { - readonly resources: ReadonlyArray<{ - readonly server: string - readonly name: string - readonly uri: string - readonly description?: string - readonly mimeType?: string - }> - readonly templates: ReadonlyArray<{ - readonly server: string - readonly name: string - readonly uriTemplate: string - readonly description?: string - readonly mimeType?: string - }> + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: { + resources: Array<{ server: string; name: string; uri: string; description?: string; mimeType?: string }> + templates: Array<{ server: string; name: string; uriTemplate: string; description?: string; mimeType?: string }> } } @@ -2660,15 +2399,15 @@ export type CredentialRemoveInput = { export type CredentialRemoveOutput = void -export type ProjectListOutput = ReadonlyArray<{ - readonly id: string - readonly worktree: string - readonly vcs?: "git" | "hg" - readonly name?: string - readonly icon?: { readonly url?: string; readonly override?: string; readonly color?: string } - readonly commands?: { readonly start?: string } - readonly time: { readonly created: number; readonly updated: number; readonly initialized?: number } - readonly sandboxes: ReadonlyArray +export type ProjectListOutput = Array<{ + id: string + worktree: string + vcs?: "git" | "hg" + name?: string + icon?: { url?: string; override?: string; color?: string } + commands?: { start?: string } + time: { created: number; updated: number; initialized?: number } + sandboxes: Array }> export type ProjectCurrentInput = { @@ -2677,7 +2416,7 @@ export type ProjectCurrentInput = { }["location"] } -export type ProjectCurrentOutput = { readonly id: string; readonly directory: string } +export type ProjectCurrentOutput = { id: string; directory: string } export type ProjectDirectoriesInput = { readonly projectID: { readonly projectID: string }["projectID"] @@ -2686,7 +2425,7 @@ export type ProjectDirectoriesInput = { }["location"] } -export type ProjectDirectoriesOutput = ReadonlyArray<{ readonly directory: string; readonly strategy?: string }> +export type ProjectDirectoriesOutput = Array<{ directory: string; strategy?: string }> export type FormRequestListInput = { readonly location?: { @@ -2695,230 +2434,360 @@ export type FormRequestListInput = { } export type FormRequestListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray< - | { - readonly id: string - readonly sessionID: string - readonly title: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "form" - readonly fields: ReadonlyArray< - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "string" - readonly format?: "email" | "uri" | "date" | "date-time" - readonly minLength?: number - readonly maxLength?: number - readonly pattern?: string - readonly placeholder?: string - readonly default?: string - readonly options?: ReadonlyArray<{ - readonly value: string - readonly label: string - readonly description?: string - }> - readonly custom?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "number" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "integer" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "boolean" - readonly default?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "multiselect" - readonly options: ReadonlyArray<{ - readonly value: string - readonly label: string - readonly description?: string - }> - readonly minItems?: number - readonly maxItems?: number - readonly custom?: boolean - readonly default?: ReadonlyArray - } - > - } - | { - readonly id: string - readonly sessionID: string - readonly title: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "url" - readonly url: string - } - > + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + id: string + sessionID: string + title: string + metadata?: { [x: string]: JsonValue } + fields: [ + ( + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "string" + format?: "email" | "uri" | "date" | "date-time" + minLength?: number + maxLength?: number + pattern?: string + placeholder?: string + default?: string + options?: Array<{ value: string; label: string; description?: string }> + custom?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "number" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "integer" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "boolean" + default?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "multiselect" + options: Array<{ value: string; label: string; description?: string }> + minItems?: number + maxItems?: number + custom?: boolean + default?: Array + } + | { key: string; type: "external"; url: string; title?: string; description?: string } + ), + ...Array< + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "string" + format?: "email" | "uri" | "date" | "date-time" + minLength?: number + maxLength?: number + pattern?: string + placeholder?: string + default?: string + options?: Array<{ value: string; label: string; description?: string }> + custom?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "number" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "integer" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "boolean" + default?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "multiselect" + options: Array<{ value: string; label: string; description?: string }> + minItems?: number + maxItems?: number + custom?: boolean + default?: Array + } + | { key: string; type: "external"; url: string; title?: string; description?: string } + >, + ] + }> } export type FormListInput = { readonly sessionID: { readonly sessionID: string }["sessionID"] } export type FormListOutput = { - readonly data: ReadonlyArray< - | { - readonly id: string - readonly sessionID: string - readonly title: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "form" - readonly fields: ReadonlyArray< - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "string" - readonly format?: "email" | "uri" | "date" | "date-time" - readonly minLength?: number - readonly maxLength?: number - readonly pattern?: string - readonly placeholder?: string - readonly default?: string - readonly options?: ReadonlyArray<{ - readonly value: string - readonly label: string - readonly description?: string - }> - readonly custom?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "number" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "integer" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "boolean" - readonly default?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "multiselect" - readonly options: ReadonlyArray<{ - readonly value: string - readonly label: string - readonly description?: string - }> - readonly minItems?: number - readonly maxItems?: number - readonly custom?: boolean - readonly default?: ReadonlyArray - } - > - } - | { - readonly id: string - readonly sessionID: string - readonly title: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "url" - readonly url: string - } - > + data: Array<{ + id: string + sessionID: string + title: string + metadata?: { [x: string]: JsonValue } + fields: [ + ( + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "string" + format?: "email" | "uri" | "date" | "date-time" + minLength?: number + maxLength?: number + pattern?: string + placeholder?: string + default?: string + options?: Array<{ value: string; label: string; description?: string }> + custom?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "number" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "integer" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "boolean" + default?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "multiselect" + options: Array<{ value: string; label: string; description?: string }> + minItems?: number + maxItems?: number + custom?: boolean + default?: Array + } + | { key: string; type: "external"; url: string; title?: string; description?: string } + ), + ...Array< + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "string" + format?: "email" | "uri" | "date" | "date-time" + minLength?: number + maxLength?: number + pattern?: string + placeholder?: string + default?: string + options?: Array<{ value: string; label: string; description?: string }> + custom?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "number" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "integer" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "boolean" + default?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "multiselect" + options: Array<{ value: string; label: string; description?: string }> + minItems?: number + maxItems?: number + custom?: boolean + default?: Array + } + | { key: string; type: "external"; url: string; title?: string; description?: string } + >, + ] + }> }["data"] export type FormCreateInput = { @@ -2927,693 +2796,983 @@ export type FormCreateInput = { readonly id?: string | null readonly title: string readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "form" | "url" - readonly fields?: ReadonlyArray< - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ + readonly fields: readonly [ + ( + | { readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "string" - readonly format?: "email" | "uri" | "date" | "date-time" - readonly minLength?: number - readonly maxLength?: number - readonly pattern?: string - readonly placeholder?: string - readonly default?: string - readonly options?: ReadonlyArray<{ - readonly value: string - readonly label: string + readonly title?: string readonly description?: string - }> - readonly custom?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "string" + readonly format?: "email" | "uri" | "date" | "date-time" + readonly minLength?: number + readonly maxLength?: number + readonly pattern?: string + readonly placeholder?: string + readonly default?: string + readonly options?: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly custom?: boolean + } + | { readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "number" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "integer" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "boolean" - readonly default?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "multiselect" - readonly options: ReadonlyArray<{ - readonly value: string - readonly label: string + readonly title?: string readonly description?: string - }> - readonly minItems?: number - readonly maxItems?: number - readonly custom?: boolean - readonly default?: ReadonlyArray - } - > | null - readonly url?: string | null + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "number" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "integer" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "boolean" + readonly default?: boolean + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "multiselect" + readonly options: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly minItems?: number + readonly maxItems?: number + readonly custom?: boolean + readonly default?: ReadonlyArray + } + | { + readonly key: string + readonly type: "external" + readonly url: string + readonly title?: string + readonly description?: string + } + ), + ...Array< + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "string" + readonly format?: "email" | "uri" | "date" | "date-time" + readonly minLength?: number + readonly maxLength?: number + readonly pattern?: string + readonly placeholder?: string + readonly default?: string + readonly options?: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly custom?: boolean + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "number" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "integer" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "boolean" + readonly default?: boolean + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "multiselect" + readonly options: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly minItems?: number + readonly maxItems?: number + readonly custom?: boolean + readonly default?: ReadonlyArray + } + | { + readonly key: string + readonly type: "external" + readonly url: string + readonly title?: string + readonly description?: string + } + >, + ] }["id"] readonly title: { readonly id?: string | null readonly title: string readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "form" | "url" - readonly fields?: ReadonlyArray< - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ + readonly fields: readonly [ + ( + | { readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "string" - readonly format?: "email" | "uri" | "date" | "date-time" - readonly minLength?: number - readonly maxLength?: number - readonly pattern?: string - readonly placeholder?: string - readonly default?: string - readonly options?: ReadonlyArray<{ - readonly value: string - readonly label: string + readonly title?: string readonly description?: string - }> - readonly custom?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "string" + readonly format?: "email" | "uri" | "date" | "date-time" + readonly minLength?: number + readonly maxLength?: number + readonly pattern?: string + readonly placeholder?: string + readonly default?: string + readonly options?: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly custom?: boolean + } + | { readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "number" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "integer" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "boolean" - readonly default?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "multiselect" - readonly options: ReadonlyArray<{ - readonly value: string - readonly label: string + readonly title?: string readonly description?: string - }> - readonly minItems?: number - readonly maxItems?: number - readonly custom?: boolean - readonly default?: ReadonlyArray - } - > | null - readonly url?: string | null + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "number" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "integer" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "boolean" + readonly default?: boolean + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "multiselect" + readonly options: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly minItems?: number + readonly maxItems?: number + readonly custom?: boolean + readonly default?: ReadonlyArray + } + | { + readonly key: string + readonly type: "external" + readonly url: string + readonly title?: string + readonly description?: string + } + ), + ...Array< + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "string" + readonly format?: "email" | "uri" | "date" | "date-time" + readonly minLength?: number + readonly maxLength?: number + readonly pattern?: string + readonly placeholder?: string + readonly default?: string + readonly options?: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly custom?: boolean + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "number" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "integer" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "boolean" + readonly default?: boolean + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "multiselect" + readonly options: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly minItems?: number + readonly maxItems?: number + readonly custom?: boolean + readonly default?: ReadonlyArray + } + | { + readonly key: string + readonly type: "external" + readonly url: string + readonly title?: string + readonly description?: string + } + >, + ] }["title"] readonly metadata?: { readonly id?: string | null readonly title: string readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "form" | "url" - readonly fields?: ReadonlyArray< - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ + readonly fields: readonly [ + ( + | { readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "string" - readonly format?: "email" | "uri" | "date" | "date-time" - readonly minLength?: number - readonly maxLength?: number - readonly pattern?: string - readonly placeholder?: string - readonly default?: string - readonly options?: ReadonlyArray<{ - readonly value: string - readonly label: string + readonly title?: string readonly description?: string - }> - readonly custom?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "string" + readonly format?: "email" | "uri" | "date" | "date-time" + readonly minLength?: number + readonly maxLength?: number + readonly pattern?: string + readonly placeholder?: string + readonly default?: string + readonly options?: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly custom?: boolean + } + | { readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "number" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "integer" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "boolean" - readonly default?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "multiselect" - readonly options: ReadonlyArray<{ - readonly value: string - readonly label: string + readonly title?: string readonly description?: string - }> - readonly minItems?: number - readonly maxItems?: number - readonly custom?: boolean - readonly default?: ReadonlyArray - } - > | null - readonly url?: string | null + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "number" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "integer" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "boolean" + readonly default?: boolean + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "multiselect" + readonly options: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly minItems?: number + readonly maxItems?: number + readonly custom?: boolean + readonly default?: ReadonlyArray + } + | { + readonly key: string + readonly type: "external" + readonly url: string + readonly title?: string + readonly description?: string + } + ), + ...Array< + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "string" + readonly format?: "email" | "uri" | "date" | "date-time" + readonly minLength?: number + readonly maxLength?: number + readonly pattern?: string + readonly placeholder?: string + readonly default?: string + readonly options?: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly custom?: boolean + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "number" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "integer" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "boolean" + readonly default?: boolean + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "multiselect" + readonly options: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly minItems?: number + readonly maxItems?: number + readonly custom?: boolean + readonly default?: ReadonlyArray + } + | { + readonly key: string + readonly type: "external" + readonly url: string + readonly title?: string + readonly description?: string + } + >, + ] }["metadata"] - readonly mode: { + readonly fields: { readonly id?: string | null readonly title: string readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "form" | "url" - readonly fields?: ReadonlyArray< - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ + readonly fields: readonly [ + ( + | { readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "string" - readonly format?: "email" | "uri" | "date" | "date-time" - readonly minLength?: number - readonly maxLength?: number - readonly pattern?: string - readonly placeholder?: string - readonly default?: string - readonly options?: ReadonlyArray<{ - readonly value: string - readonly label: string + readonly title?: string readonly description?: string - }> - readonly custom?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "string" + readonly format?: "email" | "uri" | "date" | "date-time" + readonly minLength?: number + readonly maxLength?: number + readonly pattern?: string + readonly placeholder?: string + readonly default?: string + readonly options?: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly custom?: boolean + } + | { readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "number" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "integer" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "boolean" - readonly default?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "multiselect" - readonly options: ReadonlyArray<{ - readonly value: string - readonly label: string + readonly title?: string readonly description?: string - }> - readonly minItems?: number - readonly maxItems?: number - readonly custom?: boolean - readonly default?: ReadonlyArray - } - > | null - readonly url?: string | null - }["mode"] - readonly fields?: { - readonly id?: string | null - readonly title: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "form" | "url" - readonly fields?: ReadonlyArray< - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "number" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "string" - readonly format?: "email" | "uri" | "date" | "date-time" - readonly minLength?: number - readonly maxLength?: number - readonly pattern?: string - readonly placeholder?: string - readonly default?: string - readonly options?: ReadonlyArray<{ - readonly value: string - readonly label: string + readonly title?: string readonly description?: string - }> - readonly custom?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "integer" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "number" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "integer" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "boolean" - readonly default?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "multiselect" - readonly options: ReadonlyArray<{ - readonly value: string - readonly label: string + readonly title?: string readonly description?: string - }> - readonly minItems?: number - readonly maxItems?: number - readonly custom?: boolean - readonly default?: ReadonlyArray - } - > | null - readonly url?: string | null + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "boolean" + readonly default?: boolean + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "multiselect" + readonly options: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly minItems?: number + readonly maxItems?: number + readonly custom?: boolean + readonly default?: ReadonlyArray + } + | { + readonly key: string + readonly type: "external" + readonly url: string + readonly title?: string + readonly description?: string + } + ), + ...Array< + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "string" + readonly format?: "email" | "uri" | "date" | "date-time" + readonly minLength?: number + readonly maxLength?: number + readonly pattern?: string + readonly placeholder?: string + readonly default?: string + readonly options?: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly custom?: boolean + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "number" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "integer" + readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" + readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" + readonly default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "boolean" + readonly default?: boolean + } + | { + readonly key: string + readonly title?: string + readonly description?: string + readonly required?: boolean + readonly when?: ReadonlyArray<{ + readonly key: string + readonly op: "eq" | "neq" + readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + readonly type: "multiselect" + readonly options: ReadonlyArray<{ + readonly value: string + readonly label: string + readonly description?: string + }> + readonly minItems?: number + readonly maxItems?: number + readonly custom?: boolean + readonly default?: ReadonlyArray + } + | { + readonly key: string + readonly type: "external" + readonly url: string + readonly title?: string + readonly description?: string + } + >, + ] }["fields"] - readonly url?: { - readonly id?: string | null - readonly title: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "form" | "url" - readonly fields?: ReadonlyArray< - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "string" - readonly format?: "email" | "uri" | "date" | "date-time" - readonly minLength?: number - readonly maxLength?: number - readonly pattern?: string - readonly placeholder?: string - readonly default?: string - readonly options?: ReadonlyArray<{ - readonly value: string - readonly label: string - readonly description?: string - }> - readonly custom?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "number" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "integer" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "boolean" - readonly default?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "multiselect" - readonly options: ReadonlyArray<{ - readonly value: string - readonly label: string - readonly description?: string - }> - readonly minItems?: number - readonly maxItems?: number - readonly custom?: boolean - readonly default?: ReadonlyArray - } - > | null - readonly url?: string | null - }["url"] } export type FormCreateOutput = { - readonly data: - | { - readonly id: string - readonly sessionID: string - readonly title: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "form" - readonly fields: ReadonlyArray< - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "string" - readonly format?: "email" | "uri" | "date" | "date-time" - readonly minLength?: number - readonly maxLength?: number - readonly pattern?: string - readonly placeholder?: string - readonly default?: string - readonly options?: ReadonlyArray<{ - readonly value: string - readonly label: string - readonly description?: string - }> - readonly custom?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "number" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "integer" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "boolean" - readonly default?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "multiselect" - readonly options: ReadonlyArray<{ - readonly value: string - readonly label: string - readonly description?: string - }> - readonly minItems?: number - readonly maxItems?: number - readonly custom?: boolean - readonly default?: ReadonlyArray - } - > - } - | { - readonly id: string - readonly sessionID: string - readonly title: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "url" - readonly url: string - } + data: { + id: string + sessionID: string + title: string + metadata?: { [x: string]: JsonValue } + fields: [ + ( + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "string" + format?: "email" | "uri" | "date" | "date-time" + minLength?: number + maxLength?: number + pattern?: string + placeholder?: string + default?: string + options?: Array<{ value: string; label: string; description?: string }> + custom?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "number" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "integer" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "boolean" + default?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "multiselect" + options: Array<{ value: string; label: string; description?: string }> + minItems?: number + maxItems?: number + custom?: boolean + default?: Array + } + | { key: string; type: "external"; url: string; title?: string; description?: string } + ), + ...Array< + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "string" + format?: "email" | "uri" | "date" | "date-time" + minLength?: number + maxLength?: number + pattern?: string + placeholder?: string + default?: string + options?: Array<{ value: string; label: string; description?: string }> + custom?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "number" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "integer" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "boolean" + default?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "multiselect" + options: Array<{ value: string; label: string; description?: string }> + minItems?: number + maxItems?: number + custom?: boolean + default?: Array + } + | { key: string; type: "external"; url: string; title?: string; description?: string } + >, + ] + } }["data"] export type FormGetInput = { @@ -3622,112 +3781,180 @@ export type FormGetInput = { } export type FormGetOutput = { - readonly data: - | { - readonly id: string - readonly sessionID: string - readonly title: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "form" - readonly fields: ReadonlyArray< - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "string" - readonly format?: "email" | "uri" | "date" | "date-time" - readonly minLength?: number - readonly maxLength?: number - readonly pattern?: string - readonly placeholder?: string - readonly default?: string - readonly options?: ReadonlyArray<{ - readonly value: string - readonly label: string - readonly description?: string - }> - readonly custom?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "number" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "integer" - readonly minimum?: number | "Infinity" | "-Infinity" | "NaN" - readonly maximum?: number | "Infinity" | "-Infinity" | "NaN" - readonly default?: number | "Infinity" | "-Infinity" | "NaN" - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "boolean" - readonly default?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean - }> - readonly type: "multiselect" - readonly options: ReadonlyArray<{ - readonly value: string - readonly label: string - readonly description?: string - }> - readonly minItems?: number - readonly maxItems?: number - readonly custom?: boolean - readonly default?: ReadonlyArray - } - > - } - | { - readonly id: string - readonly sessionID: string - readonly title: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly mode: "url" - readonly url: string - } + data: { + id: string + sessionID: string + title: string + metadata?: { [x: string]: JsonValue } + fields: [ + ( + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "string" + format?: "email" | "uri" | "date" | "date-time" + minLength?: number + maxLength?: number + pattern?: string + placeholder?: string + default?: string + options?: Array<{ value: string; label: string; description?: string }> + custom?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "number" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "integer" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "boolean" + default?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "multiselect" + options: Array<{ value: string; label: string; description?: string }> + minItems?: number + maxItems?: number + custom?: boolean + default?: Array + } + | { key: string; type: "external"; url: string; title?: string; description?: string } + ), + ...Array< + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "string" + format?: "email" | "uri" | "date" | "date-time" + minLength?: number + maxLength?: number + pattern?: string + placeholder?: string + default?: string + options?: Array<{ value: string; label: string; description?: string }> + custom?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "number" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "integer" + minimum?: number | "Infinity" | "-Infinity" | "NaN" + maximum?: number | "Infinity" | "-Infinity" | "NaN" + default?: number | "Infinity" | "-Infinity" | "NaN" + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "boolean" + default?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ + key: string + op: "eq" | "neq" + value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean + }> + type: "multiselect" + options: Array<{ value: string; label: string; description?: string }> + minItems?: number + maxItems?: number + custom?: boolean + default?: Array + } + | { key: string; type: "external"; url: string; title?: string; description?: string } + >, + ] + } }["data"] export type FormStateInput = { @@ -3736,13 +3963,10 @@ export type FormStateInput = { } export type FormStateOutput = { - readonly data: - | { readonly status: "pending" } - | { - readonly status: "answered" - readonly answer: { readonly [x: string]: string | number | boolean | ReadonlyArray } - } - | { readonly status: "cancelled" } + data: + | { status: "pending" } + | { status: "answered"; answer: { [x: string]: string | number | boolean | Array } } + | { status: "cancelled" } }["data"] export type FormReplyInput = { @@ -3769,31 +3993,22 @@ export type PermissionRequestListInput = { } export type PermissionRequestListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly id: string - readonly sessionID: string - readonly action: string - readonly resources: ReadonlyArray - readonly save?: ReadonlyArray - readonly metadata?: { readonly [x: string]: JsonValue } - readonly source?: { readonly type: "tool"; readonly messageID: string; readonly callID: string } + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + id: string + sessionID: string + action: string + resources: Array + save?: Array + metadata?: { [x: string]: JsonValue } + source?: { type: "tool"; messageID: string; callID: string } }> } export type PermissionSavedListInput = { readonly projectID?: { readonly projectID?: string | undefined }["projectID"] } export type PermissionSavedListOutput = { - readonly data: ReadonlyArray<{ - readonly id: string - readonly projectID: string - readonly action: string - readonly resource: string - }> + data: Array<{ id: string; projectID: string; action: string; resource: string }> }["data"] export type PermissionSavedRemoveInput = { readonly id: { readonly id: string }["id"] } @@ -3867,21 +4082,19 @@ export type PermissionCreateInput = { }["agent"] } -export type PermissionCreateOutput = { - readonly data: { readonly id: string; readonly effect: "allow" | "deny" | "ask" } -}["data"] +export type PermissionCreateOutput = { data: { id: string; effect: "allow" | "deny" | "ask" } }["data"] export type PermissionListInput = { readonly sessionID: { readonly sessionID: string }["sessionID"] } export type PermissionListOutput = { - readonly data: ReadonlyArray<{ - readonly id: string - readonly sessionID: string - readonly action: string - readonly resources: ReadonlyArray - readonly save?: ReadonlyArray - readonly metadata?: { readonly [x: string]: JsonValue } - readonly source?: { readonly type: "tool"; readonly messageID: string; readonly callID: string } + data: Array<{ + id: string + sessionID: string + action: string + resources: Array + save?: Array + metadata?: { [x: string]: JsonValue } + source?: { type: "tool"; messageID: string; callID: string } }> }["data"] @@ -3891,14 +4104,14 @@ export type PermissionGetInput = { } export type PermissionGetOutput = { - readonly data: { - readonly id: string - readonly sessionID: string - readonly action: string - readonly resources: ReadonlyArray - readonly save?: ReadonlyArray - readonly metadata?: { readonly [x: string]: JsonValue } - readonly source?: { readonly type: "tool"; readonly messageID: string; readonly callID: string } + data: { + id: string + sessionID: string + action: string + resources: Array + save?: Array + metadata?: { [x: string]: JsonValue } + source?: { type: "tool"; messageID: string; callID: string } } }["data"] @@ -3932,12 +4145,8 @@ export type FileListInput = { } export type FileListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ readonly path: string; readonly type: "file" | "directory" }> + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ path: string; type: "file" | "directory" }> } export type FileFindInput = { @@ -3968,12 +4177,8 @@ export type FileFindInput = { } export type FileFindOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ readonly path: string; readonly type: "file" | "directory" }> + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ path: string; type: "file" | "directory" }> } export type CommandListInput = { @@ -3983,18 +4188,14 @@ export type CommandListInput = { } export type CommandListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly name: string - readonly template: string - readonly description?: string - readonly agent?: string - readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly subtask?: boolean + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + name: string + template: string + description?: string + agent?: string + model?: { id: string; providerID: string; variant?: string } + subtask?: boolean }> } @@ -4005,510 +4206,402 @@ export type SkillListInput = { } export type SkillListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly id: string - readonly name: string - readonly description?: string - readonly slash?: boolean - readonly autoinvoke?: boolean - readonly location: string - readonly content: string + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + id: string + name: string + description?: string + slash?: boolean + autoinvoke?: boolean + location: string + content: string }> } export type EventSubscribeOutput = | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "models-dev.refreshed" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: {} + id: string + created: number + metadata?: { [x: string]: unknown } + type: "models-dev.refreshed" + location?: { directory: string; workspaceID?: string } + data: {} } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "integration.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: {} + id: string + created: number + metadata?: { [x: string]: unknown } + type: "integration.updated" + location?: { directory: string; workspaceID?: string } + data: {} } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "integration.connection.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly integrationID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "integration.connection.updated" + location?: { directory: string; workspaceID?: string } + data: { integrationID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "catalog.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: {} + id: string + created: number + metadata?: { [x: string]: unknown } + type: "catalog.updated" + location?: { directory: string; workspaceID?: string } + data: {} } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "agent.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: {} + id: string + created: number + metadata?: { [x: string]: unknown } + type: "agent.updated" + location?: { directory: string; workspaceID?: string } + data: {} } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.created" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly info: { - readonly id: string - readonly slug: string - readonly projectID: string - readonly workspaceID?: string - readonly directory: string - readonly path?: string - readonly parentID?: string - readonly summary?: { - readonly additions: number - readonly deletions: number - readonly files: number - readonly diffs?: ReadonlyArray<{ - readonly file?: string - readonly patch?: string - readonly additions: number - readonly deletions: number - readonly status?: "added" | "deleted" | "modified" + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.created" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + info: { + id: string + slug: string + projectID: string + workspaceID?: string + directory: string + path?: string + parentID?: string + summary?: { + additions: number + deletions: number + files: number + diffs?: Array<{ + file?: string + patch?: string + additions: number + deletions: number + status?: "added" | "deleted" | "modified" }> } - readonly cost?: number - readonly tokens?: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } - readonly share?: { readonly url: string } - readonly title: string - readonly agent?: string - readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly version: string - readonly metadata?: { readonly [x: string]: any } - readonly time: { - readonly created: number - readonly updated: number - readonly compacting?: number - readonly archived?: number - } - readonly permission?: ReadonlyArray<{ - readonly permission: string - readonly pattern: string - readonly action: "allow" | "deny" | "ask" - }> - readonly revert?: { - readonly messageID: string - readonly partID?: string - readonly snapshot?: string - readonly diff?: string - } + cost?: number + tokens?: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } + share?: { url: string } + title: string + agent?: string + model?: { id: string; providerID: string; variant?: string } + version: string + metadata?: { [x: string]: any } + time: { created: number; updated: number; compacting?: number; archived?: number } + permission?: Array<{ permission: string; pattern: string; action: "allow" | "deny" | "ask" }> + revert?: { messageID: string; partID?: string; snapshot?: string; diff?: string } } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.updated" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly info: { - readonly id: string - readonly slug: string - readonly projectID: string - readonly workspaceID?: string - readonly directory: string - readonly path?: string - readonly parentID?: string - readonly summary?: { - readonly additions: number - readonly deletions: number - readonly files: number - readonly diffs?: ReadonlyArray<{ - readonly file?: string - readonly patch?: string - readonly additions: number - readonly deletions: number - readonly status?: "added" | "deleted" | "modified" + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.updated" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + info: { + id: string + slug: string + projectID: string + workspaceID?: string + directory: string + path?: string + parentID?: string + summary?: { + additions: number + deletions: number + files: number + diffs?: Array<{ + file?: string + patch?: string + additions: number + deletions: number + status?: "added" | "deleted" | "modified" }> } - readonly cost?: number - readonly tokens?: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } - readonly share?: { readonly url: string } - readonly title: string - readonly agent?: string - readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly version: string - readonly metadata?: { readonly [x: string]: any } - readonly time: { - readonly created: number - readonly updated: number - readonly compacting?: number - readonly archived?: number - } - readonly permission?: ReadonlyArray<{ - readonly permission: string - readonly pattern: string - readonly action: "allow" | "deny" | "ask" - }> - readonly revert?: { - readonly messageID: string - readonly partID?: string - readonly snapshot?: string - readonly diff?: string - } + cost?: number + tokens?: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } + share?: { url: string } + title: string + agent?: string + model?: { id: string; providerID: string; variant?: string } + version: string + metadata?: { [x: string]: any } + time: { created: number; updated: number; compacting?: number; archived?: number } + permission?: Array<{ permission: string; pattern: string; action: "allow" | "deny" | "ask" }> + revert?: { messageID: string; partID?: string; snapshot?: string; diff?: string } } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.deleted" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly info: { - readonly id: string - readonly slug: string - readonly projectID: string - readonly workspaceID?: string - readonly directory: string - readonly path?: string - readonly parentID?: string - readonly summary?: { - readonly additions: number - readonly deletions: number - readonly files: number - readonly diffs?: ReadonlyArray<{ - readonly file?: string - readonly patch?: string - readonly additions: number - readonly deletions: number - readonly status?: "added" | "deleted" | "modified" + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.deleted" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + info: { + id: string + slug: string + projectID: string + workspaceID?: string + directory: string + path?: string + parentID?: string + summary?: { + additions: number + deletions: number + files: number + diffs?: Array<{ + file?: string + patch?: string + additions: number + deletions: number + status?: "added" | "deleted" | "modified" }> } - readonly cost?: number - readonly tokens?: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } - readonly share?: { readonly url: string } - readonly title: string - readonly agent?: string - readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly version: string - readonly metadata?: { readonly [x: string]: any } - readonly time: { - readonly created: number - readonly updated: number - readonly compacting?: number - readonly archived?: number - } - readonly permission?: ReadonlyArray<{ - readonly permission: string - readonly pattern: string - readonly action: "allow" | "deny" | "ask" - }> - readonly revert?: { - readonly messageID: string - readonly partID?: string - readonly snapshot?: string - readonly diff?: string - } + cost?: number + tokens?: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } + share?: { url: string } + title: string + agent?: string + model?: { id: string; providerID: string; variant?: string } + version: string + metadata?: { [x: string]: any } + time: { created: number; updated: number; compacting?: number; archived?: number } + permission?: Array<{ permission: string; pattern: string; action: "allow" | "deny" | "ask" }> + revert?: { messageID: string; partID?: string; snapshot?: string; diff?: string } } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "message.updated" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly info: + id: string + created: number + metadata?: { [x: string]: unknown } + type: "message.updated" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + info: | { - readonly id: string - readonly sessionID: string - readonly role: "user" - readonly time: { readonly created: number } - readonly format?: + id: string + sessionID: string + role: "user" + time: { created: number } + format?: | ( - | { readonly type: "text" } - | { - readonly type: "json_schema" - readonly schema: { readonly [x: string]: any } - readonly retryCount?: number | undefined | undefined - } + | { type: "text" } + | { type: "json_schema"; schema: { [x: string]: any }; retryCount?: number | undefined | undefined } ) | undefined - readonly summary?: + summary?: | { - readonly title?: string | undefined - readonly body?: string | undefined - readonly diffs: ReadonlyArray<{ - readonly file?: string - readonly patch?: string - readonly additions: number - readonly deletions: number - readonly status?: "added" | "deleted" | "modified" + title?: string | undefined + body?: string | undefined + diffs: Array<{ + file?: string + patch?: string + additions: number + deletions: number + status?: "added" | "deleted" | "modified" }> } | undefined - readonly agent: string - readonly model: { - readonly providerID: string - readonly modelID: string - readonly variant?: string | undefined - } - readonly system?: string | undefined - readonly tools?: { readonly [x: string]: boolean } | undefined + agent: string + model: { providerID: string; modelID: string; variant?: string | undefined } + system?: string | undefined + tools?: { [x: string]: boolean } | undefined } | { - readonly id: string - readonly sessionID: string - readonly role: "assistant" - readonly time: { readonly created: number; readonly completed?: number | undefined } - readonly error?: + id: string + sessionID: string + role: "assistant" + time: { created: number; completed?: number | undefined } + error?: + | { name: "ProviderAuthError"; data: { providerID: string; message: string } } + | { name: "UnknownError"; data: { message: string; ref?: string | undefined } } + | { name: "MessageOutputLengthError"; data: {} } + | { name: "MessageAbortedError"; data: { message: string } } + | { name: "StructuredOutputError"; data: { message: string; retries: number } } + | { name: "ContextOverflowError"; data: { message: string; responseBody?: string | undefined } } + | { name: "ContentFilterError"; data: { message: string } } | { - readonly name: "ProviderAuthError" - readonly data: { readonly providerID: string; readonly message: string } - } - | { - readonly name: "UnknownError" - readonly data: { readonly message: string; readonly ref?: string | undefined } - } - | { readonly name: "MessageOutputLengthError"; readonly data: {} } - | { readonly name: "MessageAbortedError"; readonly data: { readonly message: string } } - | { - readonly name: "StructuredOutputError" - readonly data: { readonly message: string; readonly retries: number } - } - | { - readonly name: "ContextOverflowError" - readonly data: { readonly message: string; readonly responseBody?: string | undefined } - } - | { readonly name: "ContentFilterError"; readonly data: { readonly message: string } } - | { - readonly name: "APIError" - readonly data: { - readonly message: string - readonly statusCode?: number | undefined - readonly isRetryable: boolean - readonly responseHeaders?: { readonly [x: string]: string } | undefined - readonly responseBody?: string | undefined - readonly metadata?: { readonly [x: string]: string } | undefined + name: "APIError" + data: { + message: string + statusCode?: number | undefined + isRetryable: boolean + responseHeaders?: { [x: string]: string } | undefined + responseBody?: string | undefined + metadata?: { [x: string]: string } | undefined } } | undefined - readonly parentID: string - readonly modelID: string - readonly providerID: string - readonly mode: string - readonly agent: string - readonly path: { readonly cwd: string; readonly root: string } - readonly summary?: boolean | undefined - readonly cost: number - readonly tokens: { - readonly total?: number | undefined - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } + parentID: string + modelID: string + providerID: string + mode: string + agent: string + path: { cwd: string; root: string } + summary?: boolean | undefined + cost: number + tokens: { + total?: number | undefined + input: number + output: number + reasoning: number + cache: { read: number; write: number } } - readonly structured?: any | undefined - readonly variant?: string | undefined - readonly finish?: string | undefined + structured?: any | undefined + variant?: string | undefined + finish?: string | undefined } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "message.removed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly messageID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "message.removed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; messageID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "message.part.updated" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly part: + id: string + created: number + metadata?: { [x: string]: unknown } + type: "message.part.updated" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + part: | { - readonly id: string - readonly sessionID: string - readonly messageID: string - readonly type: "text" - readonly text: string - readonly synthetic?: boolean | undefined - readonly ignored?: boolean | undefined - readonly time?: { readonly start: number; readonly end?: number | undefined } | undefined - readonly metadata?: { readonly [x: string]: any } | undefined + id: string + sessionID: string + messageID: string + type: "text" + text: string + synthetic?: boolean | undefined + ignored?: boolean | undefined + time?: { start: number; end?: number | undefined } | undefined + metadata?: { [x: string]: any } | undefined } | { - readonly id: string - readonly sessionID: string - readonly messageID: string - readonly type: "subtask" - readonly prompt: string - readonly description: string - readonly agent: string - readonly model?: { readonly providerID: string; readonly modelID: string } | undefined - readonly command?: string | undefined + id: string + sessionID: string + messageID: string + type: "subtask" + prompt: string + description: string + agent: string + model?: { providerID: string; modelID: string } | undefined + command?: string | undefined } | { - readonly id: string - readonly sessionID: string - readonly messageID: string - readonly type: "reasoning" - readonly text: string - readonly metadata?: { readonly [x: string]: any } | undefined - readonly time: { readonly start: number; readonly end?: number | undefined } + id: string + sessionID: string + messageID: string + type: "reasoning" + text: string + metadata?: { [x: string]: any } | undefined + time: { start: number; end?: number | undefined } } | { - readonly id: string - readonly sessionID: string - readonly messageID: string - readonly type: "file" - readonly mime: string - readonly filename?: string | undefined - readonly url: string - readonly source?: + id: string + sessionID: string + messageID: string + type: "file" + mime: string + filename?: string | undefined + url: string + source?: | ( + | { text: { value: string; start: number; end: number }; type: "file"; path: string } | { - readonly text: { readonly value: string; readonly start: number; readonly end: number } - readonly type: "file" - readonly path: string + text: { value: string; start: number; end: number } + type: "symbol" + path: string + range: { start: { line: number; character: number }; end: { line: number; character: number } } + name: string + kind: number } | { - readonly text: { readonly value: string; readonly start: number; readonly end: number } - readonly type: "symbol" - readonly path: string - readonly range: { - readonly start: { readonly line: number; readonly character: number } - readonly end: { readonly line: number; readonly character: number } - } - readonly name: string - readonly kind: number - } - | { - readonly text: { readonly value: string; readonly start: number; readonly end: number } - readonly type: "resource" - readonly clientName: string - readonly uri: string + text: { value: string; start: number; end: number } + type: "resource" + clientName: string + uri: string } ) | undefined } | { - readonly id: string - readonly sessionID: string - readonly messageID: string - readonly type: "tool" - readonly callID: string - readonly tool: string - readonly state: - | { readonly status: "pending"; readonly input: { readonly [x: string]: any }; readonly raw: string } + id: string + sessionID: string + messageID: string + type: "tool" + callID: string + tool: string + state: + | { status: "pending"; input: { [x: string]: any }; raw: string } | { - readonly status: "running" - readonly input: { readonly [x: string]: any } - readonly title?: string | undefined - readonly metadata?: { readonly [x: string]: any } | undefined - readonly time: { readonly start: number } + status: "running" + input: { [x: string]: any } + title?: string | undefined + metadata?: { [x: string]: any } | undefined + time: { start: number } } | { - readonly status: "completed" - readonly input: { readonly [x: string]: any } - readonly output: string - readonly title: string - readonly metadata: { readonly [x: string]: any } - readonly time: { - readonly start: number - readonly end: number - readonly compacted?: number | undefined - } - readonly attachments?: - | ReadonlyArray<{ - readonly id: string - readonly sessionID: string - readonly messageID: string - readonly type: "file" - readonly mime: string - readonly filename?: string | undefined - readonly url: string - readonly source?: + status: "completed" + input: { [x: string]: any } + output: string + title: string + metadata: { [x: string]: any } + time: { start: number; end: number; compacted?: number | undefined } + attachments?: + | Array<{ + id: string + sessionID: string + messageID: string + type: "file" + mime: string + filename?: string | undefined + url: string + source?: | ( + | { text: { value: string; start: number; end: number }; type: "file"; path: string } | { - readonly text: { - readonly value: string - readonly start: number - readonly end: number + text: { value: string; start: number; end: number } + type: "symbol" + path: string + range: { + start: { line: number; character: number } + end: { line: number; character: number } } - readonly type: "file" - readonly path: string + name: string + kind: number } | { - readonly text: { - readonly value: string - readonly start: number - readonly end: number - } - readonly type: "symbol" - readonly path: string - readonly range: { - readonly start: { readonly line: number; readonly character: number } - readonly end: { readonly line: number; readonly character: number } - } - readonly name: string - readonly kind: number - } - | { - readonly text: { - readonly value: string - readonly start: number - readonly end: number - } - readonly type: "resource" - readonly clientName: string - readonly uri: string + text: { value: string; start: number; end: number } + type: "resource" + clientName: string + uri: string } ) | undefined @@ -4516,1124 +4609,1022 @@ export type EventSubscribeOutput = | undefined } | { - readonly status: "error" - readonly input: { readonly [x: string]: any } - readonly error: string - readonly metadata?: { readonly [x: string]: any } | undefined - readonly time: { readonly start: number; readonly end: number } + status: "error" + input: { [x: string]: any } + error: string + metadata?: { [x: string]: any } | undefined + time: { start: number; end: number } } - readonly metadata?: { readonly [x: string]: any } | undefined + metadata?: { [x: string]: any } | undefined } + | { id: string; sessionID: string; messageID: string; type: "step-start"; snapshot?: string | undefined } | { - readonly id: string - readonly sessionID: string - readonly messageID: string - readonly type: "step-start" - readonly snapshot?: string | undefined - } - | { - readonly id: string - readonly sessionID: string - readonly messageID: string - readonly type: "step-finish" - readonly reason: string - readonly snapshot?: string | undefined - readonly cost: number - readonly tokens: { - readonly total?: number | undefined - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } + id: string + sessionID: string + messageID: string + type: "step-finish" + reason: string + snapshot?: string | undefined + cost: number + tokens: { + total?: number | undefined + input: number + output: number + reasoning: number + cache: { read: number; write: number } } } + | { id: string; sessionID: string; messageID: string; type: "snapshot"; snapshot: string } + | { id: string; sessionID: string; messageID: string; type: "patch"; hash: string; files: Array } | { - readonly id: string - readonly sessionID: string - readonly messageID: string - readonly type: "snapshot" - readonly snapshot: string + id: string + sessionID: string + messageID: string + type: "agent" + name: string + source?: { value: string; start: number; end: number } | undefined } | { - readonly id: string - readonly sessionID: string - readonly messageID: string - readonly type: "patch" - readonly hash: string - readonly files: ReadonlyArray - } - | { - readonly id: string - readonly sessionID: string - readonly messageID: string - readonly type: "agent" - readonly name: string - readonly source?: { readonly value: string; readonly start: number; readonly end: number } | undefined - } - | { - readonly id: string - readonly sessionID: string - readonly messageID: string - readonly type: "retry" - readonly attempt: number - readonly error: { - readonly name: "APIError" - readonly data: { - readonly message: string - readonly statusCode?: number | undefined - readonly isRetryable: boolean - readonly responseHeaders?: { readonly [x: string]: string } | undefined - readonly responseBody?: string | undefined - readonly metadata?: { readonly [x: string]: string } | undefined + id: string + sessionID: string + messageID: string + type: "retry" + attempt: number + error: { + name: "APIError" + data: { + message: string + statusCode?: number | undefined + isRetryable: boolean + responseHeaders?: { [x: string]: string } | undefined + responseBody?: string | undefined + metadata?: { [x: string]: string } | undefined } } - readonly time: { readonly created: number } + time: { created: number } } | { - readonly id: string - readonly sessionID: string - readonly messageID: string - readonly type: "compaction" - readonly auto: boolean - readonly overflow?: boolean | undefined - readonly tail_start_id?: string | undefined + id: string + sessionID: string + messageID: string + type: "compaction" + auto: boolean + overflow?: boolean | undefined + tail_start_id?: string | undefined } - readonly time: number + time: number } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "message.part.removed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly messageID: string; readonly partID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "message.part.removed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; messageID: string; partID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.agent.selected" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly agent: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.agent.selected" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; agent: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.model.selected" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.model.selected" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; model: { id: string; providerID: string; variant?: string } } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.moved" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; location: { directory: string; workspaceID?: string }; subpath?: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.renamed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; title: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.usage.updated" + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + cost: number + tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.moved" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly location: { readonly directory: string; readonly workspaceID?: string } - readonly subpath?: string - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.deleted" + durable: { aggregateID: string; seq: number; version: 2 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.renamed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly title: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.forked" + durable: { aggregateID: string; seq: number; version: 2 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; parentID: string; parentSeq: number; from?: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.usage.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly cost: number - readonly tokens: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.input.promoted" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; inputID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.deleted" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 2 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.forked" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly parentID: string; readonly from?: string } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.input.promoted" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly inputID: string } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.input.admitted" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly inputID: string - readonly input: + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.input.admitted" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + inputID: string + input: | { - readonly type: "user" - readonly data: { - readonly text: string - readonly files?: ReadonlyArray<{ - readonly data: string - readonly mime: string - readonly source: { readonly type: "inline" } | { readonly type: "uri"; readonly uri: string } - readonly name?: string - readonly description?: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } + type: "user" + data: { + text: string + files?: Array<{ + data: string + mime: string + source: { type: "inline" } | { type: "uri"; uri: string } + name?: string + description?: string + mention?: { start: number; end: number; text: string } }> - readonly agents?: ReadonlyArray<{ - readonly name: string - readonly mention?: { readonly start: number; readonly end: number; readonly text: string } - }> - readonly metadata?: { readonly [x: string]: unknown } + agents?: Array<{ name: string; mention?: { start: number; end: number; text: string } }> + metadata?: { [x: string]: unknown } } - readonly delivery: "steer" | "queue" + delivery: "steer" | "queue" } | { - readonly type: "synthetic" - readonly data: { - readonly text: string - readonly description?: string - readonly metadata?: { readonly [x: string]: unknown } - } - readonly delivery: "steer" | "queue" + type: "synthetic" + data: { text: string; description?: string; metadata?: { [x: string]: unknown } } + delivery: "steer" | "queue" } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.execution.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.execution.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.execution.succeeded" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.execution.succeeded" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.execution.failed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly error: { readonly type: string; readonly message: string } } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.execution.failed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; error: { type: string; message: string } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.execution.interrupted" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly reason: "user" | "shutdown" | "superseded" } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.execution.interrupted" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; reason: "user" | "shutdown" | "superseded" } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.instructions.updated" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly text: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.instructions.updated" + durable: { aggregateID: string; seq: number; version: 2 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; delta: { [x: string]: string | "removed" } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.synthetic" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly text: string - readonly description?: string - readonly metadata?: { readonly [x: string]: unknown } - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.synthetic" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; text: string; description?: string; metadata?: { [x: string]: unknown } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.skill.activated" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly id: string; readonly name: string; readonly text: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.skill.activated" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; id: string; name: string; text: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.shell.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly shell: { - readonly id: string - readonly status: "running" | "exited" | "timeout" | "killed" - readonly command: string - readonly cwd: string - readonly shell: string - readonly file: string - readonly pid?: number - readonly exit?: number - readonly metadata: { readonly [x: string]: unknown } - readonly time: { readonly started: number; readonly completed?: number } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.shell.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + shell: { + id: string + status: "running" | "exited" | "timeout" | "killed" + command: string + cwd: string + shell: string + file: string + pid?: number + exit?: number + metadata: { [x: string]: unknown } + time: { started: number; completed?: number } } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.shell.ended" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly shell: { - readonly id: string - readonly status: "running" | "exited" | "timeout" | "killed" - readonly command: string - readonly cwd: string - readonly shell: string - readonly file: string - readonly pid?: number - readonly exit?: number - readonly metadata: { readonly [x: string]: unknown } - readonly time: { readonly started: number; readonly completed?: number } - } - readonly output: { - readonly output: string - readonly cursor: number - readonly size: number - readonly truncated: boolean + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.shell.ended" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + shell: { + id: string + status: "running" | "exited" | "timeout" | "killed" + command: string + cwd: string + shell: string + file: string + pid?: number + exit?: number + metadata: { [x: string]: unknown } + time: { started: number; completed?: number } } + output: { output: string; cursor: number; size: number; truncated: boolean } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.step.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly agent: string - readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } - readonly snapshot?: string + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.step.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + agent: string + model: { id: string; providerID: string; variant?: string } + snapshot?: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.step.ended" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly finish: "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown" - readonly cost: number - readonly tokens: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } - readonly snapshot?: string - readonly files?: ReadonlyArray + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.step.ended" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + finish: "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown" + cost: number + tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } + snapshot?: string + files?: Array } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.step.failed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly error: { readonly type: string; readonly message: string } - readonly cost?: number - readonly tokens?: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { readonly read: number; readonly write: number } - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.step.failed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + error: { type: string; message: string } + cost?: number + tokens?: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.text.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly assistantMessageID: string; readonly ordinal: number } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.text.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; assistantMessageID: string; ordinal: number } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.text.delta" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly ordinal: number - readonly delta: string + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.text.delta" + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; assistantMessageID: string; ordinal: number; delta: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.text.ended" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; assistantMessageID: string; ordinal: number; text: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.reasoning.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; assistantMessageID: string; ordinal: number; state?: { [x: string]: unknown } } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.reasoning.delta" + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; assistantMessageID: string; ordinal: number; delta: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.reasoning.ended" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + ordinal: number + text: string + state?: { [x: string]: unknown } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.text.ended" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly ordinal: number - readonly text: string + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.tool.input.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; assistantMessageID: string; callID: string; name: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.tool.input.delta" + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; assistantMessageID: string; callID: string; delta: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.tool.input.ended" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; assistantMessageID: string; callID: string; text: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.tool.called" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + callID: string + input: { [x: string]: unknown } + executed: boolean + state?: { [x: string]: unknown } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.reasoning.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly ordinal: number - readonly state?: { readonly [x: string]: unknown } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.tool.progress" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + callID: string + structured: { [x: string]: unknown } + content: Array<{ type: "text"; text: string } | { type: "file"; uri: string; mime: string; name?: string }> } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.reasoning.delta" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly ordinal: number - readonly delta: string + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.tool.success" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + callID: string + structured: { [x: string]: unknown } + content: Array<{ type: "text"; text: string } | { type: "file"; uri: string; mime: string; name?: string }> + result?: unknown + executed: boolean + resultState?: { [x: string]: unknown } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.reasoning.ended" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly ordinal: number - readonly text: string - readonly state?: { readonly [x: string]: unknown } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.tool.failed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + callID: string + error: { type: string; message: string } + result?: unknown + executed: boolean + resultState?: { [x: string]: unknown } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.tool.input.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly callID: string - readonly name: string + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.retry.scheduled" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + assistantMessageID: string + attempt: number + at: number + error: { type: string; message: string } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.tool.input.delta" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly callID: string - readonly delta: string - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.compaction.admitted" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; inputID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.tool.input.ended" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly callID: string - readonly text: string - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.compaction.started" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; reason: "auto" | "manual"; recent: string; inputID?: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.tool.called" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly callID: string - readonly input: { readonly [x: string]: unknown } - readonly executed: boolean - readonly state?: { readonly [x: string]: unknown } - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.compaction.delta" + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; text: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.tool.progress" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly callID: string - readonly structured: { readonly [x: string]: unknown } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } - | { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string } - > - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.compaction.ended" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; reason: "auto" | "manual"; text: string; recent: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.tool.success" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly callID: string - readonly structured: { readonly [x: string]: unknown } - readonly content: ReadonlyArray< - | { readonly type: "text"; readonly text: string } - | { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string } - > - readonly result?: unknown - readonly executed: boolean - readonly resultState?: { readonly [x: string]: unknown } - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.compaction.failed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; reason: "auto" | "manual"; error: { type: string; message: string }; inputID?: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.tool.failed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly callID: string - readonly error: { readonly type: string; readonly message: string } - readonly result?: unknown - readonly executed: boolean - readonly resultState?: { readonly [x: string]: unknown } - } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.retry.scheduled" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly assistantMessageID: string - readonly attempt: number - readonly at: number - readonly error: { readonly type: string; readonly message: string } - } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.compaction.admitted" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly inputID: string } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.compaction.started" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly reason: "auto" | "manual" - readonly recent: string - readonly inputID?: string - } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.compaction.delta" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly text: string } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.compaction.ended" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly reason: "auto" | "manual" - readonly text: string - readonly recent: string - } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.compaction.failed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly reason: "auto" | "manual" - readonly error: { readonly type: string; readonly message: string } - readonly inputID?: string - } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.revert.staged" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly revert: { - readonly messageID: string - readonly partID?: string - readonly snapshot?: string - readonly files?: ReadonlyArray<{ - readonly file: string - readonly patch: string - readonly additions: number - readonly deletions: number - readonly status: "added" | "deleted" | "modified" + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.revert.staged" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + revert: { + messageID: string + partID?: string + snapshot?: string + files?: Array<{ + file: string + patch: string + additions: number + deletions: number + status: "added" | "deleted" | "modified" }> } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.revert.cleared" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.revert.cleared" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.revert.committed" - readonly durable: { readonly aggregateID: string; readonly seq: number; readonly version: 1 } - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly to: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.revert.committed" + durable: { aggregateID: string; seq: number; version: 1 } + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; to: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "filesystem.changed" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly file: string; readonly event: "add" | "change" | "unlink" } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "filesystem.changed" + location?: { directory: string; workspaceID?: string } + data: { file: string; event: "add" | "change" | "unlink" } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "reference.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: {} + id: string + created: number + metadata?: { [x: string]: unknown } + type: "reference.updated" + location?: { directory: string; workspaceID?: string } + data: {} } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "permission.v2.asked" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly id: string - readonly sessionID: string - readonly action: string - readonly resources: ReadonlyArray - readonly save?: ReadonlyArray - readonly metadata?: { readonly [x: string]: unknown } - readonly source?: { readonly type: "tool"; readonly messageID: string; readonly callID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "permission.v2.asked" + location?: { directory: string; workspaceID?: string } + data: { + id: string + sessionID: string + action: string + resources: Array + save?: Array + metadata?: { [x: string]: unknown } + source?: { type: "tool"; messageID: string; callID: string } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "permission.v2.replied" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly requestID: string - readonly reply: "once" | "always" | "reject" - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "permission.v2.replied" + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; requestID: string; reply: "once" | "always" | "reject" } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "plugin.added" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly id: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "plugin.added" + location?: { directory: string; workspaceID?: string } + data: { id: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "plugin.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: {} + id: string + created: number + metadata?: { [x: string]: unknown } + type: "plugin.updated" + location?: { directory: string; workspaceID?: string } + data: {} } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "project.directories.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly projectID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "project.directories.updated" + location?: { directory: string; workspaceID?: string } + data: { projectID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "command.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: {} + id: string + created: number + metadata?: { [x: string]: unknown } + type: "command.updated" + location?: { directory: string; workspaceID?: string } + data: {} } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "config.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: {} + id: string + created: number + metadata?: { [x: string]: unknown } + type: "config.updated" + location?: { directory: string; workspaceID?: string } + data: {} } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "skill.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: {} + id: string + created: number + metadata?: { [x: string]: unknown } + type: "skill.updated" + location?: { directory: string; workspaceID?: string } + data: {} } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "pty.created" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly info: { - readonly id: string - readonly title: string - readonly command: string - readonly args: ReadonlyArray - readonly cwd: string - readonly status: "running" | "exited" - readonly pid: number - readonly exitCode?: number + id: string + created: number + metadata?: { [x: string]: unknown } + type: "pty.created" + location?: { directory: string; workspaceID?: string } + data: { + info: { + id: string + title: string + command: string + args: Array + cwd: string + status: "running" | "exited" + pid: number + exitCode?: number } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "pty.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly info: { - readonly id: string - readonly title: string - readonly command: string - readonly args: ReadonlyArray - readonly cwd: string - readonly status: "running" | "exited" - readonly pid: number - readonly exitCode?: number + id: string + created: number + metadata?: { [x: string]: unknown } + type: "pty.updated" + location?: { directory: string; workspaceID?: string } + data: { + info: { + id: string + title: string + command: string + args: Array + cwd: string + status: "running" | "exited" + pid: number + exitCode?: number } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "pty.exited" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly id: string; readonly exitCode: number } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "pty.exited" + location?: { directory: string; workspaceID?: string } + data: { id: string; exitCode: number } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "pty.deleted" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly id: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "pty.deleted" + location?: { directory: string; workspaceID?: string } + data: { id: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "shell.created" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly info: { - readonly id: string - readonly status: "running" | "exited" | "timeout" | "killed" - readonly command: string - readonly cwd: string - readonly shell: string - readonly file: string - readonly pid?: number - readonly exit?: number - readonly metadata: { readonly [x: string]: unknown } - readonly time: { readonly started: number; readonly completed?: number } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "shell.created" + location?: { directory: string; workspaceID?: string } + data: { + info: { + id: string + status: "running" | "exited" | "timeout" | "killed" + command: string + cwd: string + shell: string + file: string + pid?: number + exit?: number + metadata: { [x: string]: unknown } + time: { started: number; completed?: number } } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "shell.exited" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly id: string - readonly exit?: number - readonly status: "running" | "exited" | "timeout" | "killed" - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "shell.exited" + location?: { directory: string; workspaceID?: string } + data: { id: string; exit?: number; status: "running" | "exited" | "timeout" | "killed" } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "shell.deleted" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly id: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "shell.deleted" + location?: { directory: string; workspaceID?: string } + data: { id: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "question.v2.asked" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly id: string - readonly sessionID: string - readonly questions: ReadonlyArray<{ - readonly question: string - readonly header: string - readonly options: ReadonlyArray<{ readonly label: string; readonly description: string }> - readonly multiple?: boolean - readonly custom?: boolean + id: string + created: number + metadata?: { [x: string]: unknown } + type: "question.v2.asked" + location?: { directory: string; workspaceID?: string } + data: { + id: string + sessionID: string + questions: Array<{ + question: string + header: string + options: Array<{ label: string; description: string }> + multiple?: boolean + custom?: boolean }> - readonly tool?: { readonly messageID: string; readonly callID: string } + tool?: { messageID: string; callID: string } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "question.v2.replied" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly requestID: string - readonly answers: ReadonlyArray> + id: string + created: number + metadata?: { [x: string]: unknown } + type: "question.v2.replied" + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; requestID: string; answers: Array> } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "question.v2.rejected" + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; requestID: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "form.created" + location?: { directory: string; workspaceID?: string } + data: { + form: { + id: string + sessionID: string + title: string + metadata?: { [x: string]: unknown } + fields: [ + ( + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ key: string; op: "eq" | "neq"; value: string | number | boolean }> + type: "string" + format?: "email" | "uri" | "date" | "date-time" + minLength?: number + maxLength?: number + pattern?: string + placeholder?: string + default?: string + options?: Array<{ value: string; label: string; description?: string }> + custom?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ key: string; op: "eq" | "neq"; value: string | number | boolean }> + type: "number" + minimum?: number + maximum?: number + default?: number + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ key: string; op: "eq" | "neq"; value: string | number | boolean }> + type: "integer" + minimum?: number + maximum?: number + default?: number + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ key: string; op: "eq" | "neq"; value: string | number | boolean }> + type: "boolean" + default?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ key: string; op: "eq" | "neq"; value: string | number | boolean }> + type: "multiselect" + options: Array<{ value: string; label: string; description?: string }> + minItems?: number + maxItems?: number + custom?: boolean + default?: Array + } + | { key: string; type: "external"; url: string; title?: string; description?: string } + ), + ...Array< + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ key: string; op: "eq" | "neq"; value: string | number | boolean }> + type: "string" + format?: "email" | "uri" | "date" | "date-time" + minLength?: number + maxLength?: number + pattern?: string + placeholder?: string + default?: string + options?: Array<{ value: string; label: string; description?: string }> + custom?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ key: string; op: "eq" | "neq"; value: string | number | boolean }> + type: "number" + minimum?: number + maximum?: number + default?: number + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ key: string; op: "eq" | "neq"; value: string | number | boolean }> + type: "integer" + minimum?: number + maximum?: number + default?: number + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ key: string; op: "eq" | "neq"; value: string | number | boolean }> + type: "boolean" + default?: boolean + } + | { + key: string + title?: string + description?: string + required?: boolean + when?: Array<{ key: string; op: "eq" | "neq"; value: string | number | boolean }> + type: "multiselect" + options: Array<{ value: string; label: string; description?: string }> + minItems?: number + maxItems?: number + custom?: boolean + default?: Array + } + | { key: string; type: "external"; url: string; title?: string; description?: string } + >, + ] + } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "question.v2.rejected" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly requestID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "form.replied" + location?: { directory: string; workspaceID?: string } + data: { id: string; sessionID: string; answer: { [x: string]: string | number | boolean | Array } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "form.created" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly form: + id: string + created: number + metadata?: { [x: string]: unknown } + type: "form.cancelled" + location?: { directory: string; workspaceID?: string } + data: { id: string; sessionID: string } + } + | { + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.status" + location?: { directory: string; workspaceID?: string } + data: { + sessionID: string + status: + | { type: "idle" } | { - readonly id: string - readonly sessionID: string - readonly title: string - readonly metadata?: { readonly [x: string]: unknown } - readonly mode: "form" - readonly fields: ReadonlyArray< - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | boolean - }> - readonly type: "string" - readonly format?: "email" | "uri" | "date" | "date-time" - readonly minLength?: number - readonly maxLength?: number - readonly pattern?: string - readonly placeholder?: string - readonly default?: string - readonly options?: ReadonlyArray<{ - readonly value: string - readonly label: string - readonly description?: string - }> - readonly custom?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | boolean - }> - readonly type: "number" - readonly minimum?: number - readonly maximum?: number - readonly default?: number - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | boolean - }> - readonly type: "integer" - readonly minimum?: number - readonly maximum?: number - readonly default?: number - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | boolean - }> - readonly type: "boolean" - readonly default?: boolean - } - | { - readonly key: string - readonly title?: string - readonly description?: string - readonly required?: boolean - readonly when?: ReadonlyArray<{ - readonly key: string - readonly op: "eq" | "neq" - readonly value: string | number | boolean - }> - readonly type: "multiselect" - readonly options: ReadonlyArray<{ - readonly value: string - readonly label: string - readonly description?: string - }> - readonly minItems?: number - readonly maxItems?: number - readonly custom?: boolean - readonly default?: ReadonlyArray - } - > - } - | { - readonly id: string - readonly sessionID: string - readonly title: string - readonly metadata?: { readonly [x: string]: unknown } - readonly mode: "url" - readonly url: string - } - } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "form.replied" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly id: string - readonly sessionID: string - readonly answer: { readonly [x: string]: string | number | boolean | ReadonlyArray } - } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "form.cancelled" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly id: string; readonly sessionID: string } - } - | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.status" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly status: - | { readonly type: "idle" } - | { - readonly type: "retry" - readonly attempt: number - readonly message: string - readonly action?: { - readonly reason: string - readonly provider: string - readonly title: string - readonly message: string - readonly label: string - readonly link?: string + type: "retry" + attempt: number + message: string + action?: { + reason: string + provider: string + title: string + message: string + label: string + link?: string } - readonly next: number + next: number } - | { readonly type: "busy" } + | { type: "busy" } } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.idle" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.idle" + location?: { directory: string; workspaceID?: string } + data: { sessionID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "tui.prompt.append" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly text: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "tui.prompt.append" + location?: { directory: string; workspaceID?: string } + data: { text: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "tui.command.execute" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly command: + id: string + created: number + metadata?: { [x: string]: unknown } + type: "tui.command.execute" + location?: { directory: string; workspaceID?: string } + data: { + command: | "session.list" | "session.new" | "session.share" @@ -5655,181 +5646,161 @@ export type EventSubscribeOutput = } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "tui.toast.show" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly title?: string - readonly message: string - readonly variant: "info" | "success" | "warning" | "error" - readonly duration?: number | undefined + id: string + created: number + metadata?: { [x: string]: unknown } + type: "tui.toast.show" + location?: { directory: string; workspaceID?: string } + data: { + title?: string + message: string + variant: "info" | "success" | "warning" | "error" + duration?: number | undefined } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "tui.session.select" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "tui.session.select" + location?: { directory: string; workspaceID?: string } + data: { sessionID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "installation.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly version: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "installation.updated" + location?: { directory: string; workspaceID?: string } + data: { version: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "installation.update-available" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly version: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "installation.update-available" + location?: { directory: string; workspaceID?: string } + data: { version: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "vcs.branch.updated" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly branch?: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "vcs.branch.updated" + location?: { directory: string; workspaceID?: string } + data: { branch?: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "mcp.status.changed" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly server: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "mcp.status.changed" + location?: { directory: string; workspaceID?: string } + data: { server: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "mcp.resources.changed" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly server: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "mcp.resources.changed" + location?: { directory: string; workspaceID?: string } + data: { server: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "permission.asked" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly id: string - readonly sessionID: string - readonly permission: string - readonly patterns: ReadonlyArray - readonly metadata: { readonly [x: string]: unknown } - readonly always: ReadonlyArray - readonly tool?: { readonly messageID: string; readonly callID: string } | undefined + id: string + created: number + metadata?: { [x: string]: unknown } + type: "permission.asked" + location?: { directory: string; workspaceID?: string } + data: { + id: string + sessionID: string + permission: string + patterns: Array + metadata: { [x: string]: unknown } + always: Array + tool?: { messageID: string; callID: string } | undefined } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "permission.replied" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly requestID: string - readonly reply: "once" | "always" | "reject" - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "permission.replied" + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; requestID: string; reply: "once" | "always" | "reject" } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "question.asked" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly id: string - readonly sessionID: string - readonly questions: ReadonlyArray<{ - readonly question: string - readonly header: string - readonly options: ReadonlyArray<{ readonly label: string; readonly description: string }> - readonly multiple?: boolean | undefined - readonly custom?: boolean | undefined + id: string + created: number + metadata?: { [x: string]: unknown } + type: "question.asked" + location?: { directory: string; workspaceID?: string } + data: { + id: string + sessionID: string + questions: Array<{ + question: string + header: string + options: Array<{ label: string; description: string }> + multiple?: boolean | undefined + custom?: boolean | undefined }> - readonly tool?: { readonly messageID: string; readonly callID: string } | undefined + tool?: { messageID: string; callID: string } | undefined } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "question.replied" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID: string - readonly requestID: string - readonly answers: ReadonlyArray> - } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "question.replied" + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; requestID: string; answers: Array> } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "question.rejected" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { readonly sessionID: string; readonly requestID: string } + id: string + created: number + metadata?: { [x: string]: unknown } + type: "question.rejected" + location?: { directory: string; workspaceID?: string } + data: { sessionID: string; requestID: string } } | { - readonly id: string - readonly created: number - readonly metadata?: { readonly [x: string]: unknown } - readonly type: "session.error" - readonly location?: { readonly directory: string; readonly workspaceID?: string } - readonly data: { - readonly sessionID?: string | undefined - readonly error?: + id: string + created: number + metadata?: { [x: string]: unknown } + type: "session.error" + location?: { directory: string; workspaceID?: string } + data: { + sessionID?: string | undefined + error?: + | { name: "ProviderAuthError"; data: { providerID: string; message: string } } + | { name: "UnknownError"; data: { message: string; ref?: string | undefined } } + | { name: "MessageOutputLengthError"; data: {} } + | { name: "MessageAbortedError"; data: { message: string } } + | { name: "StructuredOutputError"; data: { message: string; retries: number } } + | { name: "ContextOverflowError"; data: { message: string; responseBody?: string | undefined } } + | { name: "ContentFilterError"; data: { message: string } } | { - readonly name: "ProviderAuthError" - readonly data: { readonly providerID: string; readonly message: string } - } - | { - readonly name: "UnknownError" - readonly data: { readonly message: string; readonly ref?: string | undefined } - } - | { readonly name: "MessageOutputLengthError"; readonly data: {} } - | { readonly name: "MessageAbortedError"; readonly data: { readonly message: string } } - | { - readonly name: "StructuredOutputError" - readonly data: { readonly message: string; readonly retries: number } - } - | { - readonly name: "ContextOverflowError" - readonly data: { readonly message: string; readonly responseBody?: string | undefined } - } - | { readonly name: "ContentFilterError"; readonly data: { readonly message: string } } - | { - readonly name: "APIError" - readonly data: { - readonly message: string - readonly statusCode?: number | undefined - readonly isRetryable: boolean - readonly responseHeaders?: { readonly [x: string]: string } | undefined - readonly responseBody?: string | undefined - readonly metadata?: { readonly [x: string]: string } | undefined + name: "APIError" + data: { + message: string + statusCode?: number | undefined + isRetryable: boolean + responseHeaders?: { [x: string]: string } | undefined + responseBody?: string | undefined + metadata?: { [x: string]: string } | undefined } } | undefined } } | { - readonly id: string - readonly metadata?: { readonly [x: string]: unknown } | undefined - readonly location?: { readonly directory: string; readonly workspaceID?: string } | undefined - readonly type: "server.connected" - readonly data: {} + id: string + metadata?: { [x: string]: unknown } | undefined + location?: { directory: string; workspaceID?: string } | undefined + type: "server.connected" + data: {} } export type PtyListInput = { @@ -5839,20 +5810,16 @@ export type PtyListInput = { } export type PtyListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly id: string - readonly title: string - readonly command: string - readonly args: ReadonlyArray - readonly cwd: string - readonly status: "running" | "exited" - readonly pid: number - readonly exitCode?: number + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + id: string + title: string + command: string + args: Array + cwd: string + status: "running" | "exited" + pid: number + exitCode?: number }> } @@ -5898,20 +5865,16 @@ export type PtyCreateInput = { } export type PtyCreateOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: { - readonly id: string - readonly title: string - readonly command: string - readonly args: ReadonlyArray - readonly cwd: string - readonly status: "running" | "exited" - readonly pid: number - readonly exitCode?: number + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: { + id: string + title: string + command: string + args: Array + cwd: string + status: "running" | "exited" + pid: number + exitCode?: number } } @@ -5923,20 +5886,16 @@ export type PtyGetInput = { } export type PtyGetOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: { - readonly id: string - readonly title: string - readonly command: string - readonly args: ReadonlyArray - readonly cwd: string - readonly status: "running" | "exited" - readonly pid: number - readonly exitCode?: number + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: { + id: string + title: string + command: string + args: Array + cwd: string + status: "running" | "exited" + pid: number + exitCode?: number } } @@ -5953,20 +5912,16 @@ export type PtyUpdateInput = { } export type PtyUpdateOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: { - readonly id: string - readonly title: string - readonly command: string - readonly args: ReadonlyArray - readonly cwd: string - readonly status: "running" | "exited" - readonly pid: number - readonly exitCode?: number + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: { + id: string + title: string + command: string + args: Array + cwd: string + status: "running" | "exited" + pid: number + exitCode?: number } } @@ -5986,25 +5941,18 @@ export type ShellListInput = { } export type ShellListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly id: string - readonly status: "running" | "exited" | "timeout" | "killed" - readonly command: string - readonly cwd: string - readonly shell: string - readonly file: string - readonly pid?: number - readonly exit?: number | "Infinity" | "-Infinity" | "NaN" - readonly metadata: { readonly [x: string]: JsonValue } - readonly time: { - readonly started: number | "Infinity" | "-Infinity" | "NaN" - readonly completed?: number | "Infinity" | "-Infinity" | "NaN" - } + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + id: string + status: "running" | "exited" | "timeout" | "killed" + command: string + cwd: string + shell: string + file: string + pid?: number + exit?: number | "Infinity" | "-Infinity" | "NaN" + metadata: { [x: string]: JsonValue } + time: { started: number | "Infinity" | "-Infinity" | "NaN"; completed?: number | "Infinity" | "-Infinity" | "NaN" } }> } @@ -6039,25 +5987,18 @@ export type ShellCreateInput = { } export type ShellCreateOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: { - readonly id: string - readonly status: "running" | "exited" | "timeout" | "killed" - readonly command: string - readonly cwd: string - readonly shell: string - readonly file: string - readonly pid?: number - readonly exit?: number | "Infinity" | "-Infinity" | "NaN" - readonly metadata: { readonly [x: string]: JsonValue } - readonly time: { - readonly started: number | "Infinity" | "-Infinity" | "NaN" - readonly completed?: number | "Infinity" | "-Infinity" | "NaN" - } + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: { + id: string + status: "running" | "exited" | "timeout" | "killed" + command: string + cwd: string + shell: string + file: string + pid?: number + exit?: number | "Infinity" | "-Infinity" | "NaN" + metadata: { [x: string]: JsonValue } + time: { started: number | "Infinity" | "-Infinity" | "NaN"; completed?: number | "Infinity" | "-Infinity" | "NaN" } } } @@ -6069,25 +6010,18 @@ export type ShellGetInput = { } export type ShellGetOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: { - readonly id: string - readonly status: "running" | "exited" | "timeout" | "killed" - readonly command: string - readonly cwd: string - readonly shell: string - readonly file: string - readonly pid?: number - readonly exit?: number | "Infinity" | "-Infinity" | "NaN" - readonly metadata: { readonly [x: string]: JsonValue } - readonly time: { - readonly started: number | "Infinity" | "-Infinity" | "NaN" - readonly completed?: number | "Infinity" | "-Infinity" | "NaN" - } + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: { + id: string + status: "running" | "exited" | "timeout" | "killed" + command: string + cwd: string + shell: string + file: string + pid?: number + exit?: number | "Infinity" | "-Infinity" | "NaN" + metadata: { [x: string]: JsonValue } + time: { started: number | "Infinity" | "-Infinity" | "NaN"; completed?: number | "Infinity" | "-Infinity" | "NaN" } } } @@ -6100,25 +6034,18 @@ export type ShellTimeoutInput = { } export type ShellTimeoutOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: { - readonly id: string - readonly status: "running" | "exited" | "timeout" | "killed" - readonly command: string - readonly cwd: string - readonly shell: string - readonly file: string - readonly pid?: number - readonly exit?: number | "Infinity" | "-Infinity" | "NaN" - readonly metadata: { readonly [x: string]: JsonValue } - readonly time: { - readonly started: number | "Infinity" | "-Infinity" | "NaN" - readonly completed?: number | "Infinity" | "-Infinity" | "NaN" - } + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: { + id: string + status: "running" | "exited" | "timeout" | "killed" + command: string + cwd: string + shell: string + file: string + pid?: number + exit?: number | "Infinity" | "-Infinity" | "NaN" + metadata: { [x: string]: JsonValue } + time: { started: number | "Infinity" | "-Infinity" | "NaN"; completed?: number | "Infinity" | "-Infinity" | "NaN" } } } @@ -6142,17 +6069,8 @@ export type ShellOutputInput = { } export type ShellOutputOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: { - readonly output: string - readonly cursor: number - readonly size: number - readonly truncated: boolean - } + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: { output: string; cursor: number; size: number; truncated: boolean } } export type ShellRemoveInput = { @@ -6171,39 +6089,35 @@ export type QuestionRequestListInput = { } export type QuestionRequestListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly id: string - readonly sessionID: string - readonly questions: ReadonlyArray<{ - readonly question: string - readonly header: string - readonly options: ReadonlyArray<{ readonly label: string; readonly description: string }> - readonly multiple?: boolean - readonly custom?: boolean + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + id: string + sessionID: string + questions: Array<{ + question: string + header: string + options: Array<{ label: string; description: string }> + multiple?: boolean + custom?: boolean }> - readonly tool?: { readonly messageID: string; readonly callID: string } + tool?: { messageID: string; callID: string } }> } export type QuestionListInput = { readonly sessionID: { readonly sessionID: string }["sessionID"] } export type QuestionListOutput = { - readonly data: ReadonlyArray<{ - readonly id: string - readonly sessionID: string - readonly questions: ReadonlyArray<{ - readonly question: string - readonly header: string - readonly options: ReadonlyArray<{ readonly label: string; readonly description: string }> - readonly multiple?: boolean - readonly custom?: boolean + data: Array<{ + id: string + sessionID: string + questions: Array<{ + question: string + header: string + options: Array<{ label: string; description: string }> + multiple?: boolean + custom?: boolean }> - readonly tool?: { readonly messageID: string; readonly callID: string } + tool?: { messageID: string; callID: string } }> }["data"] @@ -6229,25 +6143,15 @@ export type ReferenceListInput = { } export type ReferenceListOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly name: string - readonly path: string - readonly description?: string - readonly hidden?: boolean - readonly source: - | { readonly type: "local"; readonly path: string; readonly description?: string; readonly hidden?: boolean } - | { - readonly type: "git" - readonly repository: string - readonly branch?: string - readonly description?: string - readonly hidden?: boolean - } + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + name: string + path: string + description?: string + hidden?: boolean + source: + | { type: "local"; path: string; description?: string; hidden?: boolean } + | { type: "git"; repository: string; branch?: string; description?: string; hidden?: boolean } }> } @@ -6261,7 +6165,7 @@ export type ProjectCopyCreateInput = { readonly name?: { readonly strategy: string; readonly directory: string; readonly name?: string }["name"] } -export type ProjectCopyCreateOutput = { readonly directory: string } +export type ProjectCopyCreateOutput = { directory: string } export type ProjectCopyRemoveInput = { readonly projectID: { readonly projectID: string }["projectID"] @@ -6290,17 +6194,8 @@ export type VcsStatusInput = { } export type VcsStatusOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly file: string - readonly additions: number - readonly deletions: number - readonly status: "added" | "deleted" | "modified" - }> + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ file: string; additions: number; deletions: number; status: "added" | "deleted" | "modified" }> } export type VcsDiffInput = { @@ -6322,21 +6217,17 @@ export type VcsDiffInput = { } export type VcsDiffOutput = { - readonly location: { - readonly directory: string - readonly workspaceID?: string - readonly project: { readonly id: string; readonly directory: string } - } - readonly data: ReadonlyArray<{ - readonly file: string - readonly patch: string - readonly additions: number - readonly deletions: number - readonly status: "added" | "deleted" | "modified" + location: { directory: string; workspaceID?: string; project: { id: string; directory: string } } + data: Array<{ + file: string + patch: string + additions: number + deletions: number + status: "added" | "deleted" | "modified" }> } -export type DebugLocationListOutput = ReadonlyArray<{ readonly directory: string; readonly workspaceID?: string }> +export type DebugLocationListOutput = Array<{ directory: string; workspaceID?: string }> export type DebugLocationEvictInput = { readonly location?: { diff --git a/packages/client/test/contract-identity.test.ts b/packages/client/test/contract-identity.test.ts index 3b6c1b82b7..8de2115fa7 100644 --- a/packages/client/test/contract-identity.test.ts +++ b/packages/client/test/contract-identity.test.ts @@ -1,25 +1,10 @@ import { expect, test } from "bun:test" import { Schema } from "effect" -import { AgentV2 } from "@opencode-ai/core/agent" -import { Location as CoreLocation } from "@opencode-ai/core/location" -import { ModelV2 } from "@opencode-ai/core/model" -import { ProjectV2 } from "@opencode-ai/core/project" -import { SessionV2 } from "@opencode-ai/core/session" -import { SessionInput as CoreSessionInput } from "@opencode-ai/core/session/input" -import { SessionMessage as CoreSessionMessage } from "@opencode-ai/core/session/message" import { Agent } from "@opencode-ai/schema/agent" -import { Location } from "@opencode-ai/schema/location" import { Model } from "@opencode-ai/schema/model" -import { Project } from "@opencode-ai/schema/project" -import { Provider } from "@opencode-ai/schema/provider" import { Prompt } from "@opencode-ai/schema/prompt" import { Session } from "@opencode-ai/schema/session" -import { SessionInput } from "@opencode-ai/schema/session-input" import { SessionMessage } from "@opencode-ai/schema/session-message" -import { Workspace } from "@opencode-ai/schema/workspace" -import { Api } from "@opencode-ai/server/api" -import { compile, emitPromise } from "@opencode-ai/httpapi-codegen" -import { ClientApi, groupNames, promiseOmitEndpoints } from "../src/contract" const Client = await import("../src/effect") @@ -29,34 +14,6 @@ test("effect entrypoint exposes canonical Schema contracts", () => { expect(Client.Session).toBe(Session) }) -test("Core and Server reuse the authoritative Schema and Protocol values", () => { - expect(AgentV2.ID).toBe(Agent.ID) - expect(CoreLocation.Ref).toBe(Location.Ref) - expect(ModelV2.Ref).toBe(Model.Ref) - expect(SessionV2.Info).toBe(Session.Info) - expect(ProjectV2.Current).toBe(Project.Current) - expect(ProjectV2.Directory).toBe(Project.Directory) - expect(ProjectV2.Directories).toBe(Project.Directories) - expect(CoreSessionInput.Message).toBe(SessionInput.Message) - expect(CoreSessionInput.User).toBe(SessionInput.User) - expect(CoreSessionInput.Synthetic).toBe(SessionInput.Synthetic) - expect(CoreSessionMessage.Info).toBe(SessionMessage.Info) - expect(Api.groups["server.session"].identifier).toBe("server.session") - expect(Api.groups["server.project"].identifier).toBe("server.project") - expect(Object.keys(ClientApi.groups)).toEqual(Object.keys(Api.groups)) - expect(Session.ID.create()).toStartWith("ses_") - expect(Project.ID.global).toBe("global") - expect(Provider.ID.anthropic).toBe("anthropic") - expect(Workspace.ID.create()).toStartWith("wrk_") -}) - -test("client and Server contracts generate identically", () => { - const server = compile(Api, { groupNames, omitEndpoints: promiseOmitEndpoints }) - const client = compile(ClientApi, { groupNames, omitEndpoints: promiseOmitEndpoints }) - - expect(emitPromise(client)).toEqual(emitPromise(server)) -}) - test("shared DTO schemas construct and decode plain objects", () => { const made = Prompt.make({ text: "hello" }) const decoded = Schema.decodeUnknownSync(Prompt)({ text: "hello" }) @@ -67,5 +24,4 @@ test("shared DTO schemas construct and decode plain objects", () => { expect(Object.getPrototypeOf(content)).toBe(Object.prototype) expect(Prompt.ast.annotations?.identifier).toBe("Prompt") expect(SessionMessage.AssistantText.ast.annotations?.identifier).toBe("Session.Message.Assistant.Text") - expect(CoreSessionMessage.AssistantText).toBe(SessionMessage.AssistantText) }) diff --git a/packages/client/test/import-boundaries.test.ts b/packages/client/test/import-boundaries.test.ts index 1a018a032b..5b881edc32 100644 --- a/packages/client/test/import-boundaries.test.ts +++ b/packages/client/test/import-boundaries.test.ts @@ -12,7 +12,7 @@ const server = resolve(import.meta.dir, "../../server") describe("public import boundaries", () => { test("isolates each public entrypoint", async () => { - const root = await bundleInputs("@opencode-ai/client/promise", "browser") + const root = await bundleInputs("@opencode-ai/client", "browser") expect(within(root, effect)).toEqual([]) expect(within(root, schema)).toEqual([]) diff --git a/packages/client/test/promise.test.ts b/packages/client/test/promise.test.ts index 015e9ebf5e..e29522c226 100644 --- a/packages/client/test/promise.test.ts +++ b/packages/client/test/promise.test.ts @@ -227,6 +227,34 @@ test("session instructions methods use the public HTTP contract", async () => { ]) }) +test("session.pending.list uses the public HTTP contract", async () => { + const requests: Array<{ method: string; url: string }> = [] + const pending = [ + { + admittedSeq: 3, + id: "msg_pending", + sessionID: "ses_test", + timeCreated: 1_717_171_717_000, + type: "user", + data: { text: "Fix the failing tests" }, + delivery: "steer", + }, + ] + const client = OpenCode.make({ + baseUrl: "http://localhost:3000", + fetch: async (input, init) => { + const request = input instanceof Request ? input : new Request(input, init) + requests.push({ method: request.method, url: request.url }) + return Response.json({ data: pending }) + }, + }) + + const result = await client.session.pending.list({ sessionID: "ses_test" }) + + expect(result).toEqual(pending) + expect(requests).toEqual([{ method: "GET", url: "http://localhost:3000/api/session/ses_test/pending" }]) +}) + test("event.subscribe exposes the Promise event stream wire projection", async () => { const client = OpenCode.make({ baseUrl: "http://localhost:3000", diff --git a/packages/codemode/README.md b/packages/codemode/README.md index ee2c4162e6..2b764075ae 100644 --- a/packages/codemode/README.md +++ b/packages/codemode/README.md @@ -130,6 +130,7 @@ type Result = Success | Failure interface Success { readonly ok: true readonly value: CodeMode.DataValue + readonly warnings?: ReadonlyArray readonly logs?: ReadonlyArray readonly truncated?: boolean readonly toolCalls: ReadonlyArray @@ -144,7 +145,7 @@ interface Failure { } ``` -`toolCalls` contains the names of calls admitted by the runtime in call order. It is retained on failure so hosts can audit partial execution without exposing inputs or host failures. `truncated` is present when the value or logs were cut to fit `maxOutputBytes` (see Execution Limits). +`toolCalls` contains the names of calls admitted by the runtime in call order. It is retained on failure so hosts can audit partial execution without exposing inputs or host failures. A successful execution may also contain `warnings`: runtime-authored, non-fatal diagnostics alongside a valid value - unhandled rejections from promises that failed, un-awaited, before the program returned, or background work interrupted by the timeout after the program returned. Anything still running when the program returns is interrupted - race losers and fire-and-forget calls alike - so a program must await every call whose completion matters. Failure has an `error`; success may have `warnings`; program-authored console output stays in `logs`. Keeping the value on an unhandled rejection is a deliberate divergence from Node's crash-on-unhandled-rejection default: the computed value and the background failure are independently useful to the model, so the result carries both. When warnings are cut by `maxOutputBytes`, a final `Truncated` diagnostic marks the omission in-band, and `truncated` marks any result, warning, or log truncation (see Execution Limits). ### Tool-call hooks @@ -257,11 +258,11 @@ CodeMode is an orchestration language, not a general JavaScript runtime. The limits are exactly three knobs: -| Limit | Default | Bounds | -| ---------------- | -------------------: | -------------------------------------------------------------------- | -| `timeoutMs` | none - no timeout | Wall-clock execution time. | -| `maxToolCalls` | none - unlimited | Tool calls admitted during the execution. | -| `maxOutputBytes` | none - no truncation | Model-facing output: the serialized result value plus captured logs. | +| Limit | Default | Bounds | +| ---------------- | -------------------: | ---------------------------------------------------- | +| `timeoutMs` | none - no timeout | Wall-clock execution time. | +| `maxToolCalls` | none - unlimited | Tool calls admitted during the execution. | +| `maxOutputBytes` | none - no truncation | Retained result value and logs; warnings separately. | No limit has a default, on purpose: execution budgets are host policy, not library policy - a host that wants a bound sets one; a host that can interrupt the execution fiber (as OpenCode does on user cancel) may set no timeout, and a host with its own tool-output truncation (as OpenCode has) may leave `maxOutputBytes` unset. A host with neither should set `maxOutputBytes`, or oversized results silently flood model context. @@ -279,9 +280,11 @@ const runtime = CodeMode.make({ Limits are safe integers. `timeoutMs` must be at least `1`; the others may be `0`. Invalid configuration throws a `RangeError` when `CodeMode.make` or `CodeMode.execute` is called. An explicitly `undefined` value is the same as leaving the limit unset. -Exceeding a configured `maxOutputBytes` never fails the execution. An oversized result value is replaced by its truncated serialized text plus an explanatory marker, logs are kept from the start until the remaining budget is exhausted (with a final marker line noting the cut), and the result carries `truncated: true`. +`maxOutputBytes` is a payload budget, not a strict byte cap on the final rendered tool message. It counts the serialized result value and retained log lines; warning diagnostics are bounded by a separate budget of the same size, so a large value never silences runtime diagnostics. Fixed truncation notices and framing added by a host when it renders the structured result are additional and may make the final message exceed the configured number. -When configured, the timeout interrupts in-flight tool Effects, including eagerly started calls the program has not awaited (their fibers are supervised by the execution). The interpreter yields cooperatively between steps, so the timeout also interrupts pure busy loops (`while (true) {}`) - no separate work budget exists. Tool implementations remain responsible for making their external operations interruptible or independently bounded. +Exceeding a configured `maxOutputBytes` never fails the execution. An oversized result value is replaced by its truncated serialized text plus an explanatory marker, logs are kept within the remaining budget, warnings are kept within their own budget, omitted entries receive a summary marker, and the result carries `truncated: true`. + +When configured, the timeout interrupts in-flight tool Effects, including eagerly started calls the program has not awaited (their fibers are supervised by the execution). The interpreter yields cooperatively between steps, so the timeout also interrupts pure busy loops (`while (true) {}`) - no separate work budget exists. Tool implementations remain responsible for making their external operations interruptible or independently bounded: the timeout bounds when interruption begins, not when the result is delivered, which waits for tool interruption cleanup to finish. If the timeout fires after the program has already returned a valid value - while the runtime is interrupting leftover work and waiting for its cleanup - the result stays successful: the computed value is returned with a `TimeoutExceeded` warning instead of being discarded. Two interpreter internals are fixed constants rather than knobs: at most 8 tool calls run concurrently, and values crossing a data boundary may nest at most 32 levels deep (deeper values fail as `InvalidDataValue`, which reads better than a native stack-overflow error). Neither is part of the public contract. @@ -289,18 +292,19 @@ Two interpreter internals are fixed constants rather than knobs: at most 8 tool Failures are data: -| Kind | Meaning | -| ----------------------- | -------------------------------------------------------------------------------------------------------- | -| `ParseError` | Source is empty or cannot be parsed. | -| `UnsupportedSyntax` | Parsed JavaScript is outside the supported subset. | -| `UnknownTool` | A program referenced a tool the host did not provide. | -| `InvalidToolInput` | Tool input failed schema decoding or safe-data copying. | -| `InvalidToolOutput` | Tool output failed schema decoding or safe-data copying. | -| `InvalidDataValue` | Program data violated the plain-data contract (depth, circularity, blocked properties, non-data values). | -| `ToolCallLimitExceeded` | Calls exceeded `maxToolCalls`. | -| `TimeoutExceeded` | Execution exceeded `timeoutMs`. | -| `ToolFailure` | A tool refused or failed. | -| `ExecutionFailure` | The program threw or another execution error occurred. | +| Kind | Meaning | +| ----------------------- | --------------------------------------------------------------------------------------------------------- | +| `ParseError` | Source is empty or cannot be parsed. | +| `UnsupportedSyntax` | Parsed JavaScript is outside the supported subset. | +| `UnknownTool` | A program referenced a tool the host did not provide. | +| `InvalidToolInput` | Tool input failed schema decoding or safe-data copying. | +| `InvalidToolOutput` | Tool output failed schema decoding or safe-data copying. | +| `InvalidDataValue` | Program data violated the plain-data contract (depth, circularity, blocked properties, non-data values). | +| `ToolCallLimitExceeded` | Calls exceeded `maxToolCalls`. | +| `TimeoutExceeded` | Execution exceeded `timeoutMs`; as a warning, background work was interrupted after the program returned. | +| `ToolFailure` | A tool refused or failed. | +| `ExecutionFailure` | The program threw or another execution error occurred. | +| `Truncated` | Warning-only marker: additional warnings were omitted by `maxOutputBytes`. | Unknown host failures, defects, invalid outputs, and copying failures are sanitized. To return a safe operational refusal, fail with `toolError`: diff --git a/packages/codemode/codemode.md b/packages/codemode/codemode.md index 440271dc06..0428ff0251 100644 --- a/packages/codemode/codemode.md +++ b/packages/codemode/codemode.md @@ -63,13 +63,24 @@ path lookup, namespace browsing, deterministic ranking, and pagination. ### Tool execution -Calling a tool starts its Effect eagerly on a supervised fiber. The returned sandbox promise is run-once and can be -awaited directly or through the supported `Promise` combinators. At most eight tool calls execute concurrently. -Unfinished calls are drained before successful program completion, and an unhandled call failure becomes a diagnostic. +Every sandbox promise starts eagerly on a run-once fiber owned by the whole CodeMode execution, including tool calls, +async functions, `Promise.all`, `Promise.allSettled`, `Promise.race`, `Promise.resolve`, and `Promise.reject`. Nested +functions therefore cannot end the lifetime of work they started. Independent aggregate batches overlap, and rejection +is observed at the eventual `await`. `Promise.race` uses native non-cancelling settlement semantics: its first result +wins while losers continue running. At normal completion CodeMode interrupts everything still running - race losers, +fail-fast `Promise.all` stragglers, and fire-and-forget calls alike: the program has returned, so no future await can +exist, and work whose completion matters must be awaited by the program. Waiting for any class of leftover instead +would let it hold the execution open, or deadlock it when queued work needs tool-call permits the leftovers occupy. +Rejections that settled un-awaited before the return become `Success.warnings` diagnostics. A fatal program failure or +host interruption closes the execution promise scope and interrupts its active fibers instead. A timeout does the +same, except that a value the program already returned is preserved alongside a `TimeoutExceeded` warning rather than +discarded. At most eight tool calls execute concurrently. The public execution-policy knobs are `timeoutMs`, `maxToolCalls`, and `maxOutputBytes`. The package supplies no defaults because budgets are host policy. The interpreter also enforces fixed internal boundaries for tool-call -concurrency and data nesting depth. +concurrency and data nesting depth. `maxOutputBytes` bounds retained payload bytes, not the complete rendered message; +warning diagnostics have an equal separate budget so a large value cannot starve them, and fixed truncation notices and +host-added framing are intentionally outside the budgets. ### Data, files, and failures @@ -79,7 +90,7 @@ boundary. Unknown host failures and invalid outputs are sanitized. `ToolError` is the explicit channel for a safe message that a tool wants the model to see. Diagnostic categories distinguish parsing, unsupported syntax, unknown tools, invalid -data, tool failures, limits, timeouts, and execution failures. +data, tool failures, limits, timeouts, execution failures, and warning truncation. Files and other attachment content stay outside the interpreter. A host may collect them while child tools execute and attach them to the outer result, but the program receives only the structured tool output. @@ -95,7 +106,8 @@ CodeMode is integrated into V2 through `packages/core/src/tool/registry.ts` and normally. - When visible deferred tools exist, Core reserves and materializes one `execute` tool. Grouped deferred tools become CodeMode namespaces instead of flattened model-facing names. -- Each nested call checks that its captured registration is still current before dispatching it. +- Nested calls execute the registered `Tool` values captured for the model request; later registrations affect later + requests. - Authorization and side-effect ordering remain responsibilities of the leaf tool. Catalog visibility is not execution authorization. - Structured child output enters the interpreter. File parts are collected host-side and attached to the outer result. @@ -126,18 +138,18 @@ represent accurately rather than guessing semantics. ## Decisions and Rationale -| Decision | Rationale | -| --- | --- | -| Keep an owned tree-walking interpreter. | The product need is bounded tool orchestration, not arbitrary JavaScript. Owning the language surface keeps authority and behavior explicit. | -| Treat schemas as the model-facing interface. | Signatures drive correct calls; Effect Schema also provides the runtime validation boundary, while JSON Schema supports adapter interoperability. | -| Keep authority host-owned. | CodeMode can only confine programs to supplied tools. The host chooses those tools, and each tool enforces its own authorization and side-effect policy. | -| Use progressive catalog disclosure plus search. | Large tool sets should not consume the prompt, but every namespace must remain discoverable and speculative search calls should remain valid. | -| Start tool promises eagerly and supervise them. | This preserves normal call-time parallelism while giving each call run-once settlement and interruption safety. | -| Keep files outside the sandbox value space. | Models should compose structured data without routing binary payloads through generated code or context. | -| Treat `execute` as the model-facing invocation boundary. | Nested calls are implementation details of one orchestration program. Reusing the outer context and bounding only the final result preserves complete intermediate data without inventing durable child-call identities. | -| Return expected failures as data. | Models need actionable diagnostics without exposing private host causes; host interruption and defects must still propagate correctly. | -| Leave execution-limit defaults to hosts. | Appropriate budgets depend on the surrounding product and its own cancellation, retention, and output-bounding policies. | -| Skip unsupported OpenAPI operations. | Incorrect parameter encoding, authentication, or transport behavior is worse than a precise `skipped` reason. | +| Decision | Rationale | +| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Keep an owned tree-walking interpreter. | The product need is bounded tool orchestration, not arbitrary JavaScript. Owning the language surface keeps authority and behavior explicit. | +| Treat schemas as the model-facing interface. | Signatures drive correct calls; Effect Schema also provides the runtime validation boundary, while JSON Schema supports adapter interoperability. | +| Keep authority host-owned. | CodeMode can only confine programs to supplied tools. The host chooses those tools, and each tool enforces its own authorization and side-effect policy. | +| Use progressive catalog disclosure plus search. | Large tool sets should not consume the prompt, but every namespace must remain discoverable and speculative search calls should remain valid. | +| Start promises eagerly and supervise them for the execution. | This preserves normal call-time parallelism and run-once settlement while allowing pending work to be interrupted when the program returns. | +| Keep files outside the sandbox value space. | Models should compose structured data without routing binary payloads through generated code or context. | +| Treat `execute` as the model-facing invocation boundary. | Nested calls are implementation details of one orchestration program. Reusing the outer context and bounding only the final result preserves complete intermediate data without inventing durable child-call identities. | +| Return expected failures as data. | Models need actionable diagnostics without exposing private host causes; host interruption and defects must still propagate correctly. | +| Leave execution-limit defaults to hosts. | Appropriate budgets depend on the surrounding product and its own cancellation, retention, and output-bounding policies. | +| Skip unsupported OpenAPI operations. | Incorrect parameter encoding, authentication, or transport behavior is worse than a precise `skipped` reason. | ## Remaining Work diff --git a/packages/codemode/interpreter-support.md b/packages/codemode/interpreter-support.md index aac4ac938c..6887fdaed9 100644 --- a/packages/codemode/interpreter-support.md +++ b/packages/codemode/interpreter-support.md @@ -111,13 +111,15 @@ ultimate source of truth. - [x] `Promise.resolve` and `Promise.reject`. - [x] `Promise.all`, `Promise.allSettled`, and `Promise.race` over supported collections containing promises and plain values. -- [x] `Promise.all` preserves result order and rejects on the first observed failure. +- [x] `Promise.all` preserves result order and rejects on the first observed failure without cancelling siblings. - [x] `Promise.allSettled` returns plain fulfilled/rejected outcome records. -- [x] `Promise.race` interrupts losing in-flight tool calls. -- [x] Un-awaited calls are drained before execution ends; unhandled failures become diagnostics. +- [x] `Promise.race` settles from the first result without cancelling losers at settlement time. +- [x] Real promise values from `Promise.all`, `Promise.allSettled`, and `Promise.race`; separately constructed + combinator batches overlap as in normal JavaScript. +- [x] All still-pending work (race losers, fail-fast `Promise.all` stragglers, and un-awaited calls alike) is + interrupted when the program returns; rejections that settled un-awaited become `Success.warnings` + diagnostics. - [x] `try`/`catch` can handle awaited tool and promise failures. -- [ ] Real promise values from `Promise.all`, `Promise.allSettled`, and `Promise.race`. These calls currently settle - before returning, so separately constructed combinator batches do not overlap as normal JavaScript promises do. - [ ] `Promise.any`. - [ ] Promise chaining with `.then`, `.catch`, and `.finally`. - [ ] Custom promise construction with `new Promise(...)`. @@ -269,7 +271,7 @@ ultimate source of truth. These are actionable implementation items. Check them off only when behavior and direct tests land. -- [ ] Return real promises from `Promise.all`, `Promise.allSettled`, and `Promise.race`. +- [x] Return real promises from `Promise.all`, `Promise.allSettled`, and `Promise.race`. - [ ] Bound pending tool-call admission/allocation in addition to execution concurrency. - [ ] Guarantee every advertised tool path is executable, including dotted and blocked path segments. - [ ] Define safe outbound handling for non-finite numbers and `undefined` so invalid values cannot silently become diff --git a/packages/codemode/src/codemode.ts b/packages/codemode/src/codemode.ts index 842209dac5..f35294a227 100644 --- a/packages/codemode/src/codemode.ts +++ b/packages/codemode/src/codemode.ts @@ -13,11 +13,17 @@ export type { ToolCall, ToolCallEnded, ToolCallHooks, ToolCallStarted, ToolDescr /** Resource budgets enforced independently during each CodeMode program execution. */ export type ExecutionLimits = { - /** Maximum wall-clock execution time in milliseconds. No default: absent means no timeout. */ + /** + * Wall-clock milliseconds before execution is interrupted; result delivery additionally + * waits for tool interruption cleanup. No default: absent means no timeout. + */ readonly timeoutMs?: number /** Maximum number of tool calls admitted by the runtime. No default: absent means unlimited. */ readonly maxToolCalls?: number - /** Maximum UTF-8 bytes of model-facing output. No default: absent means no truncation. */ + /** + * Maximum UTF-8 bytes retained from the result value and logs; warnings have a separate + * budget of the same size. Fixed truncation notices and host formatting are additional. + */ readonly maxOutputBytes?: number } @@ -75,8 +81,9 @@ export const DiagnosticKind = Schema.Literals([ "TimeoutExceeded", "ToolFailure", "ExecutionFailure", + "Truncated", ]) -/** Stable categories produced by program, schema, tool, and limit failures. */ +/** Stable categories produced by program, schema, tool, limit, and truncation diagnostics. */ export type DiagnosticKind = typeof DiagnosticKind.Type export const Diagnostic = Schema.Struct({ @@ -92,6 +99,8 @@ const ToolCallSchema = Schema.Struct({ name: Schema.String }) export const Success = Schema.Struct({ ok: Schema.Literal(true), value: Schema.Json, + // Runtime-authored non-fatal diagnostics; program console output stays in `logs`. + warnings: Schema.optionalKey(Schema.Array(Diagnostic)), logs: Schema.optionalKey(Schema.Array(Schema.String)), truncated: Schema.optionalKey(Schema.Boolean), toolCalls: Schema.Array(ToolCallSchema), diff --git a/packages/codemode/src/interpreter/runtime.ts b/packages/codemode/src/interpreter/runtime.ts index 7f5d015d18..ba095e74d5 100644 --- a/packages/codemode/src/interpreter/runtime.ts +++ b/packages/codemode/src/interpreter/runtime.ts @@ -1,5 +1,5 @@ import { parse } from "acorn" -import { Cause, Effect, Exit, Fiber, Semaphore } from "effect" +import { Cause, Effect, Exit, Fiber, Scope, Semaphore } from "effect" import { DiagnosticCategory, ModuleKind, ScriptTarget, flattenDiagnosticMessageText, transpileModule } from "typescript" import { copyIn, @@ -219,7 +219,7 @@ const normalizeError = (error: unknown): Diagnostic => { } } -// Shared by catch bindings, Promise.allSettled rejection reasons, and Promise.race losers. +// Shared by catch bindings and Promise.allSettled rejection reasons. const caughtErrorValue = (thrown: unknown): unknown => { if (thrown instanceof ProgramThrow) return thrown.value if (thrown instanceof InterpreterRuntimeError) return createErrorValue(thrown.errorName, thrown.message) @@ -611,6 +611,80 @@ const collectPatternNames = (pattern: AstNode, out: Array = []): Array { + private readonly active = new Set() + private readonly ids = new WeakMap() + private readonly observed = new WeakSet() + private readonly failures = new Map() + private nextID = 0 + + constructor(private readonly scope: Scope.Scope) {} + + create(effect: Effect.Effect): Effect.Effect { + return Effect.suspend(() => { + // Allocated at execution time (not construction) so re-run effects cannot share an id, + // and before the fork so diagnostics order by creation: a forked body that immediately + // creates promises of its own must sequence after its creator. + const id = this.nextID++ + return Effect.map(Effect.forkIn(effect, this.scope, { startImmediately: true }), (fiber) => { + const promise = new SandboxPromise(fiber) + this.active.add(promise) + this.ids.set(promise, id) + fiber.addObserver((exit) => { + this.active.delete(promise) + if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause) || this.observed.has(promise)) { + this.ids.delete(promise) + return + } + const failure = normalizeError(Cause.squash(exit.cause)) + this.failures.set(id, { + ...failure, + message: `Unhandled rejection from an un-awaited promise: ${failure.message}`, + }) + }) + return promise + }) + }) + } + + // Synchronous on purpose: JS makes a promise "handled" the moment a construct takes + // responsibility for it (await, or membership in a combinator call), not when the + // consuming fiber later runs. Call sites must invoke this at that moment. + markObserved(promise: SandboxPromise): void { + this.observed.add(promise) + const id = this.ids.get(promise) + this.ids.delete(promise) + if (id !== undefined) this.failures.delete(id) + } + + // Pure settlement subscription: never re-runs work and never affects rejection reporting. + await(promise: SandboxPromise): Effect.Effect> { + return Fiber.await(promise.fiber) + } + + // Unobserved rejections that already settled, in creation order. + diagnostics(): Array { + return [...this.failures].sort(([left], [right]) => left - right).map(([, failure]) => failure) + } + + // Normal-completion lifecycle: interrupts everything still running and reports the + // rejections that already settled un-awaited. interruptAll signals every fiber + // synchronously before awaiting termination, so no straggler can spawn new work between + // interrupts; the loop re-checks as a backstop because a straggler can create promises + // before its interrupt lands. + interrupt(): Effect.Effect> { + const self = this + return Effect.gen(function* () { + while (self.active.size > 0) { + yield* Fiber.interruptAll([...self.active].map((promise) => promise.fiber)) + } + return self.diagnostics() + }) + } +} + class Interpreter { private scopes: Array> private readonly invokeTool: (path: ReadonlyArray, args: Array) => Effect.Effect @@ -620,24 +694,22 @@ class Interpreter { private readonly logs: Array // Caps how many eagerly forked tool calls run at once (the parallel-call concurrency cap). private readonly callPermits: Semaphore.Semaphore - // Fiber-backed promises whose settlement no program construct has observed yet. Successful - // program completion drains these (like a runtime waiting on in-flight work at exit) and - // surfaces a never-awaited failure as an unhandled-rejection diagnostic. - private readonly pendingSettlements: Set + private readonly promises: PromiseRuntime constructor( invokeTool: (path: ReadonlyArray, args: Array) => Effect.Effect, toolKeys: (path: ReadonlyArray) => ReadonlyArray, + promises: PromiseRuntime, logs: Array = [], - shared?: { callPermits: Semaphore.Semaphore; pendingSettlements: Set }, + callPermits: Semaphore.Semaphore = Semaphore.makeUnsafe(TOOL_CALL_CONCURRENCY), ) { const globalScope = new Map() this.scopes = [globalScope] this.invokeTool = invokeTool this.toolKeys = toolKeys this.logs = logs - this.callPermits = shared?.callPermits ?? Semaphore.makeUnsafe(TOOL_CALL_CONCURRENCY) - this.pendingSettlements = shared?.pendingSettlements ?? new Set() + this.callPermits = callPermits + this.promises = promises globalScope.set("tools", { mutable: false, value: new ToolReference([]) }) globalScope.set("Promise", { mutable: false, value: new PromiseNamespace() }) globalScope.set("undefined", { mutable: false, value: undefined }) @@ -703,36 +775,12 @@ class Interpreter { // resolves before crossing the data boundary - `return tools.ns.tool(...)` works // without an explicit await, exactly as in JS. if (value instanceof SandboxPromise) value = yield* self.settlePromise(value) - yield* self.drainPendingSettlements() return value }).pipe(Effect.ensuring(Effect.sync(() => self.popScope()))) } - // Awaits every fiber-backed promise the program abandoned (fire-and-forget tool calls), so - // their work completes before the execution ends - mirroring a JS runtime waiting on - // in-flight I/O at exit. A failure nobody could have handled becomes an unhandled-rejection - // diagnostic (interrupted calls, e.g. Promise.race losers, are ignored). - private drainPendingSettlements(): Effect.Effect { - const self = this - return Effect.gen(function* () { - while (self.pendingSettlements.size > 0) { - const promise = self.pendingSettlements.values().next().value - if (promise === undefined) break - const exit = yield* self.observePromise(promise) - if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) continue - const failure = normalizeError(Cause.squash(exit.cause)) - throw new InterpreterRuntimeError( - `Unhandled rejection from an un-awaited promise: ${failure.message}`, - undefined, - failure.kind, - ["Await promises so failures can be caught and handled."], - ) - } - }) - } - - // Eagerly starts a tool call on a supervised child fiber (so the execution timeout and - // scope teardown interrupt it) gated by the concurrency semaphore, and wraps the fiber in a + // Eagerly starts a tool call in the execution's promise scope (so timeout and teardown + // interrupt it) gated by the concurrency semaphore, and wraps the fiber in a // first-class promise value. `startImmediately` makes the runtime admit the call - charging // the tool-call budget and firing onToolCallStart - at the call site, before any await. private createToolCallPromise( @@ -743,46 +791,20 @@ class Interpreter { } private createPromise(effect: Effect.Effect): Effect.Effect { - return Effect.map(Effect.forkChild(effect, { startImmediately: true }), (fiber) => { - const promise = new SandboxPromise(fiber) - this.pendingSettlements.add(promise) - return promise - }) - } - - // The promise's settlement as an Exit, marking it observed for unhandled-rejection tracking. - // Fiber settlement is idempotent, so observing the same promise repeatedly (await twice, - // Promise.all([p, p])) never re-runs the underlying call. - private observePromise(promise: SandboxPromise): Effect.Effect> { - this.pendingSettlements.delete(promise) - return promise.fiber !== undefined ? Fiber.await(promise.fiber) : Effect.exit(promise.immediate ?? Effect.void) + return this.promises.create(effect) } // `await promise`: succeed with the fulfilled value or re-raise the failure so try/catch - // observes it exactly like a synchronous throw at the await site. - private settlePromise(promise: SandboxPromise, node?: AstNode): Effect.Effect { - const self = this - return Effect.flatMap(this.observePromise(promise), (exit) => self.unwrapPromiseExit(promise, exit, node)) - } - - private unwrapPromiseExit( - promise: SandboxPromise | undefined, - exit: Exit.Exit, - node?: AstNode, - ): Effect.Effect { - if (Exit.isSuccess(exit)) return Effect.succeed(exit.value) - // A call Promise.race interrupted after losing settles as a catchable program failure; - // any other interruption is execution teardown (timeout/host) and must keep propagating - // as interruption rather than becoming program-visible data. - if (promise?.interrupted === true && Cause.hasInterruptsOnly(exit.cause)) { - return Effect.fail( - new InterpreterRuntimeError( - "This tool call was interrupted because another value settled a Promise.race first.", - node, - ), + // observes it exactly like a synchronous throw at the await site. Settlement is idempotent + // (fiber exits replay), so awaiting the same promise repeatedly never re-runs the call. + private settlePromise(promise: SandboxPromise): Effect.Effect { + const promises = this.promises + return Effect.suspend(() => { + promises.markObserved(promise) + return Effect.flatMap(promises.await(promise), (exit) => + Exit.isSuccess(exit) ? Effect.succeed(exit.value) : Effect.failCause(exit.cause), ) - } - return Effect.failCause(exit.cause) + }) } private evaluateStatement(node: AstNode): Effect.Effect { @@ -1532,7 +1554,7 @@ class Interpreter { // matching real JS semantics for non-thenables. const self = this return Effect.flatMap(this.evaluateExpression(getNode(node, "argument")), (value) => - value instanceof SandboxPromise ? self.settlePromise(value, node) : Effect.succeed(value), + value instanceof SandboxPromise ? self.settlePromise(value) : Effect.succeed(value), ) } case "NewExpression": @@ -2199,145 +2221,116 @@ class Interpreter { // Promise.* over ordinary runtime values. Combinators accept ANY array (or spreadable // collection) mixing promise values and plain data - built inline, beforehand, via spread, - // whatever - because tool calls already run eagerly on their own fibers; the combinators - // only observe settlements. Joining is therefore sequential (no extra fibers) without - // costing parallelism, and the concurrency cap stays where the work is: the fork semaphore. + // whatever - because tool calls already run eagerly on their own fibers. Each combinator + // returns a real promise whose join runs on its own scope-owned fiber, observing member + // settlements; the concurrency cap stays where the work is: the fork semaphore. private invokePromiseMethod( ref: PromiseMethodReference, args: Array, node: AstNode, ): Effect.Effect { - const self = this if (ref.name === "resolve") { // Promise.resolve of a promise is that promise (JS flattens); anything else is a - // promise already fulfilled with the value. + // promise already fulfilled with the value. Pre-settled values still fork a scope-owned + // fiber so every promise shares one lifecycle (an abandoned reject is reported, teardown + // is uniform). const value = args[0] - return Effect.succeed( - value instanceof SandboxPromise ? value : new SandboxPromise(undefined, Effect.succeed(value)), - ) + return value instanceof SandboxPromise ? Effect.succeed(value) : this.createPromise(Effect.succeed(value)) } if (ref.name === "reject") { - return Effect.sync(() => new SandboxPromise(undefined, Effect.fail(new ProgramThrow(args[0])))) + return this.createPromise(Effect.fail(new ProgramThrow(args[0]))) } const items = Array.isArray(args[0]) ? args[0] : spreadItems(args[0]) if (items === undefined) { - throw new InterpreterRuntimeError( - `Promise.${ref.name} expects an array of promises or plain values (e.g. Promise.${ref.name}(items.map((item) => tools.ns.tool(item)))).`, - node, + return this.createPromise( + Effect.fail( + new InterpreterRuntimeError( + `Promise.${ref.name} expects an array of promises or plain values (e.g. Promise.${ref.name}(items.map((item) => tools.ns.tool(item)))).`, + node, + ), + ), ) } + // JS makes combinator members "handled" synchronously at the call - their rejections + // belong to the aggregate from this moment, even ones settling before it runs. + for (const item of items) { + if (item instanceof SandboxPromise) this.promises.markObserved(item) + } + switch (ref.name) { case "all": { - // Mark every promise element observed up-front (Promise.all handles all of its - // members' failures, as in JS), race their settlements for fail-fast rejection, and - // preserve input order when they all fulfill. Rejected calls keep draining siblings. - const observations = items.map((item, index) => + // Each observation re-raises its member's failure, so Effect.all rejects on the first + // failure without waiting for the rest and preserves input order when all fulfill. + // Its failure-time interruption only unsubscribes the sibling waiters: the underlying + // fibers stay execution-owned and keep running, as in JS. + const observations = items.map((item) => item instanceof SandboxPromise - ? Effect.map(this.observePromise(item), (exit) => ({ index, item, exit })) - : Effect.succeed({ index, item: undefined, exit: Exit.succeed(item) }), + ? Effect.flatMap(this.promises.await(item), (exit) => + Exit.isSuccess(exit) ? Effect.succeed(exit.value) : Effect.failCause(exit.cause), + ) + : Effect.succeed(item), ) - return Effect.gen(function* () { - const remaining = [...observations] - const values: Array = [] - values.length = items.length - while (remaining.length > 0) { - const winner = yield* Effect.raceAll(remaining) - const position = remaining.indexOf(observations[winner.index]) - if (position >= 0) remaining.splice(position, 1) - if (Exit.isSuccess(winner.exit)) { - values[winner.index] = winner.exit.value - continue - } - yield* self.createPromise( - Effect.asVoid( - Effect.forEach( - items, - (item) => (item instanceof SandboxPromise ? self.observePromise(item) : Effect.void), - { concurrency: "unbounded" }, - ), - ), - ) - return yield* self.unwrapPromiseExit(winner.item, winner.exit, node) - } - return values - }) + return this.createPromise(Effect.all(observations, { concurrency: "unbounded" })) } case "allSettled": { const observations = items.map((item) => - item instanceof SandboxPromise - ? Effect.map(this.observePromise(item), (exit) => ({ promise: item as SandboxPromise | undefined, exit })) - : Effect.succeed({ promise: undefined as SandboxPromise | undefined, exit: Exit.succeed(item as unknown) }), + item instanceof SandboxPromise ? this.promises.await(item) : Effect.succeed(Exit.succeed(item as unknown)), ) - return Effect.gen(function* () { - const outcomes: Array = [] - for (const observation of observations) { - const { exit, promise } = yield* observation - if (Exit.isSuccess(exit)) { - outcomes.push( - Object.assign(Object.create(null) as SafeObject, { status: "fulfilled", value: exit.value }), - ) - continue - } - const raceInterrupted = promise?.interrupted === true && Cause.hasInterruptsOnly(exit.cause) - if (Cause.hasInterruptsOnly(exit.cause) && !raceInterrupted) { - // Execution teardown (timeout/host interruption), not a program-level rejection. - return yield* Effect.failCause(exit.cause) - } - const thrown = raceInterrupted - ? new InterpreterRuntimeError( - "This tool call was interrupted because another value settled a Promise.race first.", - node, + return this.createPromise( + Effect.gen(function* () { + const outcomes: Array = [] + for (const observation of observations) { + const exit = yield* observation + if (Exit.isSuccess(exit)) { + outcomes.push( + Object.assign(Object.create(null) as SafeObject, { status: "fulfilled", value: exit.value }), ) - : Cause.squash(exit.cause) - outcomes.push( - Object.assign(Object.create(null) as SafeObject, { - status: "rejected", - reason: caughtErrorValue(thrown), - }), - ) - } - return outcomes - }) + continue + } + if (Cause.hasInterruptsOnly(exit.cause)) { + // Execution teardown (timeout/host interruption), not a program-level rejection. + return yield* Effect.failCause(exit.cause) + } + outcomes.push( + Object.assign(Object.create(null) as SafeObject, { + status: "rejected", + reason: caughtErrorValue(Cause.squash(exit.cause)), + }), + ) + } + return outcomes + }), + ) } case "race": { if (items.length === 0) { - throw new InterpreterRuntimeError( - "Promise.race([]) would never settle; provide at least one promise or value.", - node, + return this.createPromise( + Effect.fail( + new InterpreterRuntimeError( + "Promise.race([]) would never settle; provide at least one promise or value.", + node, + ), + ), ) } - const observations = items.map((item, index) => - item instanceof SandboxPromise - ? Effect.map(this.observePromise(item), (exit) => ({ index, exit })) - : Effect.succeed({ index, exit: Exit.succeed(item as unknown) }), + const observations = items.map((item) => + item instanceof SandboxPromise ? this.promises.await(item) : Effect.succeed(Exit.succeed(item as unknown)), + ) + // First settlement (fulfilled OR rejected) wins; losing work stays execution-owned + // and is interrupted at normal completion (already observed) or by teardown. + return this.createPromise( + Effect.flatMap(Effect.raceAll(observations), (exit) => + Exit.isSuccess(exit) ? Effect.succeed(exit.value) : Effect.failCause(exit.cause), + ), ) - return Effect.gen(function* () { - // First settlement (fulfilled OR rejected) wins; the observations never fail, so - // racing them yields exactly that. Losing in-flight calls are then interrupted. - const winner = yield* Effect.raceAll(observations) - for (const [index, item] of items.entries()) { - if (index === winner.index || !(item instanceof SandboxPromise) || item.fiber === undefined) continue - item.interrupted = true - yield* Fiber.interrupt(item.fiber) - } - const winningItem = items[winner.index] - return yield* self.unwrapPromiseExit( - winningItem instanceof SandboxPromise ? winningItem : undefined, - winner.exit, - node, - ) - }) } } } private invokeFunction(fn: CodeModeFunction, args: Array): Effect.Effect { - const invocation = new Interpreter(this.invokeTool, this.toolKeys, this.logs, { - callPermits: this.callPermits, - pendingSettlements: this.pendingSettlements, - }) + const invocation = new Interpreter(this.invokeTool, this.toolKeys, this.promises, this.logs, this.callPermits) invocation.scopes = [...fn.capturedScopes, new Map()] const run = Effect.gen(function* () { // Seed every parameter name into the scope as a TDZ slot first, so a default that @@ -3484,68 +3477,109 @@ export const executeWithLimits = >( limits: ResolvedExecutionLimits, searchIndex: ToolRuntime.DiscoveryPlan["searchIndex"], ): Effect.Effect> => { - const hooks = { - ...(options.onToolCallStart === undefined ? {} : { onToolCallStart: options.onToolCallStart }), - ...(options.onToolCallEnd === undefined ? {} : { onToolCallEnd: options.onToolCallEnd }), - } - const tools = ToolRuntime.make( - (options.tools ?? {}) as HostTools>, - limits.maxToolCalls, - searchIndex, - hooks, - ) - const logs: Array = [] - const logged = () => (logs.length > 0 ? { logs: [...logs] } : {}) - if (options.code.trim().length === 0) { return Effect.succeed({ ok: false, error: { kind: "ParseError", message: "Code cannot be empty." }, - toolCalls: tools.calls, + toolCalls: [], }) } - const operation = Effect.gen(function* () { - const program = parseProgram(options.code) - const interpreter = new Interpreter>(tools.invoke, tools.keys, logs) - const value = yield* interpreter.run(program) - const result = copyOut(copyIn(value, "Execution result"), true) as DataValue - return { - ok: true, - value: result, - ...logged(), - toolCalls: tools.calls, - } satisfies Result - }).pipe((program) => { - const timeoutMs = limits.timeoutMs - if (timeoutMs === undefined) return program - return program.pipe( - Effect.timeoutOrElse({ - duration: timeoutMs, - orElse: () => - Effect.succeed({ - ok: false, - error: { kind: "TimeoutExceeded", message: `Execution timed out after ${timeoutMs}ms.` }, + // Suspended so all per-execution state - tool-call admission budget and audit list, logs, + // and the timeout path's completed value - binds at run time: a reused Effect must start + // from a clean slate instead of observing a previous run's state. + return Effect.suspend(() => { + const hooks = { + ...(options.onToolCallStart === undefined ? {} : { onToolCallStart: options.onToolCallStart }), + ...(options.onToolCallEnd === undefined ? {} : { onToolCallEnd: options.onToolCallEnd }), + } + const tools = ToolRuntime.make( + (options.tools ?? {}) as HostTools>, + limits.maxToolCalls, + searchIndex, + hooks, + ) + const logs: Array = [] + const logged = () => (logs.length > 0 ? { logs: [...logs] } : {}) + // Set once the program body returned and its value crossed the data boundary, so a timeout + // firing during leftover interruption reports "completed with interrupted background work" + // instead of discarding the computed value as a plain timeout. + let returned: { value: DataValue; promises: PromiseRuntime> } | undefined + + const base = Effect.acquireUseRelease( + Scope.make("parallel"), + (scope) => + Effect.gen(function* () { + const program = parseProgram(options.code) + const promises = new PromiseRuntime>(scope) + const interpreter = new Interpreter>(tools.invoke, tools.keys, promises, logs) + const value = yield* interpreter.run(program) + // Validate the result first so an invalid value is a fatal completion that closes + // the promise scope directly instead of taking the normal-completion path. + const result = copyOut(copyIn(value, "Execution result"), true) as DataValue + returned = { value: result, promises } + const warnings = yield* promises.interrupt() + return { + ok: true, + value: result, + ...(warnings.length > 0 ? { warnings } : {}), ...logged(), toolCalls: tools.calls, - } satisfies Result), - }), + } satisfies Result + }), + (scope, exit) => Scope.close(scope, exit), + ) + const timeoutMs = limits.timeoutMs + const operation = + timeoutMs === undefined + ? base + : base.pipe( + Effect.timeoutOrElse({ + duration: timeoutMs, + orElse: () => + Effect.sync(() => { + if (returned === undefined) { + return { + ok: false, + error: { kind: "TimeoutExceeded", message: `Execution timed out after ${timeoutMs}ms.` }, + ...logged(), + toolCalls: tools.calls, + } satisfies Result + } + // The timeout warning leads so byte-budget truncation cuts it last. + return { + ok: true, + value: returned.value, + warnings: [ + { + kind: "TimeoutExceeded", + message: `The program returned, but background work was still running at the ${timeoutMs}ms timeout and was interrupted. Await all started promises.`, + }, + ...returned.promises.diagnostics(), + ], + ...logged(), + toolCalls: tools.calls, + } satisfies Result + }), + }), + ) + + return operation.pipe( + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.interrupt + : Effect.succeed({ + ok: false, + error: normalizeError(Cause.squash(cause)), + ...logged(), + toolCalls: tools.calls, + } satisfies Result), + ), + Effect.map((result) => + limits.maxOutputBytes === undefined ? result : boundOutput(result, limits.maxOutputBytes), + ), ) }) - - return operation.pipe( - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) - ? Effect.interrupt - : Effect.succeed({ - ok: false, - error: normalizeError(Cause.squash(cause)), - ...logged(), - toolCalls: tools.calls, - } satisfies Result), - ), - Effect.map((result) => (limits.maxOutputBytes === undefined ? result : boundOutput(result, limits.maxOutputBytes))), - ) } const utf8ByteLength = (value: string): number => new TextEncoder().encode(value).byteLength @@ -3560,9 +3594,10 @@ const utf8Truncate = (value: string, maxBytes: number): string => { } /** - * Bounds the model-facing output (serialized result value plus logs) to `maxOutputBytes`. - * Oversized values are replaced by their truncated serialized text with an explanatory marker, - * and logs are kept from the start until the remaining budget is exhausted. Truncation never + * Bounds retained program payload bytes (serialized result value and logs) to `maxOutputBytes`. + * Warning diagnostics are bounded by a separate budget of the same size so a large value can + * never starve runtime-authored diagnostics. Fixed truncation notices are added outside those + * budgets, as is any framing added when a host renders the structured result. Truncation never * fails the execution; `truncated: true` marks affected results. Only runs when the host set * `maxOutputBytes` - with the limit absent, output passes through unbounded. */ @@ -3584,6 +3619,23 @@ const boundOutput = (result: Result, maxOutputBytes: number): Result => { } } + const warnings = result.ok ? (result.warnings ?? []) : [] + const keptWarnings: Array = [] + let warningBytes = 0 + for (const warning of warnings) { + const bytes = utf8ByteLength(JSON.stringify(warning)) + 1 + if (warningBytes + bytes > maxOutputBytes) break + warningBytes += bytes + keptWarnings.push(warning) + } + if (keptWarnings.length < warnings.length) { + truncated = true + keptWarnings.push({ + kind: "Truncated", + message: `${warnings.length - keptWarnings.length} additional warnings omitted by the output limit.`, + }) + } + const logs = result.logs ?? [] const kept: Array = [] const logBudget = Math.max(0, maxOutputBytes - valueBytes) @@ -3600,8 +3652,16 @@ const boundOutput = (result: Result, maxOutputBytes: number): Result => { } if (!truncated) return result + const warningsPart = keptWarnings.length > 0 ? { warnings: keptWarnings } : {} const logsPart = kept.length > 0 ? { logs: kept } : {} return result.ok - ? { ok: true, value, ...logsPart, truncated: true, toolCalls: result.toolCalls } + ? { + ok: true, + value, + ...warningsPart, + ...logsPart, + truncated: true, + toolCalls: result.toolCalls, + } : { ok: false, error: result.error, ...logsPart, truncated: true, toolCalls: result.toolCalls } } diff --git a/packages/codemode/src/tool-runtime.ts b/packages/codemode/src/tool-runtime.ts index 80ce828414..3cdf49cfe5 100644 --- a/packages/codemode/src/tool-runtime.ts +++ b/packages/codemode/src/tool-runtime.ts @@ -602,6 +602,7 @@ export const prepare = (tools: HostTools, catalogBudget = defaultCatalogBu "- Filter, aggregate, and transform collections in code - never return them raw or call a tool per item across messages.", "- A result typed `Promise` may be structured data or text. Before reading fields, check that it is a non-null object and not an array; otherwise handle the returned text or primitive directly.", '- Run independent calls in parallel: `await Promise.all(items.map((item) => tools..(item)))`, or use `tools.["tool-name"](item)` when the listed signature uses bracket notation.', + "- Execution ends when the program returns; pending promises are interrupted, so await every call whose completion matters.", "- `Object.keys(tools)` lists namespaces; `Object.keys(tools.)` lists its tools; `for...in` works on both.", ...(complete ? [] diff --git a/packages/codemode/src/values.ts b/packages/codemode/src/values.ts index 4ca305d815..3ba2421d5d 100644 --- a/packages/codemode/src/values.ts +++ b/packages/codemode/src/values.ts @@ -1,11 +1,7 @@ -import type { Effect, Fiber } from "effect" +import type { Fiber } from "effect" export class SandboxPromise { - interrupted = false - constructor( - readonly fiber: Fiber.Fiber | undefined, - readonly immediate?: Effect.Effect, - ) {} + constructor(readonly fiber: Fiber.Fiber) {} } export class SandboxDate { diff --git a/packages/codemode/test/codemode.test.ts b/packages/codemode/test/codemode.test.ts index 16c17ca0c2..2e09e9d3c9 100644 --- a/packages/codemode/test/codemode.test.ts +++ b/packages/codemode/test/codemode.test.ts @@ -506,6 +506,26 @@ describe("CodeMode public contract", () => { expect(Schema.decodeUnknownSync(CodeMode.Result)(JSON.parse(JSON.stringify(reusable)))).toStrictEqual(reusable) }) + test("a reused execution Effect starts from a clean slate", async () => { + const echo = Tool.make({ + description: "echo", + input: Schema.Struct({}), + output: Schema.Number, + run: () => Effect.succeed(1), + }) + const effect = CodeMode.execute({ + tools: { host: { echo } }, + code: `console.log("hi"); return await tools.host.echo({})`, + limits: { maxToolCalls: 1 }, + }) + const first = await Effect.runPromise(effect) + const second = await Effect.runPromise(effect) + // Per-execution state (tool-call budget and audit list, logs, timeout bookkeeping) must + // bind at run time, so the second run neither exhausts the budget nor leaks run 1's logs. + expect(first).toStrictEqual(second) + expect(second).toStrictEqual({ ok: true, value: 1, logs: ["hi"], toolCalls: [{ name: "host.echo" }] }) + }) + test("inlines a COMPLETE small catalog and keeps search registered but unadvertised", async () => { const runtime = CodeMode.make({ tools }) expect(runtime.catalog()).toStrictEqual([ diff --git a/packages/codemode/test/promise-test262.test.ts b/packages/codemode/test/promise-test262.test.ts new file mode 100644 index 0000000000..500b7ae45d --- /dev/null +++ b/packages/codemode/test/promise-test262.test.ts @@ -0,0 +1,906 @@ +/* + * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75. + * Every test names its upstream source; test.failing cases are executable conformance + * targets for intended Promise behavior that CodeMode does not implement yet. + * + * Copyright 2014 Cubane Canada, Inc. All rights reserved. + * Copyright 2015 Microsoft Corporation. All rights reserved. + * Copyright 2016 Microsoft, Inc. All rights reserved. + * Copyright 2017 Caitlin Potter. All rights reserved. + * Copyright (C) 2016-2020 the V8 project authors. All rights reserved. + * Copyright (C) 2018-2020 Rick Waldron. All rights reserved. + * Copyright (C) 2019 Leo Balter. All rights reserved. + * Test262 portions are governed by the BSD license in LICENSE.test262. + */ +import { describe, expect, test } from "bun:test" +import { Effect } from "effect" +import { CodeMode } from "../src/index.js" + +const execute = (code: string) => + Effect.runPromise(CodeMode.execute({ code, tools: {}, limits: { timeoutMs: 1_000 } })) + +const value = async (code: string) => { + const result = await execute(code) + if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) + return result.value +} + +describe("Test262 Promise statics", () => { + test("statics are callable and return promises", async () => { + // Sources: + // test/built-ins/Promise/all/S25.4.4.1_A1.1_T1.js + // test/built-ins/Promise/allSettled/is-function.js + // test/built-ins/Promise/allSettled/returns-promise.js + // test/built-ins/Promise/race/S25.4.4.3_A1.1_T1.js + // test/built-ins/Promise/resolve/S25.4.4.5_A1.1_T1.js + // test/built-ins/Promise/reject/S25.4.4.4_A1.1_T1.js + expect( + await value(` + const values = [ + Promise.all([]), + Promise.allSettled([]), + Promise.race([undefined]), + Promise.resolve(), + Promise.reject(), + ] + const callable = [ + typeof Promise.all, + typeof Promise.allSettled, + typeof Promise.race, + typeof Promise.resolve, + typeof Promise.reject, + ] + try { await values[4] } catch {} + return [callable, values.map((item) => item instanceof Promise)] + `), + ).toEqual([ + ["function", "function", "function", "function", "function"], + [true, true, true, true, true], + ]) + }) + + test("Promise.all returns fresh arrays for empty and settled inputs", async () => { + // Sources: + // test/built-ins/Promise/all/S25.4.4.1_A2.1_T1.js + // test/built-ins/Promise/all/S25.4.4.1_A2.3_T1.js + // test/built-ins/Promise/all/S25.4.4.1_A2.3_T2.js + // test/built-ins/Promise/all/S25.4.4.1_A2.3_T3.js + // test/built-ins/Promise/all/S25.4.4.1_A7.1_T1.js + expect( + await value(` + const input = [] + const emptyPromise = Promise.all(input) + const empty = await emptyPromise + const onePromise = Promise.all([Promise.resolve(3)]) + const one = await onePromise + return [ + emptyPromise instanceof Promise, + empty instanceof Array, + empty.length, + empty !== input, + onePromise instanceof Promise, + one instanceof Array, + one.length, + one[0], + ] + `), + ).toEqual([true, true, 0, true, true, true, 1, 3]) + }) + + test("Promise.all adopts values and preserves input order and identity", async () => { + // Sources: + // test/built-ins/Promise/all/resolve-non-thenable.js + // test/built-ins/Promise/all/S25.4.4.1_A8.2_T1.js + // test/built-ins/Promise/all/S25.4.4.1_A8.2_T2.js + const result = await value(` + const first = { id: 1 } + const second = { id: 2 } + const values = await Promise.all([Promise.resolve(3), first, Promise.resolve(second)]) + const observe = async (promise) => { + try { await promise; return "fulfilled" } catch (reason) { return reason } + } + return [ + values.length, + values[0], + values[1] === first, + values[2] === second, + await observe(Promise.all([Promise.reject(1), Promise.resolve(2)])), + await observe(Promise.all([Promise.resolve(1), Promise.reject(2)])), + ] + `) + expect(result).toEqual([3, 3, true, true, 1, 2]) + }) + + test("Promise.allSettled returns fresh arrays and ordered outcome records", async () => { + // Sources: + // test/built-ins/Promise/allSettled/resolves-empty-array.js + // test/built-ins/Promise/allSettled/resolves-to-array.js + // test/built-ins/Promise/allSettled/resolved-all-fulfilled.js + // test/built-ins/Promise/allSettled/resolved-all-rejected.js + // test/built-ins/Promise/allSettled/resolved-all-mixed.js + // test/built-ins/Promise/allSettled/resolve-non-thenable.js + expect( + await value(` + const input = [] + const empty = await Promise.allSettled(input) + const reason = { id: 4 } + const object = { id: 5 } + const outcomes = await Promise.allSettled([ + Promise.resolve(1), + Promise.reject(2), + 3, + Promise.reject(reason), + object, + ]) + return [ + empty instanceof Array, + empty.length, + empty !== input, + outcomes, + outcomes[4].value === object, + outcomes.map((item) => Object.keys(item)), + ] + `), + ).toEqual([ + true, + 0, + true, + [ + { status: "fulfilled", value: 1 }, + { status: "rejected", reason: 2 }, + { status: "fulfilled", value: 3 }, + { status: "rejected", reason: { id: 4 } }, + { status: "fulfilled", value: { id: 5 } }, + ], + true, + [ + ["status", "value"], + ["status", "reason"], + ["status", "value"], + ["status", "reason"], + ["status", "value"], + ], + ]) + }) + + test("Promise.race preserves fulfillment, rejection, and iterable order", async () => { + // Sources: + // test/built-ins/Promise/race/S25.4.4.3_A6.2_T1.js + // test/built-ins/Promise/race/S25.4.4.3_A7.1_T1.js + // test/built-ins/Promise/race/S25.4.4.3_A7.2_T1.js + // test/built-ins/Promise/race/S25.4.4.3_A7.3_T1.js + // test/built-ins/Promise/race/S25.4.4.3_A7.3_T2.js + expect( + await value(` + const observe = async (promise) => { + try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } + } + return await Promise.all([ + observe(Promise.race([23])), + observe(Promise.race([Promise.reject(7)])), + observe(Promise.race([Promise.resolve(1), Promise.resolve(2)])), + observe(Promise.race([Promise.reject(3), Promise.resolve(4)])), + ]) + `), + ).toEqual([ + ["fulfilled", 23], + ["rejected", 7], + ["fulfilled", 1], + ["rejected", 3], + ]) + }) + + test("combinators consume supported string iterables", async () => { + // Sources: + // test/built-ins/Promise/all/iter-arg-is-string-resolve.js + // test/built-ins/Promise/allSettled/iter-arg-is-string-resolve.js + // test/built-ins/Promise/race/iter-arg-is-string-resolve.js + expect( + await value(` + return [ + await Promise.all("abc"), + await Promise.allSettled("ab"), + await Promise.race("abc"), + ] + `), + ).toEqual([ + ["a", "b", "c"], + [ + { status: "fulfilled", value: "a" }, + { status: "fulfilled", value: "b" }, + ], + "a", + ]) + }) + + test("Promise.resolve adopts values and preserves sandbox-promise identity", async () => { + // Sources: + // test/built-ins/Promise/resolve/S25.4.4.5_A2.1_T1.js + // test/built-ins/Promise/resolve/resolve-non-obj.js + // test/built-ins/Promise/resolve/resolve-non-thenable.js + expect( + await value(` + const object = { id: 1 } + const promise = Promise.resolve(1) + return [ + await Promise.resolve(23), + await Promise.resolve(Promise.resolve(24)), + (await Promise.resolve(object)) === object, + [promise].includes(Promise.resolve(promise)), + ] + `), + ).toEqual([23, 24, true, true]) + }) + + test("Promise.reject preserves primitive and object reasons", async () => { + // Sources: + // test/built-ins/Promise/reject/S25.4.4.4_A2.1_T1.js + const result = await value(` + const object = { reason: true } + const reasons = [undefined, null, false, true, 0, "", 42, object] + const observe = async (reason) => { + try { await Promise.reject(reason); return false } catch (caught) { return caught === reason } + } + return await Promise.all(reasons.map(observe)) + `) + expect(result).toEqual([true, true, true, true, true, true, true, true]) + }) + + test("Promise.all resolves duplicate members into every slot", async () => { + // Sources: + // test/built-ins/Promise/all/invoke-resolve-on-promises-every-iteration-of-promise.js + // test/built-ins/Promise/all/invoke-resolve-on-values-every-iteration-of-promise.js + // (adapted: CodeMode has no observable Promise.resolve hook, so per-iteration + // handling of a repeated member is asserted through the resolved slots) + expect( + await value(` + const settled = Promise.resolve(3) + const computed = (async () => "computed")() + return [ + await Promise.all([settled, settled, settled]), + await Promise.all([computed, "plain", computed]), + ] + `), + ).toEqual([ + [3, 3, 3], + ["computed", "plain", "computed"], + ]) + }) + + test("Promise.allSettled records duplicate members independently", async () => { + // Source: test/built-ins/Promise/allSettled/invoke-resolve-on-promises-every-iteration-of-promise.js + // (adapted: per-iteration handling of a repeated member is asserted through the + // outcome records instead of a Promise.resolve hook) + expect( + await value(` + const good = Promise.resolve(1) + const bad = Promise.reject(2) + return await Promise.allSettled([good, bad, good, bad]) + `), + ).toEqual([ + { status: "fulfilled", value: 1 }, + { status: "rejected", reason: 2 }, + { status: "fulfilled", value: 1 }, + { status: "rejected", reason: 2 }, + ]) + }) + + test("combinators adopt members that settled before the call", async () => { + // Sources: + // test/built-ins/Promise/all/reject-immed.js + // test/built-ins/Promise/allSettled/reject-immed.js + // test/built-ins/Promise/race/reject-immed.js + // (adapted: immediately-rejecting thenables become sandbox promises that settled, + // and were even observed, before the combinator call) + expect( + await value(` + const fulfilled = Promise.resolve("done") + const rejected = Promise.reject("failed") + try { await rejected } catch {} + const observe = async (promise) => { + try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } + } + return [ + await observe(Promise.all([fulfilled, rejected])), + await Promise.allSettled([rejected, fulfilled]), + await observe(Promise.race([rejected, fulfilled])), + ] + `), + ).toEqual([ + ["rejected", "failed"], + [ + { status: "rejected", reason: "failed" }, + { status: "fulfilled", value: "done" }, + ], + ["rejected", "failed"], + ]) + }) + + test("combinator results follow input order, not settlement order", async () => { + // Sources: + // test/built-ins/Promise/all/resolve-non-thenable.js + // test/built-ins/Promise/allSettled/resolved-all-mixed.js + // (adapted: members are created, and therefore settle, in reverse of input order; + // deferred settlement is not expressible without host-async work in this corpus) + expect( + await value(` + const third = Promise.resolve("c") + const failing = (async () => { throw "b" })() + try { await failing } catch {} + const second = (async () => "b")() + const first = Promise.resolve("a") + return [ + await Promise.all([first, second, third]), + await Promise.allSettled([first, failing, third]), + ] + `), + ).toEqual([ + ["a", "b", "c"], + [ + { status: "fulfilled", value: "a" }, + { status: "rejected", reason: "b" }, + { status: "fulfilled", value: "c" }, + ], + ]) + }) + + test("Promise.race ignores a rejected loser once the first contender wins", async () => { + // Source: test/built-ins/Promise/race/reject-ignored-immed.js + // (adapted: the losing rejection comes from an async function instead of a thenable; + // the exact-equality check also asserts the loser leaves no unhandled-rejection warning) + expect( + await execute(` + const loser = (async () => { throw "lost" })() + return await Promise.race([Promise.resolve("won"), loser]) + `), + ).toEqual({ ok: true, value: "won", toolCalls: [] }) + }) + + test("Promise.race([]) returns a promise whose CodeMode failure is catchable", async () => { + // Sources: + // test/built-ins/Promise/race/S25.4.4.3_A2.1_T1.js + // test/built-ins/Promise/race/S25.4.4.3_A5.1_T1.js + // (adapted: upstream requires Promise.race([]) to never settle; CodeMode intentionally + // rejects with a catchable diagnostic instead of hanging, so this asserts the sandbox + // divergence rather than the spec never-settles behavior) + expect( + await value(` + const empty = Promise.race([]) + try { + await empty + return "settled" + } catch (error) { + return [empty instanceof Promise, error instanceof Error] + } + `), + ).toEqual([true, true]) + }) + + test("Promise.resolve passes the same sandbox promise through nested chains", async () => { + // Source: test/built-ins/Promise/resolve/S25.4.4.5_A2.2_T1.js + // (adapted: no executor construction, and identity is observed with Array includes + // because promises are not comparable data values in CodeMode) + expect( + await value(` + const promise = Promise.resolve({ id: 1 }) + return [ + [promise].includes(Promise.resolve(promise)), + [promise].includes(Promise.resolve(Promise.resolve(promise))), + (await Promise.resolve(Promise.resolve(promise))).id, + ] + `), + ).toEqual([true, true, 1]) + }) + + test("Promise.resolve of a rejected promise preserves identity and reason", async () => { + // Source: test/built-ins/Promise/resolve/S25.4.4.5_A2.3_T1.js + // (adapted: the source promise is already rejected instead of rejected later) + expect( + await value(` + const rejected = Promise.reject("oops") + const adopted = Promise.resolve(rejected) + const identity = [rejected].includes(adopted) + try { + await adopted + return "fulfilled" + } catch (reason) { + return [identity, reason] + } + `), + ).toEqual([true, "oops"]) + }) + + test("Promise.reject uses a promise reason without flattening it", async () => { + // Sources: + // test/built-ins/Promise/reject-via-fn-immed.js + // test/built-ins/Promise/reject-via-fn-deferred.js + // (adapted: the promise reason goes through Promise.reject instead of executor reject) + expect( + await value(` + const observe = async (reason) => { + try { + await Promise.reject(reason) + return "fulfilled" + } catch (caught) { + const identity = [reason].includes(caught) + try { return [identity, caught instanceof Promise, await caught] } + catch (inner) { return [identity, caught instanceof Promise, "rethrew " + inner] } + } + } + return [await observe(Promise.resolve(1)), await observe(Promise.reject("inner"))] + `), + ).toEqual([ + [true, true, 1], + [true, true, "rethrew inner"], + ]) + }) +}) + +describe("Test262 async functions and await", () => { + test("declaration, expression, and arrow forms return promises", async () => { + // Sources: + // test/language/statements/async-function/declaration-returns-promise.js + // test/language/expressions/async-function/expression-returns-promise.js + // test/language/expressions/async-arrow-function/arrow-returns-promise.js + expect( + await value(` + async function declaration() { return 1 } + const expression = async function() { return 2 } + const arrow = async () => 3 + const promises = [declaration(), expression(), arrow()] + return [promises.map((item) => item instanceof Promise), await Promise.all(promises)] + `), + ).toEqual([[true, true, true], [1, 2, 3]]) + }) + + test("async bodies adopt returns and reject throws before and after await", async () => { + // Sources: + // test/language/statements/async-function/evaluation-body.js + // test/language/statements/async-function/evaluation-body-that-returns.js + // test/language/statements/async-function/evaluation-body-that-returns-after-await.js + // test/language/statements/async-function/evaluation-body-that-throws.js + // test/language/statements/async-function/evaluation-body-that-throws-after-await.js + expect( + await value(` + const order = [] + const plain = async () => { order.push("body"); return 42 } + const afterAwait = async () => { await Promise.resolve(); return 43 } + const throwsBefore = async () => { throw 1 } + const throwsAfter = async () => { await Promise.resolve(); throw 2 } + const observe = async (promise) => { + try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } + } + const first = plain() + return [ + order, + await observe(first), + await observe(afterAwait()), + await observe(throwsBefore()), + await observe(throwsAfter()), + ] + `), + ).toEqual([ + ["body"], + ["fulfilled", 42], + ["fulfilled", 43], + ["rejected", 1], + ["rejected", 2], + ]) + }) + + test("default-parameter throws reject instead of escaping the call", async () => { + // Source: test/language/statements/async-function/evaluation-default-that-throws.js + expect( + await value(` + const fail = () => { throw new Error("default") } + const run = async (value = fail()) => value + let returned = false + try { + const promise = run() + returned = promise instanceof Promise + await promise + return [returned, "fulfilled"] + } catch (error) { + return [returned, error.message] + } + `), + ).toEqual([true, "default"]) + }) + + test("async try/finally completion records override earlier completion", async () => { + // Sources: the try-{return,throw,reject}-finally-{return,throw,reject}.js matrix under + // test/language/statements/async-function, test/language/expressions/async-function, + // and test/language/expressions/async-arrow-function. + expect( + await value(` + const observe = async (promise) => { + try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } + } + const returnReturn = async () => { try { return "early" } finally { return await Promise.resolve("override") } } + const returnThrow = async () => { try { return "early" } finally { throw "override" } } + const returnReject = async () => { try { return "early" } finally { await Promise.reject("override") } } + const throwReturn = async () => { try { throw "early" } finally { return await Promise.resolve("override") } } + const throwThrow = async () => { try { throw "early" } finally { throw "override" } } + const throwReject = async () => { try { throw "early" } finally { await Promise.reject("override") } } + const rejectReturn = async () => { try { await Promise.reject("early") } finally { return await Promise.resolve("override") } } + const rejectThrow = async () => { try { await Promise.reject("early") } finally { throw "override" } } + const rejectReject = async () => { try { await Promise.reject("early") } finally { await Promise.reject("override") } } + return await Promise.all([ + observe(returnReturn()), observe(returnThrow()), observe(returnReject()), + observe(throwReturn()), observe(throwThrow()), observe(throwReject()), + observe(rejectReturn()), observe(rejectThrow()), observe(rejectReject()), + ]) + `), + ).toEqual([ + ["fulfilled", "override"], + ["rejected", "override"], + ["rejected", "override"], + ["fulfilled", "override"], + ["rejected", "override"], + ["rejected", "override"], + ["fulfilled", "override"], + ["rejected", "override"], + ["rejected", "override"], + ]) + }) + + test("await preserves an object whose then property is not callable", async () => { + // Source: test/language/expressions/await/await-awaits-thenable-not-callable.js + expect( + await value(` + const thenable = { then: 42 } + return (await thenable) === thenable + `), + ).toBe(true) + }) + + test("await returns non-promise operands unchanged", async () => { + // Source: test/language/expressions/await/await-non-promise.js + // (adapted: only value pass-through is asserted here; the spec tick ordering around + // await of non-promises is covered by the failing interleaving test below) + expect( + await value(` + const object = { id: 1 } + const array = [1, 2] + return [ + await 1, + await "text", + await true, + (await null) === null, + (await undefined) === undefined, + (await object) === object, + (await array) === array, + ] + `), + ).toEqual([1, "text", true, true, true, true, true]) + }) +}) + +describe("Test262 expected Promise conformance", () => { + for (const name of ["all", "allSettled", "race"] as const) { + test.failing(`Promise.${name} rejects invalid input with TypeError`, async () => { + // Sources: + // test/built-ins/Promise/all/S25.4.4.1_A3.1_T1.js + // test/built-ins/Promise/all/S25.4.4.1_A3.1_T2.js + // test/built-ins/Promise/allSettled/iter-arg-is-number-reject.js + // test/built-ins/Promise/race/iter-arg-is-number-reject.js + expect( + await value(` + try { + const promise = Promise.${name}(42) + const returned = promise instanceof Promise + await promise + return [returned, "fulfilled"] + } catch (error) { + return [true, error.name] + } + `), + ).toEqual([true, "TypeError"]) + }) + } + + test.failing("Promise.all consumes sparse positions as undefined", async () => { + // Source: test/built-ins/Array/from/from-array.js (array iterator hole behavior) + expect( + await value(` + const input = [] + input[1] = 1 + const result = await Promise.all(input) + return [result.length, result[0] === undefined, result[1]] + `), + ).toEqual([2, true, 1]) + }) + + test.failing("Promise.allSettled consumes sparse positions as undefined", async () => { + // Source: test/built-ins/Array/from/from-array.js (array iterator hole behavior) + expect( + await value(` + const input = [] + input[1] = 1 + const result = await Promise.allSettled(input) + return [result.length, result[0].status, result[0].value === undefined, result[1]] + `), + ).toEqual([2, "fulfilled", true, { status: "fulfilled", value: 1 }]) + }) + + test.failing("Promise.race consumes a sparse first position as undefined", async () => { + // Source: test/built-ins/Array/from/from-array.js (array iterator hole behavior) + expect( + await value(` + const input = [] + input[1] = 1 + return (await Promise.race(input)) === undefined + `), + ).toBe(true) + }) + + test.failing("Promise.all settles after reactions attached to its inputs", async () => { + // Sources: + // test/built-ins/Promise/all/S25.4.4.1_A7.2_T1.js + // test/built-ins/Promise/all/S25.4.4.1_A8.1_T1.js + expect( + await value(` + const sequence = [1] + const input = Promise.resolve(1) + const aggregate = Promise.all([input]) + aggregate.then(() => sequence.push(4)) + input.then(() => sequence.push(3)).then(() => sequence.push(5)) + sequence.push(2) + await aggregate + await Promise.resolve() + return sequence + `), + ).toEqual([1, 2, 3, 4, 5]) + }) + + test.failing("Promise.allSettled settles after reactions attached to its inputs", async () => { + // Sources: + // test/built-ins/Promise/allSettled/resolved-sequence.js + // test/built-ins/Promise/allSettled/resolved-sequence-extra-ticks.js + // test/built-ins/Promise/allSettled/resolved-sequence-mixed.js + // test/built-ins/Promise/allSettled/resolved-sequence-with-rejections.js + expect( + await value(` + const sequence = [1] + const input = Promise.resolve(1) + const aggregate = Promise.allSettled([input]) + aggregate.then(() => sequence.push(4)) + input.then(() => sequence.push(3)).then(() => sequence.push(5)) + sequence.push(2) + await aggregate + await Promise.resolve() + return sequence + `), + ).toEqual([1, 2, 3, 4, 5]) + }) + + test.failing("Promise.race settles in a reaction after its winning input", async () => { + // Sources: + // test/built-ins/Promise/race/S25.4.4.3_A6.1_T1.js + // test/built-ins/Promise/race/resolved-sequence-extra-ticks.js + expect( + await value(` + const sequence = [1] + const race = Promise.race([1]) + race.then(() => sequence.push(4)) + Promise.resolve().then(() => sequence.push(3)).then(() => sequence.push(5)) + sequence.push(2) + await race + await Promise.resolve() + return sequence + `), + ).toEqual([1, 2, 3, 4, 5]) + }) + + test.failing("then reactions route and propagate fulfillment and rejection", async () => { + // Sources: + // test/built-ins/Promise/prototype/then/prfm-fulfilled.js + // test/built-ins/Promise/prototype/then/prfm-rejected.js + // test/built-ins/Promise/prototype/then/rxn-handler-identity.js + // test/built-ins/Promise/prototype/then/rxn-handler-thrower.js + // test/built-ins/Promise/prototype/then/rxn-handler-fulfilled-return-normal.js + // test/built-ins/Promise/prototype/then/rxn-handler-fulfilled-return-abrupt.js + // test/built-ins/Promise/prototype/then/rxn-handler-rejected-return-normal.js + // test/built-ins/Promise/prototype/then/rxn-handler-rejected-return-abrupt.js + expect( + await value(` + const observe = async (promise) => { + try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } + } + return await Promise.all([ + observe(Promise.resolve(1).then((value) => value + 1)), + observe(Promise.reject(2).then(undefined, (reason) => reason + 1)), + observe(Promise.resolve(3).then(undefined)), + observe(Promise.reject(4).then(undefined)), + observe(Promise.resolve(5).then(() => { throw 6 })), + observe(Promise.reject(7).then(undefined, () => { throw 8 })), + ]) + `), + ).toEqual([ + ["fulfilled", 2], + ["fulfilled", 3], + ["fulfilled", 3], + ["rejected", 4], + ["rejected", 6], + ["rejected", 8], + ]) + }) + + test.failing("then reactions preserve breadth-first queue order", async () => { + // Source: test/built-ins/Promise/prototype/then/S25.4.4_A1.1_T1.js + expect( + await value(` + const sequence = [1] + const promise = Promise.resolve() + const first = promise.then(() => sequence.push(3)).then(() => sequence.push(5)).then(() => sequence.push(7)) + const second = promise.then(() => sequence.push(4)).then(() => sequence.push(6)).then(() => sequence.push(8)) + sequence.push(2) + await Promise.all([first, second]) + return sequence + `), + ).toEqual([1, 2, 3, 4, 5, 6, 7, 8]) + }) + + test.failing("then rejects direct self-resolution for fulfilled and rejected sources", async () => { + // Sources: + // test/built-ins/Promise/prototype/then/resolve-settled-fulfilled-self.js + // test/built-ins/Promise/prototype/then/resolve-settled-rejected-self.js + // test/built-ins/Promise/prototype/then/resolve-pending-fulfilled-self.js + // test/built-ins/Promise/prototype/then/resolve-pending-rejected-self.js + expect( + await value(` + const observe = async (promise) => { + try { await promise; return "fulfilled" } catch (reason) { return reason.name } + } + let fulfilled + let rejected + fulfilled = Promise.resolve().then(() => fulfilled) + rejected = Promise.reject().then(undefined, () => rejected) + return await Promise.all([observe(fulfilled), observe(rejected)]) + `), + ).toEqual(["TypeError", "TypeError"]) + }) + + test.failing("catch delegates rejection handling and preserves fulfillment", async () => { + // Sources: + // test/built-ins/Promise/prototype/catch/S25.4.5.1_A2.1_T1.js + // test/built-ins/Promise/prototype/catch/S25.4.5.1_A3.1_T1.js + // test/built-ins/Promise/prototype/catch/S25.4.5.1_A3.1_T2.js + expect( + await value(` + return [ + await Promise.resolve(1).catch(() => 2), + await Promise.reject(3).catch((reason) => reason + 1), + ] + `), + ).toEqual([1, 4]) + }) + + test.failing("finally preserves or replaces the original settlement", async () => { + // Sources: + // test/built-ins/Promise/prototype/finally/resolution-value-no-override.js + // test/built-ins/Promise/prototype/finally/rejection-reason-no-fulfill.js + // test/built-ins/Promise/prototype/finally/rejection-reason-override-with-throw.js + expect( + await value(` + const observe = async (promise) => { + try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } + } + return await Promise.all([ + observe(Promise.resolve(1).finally(() => 2)), + observe(Promise.reject(3).finally(() => 4)), + observe(Promise.reject(5).finally(() => { throw 6 })), + ]) + `), + ).toEqual([ + ["fulfilled", 1], + ["rejected", 3], + ["rejected", 6], + ]) + }) + + test.failing("await always resumes in a later reaction and interleaves async functions", async () => { + // Sources: + // test/language/expressions/await/async-await-interleaved.js + // test/language/expressions/await/await-non-promise.js + expect( + await value(` + const sequence = [] + const first = async () => { sequence.push("first:1"); await 0; sequence.push("first:2") } + const second = async () => { sequence.push("second:1"); await 0; sequence.push("second:2") } + await Promise.all([first(), second()]) + return sequence + `), + ).toEqual(["first:1", "second:1", "first:2", "second:2"]) + }) + + test.failing("an async function rejects when it resolves with its own promise", async () => { + // Adapted from the self-resolution requirement represented by: + // test/built-ins/Promise/resolve-self.js + // test/built-ins/Promise/resolve/S25.4.4.5_A4.1_T1.js + expect( + await value(` + let promise + const run = async () => { + await Promise.resolve() + return promise + } + promise = run() + try { + await promise + return "fulfilled" + } catch (error) { + return error.name + } + `), + ).toBe("TypeError") + }) + + test.failing("Promise.resolve recursively assimilates callable thenables", async () => { + // Source: test/built-ins/Promise/resolve/resolve-thenable.js + expect( + await value(` + const value = { id: 1 } + const nested = { then: (resolve) => resolve(value) } + const thenable = { then: (resolve) => resolve(nested) } + return (await Promise.resolve(thenable)) === value + `), + ).toBe(true) + }) + + test.failing("Promise combinators assimilate callable thenable inputs", async () => { + // Sources: + // test/built-ins/Promise/all/reject-immed.js + // test/built-ins/Promise/all/reject-ignored-immed.js + // test/built-ins/Promise/allSettled/reject-ignored-immed.js + // test/built-ins/Promise/race/resolve-thenable.js + expect( + await value(` + const fulfills = { then: (resolve) => resolve(1) } + const rejects = { then: (_, reject) => reject(2) } + const resolvesFirst = { then: (resolve, reject) => { resolve(3); reject(4) } } + const observe = async (promise) => { + try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } + } + return [ + await observe(Promise.all([fulfills, rejects])), + await Promise.allSettled([fulfills, resolvesFirst]), + await observe(Promise.race([rejects])), + ] + `), + ).toEqual([ + ["rejected", 2], + [ + { status: "fulfilled", value: 1 }, + { status: "fulfilled", value: 3 }, + ], + ["rejected", 2], + ]) + }) + + test.failing("await assimilates callable thenables", async () => { + // Source: test/language/expressions/await/await-awaits-thenables.js + expect( + await value(` + const thenable = { then: (resolve) => resolve(42) } + return await thenable + `), + ).toBe(42) + }) + + test.failing("await rejects when a callable thenable throws", async () => { + // Source: test/language/expressions/await/await-awaits-thenables-that-throw.js + expect( + await value(` + const error = { id: 1 } + const thenable = { then: () => { throw error } } + try { + await thenable + return false + } catch (caught) { + return caught === error + } + `), + ).toBe(true) + }) +}) diff --git a/packages/codemode/test/promise.test.ts b/packages/codemode/test/promise.test.ts index ce5f1e03a4..847cd6fb15 100644 --- a/packages/codemode/test/promise.test.ts +++ b/packages/codemode/test/promise.test.ts @@ -48,6 +48,13 @@ const failingTool = Tool.make({ run: () => Effect.fail(toolError("Lookup refused")), }) +const interruptedTool = Tool.make({ + description: "Interrupt this call", + input: Schema.Struct({}), + output: Schema.String, + run: () => Effect.interrupt, +}) + const completedTool = (trace: Trace) => Tool.make({ description: "Return the number of completed sleepy calls", @@ -56,6 +63,25 @@ const completedTool = (trace: Trace) => run: () => Effect.succeed(trace.completed), }) +/** Never settles, and holds interruption cleanup for `cleanupMs` so completion cleanup can outlast a timeout. */ +const stubbornTool = (trace: Trace) => + Tool.make({ + description: "Never settle; clean up slowly when interrupted", + input: Schema.Struct({ cleanupMs: Schema.Number }), + output: Schema.Number, + run: ({ cleanupMs }) => + Effect.never.pipe( + Effect.onInterrupt(() => + Effect.andThen( + Effect.sleep(cleanupMs), + Effect.sync(() => { + trace.interrupted += 1 + }), + ), + ), + ), + }) + const run = ( code: string, options: { trace?: Trace; limits?: CodeMode.ExecutionLimits } = {}, @@ -63,7 +89,15 @@ const run = ( const trace = options.trace ?? makeTrace() return Effect.runPromise( CodeMode.execute({ - tools: { host: { sleepy: sleepyTool(trace), fail: failingTool, completed: completedTool(trace) } }, + tools: { + host: { + sleepy: sleepyTool(trace), + fail: failingTool, + interrupt: interruptedTool, + completed: completedTool(trace), + stubborn: stubbornTool(trace), + }, + }, code, ...(options.limits ? { limits: options.limits } : {}), }), @@ -174,8 +208,7 @@ describe("first-class promise values", () => { }) test("an awaited failure is catchable exactly like a synchronous throw", async () => { - expect( - await value(` + const result = await run(` const p = tools.host.fail({}) try { await p @@ -183,57 +216,195 @@ describe("first-class promise values", () => { } catch (e) { return e.message } - `), - ).toBe("Lookup refused") + `) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("Lookup refused") + expect(result.warnings).toBeUndefined() }) - test("a fire-and-forget call completes before the execution ends", async () => { + test("a fire-and-forget call is interrupted when the program returns", async () => { const trace = makeTrace() - const result = await value( + const result = await run( ` tools.host.sleepy({ id: 1, ms: 30 }) return "done" `, { trace }, ) - expect(result).toBe("done") - expect(trace.completed).toBe(1) - expect(trace.interrupted).toBe(0) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("done") + expect(result.warnings).toBeUndefined() + expect(trace.completed).toBe(0) + expect(trace.interrupted).toBe(1) }) - test("a never-awaited failing call surfaces as an unhandled-rejection diagnostic", async () => { - const diagnostic = await error(` + test("a never-awaited failing call preserves the result and reports the rejection", async () => { + const result = await run(` tools.host.fail({}) return "done" `) - expect(diagnostic.kind).toBe("ToolFailure") - expect(diagnostic.message).toContain("Unhandled rejection from an un-awaited promise") - expect(diagnostic.message).toContain("Lookup refused") - expect(diagnostic.suggestions?.join(" ")).toContain("Await promises") + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("done") + expect(result.warnings).toStrictEqual([ + { kind: "ToolFailure", message: "Unhandled rejection from an un-awaited promise: Lookup refused" }, + ]) + expect(Schema.decodeUnknownSync(CodeMode.Result)(JSON.parse(JSON.stringify(result)))).toStrictEqual(result) }) - test("a never-awaited failing async function surfaces as an unhandled promise rejection", async () => { - const diagnostic = await error(` + test("a never-awaited failing async function is reported with a successful result", async () => { + const result = await run(` const fail = async () => { throw new Error("boom") } fail() return "done" `) - expect(diagnostic.kind).toBe("ExecutionFailure") - expect(diagnostic.message).toContain("Unhandled rejection from an un-awaited promise") - expect(diagnostic.message).toContain("boom") + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("done") + expect(result.warnings).toStrictEqual([ + { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: boom" }, + ]) }) - test("drains promises started by an async function after an await", async () => { - const diagnostic = await error(` - const run = async () => { - await tools.host.sleepy({ id: 1 }) - tools.host.fail({}) - } - run() + test("output truncation bounds warning diagnostics with an in-band marker", async () => { + const result = await run( + ` + for (let i = 0; i < 100; i += 1) Promise.reject(new Error("x".repeat(1_000))) + return "done" + `, + { limits: { maxOutputBytes: 64 } }, + ) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.truncated).toBe(true) + expect(result.warnings).toStrictEqual([ + { kind: "Truncated", message: "100 additional warnings omitted by the output limit." }, + ]) + }) + + test("a budget-consuming value does not starve warnings", async () => { + const result = await run( + ` + Promise.reject(new Error("boom")) + return "x".repeat(500) + `, + { limits: { maxOutputBytes: 128 } }, + ) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.truncated).toBe(true) + expect(typeof result.value).toBe("string") + expect(result.warnings).toStrictEqual([ + { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: boom" }, + ]) + }) + + test("an un-awaited async function's pending chain is interrupted at the return", async () => { + const trace = makeTrace() + const result = await run( + ` + const run = async () => { + await tools.host.sleepy({ id: 1, ms: 60000 }) + tools.host.fail({}) + } + run() + return "done" + `, + { trace }, + ) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("done") + expect(result.warnings).toBeUndefined() + expect(trace.starts).toEqual([1]) + expect(trace.completed).toBe(0) + expect(trace.interrupted).toBe(1) + }) + + test("reports every unhandled rejection in promise creation order", async () => { + const result = await run(` + Promise.reject(new Error("first")) + tools.host.fail({}) + Promise.reject(new Error("third")) return "done" `) - expect(diagnostic.kind).toBe("ToolFailure") - expect(diagnostic.message).toContain("Lookup refused") + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.warnings).toStrictEqual([ + { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: first" }, + { kind: "ToolFailure", message: "Unhandled rejection from an un-awaited promise: Lookup refused" }, + { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: third" }, + ]) + }) + + test("orders an async function rejection before promises created inside its body", async () => { + const result = await run(` + const outer = async () => { + Promise.reject(new Error("inner")) + throw new Error("outer") + } + outer() + return "done" + `) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.warnings).toStrictEqual([ + { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: outer" }, + { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: inner" }, + ]) + }) + + test("un-awaited interruptions settle without becoming rejections", async () => { + const result = await run(` + tools.host.interrupt({}) + Promise.all([tools.host.interrupt({})]) + return "done" + `) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("done") + expect(result.warnings).toBeUndefined() + }) + + test("a fatal program error cancels outstanding work without reporting unhandled rejections", async () => { + const trace = makeTrace() + const result = await run( + ` + tools.host.sleepy({ id: 1, ms: 1_000 }) + throw new Error("boom") + `, + { trace }, + ) + expect(result.ok).toBe(false) + if (result.ok) return + expect(result.error.message).toBe("Uncaught: boom") + expect("warnings" in result).toBe(false) + expect(trace.completed).toBe(0) + expect(trace.interrupted).toBe(1) + }) + + test("async-function promises remain owned by the execution after the function returns", async () => { + const trace = makeTrace() + expect( + await value( + ` + const launch = async () => { + tools.host.sleepy({ id: 1, ms: 60000 }) + Promise.all([tools.host.sleepy({ id: 2, ms: 60000 })]) + return "returned" + } + return await launch() + `, + { trace }, + ), + ).toBe("returned") + // Both calls outlive launch() itself - they belong to the execution, not the function - + // and are interrupted only when the whole program returns. + expect(trace.starts).toEqual([1, 2]) + expect(trace.completed).toBe(0) + expect(trace.interrupted).toBe(2) }) }) @@ -251,6 +422,22 @@ describe("promises at data boundaries", () => { expect(diagnostic.message).toContain("un-awaited Promise") }) + test("invalid returned data cancels pending work", async () => { + const trace = makeTrace() + const result = await run( + ` + const pending = tools.host.sleepy({ id: 1, ms: 60_000 }) + return { pending } + `, + { trace, limits: { timeoutMs: 100 } }, + ) + expect(result.ok).toBe(false) + if (result.ok) return + expect(result.error.kind).toBe("InvalidDataValue") + expect(trace.completed).toBe(0) + expect(trace.interrupted).toBe(1) + }) + test("passing an un-awaited promise as a tool argument is a clear diagnostic", async () => { const diagnostic = await error(`return await tools.host.sleepy({ id: tools.host.sleepy({ id: 1 }) })`) expect(diagnostic.kind).toBe("InvalidDataValue") @@ -270,6 +457,59 @@ describe("promises at data boundaries", () => { }) describe("Promise.all over arbitrary arrays", () => { + test("combinators return promises that can be assigned and awaited later", async () => { + expect( + await value(` + const all = Promise.all([Promise.resolve(1)]) + const settled = Promise.allSettled([Promise.reject("no")]) + const race = Promise.race([Promise.resolve(2)]) + const promises = [all instanceof Promise, settled instanceof Promise, race instanceof Promise] + return [promises, await all, await settled, await race] + `), + ).toEqual([[true, true, true], [1], [{ status: "rejected", reason: "no" }], 2]) + }) + + test("separately-created aggregate batches overlap before either is awaited", async () => { + const trace = makeTrace() + expect( + await value( + ` + const first = Promise.all([tools.host.sleepy({ id: 1, ms: 40 })]) + const second = Promise.all([tools.host.sleepy({ id: 2, ms: 40 })]) + return [await first, await second] + `, + { trace }, + ), + ).toEqual([[1], [2]]) + expect(trace.starts).toEqual([1, 2]) + expect(trace.maxActive).toBeGreaterThan(1) + }) + + test("an aggregate created before a try block rejects at its later await", async () => { + expect( + await value(` + const aggregate = Promise.all([tools.host.fail({})]) + try { + await aggregate + return "no" + } catch (error) { + return error.message + } + `), + ).toBe("Lookup refused") + }) + + test("awaiting an aggregate repeatedly does not rerun its members", async () => { + const result = await run(` + const aggregate = Promise.all([tools.host.sleepy({ id: 7 })]) + return [await aggregate, await aggregate] + `) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toEqual([[7], [7]]) + expect(result.toolCalls).toStrictEqual([{ name: "host.sleepy" }]) + }) + test("mixes promises and plain values, preserving order", async () => { expect( await value(` @@ -340,16 +580,18 @@ describe("Promise.all over arbitrary arrays", () => { }) test("rejects with the first failure, catchable in-program", async () => { - expect( - await value(` + const result = await run(` try { await Promise.all([tools.host.sleepy({ id: 1 }), tools.host.fail({})]) return "no" } catch (e) { return e.message } - `), - ).toBe("Lookup refused") + `) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("Lookup refused") + expect(result.warnings).toBeUndefined() }) test("rejects before an earlier slow promise fulfills", async () => { @@ -370,10 +612,55 @@ describe("Promise.all over arbitrary arrays", () => { { trace }, ), ).toBe(0) + // The surviving member is observed (Promise.all handled it), so completion interrupts + // it instead of waiting for it. + expect(trace.completed).toBe(0) + expect(trace.interrupted).toBe(1) + }) + + test("fail-fast does not cancel a sibling the program still holds and awaits", async () => { + const trace = makeTrace() + expect( + await value( + ` + const slow = tools.host.sleepy({ id: 1, ms: 40 }) + try { + await Promise.all([slow, tools.host.fail({})]) + return "no" + } catch {} + return await slow + `, + { trace }, + ), + ).toBe(1) expect(trace.completed).toBe(1) expect(trace.interrupted).toBe(0) }) + test("a slower observed sibling is interrupted at completion after failing fast", async () => { + const trace = makeTrace() + expect( + await value( + ` + const failLater = async () => { + await tools.host.sleepy({ id: 1, ms: 40 }) + throw new Error("later") + } + const aggregate = Promise.all([Promise.reject(new Error("first")), failLater()]) + try { + await aggregate + return "no" + } catch (error) { + return error.message + } + `, + { trace }, + ), + ).toBe("first") + expect(trace.completed).toBe(0) + expect(trace.interrupted).toBe(1) + }) + test("a non-collection argument is a clear error", async () => { const diagnostic = await error(`return await Promise.all(42)`) expect(diagnostic.message).toContain("Promise.all expects an array") @@ -413,50 +700,64 @@ describe("Promise.allSettled", () => { return settled.filter((s) => s.status === "rejected").length `) expect(result.ok).toBe(true) - if (result.ok) expect(result.value).toBe(2) + if (!result.ok) return + expect(result.value).toBe(2) + expect(result.warnings).toBeUndefined() }) }) describe("Promise.race", () => { - test("first settlement wins and losers are interrupted", async () => { + test("first settlement wins and a direct loser is interrupted at completion", async () => { const trace = makeTrace() const result = await value( ` const fast = tools.host.sleepy({ id: 1, ms: 10 }) - const slow = tools.host.sleepy({ id: 2, ms: 5000 }) + const slow = tools.host.sleepy({ id: 2, ms: 40 }) return await Promise.race([fast, slow]) `, { trace }, ) expect(result).toBe(1) - expect(trace.interrupted).toBe(1) + // The loser is observed (the race handled it), so the execution does not wait for it. expect(trace.completed).toBe(1) + expect(trace.interrupted).toBe(1) }) - test("awaiting an interrupted loser afterwards is a catchable program failure", async () => { + test("a direct loser remains awaitable after the race settles", async () => { expect( await value(` const fast = tools.host.sleepy({ id: 1, ms: 10 }) - const slow = tools.host.sleepy({ id: 2, ms: 5000 }) + const slow = tools.host.sleepy({ id: 2, ms: 40 }) const winner = await Promise.race([fast, slow]) - try { - await slow - return "no" - } catch (e) { - return { winner, caught: e.message } - } + return { winner, loser: await slow } `), - ).toEqual({ - winner: 1, - caught: "This tool call was interrupted because another value settled a Promise.race first.", - }) + ).toEqual({ winner: 1, loser: 2 }) + }) + + test("a nested aggregate loser and its members are interrupted at completion", async () => { + const trace = makeTrace() + expect( + await value( + ` + const nested = Promise.all([ + tools.host.sleepy({ id: 1, ms: 40 }), + tools.host.sleepy({ id: 2, ms: 40 }), + ]) + return await Promise.race(["immediate", nested]) + `, + { trace }, + ), + ).toBe("immediate") + // The nested aggregate and its members are all observed, so nothing waits for them. + expect(trace.completed).toBe(0) + expect(trace.interrupted).toBe(2) }) test("a rejection can win the race", async () => { expect( await value(` try { - await Promise.race([tools.host.fail({}), tools.host.sleepy({ id: 1, ms: 5000 })]) + await Promise.race([tools.host.fail({}), tools.host.sleepy({ id: 1, ms: 40 })]) return "no" } catch (e) { return e.message @@ -468,11 +769,20 @@ describe("Promise.race", () => { test("a plain value wins over pending promises", async () => { const trace = makeTrace() expect( - await value(`return await Promise.race([tools.host.sleepy({ id: 1, ms: 5000 }), "immediate"])`, { trace }), + await value(`return await Promise.race([tools.host.sleepy({ id: 1, ms: 40 }), "immediate"])`, { trace }), ).toBe("immediate") + expect(trace.completed).toBe(0) expect(trace.interrupted).toBe(1) }) + test("a rejected race loser is observed by the aggregate", async () => { + const result = await run(`return await Promise.race(["winner", tools.host.fail({})])`) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("winner") + expect(result.warnings).toBeUndefined() + }) + test("an empty race is a clear error instead of hanging", async () => { const diagnostic = await error(`return await Promise.race([])`) expect(diagnostic.message).toContain("never settle") @@ -484,6 +794,9 @@ describe("Promise.resolve / Promise.reject", () => { expect(await value(`return await Promise.resolve(42)`)).toBe(42) expect(await value(`return await Promise.resolve(Promise.resolve("nested"))`)).toBe("nested") expect(await value(`return await Promise.resolve(tools.host.sleepy({ id: 3 }))`)).toBe(3) + expect(await value(`const promise = Promise.resolve(1); return [promise].includes(Promise.resolve(promise))`)).toBe( + true, + ) }) test("reject produces a promise whose await throws the reason", async () => { @@ -498,6 +811,34 @@ describe("Promise.resolve / Promise.reject", () => { `), ).toBe("nope") }) + + test("a rejection observed after settlement is handled", async () => { + expect( + await value(` + const rejected = Promise.reject(new Error("handled")) + await tools.host.sleepy({ id: 1 }) + try { + await rejected + return "no" + } catch (error) { + return error.message + } + `), + ).toBe("handled") + }) + + test("an abandoned rejected promise is reported as unhandled", async () => { + const result = await run(` + Promise.reject(new Error("abandoned")) + return "done" + `) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("done") + expect(result.warnings).toStrictEqual([ + { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: abandoned" }, + ]) + }) }) describe("timeout interruption of forked calls", () => { @@ -531,6 +872,67 @@ describe("timeout interruption of forked calls", () => { expect(result.error.kind).toBe("TimeoutExceeded") expect(trace.interrupted).toBe(2) }) + + test("a non-settling race loser cannot hold the execution to the timeout", async () => { + const trace = makeTrace() + const result = await run(`return await Promise.race(["winner", tools.host.sleepy({ id: 1, ms: 60000 })])`, { + trace, + limits: { timeoutMs: 100 }, + }) + // Completion interrupts the observed loser immediately; the race result survives. + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("winner") + expect(result.warnings).toBeUndefined() + expect(trace.starts).toEqual([1]) + expect(trace.completed).toBe(0) + expect(trace.interrupted).toBe(1) + }) + + test("a timeout during completion cleanup keeps the computed value and warns", async () => { + const trace = makeTrace() + const result = await run( + ` + tools.host.stubborn({ cleanupMs: 400 }) + return "done" + `, + { trace, limits: { timeoutMs: 100 } }, + ) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("done") + expect(result.warnings).toStrictEqual([ + { + kind: "TimeoutExceeded", + message: + "The program returned, but background work was still running at the 100ms timeout and was interrupted. Await all started promises.", + }, + ]) + expect(trace.interrupted).toBe(1) + expect(trace.completed).toBe(0) + }) + + test("a timeout during completion cleanup reports the timeout warning before settled rejections", async () => { + const result = await run( + ` + tools.host.fail({}) + tools.host.stubborn({ cleanupMs: 400 }) + return "done" + `, + { limits: { timeoutMs: 100 } }, + ) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.value).toBe("done") + expect(result.warnings).toStrictEqual([ + { + kind: "TimeoutExceeded", + message: + "The program returned, but background work was still running at the 100ms timeout and was interrupted. Await all started promises.", + }, + { kind: "ToolFailure", message: "Unhandled rejection from an un-awaited promise: Lookup refused" }, + ]) + }) }) describe("unsupported promise surface", () => { diff --git a/packages/codemode/test/test262-array.md b/packages/codemode/test/test262-array.md deleted file mode 100644 index b8e7e07a89..0000000000 --- a/packages/codemode/test/test262-array.md +++ /dev/null @@ -1,77 +0,0 @@ -# Test262 Array Coverage - -The Array tests adapt Test262 at revision `250f204f23a9249ff204be2baec29600faae7b75`. They cover CodeMode's 35 -exposed instance methods and three static methods using actual arrays, accepted argument types, deterministic behavior, -and CodeMode's materialized collection conventions. Each executable case names its exact upstream source path. -`LICENSE.test262` contains the upstream BSD terms. - -This is coverage of CodeMode's bounded Array surface, not a claim of ECMAScript or Test262 conformance. One upstream -file may contain both adapted and inapplicable assertions, so a cited source means only that the represented assertions -were adapted. - -## Inventory - -The 38 relevant upstream API directories contain 2,837 files. The executable suite adapts assertions from 83 distinct -sources. - -| API | Upstream files | Adapted sources | -| ------------------------------- | -------------: | --------------: | -| `Array.prototype.map` | 216 | 3 | -| `Array.prototype.filter` | 242 | 3 | -| `Array.prototype.find` | 23 | 4 | -| `Array.prototype.findIndex` | 23 | 3 | -| `Array.prototype.findLast` | 24 | 3 | -| `Array.prototype.findLastIndex` | 24 | 3 | -| `Array.prototype.some` | 219 | 2 | -| `Array.prototype.every` | 218 | 2 | -| `Array.prototype.includes` | 30 | 2 | -| `Array.prototype.join` | 23 | 2 | -| `Array.prototype.reduce` | 260 | 3 | -| `Array.prototype.reduceRight` | 260 | 3 | -| `Array.prototype.flatMap` | 24 | 2 | -| `Array.prototype.forEach` | 190 | 2 | -| `Array.prototype.sort` | 54 | 3 | -| `Array.prototype.toSorted` | 21 | 4 | -| `Array.prototype.slice` | 71 | 1 | -| `Array.prototype.concat` | 69 | 3 | -| `Array.prototype.indexOf` | 201 | 2 | -| `Array.prototype.lastIndexOf` | 198 | 2 | -| `Array.prototype.at` | 13 | 3 | -| `Array.prototype.flat` | 19 | 2 | -| `Array.prototype.reverse` | 18 | 1 | -| `Array.prototype.toReversed` | 17 | 2 | -| `Array.prototype.with` | 21 | 2 | -| `Array.prototype.push` | 24 | 1 | -| `Array.prototype.pop` | 23 | 1 | -| `Array.prototype.shift` | 20 | 1 | -| `Array.prototype.unshift` | 22 | 1 | -| `Array.prototype.splice` | 81 | 3 | -| `Array.prototype.fill` | 22 | 3 | -| `Array.prototype.copyWithin` | 39 | 2 | -| `Array.prototype.keys` | 12 | 1 | -| `Array.prototype.values` | 12 | 1 | -| `Array.prototype.entries` | 12 | 1 | -| `Array.from` | 47 | 3 | -| `Array.isArray` | 29 | 2 | -| `Array.of` | 16 | 1 | - -## Exclusions - -Assertions are not adapted when they test behavior outside CodeMode's documented Array surface: - -- Function metadata, property descriptors, constructibility, prototype mutation, species constructors, or cross-realm - identity. -- Generic receivers, detached methods, `.call`, `.apply`, boxed values, custom coercion objects, Symbols, BigInts, - proxies, accessors, frozen arrays, typed arrays, or ArrayBuffers. -- `Array.from` mappers, custom iterables, constructor substitution, and iterator-closing behavior. -- Native iterator identity, `.next()`, completion records, or live iterator mutation. CodeMode deliberately materializes - `keys`, `values`, and `entries` as arrays. -- Sparse-array assertions that depend on literal elisions or inherited indexed properties. CodeMode's confined data - model does not preserve those prototype and hole semantics at every boundary. -- Argument coercions outside the accepted schema-like surface. Numeric positions must be numbers and `join` separators - must be strings. -- Exact native error brands where CodeMode exposes a safe runtime error instead. -- Async/effectful callbacks, circular-data rejection, sandbox-value identity, diagnostics, and host-boundary behavior. - Those remain covered by CodeMode-specific tests. - -Handwritten tests remain where they specify CodeMode behavior rather than ordinary ECMAScript Array semantics. diff --git a/packages/codemode/test/test262-string.md b/packages/codemode/test/test262-string.md deleted file mode 100644 index 94d01f83d9..0000000000 --- a/packages/codemode/test/test262-string.md +++ /dev/null @@ -1,69 +0,0 @@ -# Test262 String Coverage - -The String tests adapt Test262 at revision `250f204f23a9249ff204be2baec29600faae7b75`. They cover CodeMode's 32 -exposed instance methods and two static methods using primitive receivers, accepted argument types, and deterministic -behavior. Each executable case names its exact upstream source path. `LICENSE.test262` contains the upstream BSD terms. - -This is coverage of CodeMode's bounded String surface, not a claim of ECMAScript or Test262 conformance. One upstream -file may contain both adapted and inapplicable assertions, so a cited source means only that the represented assertions -were adapted. - -## Inventory - -The relevant upstream directories contain 1,048 files: 1,009 core built-in files, 29 Annex B files for exposed methods, -and 10 Intl `localeCompare` files. The executable suite adapts assertions from 298 distinct sources. - -| API | Upstream files | Adapted sources | -| --- | ---: | ---: | -| `String.fromCharCode` | 17 | 6 | -| `String.fromCodePoint` | 11 | 4 | -| `String.prototype.at` | 11 | 5 | -| `String.prototype.charAt` | 30 | 9 | -| `String.prototype.charCodeAt` | 25 | 4 | -| `String.prototype.codePointAt` | 16 | 6 | -| `String.prototype.concat` | 22 | 1 | -| `String.prototype.endsWith` | 27 | 13 | -| `String.prototype.includes` | 27 | 12 | -| `String.prototype.indexOf` | 47 | 8 | -| `String.prototype.lastIndexOf` | 25 | 1 | -| `String.prototype.localeCompare` | 23 | 1 | -| `String.prototype.match` | 52 | 9 | -| `String.prototype.matchAll` | 26 | 1 | -| `String.prototype.normalize` | 14 | 3 | -| `String.prototype.padEnd` | 13 | 4 | -| `String.prototype.padStart` | 13 | 4 | -| `String.prototype.repeat` | 16 | 4 | -| `String.prototype.replace` | 56 | 16 | -| `String.prototype.replaceAll` | 46 | 12 | -| `String.prototype.search` | 44 | 10 | -| `String.prototype.slice` | 38 | 11 | -| `String.prototype.split` | 121 | 50 | -| `String.prototype.startsWith` | 21 | 7 | -| `String.prototype.substr` | 15 | 6 | -| `String.prototype.substring` | 46 | 12 | -| `String.prototype.toLowerCase` | 30 | 5 | -| `String.prototype.toString` | 7 | 1 | -| `String.prototype.toUpperCase` | 26 | 3 | -| `String.prototype.trim` | 129 | 66 | -| `String.prototype.trimEnd` | 23 | 2 | -| `String.prototype.trimLeft` | 4 | 0 | -| `String.prototype.trimRight` | 4 | 0 | -| `String.prototype.trimStart` | 23 | 2 | - -## Exclusions - -Assertions are not adapted when they test behavior outside CodeMode's documented String surface: - -- Function metadata, property descriptors, constructibility, prototype mutation, or cross-realm identity. -- The `trimLeft`/`trimRight` Test262 files assert prototype function identity, which CodeMode does not expose. Their - supported call behavior remains covered by CodeMode-specific tests. -- Boxed strings, generic receivers, custom coercion objects, Symbols, BigInts, or argument types CodeMode rejects. -- Symbol-based RegExp dispatch, custom matchers, species constructors, or iterator protocol details. CodeMode materializes - `matchAll` results instead of exposing iterators. -- Locale selection and options. CodeMode deliberately uses the host default locale and ignores those arguments. -- Test262 harness behavior or setup syntax unavailable in the confined interpreter. -- Function-replacer behavior that is covered by CodeMode-specific tests for sequential callbacks, async tool calls, - result coercion, diagnostics, and sandbox boundaries. -- Assertions requiring an exact native error type when CodeMode deliberately exposes only its safe runtime error. - -Handwritten tests remain where they specify CodeMode behavior rather than ordinary ECMAScript String semantics. diff --git a/packages/core/schema.json b/packages/core/schema.json index 06cec4eaed..82a395b4e4 100644 --- a/packages/core/schema.json +++ b/packages/core/schema.json @@ -1,8 +1,10 @@ { "version": "7", "dialect": "sqlite", - "id": "01451b27-1e51-4657-b2d0-4b457dffa3ec", - "prevIds": ["8c1748cc-f978-4df4-879d-fe7fda5c4c34"], + "id": "5f0a1db8-d4bf-42c3-becb-96b46fe66bed", + "prevIds": [ + "666138ef-82cb-4a9a-a765-e6669a436ff3" + ], "ddl": [ { "name": "workspace", @@ -49,13 +51,17 @@ "entityType": "tables" }, { - "name": "instruction_checkpoint", + "name": "instruction_blob", "entityType": "tables" }, { "name": "instruction_entry", "entityType": "tables" }, + { + "name": "instruction_state", + "entityType": "tables" + }, { "name": "message", "entityType": "tables" @@ -65,11 +71,11 @@ "entityType": "tables" }, { - "name": "session_input", + "name": "session_message", "entityType": "tables" }, { - "name": "session_message", + "name": "session_pending", "entityType": "tables" }, { @@ -786,39 +792,19 @@ "autoincrement": false, "default": null, "generated": null, - "name": "session_id", + "name": "hash", "entityType": "columns", - "table": "instruction_checkpoint" + "table": "instruction_blob" }, { "type": "text", - "notNull": true, + "notNull": false, "autoincrement": false, "default": null, "generated": null, - "name": "baseline", + "name": "value", "entityType": "columns", - "table": "instruction_checkpoint" - }, - { - "type": "text", - "notNull": true, - "autoincrement": false, - "default": null, - "generated": null, - "name": "snapshot", - "entityType": "columns", - "table": "instruction_checkpoint" - }, - { - "type": "integer", - "notNull": true, - "autoincrement": false, - "default": null, - "generated": null, - "name": "baseline_seq", - "entityType": "columns", - "table": "instruction_checkpoint" + "table": "instruction_blob" }, { "type": "text", @@ -842,7 +828,7 @@ }, { "type": "text", - "notNull": true, + "notNull": false, "autoincrement": false, "default": null, "generated": null, @@ -850,6 +836,16 @@ "entityType": "columns", "table": "instruction_entry" }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "false", + "generated": null, + "name": "removed", + "entityType": "columns", + "table": "instruction_entry" + }, { "type": "integer", "notNull": true, @@ -870,6 +866,56 @@ "entityType": "columns", "table": "instruction_entry" }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "instruction_state" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "epoch_start", + "entityType": "columns", + "table": "instruction_state" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "through_seq", + "entityType": "columns", + "table": "instruction_state" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "initial_values", + "entityType": "columns", + "table": "instruction_state" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "current_values", + "entityType": "columns", + "table": "instruction_state" + }, { "type": "text", "notNull": false, @@ -980,86 +1026,6 @@ "entityType": "columns", "table": "part" }, - { - "type": "text", - "notNull": false, - "autoincrement": false, - "default": null, - "generated": null, - "name": "id", - "entityType": "columns", - "table": "session_input" - }, - { - "type": "text", - "notNull": true, - "autoincrement": false, - "default": null, - "generated": null, - "name": "session_id", - "entityType": "columns", - "table": "session_input" - }, - { - "type": "text", - "notNull": true, - "autoincrement": false, - "default": null, - "generated": null, - "name": "type", - "entityType": "columns", - "table": "session_input" - }, - { - "type": "text", - "notNull": true, - "autoincrement": false, - "default": null, - "generated": null, - "name": "data", - "entityType": "columns", - "table": "session_input" - }, - { - "type": "text", - "notNull": false, - "autoincrement": false, - "default": null, - "generated": null, - "name": "delivery", - "entityType": "columns", - "table": "session_input" - }, - { - "type": "integer", - "notNull": true, - "autoincrement": false, - "default": null, - "generated": null, - "name": "admitted_seq", - "entityType": "columns", - "table": "session_input" - }, - { - "type": "integer", - "notNull": false, - "autoincrement": false, - "default": null, - "generated": null, - "name": "promoted_seq", - "entityType": "columns", - "table": "session_input" - }, - { - "type": "integer", - "notNull": true, - "autoincrement": false, - "default": null, - "generated": null, - "name": "time_created", - "entityType": "columns", - "table": "session_input" - }, { "type": "text", "notNull": false, @@ -1130,6 +1096,76 @@ "entityType": "columns", "table": "session_message" }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "session_pending" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "session_pending" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "type", + "entityType": "columns", + "table": "session_pending" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "data", + "entityType": "columns", + "table": "session_pending" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "delivery", + "entityType": "columns", + "table": "session_pending" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "admitted_seq", + "entityType": "columns", + "table": "session_pending" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "session_pending" + }, { "type": "text", "notNull": false, @@ -1190,6 +1226,16 @@ "entityType": "columns", "table": "session" }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "fork_seq", + "entityType": "columns", + "table": "session" + }, { "type": "text", "notNull": true, @@ -1511,9 +1557,13 @@ "table": "session_share" }, { - "columns": ["project_id"], + "columns": [ + "project_id" + ], "tableTo": "project", - "columnsTo": ["id"], + "columnsTo": [ + "id" + ], "onUpdate": "NO ACTION", "onDelete": "CASCADE", "nameExplicit": false, @@ -1522,9 +1572,13 @@ "table": "workspace" }, { - "columns": ["active_account_id"], + "columns": [ + "active_account_id" + ], "tableTo": "account", - "columnsTo": ["id"], + "columnsTo": [ + "id" + ], "onUpdate": "NO ACTION", "onDelete": "SET NULL", "nameExplicit": false, @@ -1533,9 +1587,13 @@ "table": "account_state" }, { - "columns": ["aggregate_id"], + "columns": [ + "aggregate_id" + ], "tableTo": "event_sequence", - "columnsTo": ["aggregate_id"], + "columnsTo": [ + "aggregate_id" + ], "onUpdate": "NO ACTION", "onDelete": "CASCADE", "nameExplicit": false, @@ -1544,9 +1602,13 @@ "table": "event" }, { - "columns": ["project_id"], + "columns": [ + "project_id" + ], "tableTo": "project", - "columnsTo": ["id"], + "columnsTo": [ + "id" + ], "onUpdate": "NO ACTION", "onDelete": "CASCADE", "nameExplicit": false, @@ -1555,9 +1617,13 @@ "table": "permission" }, { - "columns": ["project_id"], + "columns": [ + "project_id" + ], "tableTo": "project", - "columnsTo": ["id"], + "columnsTo": [ + "id" + ], "onUpdate": "NO ACTION", "onDelete": "CASCADE", "nameExplicit": false, @@ -1566,20 +1632,13 @@ "table": "project_directory" }, { - "columns": ["session_id"], + "columns": [ + "session_id" + ], "tableTo": "session", - "columnsTo": ["id"], - "onUpdate": "NO ACTION", - "onDelete": "CASCADE", - "nameExplicit": false, - "name": "fk_instruction_checkpoint_session_id_session_id_fk", - "entityType": "fks", - "table": "instruction_checkpoint" - }, - { - "columns": ["session_id"], - "tableTo": "session", - "columnsTo": ["id"], + "columnsTo": [ + "id" + ], "onUpdate": "NO ACTION", "onDelete": "CASCADE", "nameExplicit": false, @@ -1588,9 +1647,28 @@ "table": "instruction_entry" }, { - "columns": ["session_id"], + "columns": [ + "session_id" + ], "tableTo": "session", - "columnsTo": ["id"], + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_instruction_state_session_id_session_id_fk", + "entityType": "fks", + "table": "instruction_state" + }, + { + "columns": [ + "session_id" + ], + "tableTo": "session", + "columnsTo": [ + "id" + ], "onUpdate": "NO ACTION", "onDelete": "CASCADE", "nameExplicit": false, @@ -1599,9 +1677,13 @@ "table": "message" }, { - "columns": ["message_id"], + "columns": [ + "message_id" + ], "tableTo": "message", - "columnsTo": ["id"], + "columnsTo": [ + "id" + ], "onUpdate": "NO ACTION", "onDelete": "CASCADE", "nameExplicit": false, @@ -1610,20 +1692,13 @@ "table": "part" }, { - "columns": ["session_id"], + "columns": [ + "session_id" + ], "tableTo": "session", - "columnsTo": ["id"], - "onUpdate": "NO ACTION", - "onDelete": "CASCADE", - "nameExplicit": false, - "name": "fk_session_input_session_id_session_id_fk", - "entityType": "fks", - "table": "session_input" - }, - { - "columns": ["session_id"], - "tableTo": "session", - "columnsTo": ["id"], + "columnsTo": [ + "id" + ], "onUpdate": "NO ACTION", "onDelete": "CASCADE", "nameExplicit": false, @@ -1632,9 +1707,28 @@ "table": "session_message" }, { - "columns": ["project_id"], + "columns": [ + "session_id" + ], + "tableTo": "session", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_session_input_session_id_session_id_fk", + "entityType": "fks", + "table": "session_pending" + }, + { + "columns": [ + "project_id" + ], "tableTo": "project", - "columnsTo": ["id"], + "columnsTo": [ + "id" + ], "onUpdate": "NO ACTION", "onDelete": "CASCADE", "nameExplicit": false, @@ -1643,9 +1737,13 @@ "table": "session" }, { - "columns": ["session_id"], + "columns": [ + "session_id" + ], "tableTo": "session", - "columnsTo": ["id"], + "columnsTo": [ + "id" + ], "onUpdate": "NO ACTION", "onDelete": "CASCADE", "nameExplicit": false, @@ -1654,133 +1752,183 @@ "table": "session_share" }, { - "columns": ["email", "url"], + "columns": [ + "email", + "url" + ], "nameExplicit": false, "name": "control_account_pk", "entityType": "pks", "table": "control_account" }, { - "columns": ["project_id", "directory"], + "columns": [ + "project_id", + "directory" + ], "nameExplicit": false, "name": "project_directory_pk", "entityType": "pks", "table": "project_directory" }, { - "columns": ["session_id", "key"], + "columns": [ + "session_id", + "key" + ], "nameExplicit": false, "name": "instruction_entry_pk", "entityType": "pks", "table": "instruction_entry" }, { - "columns": ["id"], + "columns": [ + "id" + ], "nameExplicit": false, "name": "workspace_pk", "table": "workspace", "entityType": "pks" }, { - "columns": ["name"], + "columns": [ + "name" + ], "nameExplicit": false, "name": "data_migration_pk", "table": "data_migration", "entityType": "pks" }, { - "columns": ["id"], + "columns": [ + "id" + ], "nameExplicit": false, "name": "account_state_pk", "table": "account_state", "entityType": "pks" }, { - "columns": ["id"], + "columns": [ + "id" + ], "nameExplicit": false, "name": "account_pk", "table": "account", "entityType": "pks" }, { - "columns": ["id"], + "columns": [ + "id" + ], "nameExplicit": false, "name": "credential_pk", "table": "credential", "entityType": "pks" }, { - "columns": ["aggregate_id"], + "columns": [ + "aggregate_id" + ], "nameExplicit": false, "name": "event_sequence_pk", "table": "event_sequence", "entityType": "pks" }, { - "columns": ["id"], + "columns": [ + "id" + ], "nameExplicit": false, "name": "event_pk", "table": "event", "entityType": "pks" }, { - "columns": ["id"], + "columns": [ + "id" + ], "nameExplicit": false, "name": "permission_pk", "table": "permission", "entityType": "pks" }, { - "columns": ["id"], + "columns": [ + "id" + ], "nameExplicit": false, "name": "project_pk", "table": "project", "entityType": "pks" }, { - "columns": ["session_id"], + "columns": [ + "hash" + ], "nameExplicit": false, - "name": "instruction_checkpoint_pk", - "table": "instruction_checkpoint", + "name": "instruction_blob_pk", + "table": "instruction_blob", "entityType": "pks" }, { - "columns": ["id"], + "columns": [ + "session_id" + ], + "nameExplicit": false, + "name": "instruction_state_pk", + "table": "instruction_state", + "entityType": "pks" + }, + { + "columns": [ + "id" + ], "nameExplicit": false, "name": "message_pk", "table": "message", "entityType": "pks" }, { - "columns": ["id"], + "columns": [ + "id" + ], "nameExplicit": false, "name": "part_pk", "table": "part", "entityType": "pks" }, { - "columns": ["id"], - "nameExplicit": false, - "name": "session_input_pk", - "table": "session_input", - "entityType": "pks" - }, - { - "columns": ["id"], + "columns": [ + "id" + ], "nameExplicit": false, "name": "session_message_pk", "table": "session_message", "entityType": "pks" }, { - "columns": ["id"], + "columns": [ + "id" + ], + "nameExplicit": false, + "name": "session_input_pk", + "table": "session_pending", + "entityType": "pks" + }, + { + "columns": [ + "id" + ], "nameExplicit": false, "name": "session_pk", "table": "session", "entityType": "pks" }, { - "columns": ["session_id"], + "columns": [ + "session_id" + ], "nameExplicit": false, "name": "session_share_pk", "table": "session_share", @@ -1902,82 +2050,6 @@ "entityType": "indexes", "table": "part" }, - { - "columns": [ - { - "value": "session_id", - "isExpression": false - }, - { - "value": "promoted_seq", - "isExpression": false - }, - { - "value": "delivery", - "isExpression": false - }, - { - "value": "admitted_seq", - "isExpression": false - } - ], - "isUnique": false, - "where": null, - "origin": "manual", - "name": "session_input_session_pending_delivery_seq_idx", - "entityType": "indexes", - "table": "session_input" - }, - { - "columns": [ - { - "value": "session_id", - "isExpression": false - } - ], - "isUnique": true, - "where": "\"session_input\".\"type\" = 'compaction' and \"session_input\".\"promoted_seq\" is null", - "origin": "manual", - "name": "session_input_session_pending_compaction_idx", - "entityType": "indexes", - "table": "session_input" - }, - { - "columns": [ - { - "value": "session_id", - "isExpression": false - }, - { - "value": "admitted_seq", - "isExpression": false - } - ], - "isUnique": true, - "where": null, - "origin": "manual", - "name": "session_input_session_admitted_seq_idx", - "entityType": "indexes", - "table": "session_input" - }, - { - "columns": [ - { - "value": "session_id", - "isExpression": false - }, - { - "value": "promoted_seq", - "isExpression": false - } - ], - "isUnique": true, - "where": null, - "origin": "manual", - "name": "session_input_session_promoted_seq_idx", - "entityType": "indexes", - "table": "session_input" - }, { "columns": [ { @@ -2054,6 +2126,60 @@ "entityType": "indexes", "table": "session_message" }, + { + "columns": [ + { + "value": "session_id", + "isExpression": false + }, + { + "value": "delivery", + "isExpression": false + }, + { + "value": "admitted_seq", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "session_pending_session_delivery_seq_idx", + "entityType": "indexes", + "table": "session_pending" + }, + { + "columns": [ + { + "value": "session_id", + "isExpression": false + } + ], + "isUnique": true, + "where": "\"session_pending\".\"type\" = 'compaction'", + "origin": "manual", + "name": "session_pending_session_compaction_idx", + "entityType": "indexes", + "table": "session_pending" + }, + { + "columns": [ + { + "value": "session_id", + "isExpression": false + }, + { + "value": "admitted_seq", + "isExpression": false + } + ], + "isUnique": true, + "where": null, + "origin": "manual", + "name": "session_pending_session_admitted_seq_idx", + "entityType": "indexes", + "table": "session_pending" + }, { "columns": [ { @@ -2112,4 +2238,4 @@ } ], "renames": [] -} +} \ No newline at end of file diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 4533f9b378..e12f7848d6 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -119,6 +119,11 @@ export class Directory extends Schema.Class("Config.Directory")({ path: AbsolutePath, }) {} +export class File extends Schema.Class("Config.File")({ + type: Schema.Literal("file"), + path: AbsolutePath, +}) {} + export class AgentsDirectory extends Schema.Class("Config.AgentsDirectory")({ type: Schema.Literal("agents"), path: AbsolutePath, @@ -129,7 +134,7 @@ export class ClaudeDirectory extends Schema.Class("Config.Claud path: AbsolutePath, }) {} -export type Entry = Document | Directory | AgentsDirectory | ClaudeDirectory +export type Entry = Document | Directory | File | AgentsDirectory | ClaudeDirectory export function latest(entries: readonly Entry[], key: K): Info[K] | undefined { return entries @@ -138,7 +143,7 @@ export function latest(entries: readonly Entry[], key: K): } export interface Interface { - /** Returns location config documents and supplemental directories from lowest to highest priority. */ + /** Returns location config documents and discovery sources from lowest to highest priority. */ readonly entries: () => Effect.Effect } @@ -227,31 +232,36 @@ const layer = Layer.effect( const directPaths = discovered .filter((item) => ![".agents", ".claude", ".opencode"].includes(path.basename(item))) .toReversed() - const direct = yield* Effect.forEach(directPaths, loadFile).pipe( + const direct = yield* Effect.forEach(directPaths, (filepath) => + loadFile(filepath).pipe( + Effect.map((config) => [ + ...(config ? [config] : []), + new File({ type: "file", path: AbsolutePath.make(filepath) }), + ]), + ), + ).pipe( Effect.orDie, - Effect.map((configs) => configs.filter((config): config is Document => config !== undefined)), + Effect.map((entries) => entries.flat()), ) const supplementary = yield* Effect.forEach(directories, loadDirectory).pipe(Effect.orDie) - return { - entries: [...claude, ...agents, ...(supplementary[0] ?? []), ...direct, ...supplementary.slice(1).flat()], - directories: [...directories, ...claude.map((entry) => entry.path), ...agents.map((entry) => entry.path)], - files: directPaths, - } + return [...claude, ...agents, ...(supplementary[0] ?? []), ...direct, ...supplementary.slice(1).flat()] }) const initial = yield* discover() - let configs = initial.entries + let configs = initial const updates = yield* PubSub.unbounded() const subscriptions = new Map>() - const targets = (snapshot: typeof initial) => [ - ...snapshot.directories.map((path) => ({ path, type: "directory" as const })), - ...snapshot.files - .filter((file) => !snapshot.directories.some((directory) => FSUtil.contains(directory, file))) - .map((path) => ({ path, type: "file" as const })), - ] - const reconcile = Effect.fn("Config.reconcileWatches")(function* (snapshot: typeof initial) { - const next = new Map(targets(snapshot).map((target) => [JSON.stringify(target), target])) + const reconcile = Effect.fn("Config.reconcileWatches")(function* (entries: readonly Entry[]) { + const directories = entries.flatMap((entry) => (entry.type === "directory" ? [entry.path] : [])) + const files = entries.flatMap((entry) => (entry.type === "file" ? [entry.path] : [])) + const targets = [ + ...directories.map((path) => ({ path, type: "directory" as const })), + ...files + .filter((file) => !directories.some((directory) => FSUtil.contains(directory, file))) + .map((path) => ({ path, type: "file" as const })), + ] + const next = new Map(targets.map((target) => [JSON.stringify(target), target])) for (const [key, stop] of subscriptions) { if (next.has(key)) continue yield* stop @@ -272,7 +282,7 @@ const layer = Layer.effect( Stream.runForEach((update) => Effect.gen(function* () { const next = yield* discover() - configs = next.entries + configs = next yield* reconcile(next) yield* events.publish(ConfigSchema.Event.Updated, {}) }).pipe(Effect.catchCause((cause) => Effect.logError("failed to reload config", { path: update.path, cause }))), diff --git a/packages/core/src/control-plane/move-session.ts b/packages/core/src/control-plane/move-session.ts index 6f0c6e3081..84d135d3f9 100644 --- a/packages/core/src/control-plane/move-session.ts +++ b/packages/core/src/control-plane/move-session.ts @@ -8,6 +8,7 @@ import { Location } from "../location" import { ProjectV2 } from "../project" import { SessionV2 } from "../session" import { SessionEvent } from "../session/event" +import { SessionExecution } from "../session/execution" import { SessionSchema } from "../session/schema" import { SessionStore } from "../session/store" import { AbsolutePath, RelativePath } from "../schema" @@ -73,6 +74,7 @@ const layer = Layer.effect( const events = yield* EventV2.Service const project = yield* ProjectV2.Service const sessions = yield* SessionStore.Service + const execution = yield* SessionExecution.Service const moveSession = Effect.fn("MoveSession.moveSession")(function* (input: Input) { const current = yield* sessions.get(input.sessionID) @@ -86,6 +88,12 @@ const layer = Layer.effect( return yield* new DestinationProjectMismatchError({ expected: current.projectID, actual: destination.id }) } + // A move must not race active execution: a mid-drain relocation would let + // the source Location dispatch a request assembled under stale instructions + // and history. Serialize like removal does — stop the drain, then move. + yield* execution.interrupt(input.sessionID) + yield* execution.awaitIdle(input.sessionID) + const moveChanges = input.moveChanges && source.directory !== destination.directory const sourceRepository = moveChanges ? yield* git.repo.discover(current.location.directory) : undefined if (moveChanges && !sourceRepository) @@ -143,5 +151,5 @@ const layer = Layer.effect( export const node = makeGlobalNode({ service: Service, layer, - deps: [Git.node, EventV2.node, ProjectV2.node, SessionStore.node], + deps: [Git.node, EventV2.node, ProjectV2.node, SessionStore.node, SessionExecution.node], }) diff --git a/packages/core/src/database/database.ts b/packages/core/src/database/database.ts index f3cc8b3f9f..e6c36d75b8 100644 --- a/packages/core/src/database/database.ts +++ b/packages/core/src/database/database.ts @@ -54,4 +54,10 @@ export function path() { return join(Global.Path.data, `opencode-${InstallationChannel.replace(/[^a-zA-Z0-9._-]/g, "-")}.db`) } -export const node = makeGlobalNode({ service: Service, layer: layerFromPath(path()), deps: [] }) +// Resolve the database path lazily so tests and embedders that set +// Flag.OPENCODE_DB after module evaluation still control the storage target. +export const node = makeGlobalNode({ + service: Service, + layer: Layer.suspend(() => layerFromPath(path())), + deps: [], +}) diff --git a/packages/core/src/database/migration.gen.ts b/packages/core/src/database/migration.gen.ts index 9f5c5b40a3..2039393030 100644 --- a/packages/core/src/database/migration.gen.ts +++ b/packages/core/src/database/migration.gen.ts @@ -52,5 +52,7 @@ export const migrations = ( import("./migration/20260709013000_generic_session_input"), import("./migration/20260709025533_drop-todo"), import("./migration/20260709163752_time_suspended"), + import("./migration/20260709190621_session_pending_table"), + import("./migration/20260710025429_instruction_sync"), ]) ).map((module) => module.default) satisfies DatabaseMigration.Migration[] diff --git a/packages/core/src/database/migration/20260709190621_session_pending_table.ts b/packages/core/src/database/migration/20260709190621_session_pending_table.ts new file mode 100644 index 0000000000..1fc97a2257 --- /dev/null +++ b/packages/core/src/database/migration/20260709190621_session_pending_table.ts @@ -0,0 +1,35 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260709190621_session_pending_table", + up(tx) { + return Effect.gen(function* () { + // Beta reset: session_input becomes the pending-only session_pending + // table. Dropping the old table discards consumed ledger rows and any + // in-flight pending work along with every historical index variant. + yield* tx.run(`DROP TABLE \`session_input\`;`) + yield* tx.run(` + CREATE TABLE \`session_pending\` ( + \`id\` text PRIMARY KEY, + \`session_id\` text NOT NULL, + \`type\` text NOT NULL, + \`data\` text NOT NULL, + \`delivery\` text, + \`admitted_seq\` integer NOT NULL, + \`time_created\` integer NOT NULL, + CONSTRAINT \`fk_session_pending_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE + ); + `) + yield* tx.run( + `CREATE INDEX \`session_pending_session_delivery_seq_idx\` ON \`session_pending\` (\`session_id\`,\`delivery\`,\`admitted_seq\`);`, + ) + yield* tx.run( + `CREATE UNIQUE INDEX \`session_pending_session_compaction_idx\` ON \`session_pending\` (\`session_id\`) WHERE "session_pending"."type" = 'compaction';`, + ) + yield* tx.run( + `CREATE UNIQUE INDEX \`session_pending_session_admitted_seq_idx\` ON \`session_pending\` (\`session_id\`,\`admitted_seq\`);`, + ) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260710025429_instruction_sync.ts b/packages/core/src/database/migration/20260710025429_instruction_sync.ts new file mode 100644 index 0000000000..6239fd9bce --- /dev/null +++ b/packages/core/src/database/migration/20260710025429_instruction_sync.ts @@ -0,0 +1,86 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260710025429_instruction_sync", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`ALTER TABLE \`session\` ADD \`fork_seq\` integer;`) + yield* tx.run(`PRAGMA foreign_keys=OFF;`) + yield* tx.run(` + CREATE TABLE \`__new_instruction_entry\` ( + \`session_id\` text NOT NULL, + \`key\` text NOT NULL, + \`value\` text, + \`removed\` integer DEFAULT false NOT NULL, + \`time_created\` integer NOT NULL, + \`time_updated\` integer NOT NULL, + CONSTRAINT \`instruction_entry_pk\` PRIMARY KEY(\`session_id\`, \`key\`), + CONSTRAINT \`fk_instruction_entry_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE + ); + `) + yield* tx.run(` + INSERT INTO \`__new_instruction_entry\`( + \`session_id\`, \`key\`, \`value\`, \`removed\`, \`time_created\`, \`time_updated\` + ) + SELECT \`session_id\`, \`key\`, \`value\`, false, \`time_created\`, \`time_updated\` + FROM \`instruction_entry\`; + `) + yield* tx.run(`DROP TABLE \`instruction_entry\`;`) + yield* tx.run(`ALTER TABLE \`__new_instruction_entry\` RENAME TO \`instruction_entry\`;`) + yield* tx.run(`PRAGMA foreign_keys=ON;`) + yield* tx.run(` + CREATE TABLE \`instruction_blob\` ( + \`hash\` text PRIMARY KEY, + \`value\` text + ); + `) + yield* tx.run(` + CREATE TABLE \`instruction_state\` ( + \`session_id\` text PRIMARY KEY, + \`epoch_start\` integer NOT NULL, + \`through_seq\` integer NOT NULL, + \`initial_values\` text NOT NULL, + \`current_values\` text NOT NULL, + CONSTRAINT \`fk_instruction_state_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE + ); + `) + // Persisted System rows were exclusively pre-beta instruction prose, + // including fork copies whose message IDs no longer match the source event. + yield* tx.run(`DELETE FROM \`session_message\` WHERE \`type\` = 'system';`) + yield* tx.run(` + UPDATE \`session\` + SET \`fork_seq\` = COALESCE( + ( + SELECT MIN(\`seq\`) - 1 + FROM \`event\` + WHERE \`aggregate_id\` = \`session\`.\`id\` AND \`seq\` > 0 + ), + ( + SELECT \`seq\` + FROM \`event_sequence\` + WHERE \`aggregate_id\` = \`session\`.\`id\` + ), + 0 + ) + WHERE \`fork_session_id\` IS NOT NULL; + `) + yield* tx.run(` + UPDATE \`event\` + SET + \`type\` = 'session.forked.2', + \`data\` = json_set( + \`data\`, + '$.parentSeq', + COALESCE( + (SELECT \`fork_seq\` FROM \`session\` WHERE \`id\` = \`event\`.\`aggregate_id\`), + 0 + ) + ) + WHERE \`type\` = 'session.forked.1'; + `) + yield* tx.run(`DELETE FROM \`event\` WHERE \`type\` = 'session.instructions.updated.1';`) + yield* tx.run(`DROP TABLE \`instruction_checkpoint\`;`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/schema.gen.ts b/packages/core/src/database/schema.gen.ts index 27651d0c13..7d9fc7937b 100644 --- a/packages/core/src/database/schema.gen.ts +++ b/packages/core/src/database/schema.gen.ts @@ -126,25 +126,33 @@ export default { ); `) yield* tx.run(` - CREATE TABLE \`instruction_checkpoint\` ( - \`session_id\` text PRIMARY KEY, - \`baseline\` text NOT NULL, - \`snapshot\` text NOT NULL, - \`baseline_seq\` integer NOT NULL, - CONSTRAINT \`fk_instruction_checkpoint_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE + CREATE TABLE \`instruction_blob\` ( + \`hash\` text PRIMARY KEY, + \`value\` text ); `) yield* tx.run(` CREATE TABLE \`instruction_entry\` ( \`session_id\` text NOT NULL, \`key\` text NOT NULL, - \`value\` text NOT NULL, + \`value\` text, + \`removed\` integer DEFAULT false NOT NULL, \`time_created\` integer NOT NULL, \`time_updated\` integer NOT NULL, CONSTRAINT \`instruction_entry_pk\` PRIMARY KEY(\`session_id\`, \`key\`), CONSTRAINT \`fk_instruction_entry_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE ); `) + yield* tx.run(` + CREATE TABLE \`instruction_state\` ( + \`session_id\` text PRIMARY KEY, + \`epoch_start\` integer NOT NULL, + \`through_seq\` integer NOT NULL, + \`initial_values\` text NOT NULL, + \`current_values\` text NOT NULL, + CONSTRAINT \`fk_instruction_state_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE + ); + `) yield* tx.run(` CREATE TABLE \`message\` ( \`id\` text PRIMARY KEY, @@ -166,19 +174,6 @@ export default { CONSTRAINT \`fk_part_message_id_message_id_fk\` FOREIGN KEY (\`message_id\`) REFERENCES \`message\`(\`id\`) ON DELETE CASCADE ); `) - yield* tx.run(` - CREATE TABLE \`session_input\` ( - \`id\` text PRIMARY KEY, - \`session_id\` text NOT NULL, - \`type\` text NOT NULL, - \`data\` text NOT NULL, - \`delivery\` text, - \`admitted_seq\` integer NOT NULL, - \`promoted_seq\` integer, - \`time_created\` integer NOT NULL, - CONSTRAINT \`fk_session_input_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE - ); - `) yield* tx.run(` CREATE TABLE \`session_message\` ( \`id\` text PRIMARY KEY, @@ -191,6 +186,18 @@ export default { CONSTRAINT \`fk_session_message_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE ); `) + yield* tx.run(` + CREATE TABLE \`session_pending\` ( + \`id\` text PRIMARY KEY, + \`session_id\` text NOT NULL, + \`type\` text NOT NULL, + \`data\` text NOT NULL, + \`delivery\` text, + \`admitted_seq\` integer NOT NULL, + \`time_created\` integer NOT NULL, + CONSTRAINT \`fk_session_pending_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE + ); + `) yield* tx.run(` CREATE TABLE \`session\` ( \`id\` text PRIMARY KEY, @@ -199,6 +206,7 @@ export default { \`parent_id\` text, \`fork_session_id\` text, \`fork_message_id\` text, + \`fork_seq\` integer, \`slug\` text NOT NULL, \`directory\` text NOT NULL, \`path\` text, @@ -249,18 +257,6 @@ export default { ) yield* tx.run(`CREATE INDEX \`part_message_id_id_idx\` ON \`part\` (\`message_id\`,\`id\`);`) yield* tx.run(`CREATE INDEX \`part_session_idx\` ON \`part\` (\`session_id\`);`) - yield* tx.run( - `CREATE INDEX \`session_input_session_pending_delivery_seq_idx\` ON \`session_input\` (\`session_id\`,\`promoted_seq\`,\`delivery\`,\`admitted_seq\`);`, - ) - yield* tx.run( - `CREATE UNIQUE INDEX \`session_input_session_pending_compaction_idx\` ON \`session_input\` (\`session_id\`) WHERE "session_input"."type" = 'compaction' and "session_input"."promoted_seq" is null;`, - ) - yield* tx.run( - `CREATE UNIQUE INDEX \`session_input_session_admitted_seq_idx\` ON \`session_input\` (\`session_id\`,\`admitted_seq\`);`, - ) - yield* tx.run( - `CREATE UNIQUE INDEX \`session_input_session_promoted_seq_idx\` ON \`session_input\` (\`session_id\`,\`promoted_seq\`);`, - ) yield* tx.run( `CREATE UNIQUE INDEX \`session_message_session_seq_idx\` ON \`session_message\` (\`session_id\`,\`seq\`);`, ) @@ -271,6 +267,15 @@ export default { `CREATE INDEX \`session_message_session_time_created_id_idx\` ON \`session_message\` (\`session_id\`,\`time_created\`,\`id\`);`, ) yield* tx.run(`CREATE INDEX \`session_message_time_created_idx\` ON \`session_message\` (\`time_created\`);`) + yield* tx.run( + `CREATE INDEX \`session_pending_session_delivery_seq_idx\` ON \`session_pending\` (\`session_id\`,\`delivery\`,\`admitted_seq\`);`, + ) + yield* tx.run( + `CREATE UNIQUE INDEX \`session_pending_session_compaction_idx\` ON \`session_pending\` (\`session_id\`) WHERE "session_pending"."type" = 'compaction';`, + ) + yield* tx.run( + `CREATE UNIQUE INDEX \`session_pending_session_admitted_seq_idx\` ON \`session_pending\` (\`session_id\`,\`admitted_seq\`);`, + ) yield* tx.run(`CREATE INDEX \`session_project_idx\` ON \`session\` (\`project_id\`);`) yield* tx.run(`CREATE INDEX \`session_workspace_idx\` ON \`session\` (\`workspace_id\`);`) yield* tx.run(`CREATE INDEX \`session_parent_idx\` ON \`session\` (\`parent_id\`);`) diff --git a/packages/core/src/event.ts b/packages/core/src/event.ts index 8641c92859..886d76a0f1 100644 --- a/packages/core/src/event.ts +++ b/packages/core/src/event.ts @@ -137,7 +137,8 @@ export interface Interface { ) => Effect.Effect> readonly subscribe: Subscribe /** - * Durable, ordered, gap-free per-aggregate log read. `follow: false` + * Durable, ordered per-aggregate log read. Forked aggregates may reserve an + * inherited prefix before their first child-authored event. `follow: false` * completes at the end of the log; `follow: true` replays then transitions * to live. Both modes emit one `Synced` marker at the captured replay * watermark. @@ -203,7 +204,6 @@ export const layerWith = (options?: LayerOptions) => typed: new Map>(), } const projectors = new Map() - // TODO: Bind durable projectors to exact type+version before supporting incompatible historical payloads. const listeners = new Array() const { db } = yield* Database.Service const logReadPageSize = options?.logReadPageSize ?? 512 @@ -260,7 +260,7 @@ export const layerWith = (options?: LayerOptions) => }), ) } - const list = projectors.get(event.type) ?? [] + const list = projectors.get(versionedType(definition.type, durable.version)) ?? [] return yield* Effect.uninterruptible( Effect.gen(function* () { const committed = yield* db @@ -515,18 +515,6 @@ export const layerWith = (options?: LayerOptions) => }), ) } - const start = events[0]?.seq ?? 0 - for (const [index, event] of events.entries()) { - const seq = start + index - if (event.seq !== seq) { - yield* Effect.die( - new InvalidDurableEventError({ - type: event.type, - message: `Replay sequence mismatch at index ${index}: expected ${seq}, got ${event.seq}`, - }), - ) - } - } for (const event of events) { yield* replay(event, options) } @@ -727,9 +715,10 @@ export const layerWith = (options?: LayerOptions) => const project = (definition: D, projector: Subscriber): Effect.Effect => Effect.sync(() => { - const list = projectors.get(definition.type) ?? [] + const key = definition.durable ? versionedType(definition.type, definition.durable.version) : definition.type + const list = projectors.get(key) ?? [] list.push((event) => projector(event as Payload)) - projectors.set(definition.type, list) + projectors.set(key, list) }) return Service.of({ diff --git a/packages/core/src/form.ts b/packages/core/src/form.ts index 7cdda87b4c..30ae70e16c 100644 --- a/packages/core/src/form.ts +++ b/packages/core/src/form.ts @@ -16,6 +16,9 @@ export type Info = typeof Info.Type export const Field = Form.Field export type Field = Form.Field +export const Fields = Form.Fields +export type Fields = Form.Fields + export const When = Form.When export type When = Form.When @@ -64,9 +67,7 @@ export class InvalidFormError extends Schema.TaggedErrorClass( message: Schema.String, }) {} -export type CreateInput = - | (Omit & { readonly id?: ID }) - | (Omit & { readonly id?: ID }) +export type CreateInput = Omit & { readonly id?: ID } export interface ReplyInput { readonly id: ID @@ -74,7 +75,7 @@ export interface ReplyInput { } export interface ListInput { - readonly sessionID?: Form.FormInfo["sessionID"] + readonly sessionID?: Form.Info["sessionID"] } export interface Interface { @@ -125,20 +126,15 @@ export const layer = Layer.effect( const id = input.id ?? ID.create() const existing = yield* Cache.getSuccess(forms, id) if (Option.isSome(existing)) return yield* new AlreadyExistsError({ id }) - if (input.mode === "form") { - const invalid = validateFields(input.fields) - if (invalid) return yield* new InvalidFormError({ message: invalid }) - } - const base = { + const invalid = validateFields(input.fields) + if (invalid) return yield* new InvalidFormError({ message: invalid }) + const form: Info = { id, sessionID: input.sessionID, title: input.title, ...(input.metadata === undefined ? {} : { metadata: input.metadata }), + fields: input.fields, } - const form: Info = - input.mode === "form" - ? { ...base, mode: "form", fields: input.fields } - : { ...base, mode: "url", url: input.url } const entry: Entry = { form, state: { status: "pending" }, @@ -228,16 +224,16 @@ export const locationLayer = layer export const node = makeLocationNode({ service: Service, layer, deps: [EventV2.node] }) function validateAnswer(form: Info, answer: Answer) { - if (form.mode === "url") { - if (Object.keys(answer).length === 0) return - return "URL forms must be answered with an empty answer" - } - const fields = new Map(form.fields.map((field) => [field.key, field])) + const fields = new Map(form.fields.map((field) => [field.key, field] as const)) for (const key of Object.keys(answer)) { if (!fields.has(key)) return `Unknown form field: ${key}` } for (const field of form.fields) { const value = answer[field.key] + if (field.type === "external") { + if (value !== true) return `External form field must be acknowledged: ${field.key}` + continue + } const active = isActive(field, answer) if (value === undefined) { if (field.required && active) return `Missing required form field: ${field.key}` @@ -249,7 +245,9 @@ function validateAnswer(form: Info, answer: Answer) { } } -function isActive(field: Form.Field, answer: Answer) { +type InputField = Exclude + +function isActive(field: InputField, answer: Answer) { if (!field.when) return true return field.when.every((when) => matches(when, answer[when.key])) } @@ -267,9 +265,13 @@ function matches(when: Form.When, value: Form.Value | undefined) { // are closed. Rejecting these at creation surfaces authoring mistakes to the caller instead of // silently never matching. function validateFields(fields: ReadonlyArray) { - const earlier = new Map() + if (fields.length === 0) return "Form must have at least one field" + const earlier = new Map() + const keys = new Set() for (const field of fields) { - if (earlier.has(field.key)) return `Duplicate form field key: ${field.key}` + if (keys.has(field.key)) return `Duplicate form field key: ${field.key}` + keys.add(field.key) + if (field.type === "external") continue for (const when of field.when ?? []) { const target = earlier.get(when.key) if (!target) return `Form field condition must reference an earlier field: ${field.key} -> ${when.key}` @@ -280,7 +282,7 @@ function validateFields(fields: ReadonlyArray) { } } -function validateWhen(when: Form.When, target: Form.Field) { +function validateWhen(when: Form.When, target: InputField) { if (target.type === "boolean") { if (typeof when.value !== "boolean") return "Form field condition value must be a boolean" return @@ -297,7 +299,7 @@ function validateWhen(when: Form.When, target: Form.Field) { } } -function validateField(field: Form.Field, value: Form.Value): string | undefined { +function validateField(field: InputField, value: Form.Value): string | undefined { if (field.type === "string") { if (typeof value !== "string") return `Expected string for form field: ${field.key}` if (field.required && value.length === 0) return `Missing required form field: ${field.key}` diff --git a/packages/core/src/instruction-discovery.ts b/packages/core/src/instruction-discovery.ts index 0ac7b8a12d..f838083b40 100644 --- a/packages/core/src/instruction-discovery.ts +++ b/packages/core/src/instruction-discovery.ts @@ -31,15 +31,17 @@ const layer = Layer.effect( const global = yield* Global.Service const location = yield* Location.Service - const source = (value: ReadonlyArray | Instructions.Unavailable) => - Instructions.make({ + const source = (value: ReadonlyArray | Instructions.Unavailable | Instructions.Removed) => + Instructions.make>({ key, codec: Schema.toCodecJson(Files), - load: Effect.succeed(value), - baseline: render, - update: (_previous, current) => - `These instructions replace all previously loaded ambient instructions.\n\n${render(current)}`, - removed: () => "Previously loaded instructions no longer apply.", + read: Effect.succeed(value), + render: { + initial: render, + changed: (_previous, current) => + `These instructions replace all previously loaded ambient instructions.\n\n${render(current)}`, + removed: () => "Previously loaded instructions no longer apply.", + }, }) const observe = Effect.fn("InstructionDiscovery.observe")(function* () { @@ -82,11 +84,7 @@ const layer = Layer.effect( load: () => observe().pipe( Effect.map((files) => - files === Instructions.unavailable - ? source(files) - : files.length === 0 - ? Instructions.empty - : source(files), + Array.isArray(files) && files.length === 0 ? source(Instructions.removed) : source(files), ), Effect.catch(() => Effect.succeed(source(Instructions.unavailable))), Effect.catchDefect(() => Effect.succeed(source(Instructions.unavailable))), diff --git a/packages/core/src/instructions/builtins.ts b/packages/core/src/instructions/builtins.ts index 0414cc98c1..b116971834 100644 --- a/packages/core/src/instructions/builtins.ts +++ b/packages/core/src/instructions/builtins.ts @@ -15,29 +15,34 @@ const layer = Layer.effect( Service, Effect.gen(function* () { const location = yield* Location.Service - const environment = [ - "", - ` Working directory: ${location.directory}`, - ` Workspace root folder: ${location.project.directory}`, - ` Is directory a git repo: ${location.vcs?.type === "git" ? "yes" : "no"}`, - ` Platform: ${process.platform}`, - "", - ].join("\n") const instructions = Instructions.combine([ Instructions.make({ key: Instructions.Key.make("core/environment"), codec: Schema.toCodecJson(Schema.String), - load: Effect.succeed(environment), - baseline: (environment) => - ["Here is some useful information about the environment you are running in:", environment].join("\n"), - update: (_previous, environment) => ["The environment you are running in is now:", environment].join("\n"), + read: Effect.sync(() => + [ + "", + ` Working directory: ${location.directory}`, + ` Workspace root folder: ${location.project.directory}`, + ` Is directory a git repo: ${location.vcs?.type === "git" ? "yes" : "no"}`, + ` Platform: ${process.platform}`, + "", + ].join("\n"), + ), + render: { + initial: (environment) => + ["Here is some useful information about the environment you are running in:", environment].join("\n"), + changed: (_previous, environment) => ["The environment you are running in is now:", environment].join("\n"), + }, }), Instructions.make({ key: Instructions.Key.make("core/date"), codec: Schema.toCodecJson(Schema.String), - load: DateTime.nowAsDate.pipe(Effect.map((date) => date.toDateString())), - baseline: (date) => `Today's date: ${date}`, - update: (_previous, date) => `Today's date is now: ${date}`, + read: DateTime.nowAsDate.pipe(Effect.map((date) => date.toDateString())), + render: { + initial: (date) => `Today's date: ${date}`, + changed: (_previous, date) => `Today's date is now: ${date}`, + }, }), ]) diff --git a/packages/core/src/instructions/index.ts b/packages/core/src/instructions/index.ts index 7fe86cfa16..d7af2a78a3 100644 --- a/packages/core/src/instructions/index.ts +++ b/packages/core/src/instructions/index.ts @@ -1,80 +1,70 @@ export * as Instructions from "./index" -import { Effect, Option, Schema } from "effect" +import { createHash } from "crypto" +import { Instruction } from "@opencode-ai/schema/instruction" +import { Data, Effect, Option, Schema } from "effect" -/** - * Models privileged instructions as independently refreshable typed sources. - * - * `Source` describes how to observe, compare, and render one value. `make` - * closes over `A`, producing opaque `Instructions` that compose uniformly with - * instructions built from other value types. - * - * The durable `Applied` record tracks what the model was last told, per source: - * it is the model's current belief. Interpreters uphold one invariant — - * `reconcile` never rewrites the baseline; it only narrates drift as update - * text. Only `rebaseline` (compaction) and `initialize` (first step) produce - * baseline text. - * - * Returning `unavailable` means observation failed temporarily. It differs from - * removing a source from the instructions: the model's prior belief stands. - * `reconcile` retains the applied value silently, and `rebaseline` restates the - * belief by rendering the last-applied value instead of a live observation. - * - * @module - */ +export const Key = Instruction.Key +export type Key = Instruction.Key +export const Hash = Instruction.Hash +export type Hash = Instruction.Hash +export const Values = Instruction.Values +export type Values = Instruction.Values +export const Delta = Instruction.Delta +export type Delta = Instruction.Delta -/** Stable namespaced identity for one independently refreshable instruction source. */ -export const Key = Schema.String.check(Schema.isPattern(/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._/-]*$/)).pipe( - Schema.brand("Instructions.Key"), -) -export type Key = typeof Key.Type +type NonValue = Data.TaggedEnum<{ Unavailable: {}; Removed: {} }> +const NonValue = Data.taggedEnum() -/** Indicates that a source could not be observed without treating it as removed. */ -export const unavailable = Symbol.for("@opencode/Instructions.Unavailable") +/** The read failed temporarily; the stored value stands. */ +export const unavailable = NonValue.Unavailable() export type Unavailable = typeof unavailable -/** Defines one typed source before its value type is hidden by `make`. */ -export interface Source { +/** An observed absence: the source exists but its value is gone. */ +export const removed = NonValue.Removed() +export type Removed = typeof removed + +/** + * One composable instruction source over canonical JSON — the same + * representation that is hashed, stored, and replayed. `make` builds one from + * a typed definition; renderers returning `undefined` skip (undecodable or + * unrenderable historical values). + */ +export interface Source { readonly key: Key - readonly codec: Schema.Codec - readonly load: Effect.Effect - readonly baseline: (current: A) => string - readonly update: (previous: A, current: A) => string - readonly removed?: (previous: A) => string + readonly read: Effect.Effect + readonly initial: (value: Schema.Json) => string | undefined + readonly changed: (previous: Schema.Json, current: Schema.Json) => string | undefined + readonly removed: (previous: Schema.Json) => string | undefined } -const InstructionsTypeId: unique symbol = Symbol.for("@opencode/Instructions") - -/** Opaque carrier for composable instruction sources. */ -export interface Instructions { - readonly [InstructionsTypeId]: ReadonlyArray +export declare namespace Source { + /** The typed definition supplied when constructing a source. */ + export interface Definition { + readonly key: Key + readonly codec: Schema.Codec + readonly read: Effect.Effect + readonly render: { + readonly initial: (current: A) => string + readonly changed: (previous: A, current: A) => string + readonly removed?: (previous: A) => string + } + } } -/** The value last applied to the model for one admitted source. */ -export const AppliedSource = Schema.Struct({ - value: Schema.Json, - removed: Schema.optional(Schema.NonEmptyString), -}) -export type AppliedSource = typeof AppliedSource.Type +/** Ordered sources; identical values render identical bytes. */ +export type Instructions = ReadonlyArray -/** Durable record of what the model currently believes, per source. */ -export const Applied = Schema.Record(Key, AppliedSource) -export type Applied = Readonly> +export type ReadResult = ReadonlyArray<{ + readonly key: Key + readonly value: Schema.Json | Unavailable | Removed +}> -/** A rendered baseline together with the applied values it was rendered from. */ -export interface Baseline { - readonly text: string - readonly applied: Applied +export interface Admission { + readonly delta: Delta + readonly blobs: Readonly> } -export interface Updated { - readonly _tag: "Updated" - readonly text: string - readonly applied: Applied -} - -export type ReconcileResult = { readonly _tag: "Unchanged" } | Updated - export class InitializationBlocked extends Schema.TaggedErrorClass()( "Instructions.InitializationBlocked", { keys: Schema.Array(Key) }, @@ -92,71 +82,140 @@ export class DuplicateKeyError extends Schema.TaggedErrorClass - /** Restates the model's belief from a last-applied value when the source cannot be observed. */ - readonly recall: (stored: AppliedSource) => string | undefined -} +export const empty: Instructions = [] -interface Observed { - readonly applied: AppliedSource - readonly baseline: () => string - /** `undefined` means unchanged. An undecodable previous value re-renders the baseline (treat-as-new). */ - readonly update: (previous: AppliedSource) => string | undefined -} - -interface Entry { - readonly key: Key - readonly recall: PackedSource["recall"] - readonly observed: Observed | Unavailable -} - -/** The identity instruction set. */ -export const empty = instructions([]) - -/** Closes a typed source into instructions that compose with differently typed sources. */ -export function make(source: Source): Instructions { +/** Closes a typed definition into one `Source`, so differently typed sources compose. */ +export function make(source: Source.Definition): Instructions { const decode = Schema.decodeUnknownOption(source.codec) const encode = Schema.encodeSync(source.codec) - const equivalent = Schema.toEquivalence(source.codec) - const baseline = (value: A) => requireText(source.key, "baseline", source.baseline(value)) - return instructions([ + const initial = (value: A) => requireText(source.key, "initial", source.render.initial(value)) + const decodeValue = (value: Schema.Json) => Option.getOrUndefined(decode(value)) + return [ { key: source.key, - recall: (stored) => - Option.match(decode(stored.value), { - onNone: () => undefined, - onSome: baseline, - }), - load: source.load.pipe( + read: source.read.pipe( Effect.map((value) => { - if (isUnavailable(value)) return value - return { - applied: { - value: encode(value), - ...(source.removed ? { removed: requireText(source.key, "removal", source.removed(value)) } : {}), - }, - baseline: () => baseline(value), - update: (previous) => - Option.match(decode(previous.value), { - onNone: () => baseline(value), - onSome: (decoded) => - equivalent(decoded, value) - ? undefined - : requireText(source.key, "update", source.update(decoded, value)), - }), - } satisfies Observed + if (isUnavailable(value)) return unavailable + if (isRemoved(value)) return removed + return encode(value) }), ), + initial: (value) => { + const decoded = decodeValue(value) + return decoded === undefined ? undefined : initial(decoded) + }, + changed: (previous, current) => { + const before = decodeValue(previous) + const after = decodeValue(current) + if (after === undefined) return undefined + if (before === undefined) return initial(after) + return requireText(source.key, "changed", source.render.changed(before, after)) + }, + removed: (previous) => { + const decoded = decodeValue(previous) + return decoded === undefined || source.render.removed === undefined + ? undefined + : requireText(source.key, "removed", source.render.removed(decoded)) + }, }, - ]) + ] +} + +export function combine(values: ReadonlyArray): Instructions { + const sources = values.flat() + const keys = new Set() + for (const source of sources) { + if (keys.has(source.key)) throw new DuplicateKeyError({ key: source.key }) + keys.add(source.key) + } + return sources +} + +export function read(value: Instructions): Effect.Effect { + return Effect.forEach( + value, + (source) => source.read.pipe(Effect.map((observed) => ({ key: source.key, value: observed }))), + { concurrency: "unbounded" }, + ) +} + +export function diff(observed: ReadResult, previous?: Values): Effect.Effect { + const blocked = previous ? [] : observed.flatMap((entry) => (isUnavailable(entry.value) ? [entry.key] : [])) + if (blocked.length > 0) return Effect.fail(new InitializationBlocked({ keys: blocked })) + const delta: Record = {} + const blobs: Record = {} + for (const entry of observed) { + if (isUnavailable(entry.value)) continue + if (isRemoved(entry.value)) { + if (previous && Object.hasOwn(previous, entry.key)) delta[entry.key] = Instruction.removed + continue + } + const next = hash(entry.value) + if (previous?.[entry.key] === next) continue + delta[entry.key] = next + blobs[next] = entry.value + } + return Effect.succeed({ delta, blobs }) +} + +export function renderInitial(value: Instructions, values: Readonly>) { + return render( + value.flatMap((source) => { + if (!Object.hasOwn(values, source.key)) return [] + const text = source.initial(values[source.key]) + return text === undefined ? [] : [text] + }), + ) +} + +export function renderUpdate( + value: Instructions, + previous: Readonly>, + delta: Readonly>>, +) { + return render( + value.flatMap((source) => { + if (!Object.hasOwn(delta, source.key)) return [] + const current = delta[source.key] + if (Option.isNone(current)) { + if (!Object.hasOwn(previous, source.key)) return [] + const text = source.removed(previous[source.key]) + return text === undefined ? [] : [text] + } + const next = current.value + const text = Object.hasOwn(previous, source.key) + ? source.changed(previous[source.key], next) + : source.initial(next) + return text === undefined ? [] : [text] + }), + ) +} + +export function hash(value: Schema.Json) { + return Hash.make(createHash("sha256").update(canonical(value)).digest("hex")) +} + +export function applyDelta( + values: Readonly>, + delta: Readonly>>, +): Readonly> { + const result: Record = { ...values } + for (const [key, value] of Object.entries(delta)) { + if (Option.isNone(value)) delete result[key] + else result[key] = value.value + } + return result +} + +export function applyHashDelta(values: Values, delta: Delta): Values { + const result: Record = { ...values } + for (const [key, value] of Object.entries(delta)) { + if (value === Instruction.removed) delete result[key] + else result[key] = value + } + return result } -/** - * Keyed three-way diff for list-shaped sources rendering delta updates. - * `changed` compares two values sharing a key; entries equal under it are dropped. - */ export function diffByKey( previous: ReadonlyArray, current: ReadonlyArray, @@ -179,129 +238,31 @@ export function diffByKey( } } -/** Combines instructions in order and rejects duplicate source keys immediately. */ -export function combine(values: ReadonlyArray): Instructions { - const sources = values.flatMap((value) => value[InstructionsTypeId]) - assertUniqueKeys(sources) - return instructions(sources) -} - -const observe = (value: Instructions) => - Effect.forEach( - value[InstructionsTypeId], - (source) => - source.load.pipe(Effect.map((observed): Entry => ({ key: source.key, recall: source.recall, observed }))), - { concurrency: "unbounded" }, - ) - -/** Creates the first baseline. Blocks rather than admit a baseline missing an unobservable source. */ -export function initialize(value: Instructions): Effect.Effect { - return observe(value).pipe( - Effect.flatMap((entries) => { - const blocked = entries.flatMap((entry) => (entry.observed === unavailable ? [entry.key] : [])) - if (blocked.length > 0) return new InitializationBlocked({ keys: blocked }) - const parts: string[] = [] - const applied: Record = {} - for (const entry of entries) { - if (entry.observed === unavailable) continue - parts.push(entry.observed.baseline()) - applied[entry.key] = entry.observed.applied - } - return Effect.succeed({ text: render(parts), applied }) - }), - ) -} - -/** Narrates drift between current source values and the model's beliefs. Never rewrites the baseline. */ -export function reconcile(value: Instructions, previous: Applied): Effect.Effect { - return observe(value).pipe( - Effect.map((entries): ReconcileResult => { - const updates: string[] = [] - const applied: Record = {} - for (const entry of entries) { - const stored = get(previous, entry.key) - if (entry.observed === unavailable) { - // The prior belief stands while the source cannot be observed. - if (stored) applied[entry.key] = stored - continue - } - if (!stored) { - updates.push(entry.observed.baseline()) - applied[entry.key] = entry.observed.applied - continue - } - const text = entry.observed.update(stored) - if (text === undefined) { - applied[entry.key] = stored - continue - } - updates.push(text) - applied[entry.key] = entry.observed.applied - } - const keys = new Set(entries.map((entry) => entry.key)) - for (const key of Object.keys(previous).sort()) { - if (keys.has(key)) continue - const removed = previous[key].removed - // An unannounced removal retains the belief; it clears at the next rebaseline. - if (removed === undefined) applied[key] = previous[key] - else updates.push(removed) - } - if (updates.length === 0) return { _tag: "Unchanged" } - return { _tag: "Updated", text: render(updates), applied } - }), - ) -} - -/** Rebuilds the baseline, restating unobservable sources from the model's last-applied beliefs. */ -export function rebaseline(value: Instructions, previous: Applied): Effect.Effect { - return observe(value).pipe( - Effect.map((entries): Baseline => { - const parts: string[] = [] - const applied: Record = {} - for (const entry of entries) { - if (entry.observed !== unavailable) { - parts.push(entry.observed.baseline()) - applied[entry.key] = entry.observed.applied - continue - } - const stored = get(previous, entry.key) - if (!stored) continue - const text = entry.recall(stored) - // An undecodable belief cannot be restated; the source re-announces when observable again. - if (text === undefined) continue - parts.push(text) - applied[entry.key] = stored - } - return { text: render(parts), applied } - }), - ) -} - -function instructions(sources: ReadonlyArray): Instructions { - return { [InstructionsTypeId]: sources } -} - function render(parts: ReadonlyArray) { return parts.join("\n\n") } -function get(applied: Applied, key: Key) { - return Object.hasOwn(applied, key) ? applied[key] : undefined -} - +// Reference-equality guards: `A` in a typed source may itself be JSON shaped +// like these singletons, so identity, never structure, discriminates. function isUnavailable(value: unknown): value is Unavailable { return value === unavailable } +function isRemoved(value: unknown): value is Removed { + return value === removed +} + +function canonical(value: Schema.Json): string { + if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]` + if (value !== null && typeof value === "object") + return `{${Object.entries(value) + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([key, entry]) => `${JSON.stringify(key)}:${canonical(entry)}`) + .join(",")}}` + return JSON.stringify(value) +} + function requireText(key: Key, kind: string, text: string) { if (text.length === 0) throw new Error(`Instruction source ${key} rendered an empty ${kind}`) return text } - -function assertUniqueKeys(sources: ReadonlyArray) { - const keys = new Set() - for (const source of sources) { - if (keys.has(source.key)) throw new DuplicateKeyError({ key: source.key }) - keys.add(source.key) - } -} diff --git a/packages/core/src/mcp/guidance.ts b/packages/core/src/mcp/guidance.ts index 4f2c13b72c..4be0d412f5 100644 --- a/packages/core/src/mcp/guidance.ts +++ b/packages/core/src/mcp/guidance.ts @@ -70,8 +70,19 @@ export const layer = Layer.effect( load: Effect.fn("McpGuidance.load")(function* (selection) { const agent = selection.info if (!agent) return Instructions.empty + const source = (value: ReadonlyArray | Instructions.Removed) => + Instructions.make>({ + key: Instructions.Key.make("core/mcp-guidance"), + codec: Schema.toCodecJson(Schema.Array(Summary)), + read: Effect.succeed(value), + render: { + initial: render, + changed: update, + removed: () => "MCP server instructions are no longer available.", + }, + }) if (Flag.CODEMODE_ENABLED && PermissionV2.evaluate("execute", "*", agent.permissions).effect === "deny") - return Instructions.empty + return source(Instructions.removed) const [instructions, tools] = yield* Effect.all([mcp.instructions(), mcp.tools()], { concurrency: "unbounded", }) @@ -88,15 +99,8 @@ export const layer = Layer.effect( ) }) .map((item) => ({ server: item.server, instructions: item.instructions })) - if (visible.length === 0) return Instructions.empty - return Instructions.make({ - key: Instructions.Key.make("core/mcp-guidance"), - codec: Schema.toCodecJson(Schema.Array(Summary)), - load: Effect.succeed(visible), - baseline: render, - update, - removed: () => "MCP server instructions are no longer available.", - }) + .toSorted((a, b) => a.server.localeCompare(b.server)) + return source(visible.length === 0 ? Instructions.removed : visible) }), }) }), diff --git a/packages/core/src/mcp/index.ts b/packages/core/src/mcp/index.ts index 7a99c15982..c9d9a83f82 100644 --- a/packages/core/src/mcp/index.ts +++ b/packages/core/src/mcp/index.ts @@ -123,6 +123,7 @@ type ServerEntry = { // MCP elicitations are Location-scoped, not Session-scoped: the server cannot attribute them to a // persisted session row, so their forms are owned by this opaque sentinel session identifier. const GLOBAL_ELICITATION_SESSION_ID = "global" +const URL_ELICITATION_FIELD_KEY = "elicitation" export interface Interface { readonly servers: () => Effect.Effect @@ -311,8 +312,7 @@ export const layer = Layer.effect( elicitationID: input.params.elicitationId, message: input.params.message, }, - mode: "url", - url: input.params.url, + fields: [{ key: URL_ELICITATION_FIELD_KEY, type: "external", url: input.params.url }], }) .pipe( Effect.raceFirst(waitForAbort(input.signal)), @@ -325,15 +325,16 @@ export const layer = Layer.effect( ) } const params = input.params + const [field, ...fields] = Object.entries(params.requestedSchema.properties).map(([key, property]) => + toElicitationField(key, property, params.requestedSchema.required?.includes(key) === true), + ) + if (!field) return { action: "accept", content: {} } return yield* forms .ask({ sessionID: GLOBAL_ELICITATION_SESSION_ID, title: `${input.server} is requesting input`, metadata: { kind: "mcp-elicitation", server: input.server, message: params.message }, - mode: "form", - fields: Object.entries(params.requestedSchema.properties).map(([key, property]) => - toElicitationField(key, property, params.requestedSchema.required?.includes(key) === true), - ), + fields: [field, ...fields], }) .pipe( Effect.raceFirst(waitForAbort(input.signal)), @@ -355,7 +356,7 @@ export const layer = Layer.effect( Effect.gen(function* () { const formID = urlElicitations.get(input.server + "\u0000" + input.elicitationID) if (!formID) return - yield* forms.reply({ id: formID, answer: {} }).pipe(Effect.ignore) + yield* forms.reply({ id: formID, answer: { [URL_ELICITATION_FIELD_KEY]: true } }).pipe(Effect.ignore) }), } satisfies MCPClient.ElicitationHandler diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index 4e0858fd16..610d14e3c3 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -21,7 +21,7 @@ import { ToolHooks } from "./tool/hooks" import { PluginHooks } from "./plugin/hooks" export interface Interface { - readonly activate: (plugins: readonly { readonly plugin: Plugin; readonly version?: string }[]) => Effect.Effect + readonly activate: (plugins: readonly Plugin[]) => Effect.Effect readonly list: () => Effect.Effect } @@ -32,72 +32,72 @@ const layer = Layer.effect( Effect.gen(function* () { const events = yield* EventV2.Service const scope = yield* Scope.make() - const active = new Map() + const active = new Map() const lock = Semaphore.makeUnsafe(1) - let generation: readonly { readonly id: typeof ID.Type; readonly version?: string }[] | undefined = [] let host: Parameters[0] - const activate = Effect.fn("Plugin.activate")(function* ( - plugins: readonly { readonly plugin: Plugin; readonly version?: string }[], - ) { - const definitions = plugins.map((entry) => ({ - ...entry.plugin, - id: ID.make(entry.plugin.id), - ...(entry.version === undefined ? {} : { version: entry.version }), - })) + const load = Effect.fnUntraced(function* (plugin: Plugin) { + const child = yield* Scope.fork(scope) + const inherit = yield* State.inherit() + const loaded = yield* Effect.suspend(() => plugin.effect(host)).pipe( + inherit, + Effect.updateContext((_context: Context.Context) => Context.make(Scope.Scope, child)), + Effect.withSpan("Plugin.load", { attributes: { "plugin.id": plugin.id } }), + Effect.andThen(events.publish(Event.Added, { id: ID.make(plugin.id) })), + Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(child, exit) : Effect.void)), + Effect.exit, + ) + if (Exit.isSuccess(loaded)) return child + yield* Effect.logWarning("failed to load plugin", { + "plugin.id": plugin.id, + cause: loaded.cause, + }) + return undefined + }) + + const activate = Effect.fn("Plugin.activate")(function* (plugins: readonly Plugin[]) { + const definitions = plugins.map((plugin) => ({ ...plugin, id: ID.make(plugin.id) })) const ids = new Set() for (const definition of definitions) { - if (ids.has(definition.id)) return yield* Effect.die(new Error(`Duplicate plugin ID: ${definition.id}`)) + if (ids.has(definition.id)) yield* Effect.die(new Error(`Duplicate plugin ID: ${definition.id}`)) ids.add(definition.id) } yield* lock.withPermit( Effect.gen(function* () { - if ( - generation !== undefined && - generation.length === definitions.length && - generation.every( - (plugin, index) => plugin.id === definitions[index]?.id && plugin.version === definitions[index]?.version, - ) && - definitions.every((definition) => active.has(definition.id)) - ) { - return - } - generation = undefined yield* State.batch( Effect.gen(function* () { - const scopes = Array.from(active.values()).toReversed() - active.clear() - const inherit = yield* State.inherit() - yield* Effect.forEach(scopes, (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore), { - discard: true, - }) - for (const definition of definitions) { - const child = yield* Scope.fork(scope) - const loaded = yield* Effect.suspend(() => definition.effect(host)).pipe( - inherit, - Effect.updateContext((_context: Context.Context) => Context.make(Scope.Scope, child)), - Effect.withSpan("Plugin.load", { attributes: { "plugin.id": definition.id } }), - Effect.andThen(events.publish(Event.Added, { id: definition.id })), - Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(child, exit) : Effect.void)), - Effect.exit, - ) - if (Exit.isFailure(loaded)) { - yield* Effect.logWarning("failed to load plugin", { - "plugin.id": definition.id, - cause: loaded.cause, - }) + const previous = active.get(definition.id) + active.delete(definition.id) + if (previous) yield* Scope.close(previous.scope, Exit.void).pipe(Effect.ignore) + + const loaded = yield* load(definition) + if (loaded) { + active.set(definition.id, { plugin: definition, scope: loaded }) continue } - active.set(definition.id, child) + + if (!previous) continue + const restored = yield* load(previous.plugin) + if (restored) { + active.set(definition.id, { plugin: previous.plugin, scope: restored }) + continue + } + yield* Effect.logError("failed to restore plugin; deactivating", { + "plugin.id": definition.id, + }) } + + const removed = Array.from(active.entries()) + .filter(([id]) => !ids.has(id)) + .toReversed() + removed.forEach(([id]) => active.delete(id)) + yield* Effect.forEach(removed, ([, entry]) => Scope.close(entry.scope, Exit.void).pipe(Effect.ignore), { + discard: true, + }) }), ) - generation = definitions.map((definition) => ({ - id: definition.id, - ...(definition.version === undefined ? {} : { version: definition.version }), - })) yield* events.publish(Event.Updated, {}) }), ) @@ -106,7 +106,6 @@ const layer = Layer.effect( yield* Effect.addFinalizer((exit) => Effect.gen(function* () { active.clear() - generation = [] yield* State.batch(Scope.close(scope, exit)) }), ) diff --git a/packages/core/src/plugin/hooks.ts b/packages/core/src/plugin/hooks.ts index 4ac437d392..0023e62f6c 100644 --- a/packages/core/src/plugin/hooks.ts +++ b/packages/core/src/plugin/hooks.ts @@ -1,7 +1,6 @@ export * as PluginHooks from "./hooks" import type { AISDKHooks } from "@opencode-ai/plugin/v2/effect/aisdk" -import type { SessionHooks } from "@opencode-ai/plugin/v2/effect/session" import type { ToolHooks } from "@opencode-ai/plugin/v2/effect/tool" import { Context, Effect, Layer, Scope } from "effect" import { makeLocationNode } from "../effect/app-node" @@ -9,7 +8,6 @@ import { State } from "../state" export interface Domains { readonly aisdk: AISDKHooks - readonly session: SessionHooks readonly tool: ToolHooks } diff --git a/packages/core/src/plugin/host.ts b/packages/core/src/plugin/host.ts index a109dd02e7..007a53ed70 100644 --- a/packages/core/src/plugin/host.ts +++ b/packages/core/src/plugin/host.ts @@ -367,7 +367,6 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: PluginV2.Int }, }, session: { - hook: (name, callback) => hooks.register("session", name, callback), create: (input) => runtime.session.create({ id: input?.id, diff --git a/packages/core/src/plugin/promise.ts b/packages/core/src/plugin/promise.ts index 8eafe52734..716d69c10d 100644 --- a/packages/core/src/plugin/promise.ts +++ b/packages/core/src/plugin/promise.ts @@ -1,7 +1,9 @@ export * as PluginPromise from "./promise" import { Plugin } from "@opencode-ai/plugin/v2/effect" +import type { AnyTool } from "@opencode-ai/plugin/v2/tool" import { Effect, Scope, Stream } from "effect" +import { Tool } from "../tool/tool" type HostRegistration = { readonly dispose: Effect.Effect } type Registration = { readonly dispose: () => Promise } @@ -108,7 +110,14 @@ export function fromPromise(plugin: PromisePlugin) { reload: () => run(host.skill.reload()), }, tool: { - transform: transform(host.tool), + transform: (callback) => + register( + host.tool.transform((draft) => + callback({ + add: (tool: AnyTool) => draft.add(tool.name, fromPromiseTool(tool), tool.options), + }), + ), + ), hook: (name, callback) => register(host.tool.hook(name, (event) => Effect.promise(() => Promise.resolve(callback(event))))), }, @@ -118,12 +127,24 @@ export function fromPromise(plugin: PromisePlugin) { prompt: (input) => run(host.session.prompt(input)), command: (input) => run(host.session.command(input)), interrupt: (input) => run(host.session.interrupt(input)), - hook: (name, callback) => - register(host.session.hook(name, (event) => Effect.promise(() => Promise.resolve(callback(event))))), }, } - yield* Effect.promise(() => Promise.resolve(plugin.setup(context2))) + const cleanup = yield* Effect.promise(() => Promise.resolve(plugin.setup(context2))) + if (!cleanup) return + yield* Effect.addFinalizer(() => Effect.promise(() => Promise.resolve(cleanup()))) }), }) } + +function fromPromiseTool(tool: AnyTool) { + if ("jsonSchema" in tool) + return Tool.make({ + ...tool, + execute: (input, context) => Effect.promise(() => tool.execute(input, context)), + }) + return Tool.make({ + ...tool, + execute: (input, context) => Effect.promise(() => tool.execute(input, context)), + }) +} diff --git a/packages/core/src/plugin/skill.ts b/packages/core/src/plugin/skill.ts index 9e8726c4e4..0729ac8684 100644 --- a/packages/core/src/plugin/skill.ts +++ b/packages/core/src/plugin/skill.ts @@ -20,7 +20,7 @@ export const OpencodeContent = opencodeContent export const ReportContent = reportContent export const OpencodeDescription = - "Use this skill for any question about OpenCode itself, including how OpenCode works, using or configuring it, troubleshooting it, developing plugins or integrations, using the OpenCode SDK, clients, server, or API, and contributing to the OpenCode codebase. Also use it for OpenCode agents, commands, skills, tools, permissions, MCP servers, providers, models, themes, keybinds, formatters, the CLI, TUI, desktop app, and web app." + "Use this skill for any question about OpenCode itself, including how OpenCode works, using or configuring it, migrating from V1 to V2, troubleshooting it, developing plugins or integrations, using the OpenCode SDK, clients, server, or API, and contributing to the OpenCode codebase. Also use it for OpenCode agents, commands, skills, tools, permissions, MCP servers, providers, models, themes, keybinds, formatters, the CLI, TUI, desktop app, and web app." const REPORT_DESCRIPTION = "Use when the user wants to report an opencode issue or bug. Collect standard diagnostics, add user-specific reproduction context, and publish the issue with GitHub CLI." diff --git a/packages/core/src/plugin/skill/opencode.md b/packages/core/src/plugin/skill/opencode.md index fd58be201e..1d41476ca0 100644 --- a/packages/core/src/plugin/skill/opencode.md +++ b/packages/core/src/plugin/skill/opencode.md @@ -4,17 +4,39 @@ Use this guide as the starting point for work involving OpenCode itself. It covers the core concepts needed to configure and customize OpenCode, extend it with plugins, and build integrations with the OpenCode SDK, clients, and API. -Full documentation is available at . Consult -it when this overview does not contain enough detail for the task. +Full documentation is available at . This overview is +only an index of core concepts. Before answering a question about a topic below, +fetch the URL named in that section and use the full page as the source of +truth. Follow links from that page when the question needs more detail. Fetch + first when you need to discover the relevant +documentation page. -## Configuration +## Version policy + +Always answer for OpenCode V2 unless the user explicitly asks about V1, +legacy OpenCode, or migrating from V1. + +Use only documentation as the source of truth for V2. +Do not use , which documents V1, and do not use +general web search to resolve a V2 documentation question when the V2 docs or +their `llms.txt` index cover it. The schema served from + may describe V1 even though V2 configuration +files include that URL for editor integration. Never use it to infer V2 field +names or shapes. If V2 documentation is missing or contradictory, state the +uncertainty or ask for clarification instead of falling back to V1. + +V1 documentation and syntax may be consulted only when the user explicitly +asks about V1 or when needed as migration input. Outputs and recommendations +must still use V2 unless the user specifically requests a V1 result. + +## [Configuration](https://v2.opencode.ai/config) OpenCode configuration uses JSON or JSONC. Include the published schema so the user's editor can validate fields and provide autocomplete: ```jsonc { - "$schema": "https://opencode.ai/config.json" + "$schema": "https://opencode.ai/config.json", } ``` @@ -23,28 +45,56 @@ to every project for that user. Project configuration can live in any directory as `opencode.json(c)` or `.opencode/opencode.json(c)`, including nested packages in a monorepo. -When OpenCode starts, it searches upward from the current directory for project -configuration and merges the files it finds with the global configuration. +When OpenCode starts, it searches from the current directory up to the project +root. It merges direct `opencode.json(c)` files from root to current directory, +then does the same for `.opencode/opencode.json(c)` files. This means every +`.opencode` config overrides every direct config. Global configuration has the +lowest precedence. Common configuration fields include `model`, `default_agent`, `permissions`, `agents`, `commands`, `plugins`, `providers`, `mcp`, `skills`, `instructions`, `references`, `formatter`, and `lsp`. -Do not guess field names or shapes. Use - as the source of truth and preserve unrelated -settings when editing an existing file. +Do not guess field names or shapes. Fetch the V2 configuration guide and its +linked topic guide as the source of truth, and preserve unrelated settings when +editing an existing file. Keep the published `$schema` URL in configuration +examples, but do not fetch it to determine the V2 configuration shape. -See the [full configuration guide](https://opencode.mintlify.site/config) for +See the [full configuration guide](https://v2.opencode.ai/config) for every field, examples, config locations, and links to dedicated feature guides. -## Service +## [V1 to V2 migration](https://v2.opencode.ai/migrate-v1) + +For any request to migrate OpenCode configuration, agents, commands, skills, +plugins, integrations, or other behavior from V1 to V2, read the full +[migration guide](https://v2.opencode.ai/migrate-v1) before acting. In +the repository, its source is `packages/docs/migrate-v1.mdx`. + +V1 config files and `.opencode/` definitions are intended to remain compatible. +The only intentional breaking changes are the server API and plugin API. Native +V2 config uses more ergonomic shapes, but conversion is optional. When the user +requests conversion, inspect the complete configuration, preserve behavior and +unrelated settings, and apply only the relevant migrations from the guide. For +plugin migrations, fetch and follow both the migration guide and the full +[plugins guide](https://v2.opencode.ai/build/plugins). If non-API V1 +functionality fails in V2, use the `report` skill to file it as a compatibility +bug. + +## [Plugins](https://v2.opencode.ai/build/plugins) + +For questions about creating, configuring, loading, publishing, or migrating +plugins, fetch the full [plugins guide](https://v2.opencode.ai/build/plugins) +before answering. This includes questions about the Effect plugin API, hooks, +transforms, tools, plugin context capabilities, and package entrypoints. + +## [Service](https://v2.opencode.ai/troubleshooting#check-the-background-service) OpenCode uses a client-server architecture. Interfaces such as the TUI connect to a background OpenCode service, which owns sessions, configuration, plugins, permissions, and tool execution. -Configuration and related files are typically watched and reloaded while the -service is running. If a change does not appear, restart the service: +OpenCode normally discovers or starts the shared background service +automatically. If the service is stuck or unhealthy, restart it: ```sh opencode2 service restart @@ -56,14 +106,15 @@ Check its status after restarting: opencode2 service status ``` -## API +## [API](https://v2.opencode.ai/api) OpenCode exposes an HTTP API from its server. The API is described by an OpenAPI document available from the running server at `/openapi.json`. -Use OpenCode's built-in `api` command for local requests. It discovers the same -background server used by the TUI, starts it when necessary, and applies the -server's authentication headers automatically. +Use OpenCode's built-in `api` command for local requests. It uses the same +discovery and authentication flow as the TUI and may start the background +service when no compatible healthy service is available. It accepts either an +HTTP method and path or an OpenAPI operation ID. Call an endpoint with an HTTP method and path: @@ -84,18 +135,34 @@ connected to an explicit server instead of its managed background service, use the same configured server and authentication context rather than constructing an unauthenticated request separately. -See the [full API reference](https://opencode.mintlify.site/api) for available +See the [full API reference](https://v2.opencode.ai/api) for available endpoints, parameters, request bodies, and response schemas. The -raw [OpenAPI specification](https://opencode.mintlify.site/openapi.json) is also +raw [OpenAPI specification](https://v2.opencode.ai/openapi.json) is also available for code generation and other tooling. -## Troubleshooting +## [Client](https://v2.opencode.ai/build/client) + +For questions about connecting an application to OpenCode over the network, +fetch the full [client guide](https://v2.opencode.ai/build/client) before +answering. + +`@opencode-ai/client` is the generated TypeScript client for the OpenCode HTTP +API. Its methods and types come from the same contract as the API reference. +The default entrypoint exposes Promise-based resource clients and async +iterables for streaming endpoints. The `@opencode-ai/client/effect` entrypoint +exposes typed Effects, Streams, and decoded OpenCode schema values. Its +`Service` API can discover, start, stop, and authenticate with the local +background service from a Node application. + +## [Troubleshooting](https://v2.opencode.ai/troubleshooting) OpenCode runs a client and a background server. Start by determining whether a problem belongs to the client, the shared server, or one project. - Check the service with `opencode2 service status` and verify the API with `opencode2 api get /api/health`. +- Compare with `opencode2 --standalone`, which runs the TUI with a private + server, to isolate shared-service issues. - Inspect `~/.local/share/opencode/log/opencode.log`. Filter `role=cli` for client startup and `role=server` for sessions, providers, plugins, permissions, and tools. @@ -107,6 +174,6 @@ problem belongs to the client, the shared server, or one project. - Redact API keys, authorization headers, prompts, file contents, and other sensitive data before sharing diagnostics. -See the [full troubleshooting guide](https://opencode.mintlify.site/troubleshooting) +See the [full troubleshooting guide](https://v2.opencode.ai/troubleshooting) for service lifecycle commands, API inspection, log locations, explicit server connections, issue-reporting details, and local development paths. diff --git a/packages/core/src/plugin/supervisor.ts b/packages/core/src/plugin/supervisor.ts index 0dd3a31d72..9b056c994e 100644 --- a/packages/core/src/plugin/supervisor.ts +++ b/packages/core/src/plugin/supervisor.ts @@ -72,23 +72,6 @@ type Operation = readonly target: string } -type Candidate = - | { - readonly type: "definition" - readonly definition: Plugin - } - | { - readonly type: "package" - readonly specifier: string - readonly options: Record - readonly mtime?: number - } - -type ConfiguredPackage = { - readonly operation: Extract - enabled: boolean -} - function parse(input: ConfigPlugin.Plugin): Operation { if (typeof input !== "string") { return { type: "add", target: input.package, options: input.options ?? {} } @@ -109,13 +92,14 @@ const scan = Effect.fn("PluginSupervisor.scan")(function* (entries: readonly Con .filter((entry): entry is Config.Document => entry.type === "document") .flatMap((entry) => (entry.info.plugins ?? []).map(parse).map((operation) => { + if (operation.type === "remove") return operation const directory = entry.path ? path.dirname(entry.path) : location.directory const target = operation.target.startsWith("file://") ? fileURLToPath(operation.target) : operation.target.startsWith("./") || operation.target.startsWith("../") ? path.resolve(directory, operation.target) : operation.target - return operation.type === "add" ? { ...operation, target } : { type: "remove" as const, target } + return { ...operation, target } }), ) // Explicit config is applied last so it can remove auto-discovered packages. @@ -136,91 +120,66 @@ const resolve = Effect.fn("PluginSupervisor.resolve")(function* ( post: readonly Plugin[], operations: readonly Operation[], ) { - const plan = apply(pre, post, operations) - return yield* load(plan) -}) - -function apply(pre: readonly Plugin[], post: readonly Plugin[], operations: readonly Operation[]) { const matches = (selector: string, target: string) => selector === "*" || (selector.endsWith(".*") ? target.startsWith(selector.slice(0, -1)) : selector === target) - const plugins = [...pre, ...post] - const enabled = new Set(plugins.map((plugin) => plugin.id)) - const packages = new Map() + const definitions = [...pre, ...post] + const enabled = new Set(definitions.map((plugin) => plugin.id)) + const packages = new Map() + const plugins = () => [...definitions, ...packages.values()] for (const operation of operations) { if (operation.type === "remove") { - plugins.filter((plugin) => matches(operation.target, plugin.id)).forEach((plugin) => enabled.delete(plugin.id)) - packages.forEach((item, target) => { - if (matches(operation.target, target)) item.enabled = false - }) + plugins() + .filter((plugin) => matches(operation.target, plugin.id)) + .forEach((plugin) => enabled.delete(plugin.id)) continue } - const matched = plugins.filter((plugin) => matches(operation.target, plugin.id)) - const selectsDefinitions = + const matched = plugins().filter((plugin) => matches(operation.target, plugin.id)) + const selectsPlugins = matched.length > 0 || operation.target === "*" || operation.target.endsWith(".*") || operation.target.startsWith("opencode.") - if (selectsDefinitions) { + if (selectsPlugins) { matched.forEach((plugin) => enabled.add(plugin.id)) - packages.forEach((item, target) => { - if (matches(operation.target, target)) item.enabled = true - }) continue } - packages.set(operation.target, { operation, enabled: true }) + const plugin = yield* load(operation).pipe(Effect.catchCause(() => Effect.succeed(undefined))) + if (!plugin) continue + const previous = packages.get(operation.target) + if (previous) enabled.delete(previous.id) + packages.set(operation.target, plugin) + enabled.add(plugin.id) } - const definitions: Candidate[] = pre.flatMap((definition) => - enabled.has(definition.id) ? [{ type: "definition", definition }] : [], - ) - const configured: Candidate[] = Array.from(packages.values()).flatMap((item) => - item.enabled - ? [ - { - type: "package", - specifier: item.operation.target, - options: item.operation.options, - ...(item.operation.mtime === undefined ? {} : { mtime: item.operation.mtime }), - }, - ] - : [], - ) - const posts: Candidate[] = post.flatMap((definition) => - enabled.has(definition.id) ? [{ type: "definition", definition }] : [], - ) - return [...definitions, ...configured, ...posts] -} + return [ + ...pre.filter((plugin) => enabled.has(plugin.id)), + ...Array.from(packages.values()).filter((plugin) => enabled.has(plugin.id)), + ...post.filter((plugin) => enabled.has(plugin.id)), + ] +}) -const load = Effect.fn("PluginSupervisor.load")(function* (plan: readonly Candidate[]) { - return yield* Effect.forEach(plan, (candidate) => { - if (candidate.type === "definition") return Effect.succeed({ plugin: candidate.definition }) - return Effect.gen(function* () { - const npm = yield* Npm.Service - const entrypoint = path.isAbsolute(candidate.specifier) - ? pathToFileURL(candidate.specifier).href - : (yield* npm.add(candidate.specifier)).entrypoint - if (!entrypoint) return - // Bun currently ignores query parameters when caching file:// imports. - const source = - candidate.mtime === undefined - ? entrypoint - : `${candidate.specifier.replaceAll("\\", "/")}?mtime=${candidate.mtime}` - yield* Effect.log({ msg: "loading plugin", id: candidate.specifier, entrypoint: source }) - const mod = yield* Effect.promise(() => import(source)) - const value = (yield* Schema.decodeUnknownEffect(PluginModule)(mod)).default - const plugin = "effect" in value ? value : PluginPromise.fromPromise(value) - return { - plugin: { - id: plugin.id, - effect: (host) => plugin.effect({ ...host, options: candidate.options }), - } satisfies Plugin, - ...(candidate.mtime === undefined ? {} : { version: String(candidate.mtime) }), - } - }).pipe(Effect.catchCause(() => Effect.succeed(undefined))) - }).pipe(Effect.map((plugins) => plugins.filter((plugin) => plugin !== undefined))) +const load = Effect.fn("PluginSupervisor.load")(function* (operation: Extract) { + const npm = yield* Npm.Service + const entrypoint = path.isAbsolute(operation.target) + ? pathToFileURL(operation.target).href + : (yield* npm.add(operation.target)).entrypoint + if (!entrypoint) return + // Bun currently ignores query parameters when caching file:// imports. + const source = + operation.mtime === undefined + ? entrypoint + : `${operation.target.replaceAll("\\", "/")}?mtime=${operation.mtime}` + yield* Effect.log({ msg: "loading plugin", id: operation.target, entrypoint: source }) + const mod = yield* Effect.promise(() => import(source)) + const value = (yield* Schema.decodeUnknownEffect(PluginModule)(mod)).default + const plugin = "effect" in value ? value : PluginPromise.fromPromise(value) + return { + id: plugin.id, + effect: (host) => plugin.effect({ ...host, options: operation.options }), + } satisfies Plugin }) function discoverDirectory(fs: FSUtil.Interface, directory: string) { diff --git a/packages/core/src/reference/guidance.ts b/packages/core/src/reference/guidance.ts index 1ddc1a3a8b..a9fd9eb980 100644 --- a/packages/core/src/reference/guidance.ts +++ b/packages/core/src/reference/guidance.ts @@ -74,14 +74,16 @@ const layer = Layer.effect( description: reference.description, })) .toSorted((a, b) => a.name.localeCompare(b.name)) - if (available.length === 0) return Instructions.empty - return Instructions.make({ + return Instructions.make>({ key: Instructions.Key.make("core/reference-guidance"), codec: Schema.toCodecJson(Schema.Array(Summary)), - load: Effect.succeed(available), - baseline: render, - update, - removed: () => "Project reference guidance is no longer available. Do not use previously listed references.", + read: Effect.succeed(available.length === 0 ? Instructions.removed : available), + render: { + initial: render, + changed: update, + removed: () => + "Project reference guidance is no longer available. Do not use previously listed references.", + }, }) }), }) diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 3d3a3a5e45..a888498c15 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -32,7 +32,7 @@ import { makeGlobalNode } from "./effect/app-node" import { LocationServiceMap } from "./location-service-map" import { MessageDecodeError } from "./session/error" import { SessionEvent } from "./session/event" -import { SessionInput } from "./session/input" +import { SessionPending } from "./session/pending" import { Snapshot } from "./snapshot" import { SessionRevert } from "./session/revert" import { Session } from "@opencode-ai/schema/session" @@ -188,7 +188,13 @@ export interface Interface { sessionID: SessionSchema.ID, ) => Effect.Effect /** - * Durable, ordered, gap-free session log read. Replays public durable + * Durable admitted session work not yet visible in projected history, + * ordered by admission. Includes unpromoted user and synthetic inputs and + * unhandled compaction barriers. + */ + readonly pending: (sessionID: SessionSchema.ID) => Effect.Effect + /** + * Durable, ordered session log read. Replays public durable * session events after the exclusive `after` cursor, emits a `Synced` * marker at the captured replay watermark, then continues live when `follow` * is set. @@ -216,9 +222,9 @@ export interface Interface { files?: PromptInput.Prompt["files"] agents?: PromptInput.Prompt["agents"] metadata?: Record - delivery?: SessionInput.Delivery + delivery?: SessionPending.Delivery resume?: boolean - }) => Effect.Effect + }) => Effect.Effect readonly command: (input: { id?: SessionMessage.ID sessionID: SessionSchema.ID @@ -228,10 +234,10 @@ export interface Interface { model?: ModelV2.Ref files?: PromptInput.Prompt["files"] agents?: PromptInput.Prompt["agents"] - delivery?: SessionInput.Delivery + delivery?: SessionPending.Delivery resume?: boolean }) => Effect.Effect< - SessionInput.User, + SessionPending.User, NotFoundError | PromptConflictError | AttachmentError | CommandV2.NotFoundError | CommandV2.EvaluationError > readonly shell: (input: { @@ -247,7 +253,7 @@ export interface Interface { }) => Effect.Effect readonly compact: ( input: CompactInput, - ) => Effect.Effect + ) => Effect.Effect readonly wait: (id: SessionSchema.ID) => Effect.Effect readonly active: Effect.Effect> readonly background: (sessionID: SessionSchema.ID) => Effect.Effect @@ -259,9 +265,9 @@ export interface Interface { text: string description?: string metadata?: Record - delivery?: SessionInput.Delivery + delivery?: SessionPending.Delivery resume?: boolean - }) => Effect.Effect + }) => Effect.Effect readonly revert: { readonly stage: (input: { sessionID: SessionSchema.ID @@ -378,9 +384,11 @@ const layer = Layer.effect( if (input.messageID && !boundary) return yield* new MessageNotFoundError({ sessionID: input.sessionID, messageID: input.messageID }) const sessionID = SessionSchema.ID.create() + const parentSeq = boundary ? boundary.seq - 1 : yield* EventV2.latestSequence(db, parent.id) yield* events.publish(SessionEvent.Forked, { sessionID, parentID: parent.id, + parentSeq, from: input.messageID, }) return yield* result.get(sessionID).pipe(Effect.orDie) @@ -481,6 +489,10 @@ const layer = Layer.effect( yield* result.get(sessionID) return yield* store.context(sessionID) }), + pending: Effect.fn("V2Session.pending")(function* (sessionID) { + yield* result.get(sessionID) + return yield* SessionPending.list(db, sessionID) + }), log: (input) => Stream.unwrap( result @@ -504,25 +516,25 @@ const layer = Layer.effect( Effect.provideService(FSUtil.Service, fs), ) const messageID = input.id ?? SessionMessage.ID.create() - const admittedInput = SessionInput.Message.make({ + const admittedInput = SessionPending.Message.make({ type: "user", data: { ...prompt, metadata: input.metadata }, delivery: input.delivery ?? "steer", }) - const admitted = yield* SessionInput.admit(db, events, { + const admitted = yield* SessionPending.admit(db, events, { id: messageID, sessionID: input.sessionID, input: admittedInput, }).pipe( Effect.catchDefect((defect) => - defect instanceof SessionInput.LifecycleConflict + defect instanceof SessionPending.LifecycleConflict ? new PromptConflictError({ sessionID: input.sessionID, messageID }) : Effect.die(defect), ), ) if ( admitted.type !== "user" || - !SessionInput.equivalent(admitted, { sessionID: input.sessionID, input: admittedInput }) + !SessionPending.equivalent(admitted, { sessionID: input.sessionID, input: admittedInput }) ) return yield* new PromptConflictError({ sessionID: input.sessionID, messageID }) if (input.resume !== false) { @@ -571,7 +583,7 @@ const layer = Layer.effect( yield* shellLocks.withLock(input.sessionID)( Effect.gen(function* () { activeShells.add(input.sessionID) - if ((yield* execution.active).has(input.sessionID)) yield* execution.awaitIdle(input.sessionID) + yield* execution.awaitIdle(input.sessionID) const started = yield* Effect.gen(function* () { const shell = yield* Shell.Service return yield* shell.create({ command: input.command, cwd: session.location.directory, timeout: 0 }) @@ -664,12 +676,12 @@ const layer = Layer.effect( compact: Effect.fn("V2Session.compact")(function* (input) { yield* result.get(input.sessionID) const inputID = input.id ?? SessionMessage.ID.create() - const admitted = yield* SessionInput.admitCompaction(db, events, { + const admitted = yield* SessionPending.admitCompaction(db, events, { id: inputID, sessionID: input.sessionID, }).pipe( Effect.catchDefect((defect) => - defect instanceof SessionInput.LifecycleConflict + defect instanceof SessionPending.LifecycleConflict ? new CompactionConflictError({ sessionID: input.sessionID, inputID }) : Effect.die(defect), ), @@ -709,7 +721,7 @@ const layer = Layer.effect( Effect.gen(function* () { yield* result.get(input.sessionID) const inputID = input.id ?? SessionMessage.ID.create() - const admittedInput = SessionInput.Message.make({ + const admittedInput = SessionPending.Message.make({ type: "synthetic", data: { text: input.text, @@ -718,20 +730,20 @@ const layer = Layer.effect( }, delivery: input.delivery ?? "steer", }) - const admitted = yield* SessionInput.admit(db, events, { + const admitted = yield* SessionPending.admit(db, events, { id: inputID, sessionID: input.sessionID, input: admittedInput, }).pipe( Effect.catchDefect((defect) => - defect instanceof SessionInput.LifecycleConflict + defect instanceof SessionPending.LifecycleConflict ? new SyntheticConflictError({ sessionID: input.sessionID, inputID }) : Effect.die(defect), ), ) if ( admitted.type !== "synthetic" || - !SessionInput.equivalent(admitted, { sessionID: input.sessionID, input: admittedInput }) + !SessionPending.equivalent(admitted, { sessionID: input.sessionID, input: admittedInput }) ) return yield* new SyntheticConflictError({ sessionID: input.sessionID, inputID }) if (input.resume !== false && !(yield* result.get(input.sessionID)).revert) diff --git a/packages/core/src/session/compaction.ts b/packages/core/src/session/compaction.ts index ab5e41e405..d9db191b57 100644 --- a/packages/core/src/session/compaction.ts +++ b/packages/core/src/session/compaction.ts @@ -1,7 +1,8 @@ export * as SessionCompaction from "./compaction" import { LLM, LLMClient, LLMError, LLMEvent, Message, type LLMRequest, type Model } from "@opencode-ai/llm" -import { Context, DateTime, Effect, Layer, Stream } from "effect" +import { SessionError } from "@opencode-ai/schema/session-error" +import { Context, Effect, Layer, Stream } from "effect" import { Config } from "../config" import { EventV2 } from "../event" import { makeLocationNode } from "../effect/app-node" @@ -10,12 +11,12 @@ import { SessionEvent } from "./event" import type { SessionMessage } from "./message" import { SessionRunnerModel } from "./runner/model" import { SessionSchema } from "./schema" +import { toSessionError } from "./to-session-error" import { Token } from "../util/token" const DEFAULT_BUFFER = 20_000 const DEFAULT_KEEP_TOKENS = 8_000 const TOOL_OUTPUT_MAX_CHARS = 2_000 -const SUMMARY_OUTPUT_TOKENS = 4_096 const SUMMARY_TEMPLATE = `Output exactly the Markdown structure shown inside