import { B as BootingRuntime, S as Store, n as BootedRunHandle, E as EngineRun, a as StoreAndOnError, o as PendingEffectsRecorder, l as EffectOwed, k as EffectConfirmed, g as RunHandle, M as Migrated, F as FencedStore, D as DeletableStore } from '../runtime-types-f231H8Gq.js'; export { j as EffectLedgerEvent, p as OwedEffect, q as PendingEffectsLedger, r as applyEffectEvent, m as emptyLedger, s as foldLedger, t as isOwed, u as pendingEffectsLedger, v as survivingEffects } from '../runtime-types-f231H8Gq.js'; import { M as Machine, c as Sub, b as Cmd, v as Tagged, W as Wired } from '../core-sEWVgnpI.js'; export { i as DeliveryId } from '../core-sEWVgnpI.js'; export { A as AppliedEffects, a as AppliedEffectsEvent, b as AppliedEffectsGuard, E as EffectApplied, c as EffectForgotten, d as EffectKey, I as IdempotentEffect, e as IdempotentOutcome, f as appliedEffects, g as applyAppliedEvent, h as emptyApplied, i as foldApplied, j as idempotentEffect, k as isApplied } from '../idempotent-effect-BhlYUVBf.js'; import { AnyRetryPolicy, Rng, RetryState, TimedRetryState } from '../retry-backoff/index.js'; import { A as AgentEvent, f as AgentTurn, i as AgentMachineMsg, e as AgentState, L as AgentStatus } from '../machine-rN7E-yh-.js'; import '@standard-schema/spec'; import '../index-tFnc-ElD.js'; import '../index-DUdoElz8.js'; import '../index-CCs-QGGu.js'; import '../types-CtM4tWPp.js'; import '../index-DmoyvP-O.js'; import '../index-C1BK3MNo.js'; import '../protocol-CqdURF0g.js'; import '../index-D5RP0MjN.js'; /** * @demlik/tea/do — `stepHost`, the HTTP-PULL control carrier (#92). * * ## Carrier selection — pick by WHO INITIATES the message * * `stepHost` is a SIBLING to {@link acceptCommandSocket}, never a replacement. * Both carriers commonly run together in ONE Durable Object; choose between * them per *plane*, by who sends the next message: * * - **Pull (this file — `stepHost` over `/step`)** — the CONTROL plane. One * driver (the hands) initiates every message: it asks for the next tool, * runs it, posts the result, asks again. There is exactly one outstanding * question at a time and the DO is COLD between steps — nothing is owed * while no request is in flight. Hibernation is the resting state, not a * failure: each POST wakes the DO, advances the run one step from its * durable checkpoint, and lets it hibernate again. * - **Push (`acceptCommandSocket` / `sseHub` — WS + SSE)** — the VIEW / * fan-out plane. The DO initiates UNSOLICITED messages: broadcast a frame * to every connected client, stream a live dashboard, push an event no * client asked for. A long-lived socket is the right carrier because the * sender is the DO, not a polling client. * * The rule in one line: **pull when the client drives a cold-between-steps * control loop; push when the DO drives unsolicited fan-out.** A hibernating * agent whose only traffic is "run the next tool" wants pull — that is the case * a production consumer adopted this carrier for. * * ## Why pull is hibernation-correct * * The WS push carrier keeps a socket open across steps; if the DO evicts, the * socket dies (or, with #91's `acceptDurableCommandSocket`, survives but still * holds an in-flight round-trip the heap forgot). The pull carrier holds NO * cross-step state in the heap. Every `/step` POST is a FRESH request that: * * 1. **validates** the per-run capability token (constant-time compare), * 2. **re-arms** the eviction-safe give-up alarm via `ctx.storage.setAlarm` * (the DO-native alarm API — the `do_alarm` Sub was dropped, see the * `host.ts` header; the alarm is a host concern, not a machine Sub), * 3. **admits** the pull through the engine's optional `beforeResume` — it * may answer with the terminal response itself, and then nothing below * runs for this request, * 4. **settles** the posted tool result IDEMPOTENTLY through * `idempotent-intake` — a re-POSTed result is absorbed exactly once and * the duplicate replays the same next step, * 5. **resumes** the run from its durable checkpoint (the #68 event-sourced * store / #91 in-flight ledger) by dispatching the settle and running to * DISPATCH-QUIESCENCE, * 6. **returns** the next step (the next tool call) — or the terminal output * read off `runtime.result()` — and lets the DO HIBERNATE. * * No warm loop is held between responses. The durable checkpoint IS the loop's * continuation; the heap is disposable. * * ## It is ASSEMBLY over bricks tea already ships * * - `idempotent-intake` (`createIntake`) — the dedupe-by-key receive-once * settle. The posted result's `callId` is the idempotency key, so a * re-POST lands as a duplicate and replays the cached decision. * - `poller` primitives (`retry-backoff`) — the hands-side {@link runStepLoop} * pull loop: absolute deadline + backoff + dedupe-by-callId. * - the #68/#91 durable checkpoint — read by the consumer's `resume` callback * (it dispatches the settle into the runtime, whose `doEventSourcedStore` * rebuilt state from the log on this cold wake). * * This file owns NONE of those primitives — it wires them into the `/step` * request/response contract and the token lifecycle. */ /** * The tool result the hands POST back for the step they just executed. `callId` * matches the step the previous response handed out (it is BOTH the correlation * id and the idempotency key — a re-POST carries the same `callId` and is * absorbed once). `result` is the opaque tool output `R`. */ interface StepResult { readonly callId: string; readonly result: R; } /** * A `/step` request. `token` is the per-run capability (validated * constant-time). `runId` names the run. `posted` is the result of the * previously-returned step, or `null` on the FIRST request (no step has been * handed out yet, so there is nothing to settle). */ interface StepRequest { readonly token: string; readonly runId: string; readonly posted: StepResult | null; } /** * The next tool call to execute — the "continue" arm of a `/step` response. * `callId` is the correlation/idempotency id the hands echo back in the next * request's `posted`. `tool` + `input` describe the call (opaque to the host). */ interface NextStep { readonly callId: string; readonly tool: string; readonly input: I; } /** * A `/step` response — a discriminated union on `done`: * - `{ done: false, step }` — execute `step`, POST its result, ask again. * - `{ done: true, output }` — the run is terminal; `output` is its result. * * This is the ORIGINAL 2-arm INLINE contract, kept byte-identical: a host that * resolves each step inside the held request returns exactly these two shapes. * The not-ready arm ({@link StepWorking}) is a SEPARATE, opt-in type reachable * only through the defer-resume hook — see {@link DeferredStepResponse}. Keeping * `StepResponse` a strict subset is what makes inline adopters unaffected: their * `if (r.done) … else r.step` narrowing never sees a third member. */ type StepResponse = { readonly done: false; readonly step: NextStep; } | { readonly done: true; readonly output: O; }; /** * The NOT-READY arm — the run is computing OUT-OF-BAND under a defer-resume host * (a production incident: a non-blocking pull carrier must * answer a pull with an explicit "computing, poll again" instead of holding the * request across a multi-second step). The held `/step` request returns this * IMMEDIATELY instead of inline-awaiting `engine.resume`; the hands re-poll * (optionally after `retryAfterMs`) until the deferred compute lands in the * durable checkpoint and a real {@link StepResponse} step/done arm is returned. * * It is a first-class discriminated member (`working: true`), NOT a hollow * `{ done: false }` with an absent/stale `step` — the not-ready state is made * representable so it can never be confused with a real pending step. */ interface StepWorking { readonly done: false; readonly working: true; /** * Advisory earliest re-poll delay as a hint to the hands (ms to wait before * the next pull). Purely advisory — a host may omit it and the hands fall back * to their own backoff curve. */ readonly retryAfterMs?: number; } /** * The 3-arm response a DEFER-RESUME host returns — the inline {@link StepResponse} * arms PLUS {@link StepWorking}. A superset of `StepResponse`, so a 2-arm value is * assignable to it (the widening is safe for existing transports); discriminate * with `if (r.done)` for terminal, then `"working" in r` for the not-ready arm, * else the step arm. */ type DeferredStepResponse = StepResponse | StepWorking; /** * Mint a fresh per-run capability token: 32 random bytes, hex-encoded. Uses the * Web Crypto `crypto.getRandomValues` available in the Workers runtime (and in * Node's test runtime via the global `crypto`). Persist the returned string in * DO storage keyed by runId; hand the SAME string to the hands once, at run * start. */ declare function mintRunToken(randomBytes?: (n: number) => Uint8Array): string; /** * Constant-time string equality. Returns `true` iff `a` and `b` are * byte-for-byte equal, in time that depends ONLY on `a.length` — never on WHERE * the first mismatch is. A length mismatch still returns `false`, but the * comparison loop always runs `a.length` iterations against a same-length view, * so the early-exit timing oracle a naive `===` leaks is closed. * * The XOR-accumulate idiom: fold every position's difference into one * accumulator and test it once at the end. No `break`, no short-circuit. */ declare function constantTimeEqual(a: string, b: string): boolean; /** * The DO-native alarm slice `stepHost` re-arms. A real `DurableObjectStorage` * satisfies this structurally; a test supplies a fake (no live Workers runtime). * Only `setAlarm` is needed — the give-up deadline is re-armed on every step so * a run abandoned mid-loop (the hands stop POSTing) is eventually evicted by the * alarm firing, not left resident forever. */ interface AlarmStorage { setAlarm(scheduledTime: number): void | Promise; } /** The minimal `ctx` slice `stepHost` reads — just the alarm-bearing storage. */ interface StepCtx { readonly storage: AlarmStorage; } /** * The run-specific operations `stepHost` orchestrates. The consumer implements * these against its runtime + storage; `stepHost` never reaches into the agent * machine itself (that lives in `../agent`, off-limits to this carrier). */ interface StepEngine { /** * The persisted capability token for `runId`, or `null` if the run is * unknown. Read from DO storage. `stepHost` compares the request token * against this constant-time. */ tokenFor(runId: string): Promise | string | null; /** * Settle the posted tool result into the run, then RESUME from the durable * checkpoint: dispatch the settle and run to DISPATCH-QUIESCENCE (e.g. * `await runtime.dispatch(settleMsg)` — dispatch drains the follow-up chain * by default, #50). `stepHost` calls it once per distinct `callId` of a run * for as long as this host instance lives, because it runs one request of a * run at a time and dedupes a re-POST through `idempotent-intake` BEFORE * calling this. A resume that throws or rejects does not count: the same * `callId` posted again calls it again, so it must be safe to run twice. A * new host instance (an evicted object waking up) has an empty ledger and * settles a re-POST once more, which the durable checkpoint absorbs. On the * first request (`posted === null`) `stepHost` skips settle and calls * {@link nextStep} directly to hand out the first step. */ resume(runId: string, posted: StepResult): Promise | void; /** * Read the next step the run is now waiting on — the next tool call — off the * resumed runtime's durable state, or `null` if the run has reached its * terminal State (then {@link terminalOutput} supplies the output). */ nextStep(runId: string): Promise | null> | NextStep | null; /** * Read the run's terminal output (off `runtime.result()`). Only called when * {@link nextStep} returned `null`. */ terminalOutput(runId: string): Promise | O; /** * Optional admission check, run for EVERY authenticated pull — the first pull, * a result post, a duplicate — after the token is accepted, the run's earlier * requests have settled and the give-up alarm is re-armed, and BEFORE the * settle, the deferred readiness probe and enqueue, {@link nextStep} and * {@link terminalOutput}. Return `null` to * continue exactly as a host without the hook does. Return the terminal * `{ done: true, output }` response to end the pull there: `stepHost` sends * it and does no further work for this request. * * It decides nothing for the host. The engine reads whatever persisted state it * keeps for the run (a stop it recorded, say), acts on it (dispatches the run's * cancel Msg through its own runtime), and answers. `stepHost` owns only the * order and the short-circuit. A throw or a rejection propagates out of * `handle` before the intake is touched, so the same result posted again is * still new. It bounds this pull only: a step already started, or a stop that * arrives after the hook returned, is outside it, and a worker that runs queued * work later must check again. It runs inside the run's turn, so it must not * call `handle` for the same run and wait for it: that request queues behind * the turn that is waiting for it. */ beforeResume?(runId: string): Promise, { readonly done: true; }> | null> | Extract, { readonly done: true; }> | null; } /** Tuning for `stepHost`'s give-up alarm. */ interface StepHostConfig { /** * How far ahead, in ms, to re-arm the give-up alarm on every step. A run that * stops POSTing for longer than this is abandoned and the alarm fires (the * consumer's `alarm()` handler tears the run down). Defaults to 5 minutes. */ readonly giveUpAfterMs?: number; } /** * The DEFER-RESUME hook — the opt-in seam that drives `engine.resume` OUT of the * held `/step` request. A non-blocking host (a non-blocking production audit carrier) * cannot inline-await a multi-second step inside the held request, so instead of * `stepHost` calling `engine.resume` inline it hands the posted result to this * hook to SETTLE-AND-ENQUEUE (record it durably, schedule the compute in a * returning activation) and returns the {@link StepWorking} arm PROMPTLY. A later * pull re-reads the durable next-step once {@link DeferResumeHook.settled} reports * the enqueued compute has landed. * * Providing this hook is what flips `stepHost` from the 2-arm inline contract to * the 3-arm deferred contract — see the `stepHost` overloads. Omit it and the * host stays byte-identical inline. */ interface DeferResumeHook { /** * SETTLE-AND-ENQUEUE the posted result to resume OUT of the held request: * durably record it and schedule the compute (e.g. `ctx.storage.setAlarm` or a * queue) so a returning activation runs `engine.resume`. MUST return promptly — * it never awaits the step compute. Called at most once per distinct `callId` * (`stepHost` dedupes re-POSTs through `idempotent-intake` first), so a re-POST * of the same step does not re-enqueue. */ enqueue(runId: string, posted: StepResult): void | Promise; /** * Has the enqueued resume for `callId` COMPLETED and been written to the * durable checkpoint? `false` ⇒ the held request returns {@link StepWorking} * (poll again); `true` ⇒ `stepHost` reads the next step / terminal output off * the now-advanced checkpoint, exactly as the inline path does. */ settled(runId: string, callId: string): boolean | Promise; /** * Optional advisory re-poll delay (ms) surfaced on the {@link StepWorking} arm * so the hands can back off to the host's expected step latency. */ readonly retryAfterMs?: number; } /** * `StepHostConfig` with the defer-resume hook engaged — the presence of * `deferResume` is the type-level switch that selects the 3-arm response (see the * `stepHost` overloads). Extends the inline config, so the alarm tuning is shared. */ interface DeferStepHostConfig extends StepHostConfig { readonly deferResume: DeferResumeHook; } /** * A structured `/step` outcome `stepHost` returns — the response body plus the * HTTP status the consumer's route should send. Kept transport-agnostic (no * `Response`) so the same handler is unit-testable without a live `fetch`. */ type StepOutcome = { readonly status: 200; readonly body: StepResponse; } | { readonly status: 401 | 404; readonly body: { readonly error: string; }; }; /** * The `/step` outcome a DEFER-RESUME host returns — like {@link StepOutcome} but * its 200 body is the 3-arm {@link DeferredStepResponse} (it can carry the * not-ready arm). Returned only from the `deferResume` overload of `stepHost`; * the inline overload keeps the narrower {@link StepOutcome}. */ type DeferredStepOutcome = { readonly status: 200; readonly body: DeferredStepResponse; } | { readonly status: 401 | 404; readonly body: { readonly error: string; }; }; /** * Build the `/step` handler for a DO that drives one or more runs over the pull * carrier. Returns `handle(request, now)` — call it from the DO's `/step` * route, map the `StepOutcome` to a `Response`, and let the DO hibernate. * * Requests of ONE run take turns. After the token is accepted, each request * waits for the run's earlier requests to settle, then runs the whole turn: the * alarm re-arm, the admission hook, the settle (or the deferred probe and * enqueue), and the read of the next step or the output. So a duplicate POST that * arrives while the first is still resuming waits, and then reads the State that * resume produced, never one from the middle of it. A turn that throws is * released, and its caller gets that error. Runs do not wait for each other. * This holds for one `stepHost` instance, which is one activation. Two hosts or * two processes over the same run are not ordered by it, and it cannot interrupt * a model call that is already running. * * The handler is STATELESS between calls except for its `idempotent-intake` * dedupe ledger, kept per run and per `callId` (two runs may reuse a `callId`). * The consumer should itself persist it alongside the run's checkpoint if * cross-eviction dedupe of an identical re-POST is required; the in-isolate * ledger here dedupes re-POSTs within one activation (the common "the hands' * POST timed out and got retried" case), and the underlying `resume` is itself * idempotent against the durable checkpoint, so a re-POST that crosses an * eviction re-settles harmlessly. * * @param ctx the DO state slice (alarm-bearing storage) * @param engine the run-specific operations * @param config alarm tuning */ declare function stepHost(ctx: StepCtx, engine: StepEngine, config: DeferStepHostConfig): { handle(request: StepRequest, now: number): Promise>; }; declare function stepHost(ctx: StepCtx, engine: StepEngine, config?: StepHostConfig): { handle(request: StepRequest, now: number): Promise>; }; /** * The `/step` transport the hands POST through (injected; faked in tests). * Returns the 3-arm {@link DeferredStepResponse} — a defer-resume host may answer * with the not-ready arm, which {@link runStepLoop} re-polls. An inline host's * 2-arm transport (`=> Promise`) is assignable here (the narrower * return widens), so existing inline adopters are unaffected. */ type StepTransport = (request: StepRequest) => Promise>; /** Execute one tool call and produce its result (the consumer's hands). */ type ExecuteStep = (step: NextStep) => Promise | R; /** * What {@link ExecutedSteps} holds for a step that ran. The box is what tells a * step whose result is `undefined` apart from a step that never ran, and it * still does after a JSON round trip (`{}` is a box; a missing entry is not). */ interface ExecutedStep { readonly result: R; } /** * The hands' memory of the steps they already ran, keyed by `callId`. Pass one * that outlives the process and a restarted {@link runStepLoop} re-POSTs a saved * result instead of running the step again. * * Use one store per run: a host's `callId` only has to be unique inside its run. * The caller owns where it lives and when it is cleared. */ interface ExecutedSteps { /** The box saved for `callId`, or `undefined` if that step never ran. */ get(callId: string): Promise | undefined> | ExecutedStep | undefined; /** Save the box for `callId`. Settled before the result is POSTed. */ set(callId: string, step: ExecutedStep): Promise | void; } /** * Tuning for {@link runStepLoop}. * * `R` is the step result type, and only {@link RunStepLoopConfig.executed} reads * it. It defaults to `never` because a bare `RunStepLoopConfig` says nothing * about results: it has to fit a drive of any `R`, and a store of `unknown` * could not hand a drive its `R` back. `I` and `O` are the step input and the * output, which only {@link RunStepLoopConfig.attach} reads, and default the * same way. */ interface RunStepLoopConfig { /** * Absolute wall-clock deadline (ms epoch). The loop stops asking once `now()` * reaches it, surfacing a `deadline_exceeded` outcome. Mirrors the poller's * absolute-deadline contract (a resumed loop honors the SAME moment). */ readonly deadlineMs: number; /** * Where the hands remember the steps they ran. Defaults to a fresh in-memory * store per drive, which a restart forgets. See {@link runStepLoop}. */ readonly executed?: ExecutedSteps; /** * Backoff policy for FAILED `/step` POSTs. Defaults to `defaultRetryPolicy`. * A count bound, a duration bound (`maxElapsedMs`, measured on `now()` from * the first failure of the current streak) or an unbounded budget. */ readonly retry?: AnyRetryPolicy; /** * Whether a FAILED `/step` POST may be retried. Defaults to `() => true`. * When it returns `false` the failure is terminal at once: the loop stops * with `gave_up` carrying the error, and the failure consumes no budget. A * `retryable` that throws replaces the failure it was asked about: its throw * is what rejects the loop. */ readonly retryable?: (error: unknown) => boolean; /** Clock, injected for determinism. Defaults to `Date.now`. */ readonly now?: () => number; /** `(ms) => Promise` sleep, injected for determinism. Defaults to real sleep. */ readonly sleep?: (ms: number) => Promise; /** Backoff jitter RNG, injected for determinism. Defaults to `Math.random`. */ readonly rng?: Rng; /** * Called once with the drive's runtime, before it boots, so the caller can * attach to it what attaches to any tea run. `recorder(runtime, { * captureSteps: true })` records the drive, and `replayTrace` or * `replayStoredTrace` with {@link stepLoopMachine} replays the recording. * Attach before boot to record the starting State. A throw rejects the drive. * Declared as a method so that a bare `RunStepLoopConfig` still fits a drive * of any `R`, `I` and `O`. */ attach?(runtime: BootingRuntime, StepLoopMsg>): void; } /** The terminal outcome of a full {@link runStepLoop} drive. */ type StepLoopOutcome = { readonly kind: "done"; readonly output: O; } | { readonly kind: "deadline_exceeded"; } | { readonly kind: "gave_up"; readonly error: unknown; }; /** * What every phase of a drive in motion carries. Plain data, so a recording of * it survives `JSON.stringify` and a replay from the parsed text decides as the * live drive did, except that a deadline or retry-policy number that is * `NaN` or infinite (other than a `deadlineMs` of `Infinity`) may not replay * from stored text: see {@link runStepLoop}. */ interface StepLoopRun { /** The absolute deadline, or `null` for none: `Infinity` does not survive JSON. */ readonly deadlineMs: number | null; readonly policy: AnyRetryPolicy; /** The result the next POST carries, or `null` on the first. */ readonly posted: StepResult | null; /** The not-ready polls since the last real step. */ readonly polls: RetryState; } /** * The phases of a {@link runStepLoop} drive. `asking` waits for the clock * before a POST, `posting` for the transport, `failing` for the clock after a * failed POST, `backing_off` and `waiting` for the sleep that ends a failure * streak's pause or a not-ready poll's, `polling` for the clock after a * not-ready answer, and `running` for the hands. Every phase but `idle` and * `finished` also carries `deadlineMs`, `policy`, `posted` (the result the next * POST carries, or `null` on the first) and `polls` (the not-ready polls since * the last real step). */ type StepLoopState = { readonly _tag: "idle"; } | (StepLoopRun & { readonly _tag: "asking"; }) | (StepLoopRun & { readonly _tag: "posting"; readonly failures: RetryState; }) | (StepLoopRun & { readonly _tag: "failing"; readonly failures: RetryState; readonly error: unknown; }) | (StepLoopRun & { readonly _tag: "backing_off"; readonly failures: TimedRetryState; }) | (StepLoopRun & { readonly _tag: "polling"; /** The host's advisory re-poll delay, or `null` for the backoff curve. */ readonly hintMs: number | null; }) | (StepLoopRun & { readonly _tag: "waiting"; }) | (StepLoopRun & { readonly _tag: "running"; readonly step: NextStep; }) | { readonly _tag: "finished"; readonly outcome: StepLoopOutcome; }; /** * What a {@link runStepLoop} drive's Cmds report back. Each carries the value * the decision reads: the instant, the response, the failure, the result. */ type StepLoopMsg = { readonly _tag: "start"; readonly deadlineMs: number | null; readonly policy: AnyRetryPolicy; } | { readonly _tag: "clock_read"; readonly at: number; } | { readonly _tag: "responded"; readonly response: DeferredStepResponse; } | { readonly _tag: "post_failed"; readonly error: unknown; /** What `config.retryable` said of `error`. */ readonly retryable: boolean; } | { readonly _tag: "slept"; readonly ms: number; } | { readonly _tag: "step_ran"; readonly callId: string; readonly result: R; } | { readonly _tag: "store_failed"; readonly error: unknown; }; /** The effects of a {@link runStepLoop} drive, all of them plain data. */ type StepLoopCmd = { readonly _tag: "read_clock"; } | { readonly _tag: "post"; readonly posted: StepResult | null; } | { readonly _tag: "run_step"; readonly step: NextStep; } | { readonly _tag: "sleep"; readonly ms: number; } | { readonly _tag: "back_off"; readonly retry: RetryState; readonly policy: AnyRetryPolicy; }; /** * The decisions of {@link runStepLoop} as a machine: when to POST, what a * response means, when to run a step, retry, back off, give up, stop at the * deadline or finish. It reads the clock, the transport, the hands and the * sleep through Cmds and holds none of them. Replay a drive recorded with * `recorder` by handing this machine and the recording to `replayTrace`, or to * `replayStoredTrace` when the recording was read back from storage. */ declare function stepLoopMachine(): Machine, StepLoopMsg, StepLoopCmd, Sub, unknown>; /** * Drive the pull loop to completion. Starting from `{ posted: null }`, POST * `/step`, and for each non-terminal response execute the step and POST its * result, until the response is terminal (`done: true`) — then return its * output. * * Resilience composed from `poller`'s primitives: * - **absolute deadline** — `config.deadlineMs`. Before each POST the loop * checks `now() >= deadlineMs` and stops with `deadline_exceeded` rather * than asking forever. * - **backoff** — a FAILED POST (transport reject) is retried on the * `retry-backoff` curve; once `shouldRetry` is exhausted the loop stops * with `gave_up`, and a failure `config.retryable` refuses stops it at * once, spending no budget. A success resets the retry counter. * - **dedupe** — a step whose `callId` is already in `config.executed` is not * re-executed; its saved result is re-POSTed. Closes the "the host re-handed * the same step after a duplicate settle" path (the host side is idempotent; * the hands match it). That memory lives in `config.executed`. Left out, it * is a fresh in-memory store that lasts one drive, so hands that restart * forget it and run the re-handed step again; pass a store that outlives the * process to keep it across restarts. * - **store failure** — a `get` or `set` that throws or rejects ends the drive * with `gave_up` carrying the store's error. A failed `get` runs nothing. A * failed `set` means the step ran but is not remembered, and its result is * not POSTed, so a later drive over that store would run it again. * - **not-ready re-poll** — a {@link StepWorking} arm (a defer-resume host * computing the step out-of-band) is not a step: the loop re-POSTs the SAME * `posted` after a backoff (honoring the host's advisory `retryAfterMs`), * until a real step / done arrives. Bounded only by the absolute deadline — * an inline host never returns this arm, so its drive is unchanged. * * **Crash window:** a store gives "run once per `callId`" except between * `execute` finishing and `set` landing. Hands that die there have run the step * with no record of it, and the next drive runs it again. No store can close * that: the step itself has to be safe to repeat, as with `idempotentEffect`. * * **A machine:** the decisions above are {@link stepLoopMachine}, run by `run` * and driven to its end by `driveToDone`; the clock, the transport, the hands * and the sleep are its Cmds. {@link RunStepLoopConfig.attach} hands the caller * the runtime, so `recorder` records the drive and `replayTrace` replays it. * The machine's State carries the values the drive was handed, so these differ * from the loop this replaced: * * - **Frozen values (dev builds).** Where tea's dev checks run (`NODE_ENV` is * not `production`) the State is deep-frozen before each reducer step. The * result `execute` returned, a step's `input` once its result is posted, a * failure that is a plain object, and the `config.retry` object (the shared * `defaultRetryPolicy` from `retry-backoff`, process-wide, when you omit * it) are frozen in place, and a caller that mutates one throws a * `TypeError`: an `execute` that returns a shared object and changes it on * the next call rejects the drive, and so does pushing onto a returned * result after the drive. Return a fresh value. `done`'s `output` is not * frozen. A production build freezes nothing. * - **A bound.** A drive is one `dispatch`, which tea ends with * `QuiescenceTimeoutError` after 100,000 follow-up Msgs counted over the * whole drive: 3 for a step, 4 for a not-ready poll, and 3 more for each * failed POST that is retried, plus 3 for the start and the final answer. * That is about 33,000 steps, or 25,000 polls, or a mix. The loop this * replaced had no bound. * - **Stored recordings and non-finite numbers.** The machine decides on * exactly the numbers you pass, and the recorded `start` Msg carries them. * JSON has no `NaN` or `Infinity`, so a `deadlineMs` or a `retry` number * that is `NaN` or infinite replays from the dumped trace, but may not * replay from the text `toJSONL` wrote, which reads it back as `null` * (`maxAttempts` of `NaN` or `Infinity` does not; a `NaN` deadline and a * `NaN` `maxElapsedMs` happen to). The one exception is `deadlineMs: * Infinity`, which the machine already holds as `null`, "no deadline". * Write a policy with no limit as `unbounded: true`, not as an infinite * `maxAttempts` or `maxElapsedMs`. */ declare function runStepLoop(token: string, runId: string, transport: StepTransport, execute: ExecuteStep, config: RunStepLoopConfig): Promise>; /** * `@demlik/tea/do` — the durable-timer / alarm-carrier port (#180). * * Every native-DO grain that wants a wall-clock tick hand-rolls the SAME * eviction-safe pattern: compute the next absolute deadline off the live state, * push it to `ctx.storage.setAlarm`, and — when the DO `alarm()` lifecycle hook * fires — map that fire back to a Msg, then re-arm off the post-fire state. The * `raft/do.ts` election/heartbeat deadline does it (`rearmAlarm` + `onAlarm`), * and the vortex arena tick (`room.ts` `armTick` + `onTick`) replicates the * exact shape for the 18 Hz game clock. The two old `do_alarm`/`do_ws` Subs were * dropped (see `./index`'s historical note) because `toMachine` fixes the agent * machine's Sub type to `DeadlinesSub`, so they could never union into a grain's * Sub set — leaving the alarm re-arm a HOST concern with no first-class home. * * {@link durableTimer} is that home: a tiny, transport- and Msg-agnostic helper * that owns the three repeated responsibilities and nothing else — * * 1. **Compute-next-deadline → `setAlarm`.** {@link DurableTimer.rearm} calls * the injected {@link DurableTimerConfig.nextDeadline}, and arms the alarm * at the returned absolute epoch-ms target. * 2. **Idle-when-no-work.** `nextDeadline` returns `null` when there is nothing * to schedule (an empty room, a node with no pending election/heartbeat), * and `rearm` then arms NOTHING — the DO is allowed to go idle / hibernate * instead of spinning the alarm forever. Re-arming is a positive act gated * on real work, never an unconditional reschedule. * 3. **Fire → Msg → re-arm.** {@link DurableTimer.onAlarm} is the body the DO * `alarm()` hook calls: it runs the injected {@link DurableTimerConfig.onFire} * (the consumer dispatches its timer Msg there — a `Tick`, a re-derived * deadline Msg) and THEN re-arms off the now-advanced state. Re-arm always * follows the fire, so a still-active grain keeps ticking and an idle one * stops by construction. * * **Eviction-safe across hibernation.** A DO alarm is the one timer that * survives eviction (an isolate `setInterval` dies the moment the isolate * sleeps), so the same `durableTimer` re-armed on a cold wake resumes the * schedule that a never-evicted instance would have held. The recovery contract * is just: after the host rebuilds state (`store.load()` → `replay`), call * {@link DurableTimer.rearm} once — it recomputes `nextDeadline` off the * recovered state and re-arms (or idles) identically to the live path. The timer * holds no in-memory schedule of its own; the deadline is always a pure function * of the persisted state, which is what makes the cold-wake re-arm correct. * * **Dependency-injected / testable.** The alarm arrives as a {@link AlarmStorage} * port — the SAME minimal `setAlarm` slice `stepHost` already takes (a real * `DurableObjectStorage` satisfies it structurally; a test supplies a fake with * no live Workers runtime), mirroring how `event-sourced-store.ts` takes its * storage. `nextDeadline` and `onFire` are injected thunks, so the whole timer * unit-tests with a faked alarm + a faked clock and no `cloudflare:workers` * import. See `.patterns/tea-do/recovery.md` for the cold-wake replay contract * the re-arm rides on. */ /** * The construction inputs for {@link durableTimer} — the impure edges the grain * injects, kept out of the pure reducer exactly like raft/do's * `RaftGrainCtx`/room's `ArenaPorts`. */ interface DurableTimerConfig { /** * The DO alarm carrier. `setAlarm(atMs)` schedules the next fire at an * absolute epoch-ms target. A real `DurableObjectStorage` satisfies this * structurally; a test supplies a fake. Only `setAlarm` is read — never the * whole `DurableObjectStorage`. */ readonly alarm: AlarmStorage; /** * Compute the next absolute deadline (epoch ms) off the live state, or `null` * when there is no work to schedule. Returning `null` is the idle signal: * {@link DurableTimer.rearm} arms nothing and the DO is free to hibernate. * * Called fresh on every `rearm` (including the post-fire re-arm and the * cold-wake re-arm), so it MUST read live state / the injected clock each call * — that freshness is what keeps the schedule a pure function of the persisted * state and the re-arm eviction-safe. Examples: * - raft: `node.subs(state, now())[0]?.atMs ?? null` (election XOR heartbeat). * - vortex: `connectionCount() > 0 ? now() + TICK_INTERVAL_MS : null`. */ nextDeadline(): number | null | Promise; /** * Run the timer's effect when the alarm fires — the consumer dispatches its * timer Msg here (a `Tick`, a re-derived deadline Msg) and persists/broadcasts * as its grain requires. {@link DurableTimer.onAlarm} awaits this BEFORE it * re-arms, so the re-arm sees the post-fire state. */ onFire(): void | Promise; } /** * The activated durable timer. Two methods, both idempotent to call from the * host edge: * - {@link DurableTimer.rearm} — recompute + (re-)arm or idle. Call it once * after cold-wake recovery, and after any state transition that can change * whether/when the next deadline should fire. * - {@link DurableTimer.onAlarm} — the DO `alarm()` body: fire, then re-arm. */ interface DurableTimer { /** * Recompute {@link DurableTimerConfig.nextDeadline} off the live state and arm * the alarm at it — or, when it returns `null`, arm nothing (idle). Safe to * call repeatedly; arming the same absolute target twice is a harmless * overwrite on the DO alarm API. */ rearm(): Promise; /** * The body the DO `alarm()` lifecycle hook delegates to: run * {@link DurableTimerConfig.onFire}, then {@link DurableTimer.rearm} off the * post-fire state. A still-active grain keeps ticking; an idle one (its * `nextDeadline` now `null`) stops here. */ onAlarm(): Promise; } /** * Build a {@link DurableTimer} over an injected alarm carrier, a next-deadline * computation, and a fire handler. The returned timer owns the * compute-next-deadline → `setAlarm` → `alarm()` → fire → re-arm loop and holds * no schedule of its own (the deadline is always recomputed from live state), * which is what makes it eviction-safe across hibernation. */ declare function durableTimer(config: DurableTimerConfig): DurableTimer; /** Which format a log's cells are written in. */ type LogFormat = "messages" | "recording"; /** How a frame's evidence is stored. */ type EvidenceEncoding = StoredEvidence["encoding"]; /** A frame's evidence: the State after it and the Cmds it started. */ interface FrameEvidence { readonly state: unknown; /** `null` when the engine did not report the Cmds. */ readonly cmds: readonly unknown[] | null; } /** * Why a recording cell does not decode as a frame: its text is not a frame of * this format (`frame`), a delta's basis is missing (`basis`), or the evidence * does not rebuild, or fails its checksum (`checksum`). */ type FrameRefusal = "frame" | "basis" | "checksum"; /** A frame's evidence as stored, before it is rebuilt. */ type StoredEvidence = { readonly encoding: "full"; readonly state: string; readonly cmds: string | null; } | { readonly encoding: "delta"; readonly delta: string; }; /** * @demlik/tea/do — event-sourced persistence mode for a Durable Object actor. * * `doStore` (sibling, `./index`) is the DEFAULT and stays snapshot-only: it * writes the whole `S` blob to one cell on every transition and reads it back * on boot. That is byte-for-byte unchanged by this file. * * `doEventSourcedStore` is the OPT-IN alternative. Instead of (only) * checkpointing the latest state, it: * * 1. APPENDS each applied `Msg` to an append-only log in `DurableObjectStorage` * (one cell per event, monotonically keyed), from `store.save(state, msg)`. * The engine awaits that save before it starts the transition's Cmds, so * the event is durable before any effect runs: the log is write-ahead. An * activation lost inside a model call finds that call's input in the log. * 2. Takes a PERIODIC SNAPSHOT every `snapshotEvery` events (count-based * retention — mirrors Akka `RetentionCriteria.snapshotEvery`) so the log * that must replay on the next activation is bounded. The event, its meta * cell and the snapshot, when one is due, are written in ONE storage * transaction. A grain that needs replay bounded by ELAPSED TIME/TICKS * rather than raw event count drives `snapshotNow()` instead (or * alongside) — see that method. * 3. On activation REBUILDS state by FOLDING the log on top of the latest * snapshot. The fold starts directly from a snapshot; without one it * starts from fresh init. One reducer step per logged Msg follows, with * no Cmd handlers executed: **side effects are suppressed on replay** * (recovery.md). This is the same primitive `foldEvents` / the recorder * use; it is reused here, not reinvented (ADR 0003: "the fold already * exists; wire it to Store"). * * With `recording`, the store keeps evidence instead of bare Msgs. Each cell is a * frame: an `init` frame for every boot save and a `step` frame for every * applied Msg, each holding the State after it and the Cmds the engine started * for it (see `./recording-frames`). The recovery fold skips the `init` frames, * and `snapshotEvery` counts only Msgs, so a recording snapshots, restores and * reads (`doEventLogReader`) like the log of Msgs it contains. * * The "recovered/ready" signal (recovery.md `RecoveryCompleted`) is delivered * exactly once per activation via `onReady`, EVEN for a fresh actor with an * empty log, and is documented to be idempotent (it may fire again on a later * activation, so the handler must tolerate repeats). * * Integration with the cooperating DO: * * const es = doEventSourcedStore(storage, machine, ctx, { * snapshotEvery: 100, * parse, // optional boundary parse for the snapshot * onReady: (state) => { ... }, // optional, idempotent end-of-recovery hook * }); * const runtime = run(machine, { ctx, store: es.store }); * await runtime.ready; // store.load() has folded; onReady has fired once. * * Nothing else feeds the log: do not append from `runtime.observe`, which * fires after the Cmds, and do not append a Msg by hand before dispatching it, * which would record it twice. * * A time/tick-driven grain (e.g. one that derives simulation ticks between * sparse intents) bounds its cold-wake replay by ELAPSED TIME rather than event * count by calling `es.snapshotNow()` on its own cadence — every N derived ticks * or on a wall-clock interval — so a quiet span that never trips `snapshotEvery` * is still snapshotted before its replay tail grows unbounded (#190): * * // in the grain's tick loop, after the turn's dispatches have settled: * if (tick % SNAPSHOT_EVERY_TICKS === 0) await es.snapshotNow(); * * This is a legacy-replay store: it journals each APPLIED message after the * reducer ran and before its effects start, and recovers by folding the * reducer again. A `LoggedStore` (`logged: true`, ADR 0038) instead admits a * message before reduction and keeps committed State and owed deliveries, and * its recovery never runs a committed reducer again. Do not give one run both. */ /** JSON restore evidence retained until a load succeeds. Counts started attempts. */ interface RestoreAttempt { readonly attempts: number; } /** A previous restore did not finish and its automatic retry budget is spent. */ declare class RestoreInterruptedError extends Error { readonly attempts: number; readonly retryLimit: number; readonly name = "RestoreInterruptedError"; readonly _tag: "restore_interrupted"; constructor(attempts: number, retryLimit: number); } /** * How a log's events are decoded and where its cells live: the part of * {@link EventSourcedOptions} that {@link doEventLogReader} also takes. A * reader given the writing store's options finds and decodes the cells that * store wrote, so an `EventSourcedOptions` value is accepted as is. */ interface EventLogReaderOptions { /** * Boundary parse for a persisted EVENT (one logged `Msg`). Returns the `M` on * a recognized shape; returning `null` DROPS the event from replay (use for a * removed Msg variant). Must NOT throw. Default accepts any object carrying a * string `_tag` as `M`. */ readonly parseEvent?: (raw: unknown) => M | null; /** Cell-key overrides (rarely needed; for coexisting actors in one DO). */ readonly keys?: { readonly snapshot?: string; readonly meta?: string; readonly eventPrefix?: string; }; } /** * Options for {@link doEventSourcedStore}. */ interface EventSourcedOptions extends EventLogReaderOptions { /** * Take a snapshot every N appended events (count-based retention, mirrors * Akka `RetentionCriteria.snapshotEvery`). A snapshot bounds how many events * replay on the next activation — it never changes the fold's result, only * its length (recovery.md). Must be >= 1. Default 100. */ readonly snapshotEvery?: number; /** * Automatic retries after an unfinished restore. Default 1: an initial * attempt and one retry; a second unfinished attempt refuses before reading * the snapshot or journal. Must be a non-negative safe integer. A thrown * load also leaves an unfinished attempt. Only success clears the record. */ readonly restoreRetryLimit?: number; /** * Boundary parse for the persisted SNAPSHOT cell (the `S` blob). Returns `S` * on a recognized shape, `null` on an unrecognized one, and must NOT throw. * A present snapshot that returns `null` refuses restore; it never falls * back to replaying the full journal. Default accepts any non-null, * non-array object as `S`. */ readonly parse?: (raw: unknown) => S | null; /** * End-of-recovery hook (recovery.md `RecoveryCompleted`). Fires EXACTLY ONCE * per activation, after the fold completes, carrying the recovered state — * even when the log was empty (fresh actor). It may fire again on a later * activation, so it MUST be idempotent. Side effects that belong "once after * recovery" go here, never in the reducer (the reducer re-runs on every * replay). */ readonly onReady?: (state: S) => void; /** * Record each boundary's evidence. A log this store starts is written as a * recording: an `init` frame for every boot save, carrying `provenance`, and * a `step` frame for every applied Msg, each with the State after it and the * Cmds the engine started for it. A log already written as bare messages * keeps being written that way; its missing evidence is never invented. * A recording log is written as one whatever this option says, and gets no * `init` frame without it. */ readonly recording?: { /** JSON written into every `init` frame, unread by the store. */ readonly provenance: unknown; }; /** * Hears a recording whose last frames cannot be rebuilt, once per `load()`. * Evidence is not State: the Msgs and the snapshot rebuild the State exactly, * so restore still succeeds and the next frame is written whole, as a new * basis for the frames after it. This reports which frames are broken; a read * of them with `readFrames` still refuses them. Default: a `console.warn`. * A hook that throws is warned about and does not fail the restore. */ readonly onRecordingBreak?: (broken: RecordingBreak) => void; readonly keys?: EventLogReaderOptions["keys"] & { /** Restore-attempt cell. Default: `${meta}/restore-attempt`. */ readonly restoreAttempt?: string; }; } /** * One persisted log entry handed to a {@link EventSourcedStore.readEvents} * consumer: the monotonic `seq` the event was appended under, paired with the * decoded `event`. `seq` is the store's own append counter (the key the event * lives under), so it both orders the stream and bounds an {@link EventLogRange}. */ interface PersistedEvent { /** The append sequence number this event was logged under (1-based, gap-free). */ readonly seq: number; /** The decoded `Msg`, parsed through the store's `parseEvent` boundary. */ readonly event: M; } /** * Optional inclusive bounds for {@link EventSourcedStore.readEvents}. Both ends * are inclusive and match against the event's `seq`; omitting an end leaves it * unbounded. `{ fromSeq: 5, toSeq: 10 }` yields seqs 5..10; `{}` (or no * argument) yields the whole log. */ interface EventLogRange { /** Lowest `seq` to include (inclusive). Default: the first event. */ readonly fromSeq?: number; /** Highest `seq` to include (inclusive). Default: the last event. */ readonly toSeq?: number; } /** * The handle returned by {@link doEventSourcedStore}: a `Store` to hand to * `run(...)`, plus the snapshot and read surface the cooperating DO drives. */ interface EventSourcedStore { /** * The `Store` to pass as `run(machine, { ctx, store })`, and the only way * the log grows. Its `load()` performs the fold (snapshot + log replay). Its * `save(state, msg)` appends the applied `msg`, advances the meta cell and, * when `snapshotEvery` events have accumulated, writes the snapshot, all in * one storage transaction that settles before the engine starts the * transition's Cmds. A save without a Msg (the boot save, the flush at * `stop()`) appends nothing, except that the boot save of a recording * (`recording`) appends an `init` frame; a recording's frames are not Msgs, * so restore skips them. A write that fails rejects the save and leaves the * stored bytes as they were. `migrate` forwards to `parse`. * * Its `load()` also takes the log for this isolate. A store built earlier on * the same storage can no longer write: a `save` or `snapshotNow()` it called * before the later `load()` is refused with `StoreConflictError` at its write * point, whenever it gets there, so a stopped run's save that lands late never * overwrites what the later run saved. A save with no later `load()` behind it * still lands, whether or not its run was given up on. Every `load()` counts, * this store's own included, so a store a host hands to each run it rebuilds * is covered too. * * Loads on the same storage object and meta key are serialized, including * across handles. Before snapshot or journal reads, load persists a JSON * {@link RestoreAttempt}. Success clears it; failure leaves it. Once * `restoreRetryLimit` is spent, load throws {@link RestoreInterruptedError} * before expensive reads. The engine preserves it as StoreRefusedError.cause. */ readonly store: Store; /** * Take a snapshot NOW, independent of the count-based `snapshotEvery` trigger * (a time/tick-based retention trigger, #190). The count-based trigger bounds * the replay tail by raw EVENT COUNT; a grain that derives many state * transitions per logged event (e.g. simulation ticks between sparse intents) * needs the tail bounded by ELAPSED TIME instead — so it calls `snapshotNow()` * on its own cadence (every N derived ticks, or on a wall-clock interval) to * checkpoint the current folded state without injecting filler events purely * to advance the counter. * * It checkpoints the State of the highest event the store has durably * written, at that event's sequence, then advances the count-based baseline * (`snapshotEvery` counts afresh from here, so a manual snapshot defers the * next automatic one). * * Returns `true` if a snapshot was written, `false` on a no-op: nothing has * been applied yet (fresh actor), or no new event exists since the last * snapshot (already current). The State and the sequence it pairs move * together, only once an event is durable, so a transition whose save failed * is never checkpointed. Resolves once the snapshot is durably written. */ snapshotNow(): Promise; /** * Highest committed append sequence, or 0 for an empty log. Reads only meta * before load; after load/save it uses the acknowledged sequence in memory. * Consumers can resume readEvents at this sequence + 1 without scanning history. * Assumes this handle is the active writer, like save and snapshotNow. */ getCommittedSeq(): Promise; /** * Stream the persisted event log in `seq` order, optionally bounded by an * inclusive {@link EventLogRange}. This is the PUBLIC read side of the * event-sourced write model — the surface replay / projection / audit * consumers (CQRS reads, recovery.md / projections.md) read through, instead * of mirroring the store's private `@@es/evt/` key convention. * * The log is APPEND-ONLY and is never truncated by snapshotting (a snapshot * only bounds the *replay* tail, never the log), so this yields EVERY event * in range — including ones a snapshot already folds. Each entry carries its * `seq`, so a consumer can resume from a known offset (`{ fromSeq }`) or read * a window (`{ fromSeq, toSeq }`). An empty (or fully out-of-range) log yields * nothing. Events whose `parseEvent` returns `null` (a retired Msg variant) * are dropped, identical to the recovery fold. * Bounds are applied in storage queries, in pages of at most 128 rows. * * Read-only: it never appends, snapshots, or mutates store state, so streaming * the log can never perturb the live actor. */ readEvents(range?: EventLogRange): AsyncIterable>; } /** * What a log's head cells say: the highest committed append sequence (0 when * no event was committed) and whether a snapshot cell is present. */ interface EventLogHead { readonly lastSeq: number; readonly snapshot: boolean; /** The format of the log's first cell, or `null` when it has none. */ readonly format: LogFormat | null; } /** * An {@link EventLogRange} with an optional cap on how many stored cells are * read. `limit` counts every cell in range, refused ones included. */ interface StoredEventRange extends EventLogRange { readonly limit?: number; } /** * Why a stored event cell did not decode: its value is not text (`not-text`), * its key carries no integer sequence (`key`), its text is not JSON (`json`), * `parseEvent` returned `null` (`event`), or it is a recording cell that does * not decode as a frame, lacks the frame its delta needs, or fails its checksum * ({@link FrameRefusal}). */ type StoredEventRefusal = "not-text" | "key" | "json" | "event" | FrameRefusal; /** * One stored event cell as read, decoded or refused. `serializedBytes` is the * UTF-8 size of the stored text (0 when the value is not text); for a step * frame of a recording it is the size of the Msg JSON inside it. */ type StoredEvent = { readonly _tag: "decoded"; readonly key: string; readonly seq: number; readonly serializedBytes: number; readonly event: M; } | { readonly _tag: "refused"; readonly key: string; readonly seq: number | null; readonly serializedBytes: number; readonly reason: StoredEventRefusal; readonly cause?: unknown; }; /** * One stored cell read as a frame of the log. A `message` is a cell of a log * written as bare messages, with no evidence. An `init` or `step` frame is a * recording frame; its `evidence` is rebuilt only when the read asked for it. * `serializedBytes` is the UTF-8 size of the whole stored text and * `messageBytes` the size of the Msg JSON inside it. */ type StoredFrame = { readonly _tag: "message"; readonly key: string; readonly seq: number; readonly serializedBytes: number; readonly messageBytes: number; readonly event: M; } | { readonly _tag: "step"; readonly key: string; readonly seq: number; readonly serializedBytes: number; readonly messageBytes: number; readonly event: M; readonly encoding: EvidenceEncoding; readonly evidence?: FrameEvidence; } | { readonly _tag: "init"; readonly key: string; readonly seq: number; readonly serializedBytes: number; readonly restored: boolean; readonly provenance: unknown; readonly encoding: EvidenceEncoding; readonly evidence?: FrameEvidence; } | Extract, { _tag: "refused"; }>; /** * A recording whose evidence cannot be rebuilt where the next frame would take * its delta from. Frames `fromSeq` to `toSeq` (the log's last) are the ones that * depend on the first frame that does not rebuild, and `reason` is the refusal * {@link EventLogReader.readFrames} gives that frame. */ interface RecordingBreak { readonly fromSeq: number; readonly toSeq: number; readonly reason: FrameRefusal; } /** Options for {@link EventLogReader.readFrames}. */ interface FrameReadOptions { /** * Rebuild each recording frame's evidence. `"verify"` rebuilds and checks * it, refusing a frame that does not rebuild, but yields no evidence. * Default `false`. */ readonly evidence?: boolean | "verify"; /** Read the range from its highest `seq` down. Evidence is not rebuilt. */ readonly reverse?: boolean; } /** * A read-only view over a durable agent's event log, built by * {@link doEventLogReader}. Every call reads storage afresh; none writes a * cell, sets an alarm, or loads the agent. */ interface EventLogReader { /** The log's head, or `null` when neither meta nor snapshot cell exists. */ readHead(): Promise; /** Highest committed append sequence from the meta cell, or 0 when absent. */ readCommittedSeq(): Promise; /** * Every stored event cell in range, in `seq` order, with refusals reported * instead of thrown. Read in pages of at most 128 rows. */ readStoredEvents(range?: StoredEventRange): AsyncIterable>; /** * Decoded events in range, in `seq` order, exactly as the store's * {@link EventSourcedStore.readEvents}: events `parseEvent` refuses are * dropped, and text that is not JSON throws. */ readEvents(range?: EventLogRange): AsyncIterable>; /** * Every stored cell in range as a {@link StoredFrame}, in `seq` order, with * refusals reported instead of thrown. With `evidence`, each recording * frame's State and Cmds are rebuilt; a delta whose basis is missing or whose * checksum fails is refused. Only the current basis is held, and the frames * before the range that a delta needs are read in one bounded page. */ readFrames(range?: StoredEventRange, options?: FrameReadOptions): AsyncIterable>; } /** * Read a durable agent's event log without waking it. * * A host holding the agent's `DurableObjectStorage` reads the log's head, its * committed sequence and its events in a range. The reader never writes * storage, never runs a restore or a fold, and sets no alarm. Every call reads * the cells afresh (`noCache`), and events are listed in bounded pages. * * Cells the store cannot write — a value that is not a string, or a key whose * suffix is not an integer sequence — are skipped by `readEvents` and reported * as refused by `readStoredEvents`. */ declare function doEventLogReader(storage: DurableObjectStorage, opts?: EventLogReaderOptions): EventLogReader; /** * Build an event-sourced `Store` over `DurableObjectStorage`. * * The substrate calls `store.load()` once at boot — that is where the fold * happens — and `store.save(state, msg)` after every transition, before that * transition's Cmds start — that is where the event is appended and the * count-based snapshot is taken. No other call grows the log. * * Snapshot recovery folds update directly from the captured State; it does * not initialize that State again. With no snapshot, `ctx` supplies the fresh * init used to establish the event log's starting State. Live resume commands * belong to the runtime's subsequent init over the recovered State. */ declare function doEventSourcedStore(storage: DurableObjectStorage, machine: Machine, ctx: Ctx, opts?: EventSourcedOptions): EventSourcedStore; /** * @demlik/tea/do — CQRS projections as a first-class seam. * * TODAY (`./host`), "Model → views" is ad-hoc: `sseHub` is a hand-rolled * sink-set fanning `runtime.observe` events out. It re-derives a common shape: * subscribe to `observe`, fold each update into a private view, push the view * at a sink. (The run's terminal output was once another such observe-driven * read model — `captureLastTurn` — but that is now modelled first-class on the * write model itself as `state.output` / `runtime.result()`, #46.) * * This file names that shape. A `Projection` is the canon's * "one write model, many projections" contract made concrete on the tea * substrate (`.patterns/tea-do/projections.md`): * * 1. ONE WRITE MODEL, MANY PROJECTIONS. The write model is the agent's `run()` * State (`Model`) plus its `Msg` stream. Each projection is an INDEPENDENT * `(events|Model) → view` derivation into its OWN read model, with its own * id-scoped offset. Adding a projection never touches the write model or * any other projection — it only registers another consumer of `observe`. * * 2. OFFSET-RESUME + IDEMPOTENT APPLY ARE ONE UNIT. A durable projection * tracks an EXCLUSIVE offset — the last applied position. On restart it * resumes STRICTLY AFTER the stored offset (never ±1); at-least-once * delivery means the same update may be re-presented, so `apply` must be * idempotent (an upsert of the derived view, never a blind increment). * WHEN the offset is committed relative to the view write IS the delivery * semantic (`.patterns/tea-do/delivery-semantics.md`): * - commit AFTER the view write → at-least-once (may reprocess) * - commit in the SAME step → exactly-once (the default here) * We persist offset-with-view as one unit (a single `OffsetView` cell), so * a durable projection is exactly-once by construction; the at-least-once * replay window is still exercised because `drive()` may re-present an * update at/below the stored offset (boot reconcile, double-observe), and * the exclusive-offset guard makes that a no-op. * * 3. A VIEW IS ALWAYS REBUILDABLE. Clearing the view and resetting the offset * to the start (`rebuild`) replays the `Msg`/`Model` stream from zero. The * live view and the rebuilt view are equal by construction — both are the * same pure `apply` fold over the same ordered updates. * * Relationship to `./host`: `sseHub` is re-expressed here as ONE projection * (`sseProjection`) WITHOUT changing its public API — `host.sseHub()` keeps * working for existing callers (it is the volatile, offset-free case: a live * SSE stream has no durable read model to resume). * * Relationship to `./event-sourced-store`: a durable projection resumes over * the SAME append-only event log `doEventSourcedStore` (#68) writes. The fold * is the projection's `apply`, scoped to the projection's offset — independent * of the write model's snapshot/replay. This file does NOT import the store; it * is offset-shaped so a consumer can wire either the live `observe` stream or a * replay over the log into the same `apply`. */ /** A projection's identity: `name` (the view) + `key` (the instance). */ interface ProjectionId { readonly name: string; readonly key: string; } /** Render a `ProjectionId` to its canonical `name-key` string. */ declare function projectionIdString(id: ProjectionId): string; /** Context handed to a {@link ProjectionOnError} sink alongside the throw. */ interface ProjectionErrorContext { /** The id of the projection whose `apply`/`emit` threw. */ readonly id: ProjectionId; } /** * Sink for a projection `apply`/`emit` throw the driver isolated. Injected into * {@link projectionRegistry}; called with the original error and the id of the * failing projection so a broken projection surfaces instead of being silently * discarded (errors-are-data). Should be total. */ type ProjectionOnError = (error: unknown, context: ProjectionErrorContext) => void; /** * One unit the projection driver presents to a projection's `apply`. Mirrors * the `(msg, model)` pair `runtime.observe` fans out, plus the exclusive * `offset` the driver assigns. `msg === null` is the boot update (no event). */ interface ProjectionUpdate { /** The applied event, or `null` on the boot update (initial state). */ readonly msg: Msg | null; /** The post-transition write-model state. */ readonly model: Model; /** * The exclusive position of this update in the ordered stream — monotonic, * 1-based; 0 is the boot update (the `NoOffset` start). The stored offset is * EXCLUSIVE: re-presenting an update whose offset is `<=` the stored offset * must be a no-op (the at-least-once replay window). Do NOT ±1 it. */ readonly offset: number; } /** * A named CQRS projection: an independent fold of the write model's * `(Msg|Model)` stream into a private `View`, plus a sink to publish it. * * @typeParam Model The write-model state (`run()`'s `S`). * @typeParam Msg The write-model event (`run()`'s `M`). * @typeParam View The read model this projection derives. */ interface Projection { /** This projection's id (offset-isolation unit). */ readonly id: ProjectionId; /** The seed view for a fresh or rebuilt run (the `NoOffset` start). */ readonly initial: View; /** * The per-envelope reducer: derive the next view from the previous view and * one update. Pure; MUST be idempotent — re-applying an update at the same * offset yields the same view (upsert the derived value, never a blind * increment). Returning the SAME view reference (or an equal one) for an * update the view does not care about is the canonical "skip". */ apply(view: View, update: ProjectionUpdate): View; /** * The sink — publish the derived view. SSE frame, durable cell, report row. * Fired by the driver after `apply` produces a new view. A throwing `emit` is * isolated by the driver (it must not strand sibling projections). */ emit(view: View): void; } /** * A live, running projection instance: the projection's current `View`, its * exclusive stored `offset`, and the `present`/`reset` operations the driver * (or a rebuild) calls. */ interface ProjectionRunner { readonly id: ProjectionId; /** The current derived view (the read model). */ view(): View; /** * The exclusive stored offset — the position of the LAST applied update. * Resume reads strictly after this; `0` is the `NoOffset` start. */ offset(): number; /** * Present one update to the projection. At-least-once entry point: * - if `update.offset <= storedOffset` the update was already applied → * NO-OP (idempotent replay window; offset stays, view stays, no emit). * - otherwise fold via `apply`, advance the offset TO `update.offset`, and * `emit` the new view. Offset-and-view advance together (one unit) → * exactly-once: the stored offset always matches the folded view. * Returns true iff the update was applied (false on the no-op replay). */ present(update: ProjectionUpdate): boolean; /** * Clear the view to `initial` and the offset to 0 — the canonical rebuild * reset (offset-tracking.md: "resetting it to NoOffset is the view-rebuild * operation"). After `reset`, re-presenting the full stream rebuilds the view. */ reset(): void; } /** * Build a {@link ProjectionRunner} for a projection, starting from a stored * offset (default 0 = `NoOffset`, a fresh run). The view is seeded to * `projection.initial`; the caller resumes by presenting updates strictly after * `startOffset` (the driver's offset guard enforces exclusivity even if an * already-applied update is re-presented). * * The runner never emits the seed: a fresh runner holds `initial` but does not * push it at the sink until the first real update lands (an SSE client that just * connected wants the next event, not a replay of the seed), and `reset()` * likewise re-seeds `view`/`offset` silently — `emit` fires only from `present` * when a strictly-newer update is folded. */ declare function runProjection(projection: Projection, startOffset?: number): ProjectionRunner; /** * A driver over a set of projections sharing one write-model stream. Holds the * monotonic offset counter; presents each observed update to every registered * runner independently. */ interface ProjectionRegistry { /** Register a projection; returns its live runner. */ register(projection: Projection, startOffset?: number): ProjectionRunner; /** * Present one update to EVERY registered runner. Each folds independently; an * `apply`/`emit` throw in one runner is caught so it cannot strand the others * (errors-are-data: a broken projection is dropped from THIS update, not * allowed to corrupt siblings) and routed to the registry's `onError` sink so * it surfaces rather than vanishing. Returns the offset assigned to this update. */ dispatch(msg: Msg | null, model: Model): number; /** The current monotonic offset (the last dispatched update's position). */ offset(): number; /** The registered runners (introspection / tests). */ runners(): readonly ProjectionRunner[]; } /** * Build an empty {@link ProjectionRegistry}. Pass an `onError` sink to receive * any `apply`/`emit` throw the driver isolates — without it a broken projection * is still isolated from its siblings, but its failure is not surfaced (the * substrate's `run(machine, { onError })` is the natural source to forward). */ declare function projectionRegistry(onError?: ProjectionOnError): ProjectionRegistry; /** * Wire a {@link ProjectionRegistry} to a runtime's transition stream. The boot * update (the initial state, offset 0) is presented via `onBoot`; every applied * transition (offset 1, 2, …) via `observe` — together they reproduce the * "every transition including boot" stream the single `observe(msg | null)` * channel used to carry, now that `observe`'s `msg` is total (#47). The registry * still assigns its monotonic exclusive offset (boot → 0, first Msg → 1). * Returns a cleanup that detaches both subscriptions. * * Typed structurally against `{ observe, onBoot }` so it accepts any * `Runtime` without importing the substrate's `Runtime` (types-only * boundary). */ declare function driveProjections(registry: ProjectionRegistry, runtime: { observe(observer: (msg: Msg, model: Model) => void): () => void; onBoot(handler: (model: Model) => void): () => void; }): () => void; /** * Rebuild a projection's view by folding an ordered event stream from the * `NoOffset` start. The runner is seeded to `projection.initial` (the implicit * boot / `NoOffset` state), then each `updates[i]` is presented at offset * `i + 1` — so the FIRST event (`updates[0]`) lands at offset 1 and is folded, * exactly mirroring the live driver, which assigns the first applied `Msg` * offset 1 (the boot observe is offset 0 and never enters this list). Returns * the rebuilt runner whose `view()` equals the live runner's view for the same * ordered stream. * * Pass the ordered events only; do NOT prepend a boot (`msg === null`) entry. * With the `i + 1` offsets a leading boot entry would be applied at offset 1 * like any event (the seed already covers the `NoOffset` start), not skipped — * the offset-0 skip that drops the boot is the live driver's, not this fold's. * * This is the rebuild-equivalence oracle: a view cleared and replayed from the * stream equals the live view. */ declare function rebuildProjection(projection: Projection, updates: readonly { readonly msg: Msg | null; readonly model: Model; }[]): ProjectionRunner; /** * The runtime→SSE plumbing — the hub, its projection expression, and the * semantic-event adapter. See `./host` for the transport-model rationale. */ /** * A set of SSE sinks plus the plumbing to fan an event out to all of them and * to open a `text/event-stream` Response wired to a fresh sink. * * The consumer: * 1. holds one `SseHub` per DO, * 2. calls `hub.emit(event)` from its Msg→event mapping (driven off * `runtime.observe`), and * 3. returns `hub.open()` from the `/sse` route. * * `register(sink)` exists for tests: subscribe a sink directly and observe the * exact event sequence a live client would receive (a live `text/event-stream` * fights vitest-pool-workers teardown). Deletes the consumer's `sseSinks` set, * `openSse`, `emitSse`, and `onSseEvent`. */ interface SseHub { emit(event: E): void; open(): Response; register(sink: (event: E) => void): () => void; } /** Build an SSE hub for event type `E` (the consumer's domain event shape). */ declare function sseHub(): SseHub; /** * Express an {@link SseHub} as a {@link Projection}. The projection's view is * the latest emitted SSE event (or `null` before the first); `apply` maps each * write-model update to an event via `toEvent` and emits it through `hub.emit`, * so the SSE stream is driven by the SAME hub `sseHub()` returns — no API * change for the `/sse` route (`hub.open()`) or any existing caller. * * - `toEvent(msg, model)` returns the SSE event for this update, or `null` to * skip it (the view stays, nothing is emitted). * - `name`/`key` default to `"sse"`/`"main"`; override for a second SSE view. * * @example * ```ts * import type { Runtime } from "@demlik/tea"; * import { * driveProjections, * projectionRegistry, * sseHub, * sseProjection, * } from "@demlik/tea/do"; * * type MyState = { readonly turns: number }; * type MyMsg = { _tag: "turn_done"; turn: number } | { _tag: "tick" }; * type MyEvent = { kind: "turn"; turn: number }; * declare const runtime: Runtime; * * const hub = sseHub(); * const registry = projectionRegistry(); * registry.register(sseProjection(hub, (msg: MyMsg | null) => * msg?._tag === "turn_done" ? { kind: "turn", turn: msg.turn } : null, * )); * driveProjections(registry, runtime); // SSE is now one projection * // /sse route unchanged: * const sseRoute = (): Response => hub.open(); * ``` */ declare function sseProjection(hub: SseHub, toEvent: (msg: Msg | null, model: Model) => E | null, id?: { name?: string; key?: string; }): Projection; /** * Wire an {@link SseHub} to a runtime's semantic {@link AgentEvent} stream. * For each event `_tag` the runtime can emit, subscribes via `runtime.on` and * pushes `toFrame(event)` at the hub (returning `null` skips that event). The * runtime MUST have been built with `run(machine, { events: agentEvents() })`, * which is what makes `on` deliver the `AgentEvent`s. Returns a cleanup that * detaches every subscription. * * This is the runtime→SSE adapter expressed over the typed event channel: no * `observe` firehose, no private-Msg coupling. `hub.open()` and every existing * `sseHub` caller are unchanged — only the SOURCE of `hub.emit` moves from a * hand-rolled Msg switch to `on`. * * @example * ```ts * import type { Runtime } from "@demlik/tea"; * import type { AgentEndedStatus, AgentEvent } from "@demlik/tea/agent"; * import { sseFromAgentEvents, sseHub } from "@demlik/tea/do"; * * type MyFrame = { kind: "ended"; status: AgentEndedStatus }; * // Built with `run(machine, { ctx, events: agentEvents() }).ready`. * declare const runtime: Runtime>; * * const hub = sseHub(); * const off = sseFromAgentEvents(runtime, hub, (e) => * e._tag === "RunDone" ? { kind: "ended", status: e.status } : null, * ); * // /sse route unchanged: * const sseRoute = (): Response => hub.open(); * ``` */ declare function sseFromAgentEvents(runtime: { on["_tag"]>(type: K, handler: (event: Extract, { _tag: K; }>) => void): () => void; }, hub: SseHub, toFrame: (event: AgentEvent) => Frame | null): () => void; /** * `createAgentHost` — the runtime+events+autoBoot assembly + the test seam, * ONCE (issue #53). The facade over the concern modules: the deferred gateway * (`./deferred-gateway`), the WS carrier (`./command-socket`), the SSE plumbing * (`./sse`), and the cold-wake resume (`./resume`). See `./host` for the * transport-model rationale. */ /** * What the consumer supplies to {@link createAgentHost} — the domain mappings, * nothing of the wiring. `Stage`/`P`/`O`/`R` are the agent slice's type * parameters (the consumer names them once); `Frame` is its SSE event shape. * `C`/`U`/`Ctx` are the machine's own Cmd/Sub/Ctx — inferred from * `buildMachine` at the `createAgentHost` call site (never name them by hand; * an erased `any` here cost consumers all checking on this layer — #278). * * `M` carries the machine's message union, including registered tools' settle * messages. The wired machine must accept `AgentMachineMsg | M`, * so the host can always send the agent protocol. It defaults to that protocol. * * `store` is required, and a fenced one needs an `onError` (see * {@link StoreAndOnError}). */ type AgentHostConfig, R, Frame, C extends Cmd = Cmd, U extends Sub = Sub, Ctx = unknown, M extends Tagged = AgentMachineMsg> = AgentHostWiring & StoreAndOnError> & { /** The durable `Store` for the agent slice (typically `doStore(storage, parse)`). */ readonly store: Store>; }; /** The part of {@link AgentHostConfig} that is not the store and its sink. */ interface AgentHostWiring, R, Frame, C extends Cmd = Cmd, U extends Sub = Sub, Ctx = unknown, M extends Tagged = AgentMachineMsg> { /** * The engine's `run` — `run` from `@demlik/tea/promise`, or any engine's. The * host imports no engine; it boots the machine through this. `NoInfer` keeps * the generic engine from widening the messages inferred from `buildMachine`. */ readonly run: EngineRun, AgentMachineMsg | NoInfer, C, U, Ctx, AgentEvent>; /** * Build the wired agent machine and the handlers it runs under — its * `interpret` table and `subscribe` runners (a machine carries none — #278, * #279). Called once per host build (per activation), AFTER the previous * runtime — if any — was torn down. The consumer wires its per-tool interpret * here, and `agent.toMachine({ toolInterpret })` already returns exactly this. */ readonly buildMachine: () => Wired, AgentMachineMsg | M, C, U, Ctx>; /** The plain Ctx the machine threads to its interpret cells. */ readonly ctx: Ctx; /** * The run-terminality predicate (#46) — what makes `result()` first-class. * Defaults to the agent's own terminal phases (`done` / `failed`). */ readonly terminal?: (state: AgentState) => boolean; /** * Map one semantic {@link AgentEvent} to the consumer's SSE frame, or `null` * to skip it. This is the ONLY place the consumer touches the SSE seam — the * host owns the subscription wiring (`sseFromAgentEvents`) and the hub. */ readonly toSseFrame: (event: AgentEvent) => Frame | null; /** Clock injected for `autoBoot` (the host's only boot clock read). */ readonly now?: () => number; } /** * The assembled host: the runtime handle + the SSE hub + the framework test seam, * owned ONCE. A DO holds one `AgentHost` and delegates to it; its own surface * shrinks to the domain (the gateway, the WS bridge, the command-send mapping). * * @typeParam Stage Pipeline stage type. * @typeParam P Brain-call purposes. * @typeParam O Per-purpose outputs (bound to {@link AgentTurn}). * @typeParam R Tool result type. * @typeParam Frame The consumer's SSE event shape. * @typeParam M The machine's messages, combined with the required agent protocol. */ interface AgentHost, R, Frame, M extends Tagged = AgentMachineMsg> { /** * Get (or build) the booted runtime. Build-once-boot-once: the first call * builds the machine, wires SSE off the semantic event stream, awaits the boot * gate, dispatches `agent_boot` for a rehydrated running or suspended run (one * that was waiting on its model call, its compaction or its tools), and caches * the booted handle; subsequent calls return the cached handle. The single * assembly every consumer used to hand-roll in `getRuntime()`. * * The call resolves once `agent_boot` is queued, not when the work it * re-fired is done. That work can wait on a tool whose result a driver has not * posted yet, and the driver reaches the run through this call, so waiting for * it would deadlock. Read how far the run got from `getState()`, `subscribe` or * `status()`. * * @throws {HostOverlapError} While a `reset()` is still stopping the run. */ runtime(): Promise, AgentMachineMsg | M, AgentEvent>>; /** * The agent's lifecycle status (#49) — the ONE typed channel a consumer reads * instead of re-deriving `run.phase` / `awaiting` by hand. Ensures the runtime * is built + boot-reconciled first. Replaces the per-consumer `isSuspended` / * `runPhase` test methods (read `status().kind`: `idle` / `running` / * `suspended` / `done` / `failed`). A hydrated DO that has not yet seen * `agent_start` reads `idle`, not `running` (#92). */ status(): Promise>; /** * The run's terminal State (#46), or `undefined` while in flight. Read the * run's product off it (e.g. `result()?.output`). Replaces the per-consumer * `verdict` plumbing's source. Ensures the runtime is built first. */ result(): Promise | undefined>; /** * The SSE hub — the route (`host.sse.open()`) AND the test seam * (`host.sse.register(sink)`). The host drives `hub.emit` off the semantic * event stream; the consumer never touches it except to open / register. */ readonly sse: SseHub; /** * Tear down the cached runtime (drain its tail via `stop()`, up to * `disposeTimeoutMs`, then drop the handle) so the next `runtime()` rebuilds * from storage. A Cmd handler that has not returned by the limit is given up * on, so `reset()` returns either way, including while the run is waiting on a * tool nobody has answered. It stops the handle the host holds from the moment * `run` returned it, so it also stops a build that has not finished booting: * that build dispatches nothing more, and a `runtime()` still waiting on it * rejects with a `DispatchDiscardedError`. * * The framework `settle` test seam, owned once: a test and lifecycle seam for * one caller at a time, not the way to stop a run in production. Give `run` * a `cancellation` signal and abort it for that, and await a `reset()` before * the next `reset()` or `runtime()`. * * @throws {HostOverlapError} A `reset()` while another `reset()` is still * stopping the run, or from inside `run()`, and a `runtime()` while a * `reset()` is still stopping the run. */ reset(): Promise; } /** * Build an {@link AgentHost} from the consumer's domain mappings. Owns the * runtime+events+autoBoot assembly and the framework test seam — the wiring * issue #53 had every consumer re-write. * * @example * ```ts * import type { Interpret, Migrated } from "@demlik/tea"; * import type { * AgentKnob, * AgentMachineMsg, * AgentState, * AgentTurn, * ToolCall, * } from "@demlik/tea/agent"; * import { createAgentHost, doStore } from "@demlik/tea/do"; * import { run } from "@demlik/tea/promise"; * * type Stage = "plan" | "act"; * type Purpose = "plan_turn" | "act_turn"; * type Outputs = Record; * type ClientResult = string; * type ToolCmd = { readonly _tag: "run_tool" } & ToolCall; * type SseEvent = * | { kind: "result"; callId: string; result: ClientResult } * | { kind: "verdict"; verdict: string } * | { kind: "phase"; phase: string }; * interface Ctx { readonly apiKey: string } * type S = AgentState; * * // From `createAgent(...)`, and the interpret for its tool Cmd. * declare const agent: AgentKnob; * declare const toolInterpret: Interpret, ToolCmd, Ctx>; * declare const storage: DurableObjectStorage; * declare const parse: (raw: unknown) => Migrated; * declare const ctx: Ctx; * * const host = createAgentHost({ * run, * buildMachine: () => agent.toMachine({ toolInterpret }), * store: doStore(storage, parse), * ctx, * toSseFrame: (e): SseEvent | null => * e._tag === "ToolSettled" ? { kind: "result", callId: e.callId, result: e.result } : * e._tag === "TurnSettled" && e.turn.toolCalls.length === 0 * ? { kind: "verdict", verdict: e.turn.content } : * e._tag === "RunDone" ? { kind: "phase", phase: e.status.kind } : null, * }); * // route: * const sseRoute = (): Response => host.sse.open(); * // start: * await (await host.runtime()).dispatch({ _tag: "agent_start", runId: "run-1", at: Date.now() }); * // test: * const suspended = (await host.status()).kind === "suspended"; * ``` */ declare function createAgentHost, R, Frame, C extends Cmd = Cmd, U extends Sub = Sub, Ctx = unknown, M extends Tagged = AgentMachineMsg>(config: AgentHostConfig): AgentHost; /** * The command-runner WebSocket host + broadcast — the WS half of the * `@demlik/tea/do` transport, in both the resident (`acceptCommandSocket`) and * hibernation-aware (`acceptDurableCommandSocket`) forms. See `./host` for the * transport-model rationale (ONE Sub type, gateway-bridged I/O). */ /** * Accept a command-runner WebSocket on the DO's `fetch`. Adds the server end to * `clients`, wires `message` → `onFrame(data)` (string frames only) and * `close` → deregister, and returns the 101 upgrade Response. * * The consumer's `onFrame` parses the frame and calls `gateway.settle(callId, * result)` — the inbound bridge. Deletes the consumer's `acceptClient` method. */ declare function acceptCommandSocket(clients: Set, onFrame: (data: string) => void): Response; /** * Broadcast a JSON frame to every connected command-runner socket. A dead * socket is skipped (dropped on its own `close` event). Lifts the consumer's * fan-out loop in `sendCommand`. * * Thin delegation to {@link broadcastFrame} — the general fan-out (serialize * once, send to every OPEN socket, skip a closed/errored one). The * {@link BroadcastReport} it returns is discarded here to keep the `void` * command-socket signature. */ declare function broadcast(clients: Set, frame: unknown): void; /** * The slice of `DurableObjectState` the durable carrier needs: the Hibernation * API accept + the registry of hibernatable sockets. A real `DurableObjectState` * satisfies this structurally; a test supplies a fake (no live Workers runtime * needed to exercise the accept/registry seam). */ interface HibernatableCtx { acceptWebSocket(ws: WebSocket): void; getWebSockets(): WebSocket[]; } /** * Accept a command-runner WebSocket using the Cloudflare **Hibernation API** so * the socket survives DO eviction. Unlike {@link acceptCommandSocket}, this does * NOT attach an isolate-resident `message` listener (that listener is what dies * on eviction) — instead `ctx.acceptWebSocket(server)` hands the socket to the * runtime, which re-creates the DO and calls its `webSocketMessage(ws, data)` * lifecycle method on the next inbound frame. The consumer routes that method to * its `onFrame` (which calls `carrier.settle(callId, result)`). * * Returns the 101 upgrade Response. There is no `clients` registry to keep — the * live sockets are `ctx.getWebSockets()` (see {@link broadcastHibernatable}), * which the runtime repopulates after a wake. */ declare function acceptDurableCommandSocket(ctx: HibernatableCtx): Response; /** * Broadcast a JSON frame to every hibernatable command-runner socket. The live * set is read from `ctx.getWebSockets()` (the runtime repopulates it after a * wake), NOT a resident `Set` — so it is correct immediately after an * eviction, before any other lifecycle method has run. A dead socket is skipped. * * Thin delegation to {@link broadcastFrame} over `ctx.getWebSockets()` — the * general fan-out (serialize once, send to every OPEN socket, skip a * closed/errored one). The {@link BroadcastReport} it returns is discarded here * to keep the `void` command-socket signature. */ declare function broadcastHibernatable(ctx: HibernatableCtx, frame: unknown): void; /** * The deferred-tool gateway + its durable wrappers — the Promise-owning half of * the `@demlik/tea/do` transport. See `./host` for the transport-model * rationale (ONE Sub type, gateway-bridged I/O). */ /** * The deferred-tool gateway. `R` is the consumer's tool-result type (what * `agent_tool_ok` carries). * * - `await(callId, send, deadlineMs)` — register the round-trip, fire `send`, * return the Promise the reply (or the deadline) settles. Idempotent per * `callId`: a second call for an in-flight id returns the SAME promise * without re-firing `send` (the boot-reconcile re-fire is a no-op at the * gateway, mirroring the agent's idempotent boot). * - `settle(callId, result)` — the transport calls this on a reply; resolves * the awaited promise. A settle for an unknown / already-settled id is a * no-op (the callId guard the consumer used to keep in its pending Map). * - `fail(callId, reason)` — settle the round-trip as an error on demand * (e.g. a transport-level close). Same unknown-id no-op. * - `inFlight()` — the callIds with an open round-trip (tests / introspection). * * The deadline → reject path is what makes "timeout is data": the tool cell's * `catch` maps the rejection to `agent_tool_err`, recorded on the conversation, * never a hang. */ interface DeferredGateway { await(callId: string, send: () => void, deadlineMs: number): Promise; settle(callId: string, result: R): void; fail(callId: string, reason: string): void; inFlight(): readonly string[]; } /** * Build a deferred-tool gateway. No clock / RNG captured at construction — the * deadline is per-call (`await(..., deadlineMs)`), so one gateway serves every * tool family with its own timeout. * * Deletes from the consumer: the `pending` Map, the `Pending` interface, the * `awaitClient` method, the `forceTimeout` plumbing, and the `deliverResult` * callId-guard body — all of it collapses to this object plus the tool cell's * `await` + try/catch. */ declare function deferredGateway(): DeferredGateway; /** A `callId`-keyed durable round-trip: maps the gateway's string id to the * ledger's monotonic delivery id so a `settle(callId)` finds the owed entry. */ interface DurableDeferredGateway extends DeferredGateway { /** The ledger recorder this gateway feeds (for `surviving()` on activation). */ readonly recorder: PendingEffectsRecorder<{ callId: string; }>; } /** * Wrap a `DeferredGateway` so every round-trip is also recorded in a durable * `PendingEffectsRecorder`. The in-memory gateway is the fast path; the recorder * is the durability slice. * * - `recordOwed(callId, event)` — fires from `await`, BEFORE `send`, carrying * the `effect_owed` event the consumer must persist (then deliver). * - `recordConfirmed(callId, event)` — fires from `settle`/`fail` for a known * id, carrying the `effect_confirmed` event to persist. * - `reissue(callId, send, deadlineMs)` — re-arm a surviving round-trip on * activation. Idempotent: the gateway's own `await` returns the open promise * without re-firing `send` for an in-flight `callId`, so re-issuing an id * that is somehow still pending is a no-op (mirrors the boot-reconcile * re-fire). The effect is already owed, so no second `effect_owed` is * recorded. * * The effect payload the ledger stores is the `callId` (the correlation key the * consumer round-trips); the consumer maps it back to its tool-call context. */ declare function durableDeferredGateway(inner: DeferredGateway, recorder: PendingEffectsRecorder<{ callId: string; }>, hooks: { recordOwed(callId: string, event: EffectOwed<{ callId: string; }>): void; recordConfirmed(callId: string, event: EffectConfirmed): void; }): DurableDeferredGateway; /** * The durable command carrier — a {@link DurableDeferredGateway} whose every * tool round-trip is also a durable owed effect. * * A consumer's tool interpret cell still calls `carrier.await(callId, send, * deadlineMs)` and awaits the Promise (mapping Ok/Err to `agent_tool_ok` / * `agent_tool_err`) — the SAME fast path as the volatile gateway. The addition * is durability: `await` hands the consumer an `effect_owed` event (via * `recordOwed`) to PERSIST before the send, and `settle`/`fail` hand it an * `effect_confirmed` (via `recordConfirmed`) to persist. On the next activation * the consumer reads its persisted ledger events back and calls * `reissueSurvivingEffects` (see `./resume`) to re-fire the survivors. * * It IS a `DurableDeferredGateway` (so it is a drop-in for the gateway the * interpret cell already awaits) and exposes the underlying `recorder` for a * host that wants to read `surviving()` directly. The #91 "command carrier" * concept is exactly the durable gateway under a domain name — a type alias, not * a second byte-identical interface that could drift. */ type DurableCommandCarrier = DurableDeferredGateway; /** * Build a durable command carrier over a (volatile) `DeferredGateway` and a * `PendingEffectsRecorder`. Thin assembly over {@link durableDeferredGateway}: * it names the #91 piece — "the command carrier whose round-trips survive * eviction" — and keeps the recorder reachable for the activation-time re-emit. * * - `inner` — the volatile gateway whose in-isolate Promise the interpret cell * awaits (typically `deferredGateway()`). * - `recorder` — the durable-effects recorder (typically * `pendingEffectsLedger({ events, lastId })` rehydrated from the persisted * log on a wake, or a fresh `pendingEffectsLedger()` on a cold boot). * - `hooks.recordOwed` / `hooks.recordConfirmed` — the persist callbacks the * consumer points at its event log (so the ledger survives eviction). * * The carrier never persists anything itself (it does not own the consumer's * log) — it hands the consumer the events, faithful to "persist the intent * before deliver". */ declare function durableCommandCarrier(inner: DeferredGateway, recorder: PendingEffectsRecorder<{ callId: string; }>, hooks: { recordOwed(callId: string, event: EffectOwed<{ callId: string; }>): void; recordConfirmed(callId: string, event: EffectConfirmed): void; }): DurableCommandCarrier; /** * @demlik/tea/do — the agent host's lifecycle, as one state × message table. * * `createAgentHost` interprets it. The host's whole life is the four phases * below and the five messages that move between them, so a build that settles * after it was reset and a `runtime()` that arrives mid-teardown each have one * cell, and `ExhaustiveTransitions` makes a missing cell a compile error. The * cells are pure: every value a cell may keep (the next build's record, the * promise a teardown settles) arrives on the message, made by the interpreter * before it sends, and every effect leaves as a Cmd. * * `reset()` is a test and lifecycle seam for one caller at a time, so an * overlap is an illegal state and the table refuses it: a `reset()` while a * teardown is in flight, a `reset()` from inside `run()`, and a `runtime()` * while a teardown is in flight each leave the phase as it was and answer with a * `refuse` Cmd, which the interpreter throws as a {@link HostOverlapError}. */ /** * Thrown by `createAgentHost` when a call overlaps a lifecycle step that has to * finish first: a `reset()` while another `reset()` is still stopping the run, a * `reset()` from inside `run()`, or a `runtime()` while a `reset()` is still * stopping the run. `reset()` is a test and lifecycle seam for one caller at a * time, so no handler can do anything useful with the overlap: await the first * call before making the next. To stop a run from production code, give `run` * a `cancellation` signal and abort it. */ declare class HostOverlapError extends Error { readonly call: "reset" | "runtime"; readonly during: "teardown" | "run"; readonly name = "HostOverlapError"; readonly _tag: "HostOverlapError"; constructor(call: "reset" | "runtime", during: "teardown" | "run"); } /** * Cold-wake resume — the boot/hibernation re-fire path: the generalized * `bootResume` port, its agent specialization `autoBoot`, and the wake-time * re-emit of surviving tool round-trips. See `./host` for the transport-model * rationale. */ /** * The typed cold-wake resume port `bootResume` fires through — the agent's * `AgentBootPort`, generalized to any DO-hosted machine. * * - `isResumable(state)` — true iff the rehydrated State is mid-loop and needs a * resume dispatch. False on a fresh boot, which makes `bootResume` a no-op. * - `resumeMsg(now)` — the TYPED constructor for the single resume Msg (never a * hand-built `{ _tag: … }` literal); the `agentBootMsg` shape lifted out so a * non-agent grain supplies its own boot Msg constructor. */ interface ResumePort { readonly isResumable: (state: S) => boolean; readonly resumeMsg: (now: number) => M; } /** * After `runtime.ready`, derive the single resume Msg from the rehydrated State * via `port` and dispatch it exactly once — the generalized AgentBoot. On a * fresh (non-rehydrated) machine `port.isResumable` is false and this is a * no-op. Call once right after building the runtime; it standardizes the * hand-written `if (isResumable(state)) await runtime.dispatch(bootMsg(now()))` * every DO-hosted machine otherwise re-derives. * * Use this when the host deliberately supplies a Msg after boot, including * the existing agent boot protocol. Subs are already open after `ready`; this * helper cannot order resume ahead of their Msgs. Prefer restored init Cmds * when the machine owns its first move, and do not resume the same work twice. * * `await ready` is the single boot gate (issue #45): `getState()` is total only * on the booted handle, so state cannot be inspected before boot populates * it. Takes any engine's {@link RunHandle}. `now` is injected (the sole boot clock read) so a test can pin it. */ declare function bootResume(booting: RunHandle, port: ResumePort, now?: () => number): Promise; /** * True iff an agent slice loaded from storage is mid-flight: `running` or * `suspended`. A run lost while its model call or its compaction was in flight * restores as `running`, with that call still owed, and one lost while its tools * were in flight restores as `suspended`. `agent_boot` reissues the one * outstanding operation in each case. Idle and ended runs (`done`, `failed`, * `cancelled`) are false. * * It reads the agent's own typed `status` channel (issue #49), so a failure * annotation on a still-`running` phase reads as `failed`, and a `stale` run * reads as `running`. The host does not inspect the slice's private `awaiting` * shape, and a new status kind is a compile error in the table that answers * this, not a silent `false` here. */ declare function agentIsResumable, R>(state: AgentState): boolean; /** * The AGENT specialization of {@link bootResume}: after * `runtime.ready`, self-dispatch `agent_boot` iff the rehydrated slice is * resumable, a no-op on a fresh DO. Wires the agent slice's `agentIsResumable` * predicate + the agent-owned `agentBootMsg` typed port into the * generalized helper, so the resume dispatch lives in ONE place — see * `bootResume`'s docblock for the post-boot ordering boundary. * * `now` is injected (the host's only clock read for boot) so a test can pin it. */ declare function autoBoot, R, E extends { _tag: string; } = never>(booting: RunHandle, AgentMachineMsg, E>, now?: () => number): Promise; /** * Re-fire every round-trip a rehydrated actor still owes, on wake. Given a * durable carrier whose recorder was rehydrated from the persisted ledger * events (e.g. * `durableCommandCarrier(deferredGateway(), pendingEffectsLedger({ events }), * …)` on a wake), re-fire every owed-but-unconfirmed round-trip via * `reissue(callId)` — the consumer's "re-send the command frame for this * `callId`" callback. The survivors are read straight off the carrier's own * recorder (`recorder.surviving()`), which folded the restore log at * construction — the carrier is the single source of the in-flight set, so the * caller does not re-fold the log here. * * Idempotent by construction: * - the ledger's monotonic `deliveryId` is the dedup key the RECEIVER uses, so * a late/duplicate reply for an already-resolved round-trip is absorbed * (at-least-once delivery — see `survivingEffects`); * - re-issuing the SAME survivor twice within one activation re-sends once — * if `reissue` routes through the carrier's `await`, the gateway returns the * open Promise for an in-flight `callId` without re-firing `send`. * * Returns the `callId`s re-emitted (oldest-first by id) — the host can log / * assert the re-emit set. On a fresh or fully-confirmed carrier this is empty * (nothing re-fired). * * Call this once, right after the runtime's boot gate resolves (alongside * {@link autoBoot}): `autoBoot` re-fires the agent's own `agent_boot`; * `reissueSurvivingEffects` re-fires the in-flight TOOL round-trips. Together * they restore a suspended run's full in-flight state after a wake. */ declare function reissueSurvivingEffects(carrier: DurableCommandCarrier, reissue: (callId: string) => void): readonly string[]; /** * @demlik/tea/do — generic hibernatable PRESENCE + BROADCAST for a NATIVE * (non-agent) Durable-Object grain. * * ## The gap this fills * * `./host` ships `acceptCommandSocket` / `acceptDurableCommandSocket` / * `broadcast` / `broadcastHibernatable`, but those are framed for — and live * alongside — the LLM-agent **deferred-tool gateway** (`createAgentHost`): the * socket is "the command-runner socket", the frame is "a command", and the * fan-out is the agent's `sendCommand` loop. A plain realtime grain — a game * room, a presence list, a collab document — does not have an agent, a gateway, * or commands. It just wants to accept hibernatable client sockets and fan a * frame out to whoever is connected. Today every such grain (vortex's * `ArenaGrain`, #162) hand-rolls the same `ctx.acceptWebSocket(server)` + * `for (const ws of ctx.getWebSockets()) ws.send(...)` boilerplate (#181). * * This module lifts exactly that, decoupled from the agent host: * * - {@link broadcastFrame} — the fan-out, with the **socket set as the input** * (not a `ctx`), so it is a pure function testable with fake sockets and * reusable over any iterable (`ctx.getWebSockets()`, a filtered subset, a * test array). It serializes once, sends to every OPEN socket, and skips a * closed/errored one — returning a {@link BroadcastReport} count rather than * swallowing the skip silently (errors are data). * - {@link registerHibernatableSocket} — register an already-created server * socket on the DO via the Cloudflare **Hibernation API** * (`ctx.acceptWebSocket`), optionally tagging it and persisting a * per-socket attachment that survives eviction. Pure over the `ctx` + * socket seam, so the registration logic is testable with fakes. * - {@link acceptPresenceSocket} — the full upgrade: build the * `WebSocketPair`, register the server end, and return the `server` socket * plus the 101 upgrade `Response`. The one piece that touches the * runtime-only `WebSocketPair` (so it is exercised by type, not by a unit * test without workerd) — the registration it delegates to *is* unit-tested. * - {@link presenceCount} — the live connection count off `ctx.getWebSockets`, * the trivial roster-size lift a presence grain reaches for. * * It is transport/Msg-agnostic: `frame` is `unknown` (JSON-serialized by * default, or via a caller `serialize`), and nothing here references an agent, * a gateway, a Sub, or a Msg. It is ADDITIVE — `./host`'s agent-coupled * helpers keep working untouched for the agent consumer. */ /** * The minimal "send a string frame" surface {@link broadcastFrame} needs. A real * Cloudflare `WebSocket` satisfies it structurally (its `send` accepts a string * and it carries a numeric `readyState`), so `ctx.getWebSockets()` flows in * directly; a test supplies a fake with just `send` (and optionally * `readyState`). * * `readyState` is OPTIONAL: when present and not {@link WS_READY_STATE_OPEN}, * the socket is skipped WITHOUT calling `send`; when absent, `send` is attempted * and a throw is caught (a fake that models only liveness via a throwing `send` * needs no `readyState`). */ interface PresenceSocket { send(message: string): void; readonly readyState?: number; } /** * The Hibernation slice of `DurableObjectState` a presence grain needs — the * accept that hands the socket to the runtime (surviving eviction) and the * getter that repopulates the live set after a wake. A real `DurableObjectState` * satisfies this structurally; a test supplies a fake (no live Workers runtime * needed to exercise the accept/registry seam). */ interface PresenceCtx { acceptWebSocket(ws: WebSocket, tags?: string[]): void; getWebSockets(tag?: string): WebSocket[]; } /** * The OPEN `readyState` value (`WebSocket.READY_STATE_OPEN` in the Cloudflare * runtime). Named here so {@link broadcastFrame} can skip a non-open socket * without referencing the runtime constant (keeping the fold pure + testable). */ declare const WS_READY_STATE_OPEN = 1; /** * What a {@link broadcastFrame} fan-out did, surfaced rather than swallowed: * `sent` is the number of sockets the frame reached; `skipped` is the number * passed over (not OPEN, errored on `send`, or the `except` socket). A caller * can log or assert these — a silent fan-out hides a room going dark. */ interface BroadcastReport { readonly sent: number; readonly skipped: number; } /** Optional settings for {@link broadcastFrame}. */ interface BroadcastOptions { /** * A socket to exclude from the fan-out — typically the sender, so a collab / * chat frame is not echoed back to its originator. Compared by identity. */ readonly except?: S; /** * How to turn `frame` into the wire string. Defaults to `JSON.stringify`. * Override for a non-JSON wire format (e.g. a pre-encoded string passthrough). */ readonly serialize?: (frame: unknown) => string; } /** * Serialize `frame` ONCE and send it to every OPEN socket in `sockets`, skipping * any that is closed, errors on `send`, or is the `except` socket. The socket * set is the INPUT (not a `ctx`), so this is a pure function: pass * `ctx.getWebSockets()` in a live grain, a filtered subset for a targeted * fan-out, or a fake array in a test. * * Skip semantics (a dead socket never crashes the broadcast): * - `readyState` present and not {@link WS_READY_STATE_OPEN} → skipped, `send` * not called; * - `send` throws (a socket closing mid-fan-out) → skipped, the throw is * caught (the close lifecycle reaps it); * - the `except` socket → skipped. * * Returns a {@link BroadcastReport} of `{ sent, skipped }` — the skip is data, * not silence. */ declare function broadcastFrame(sockets: Iterable, frame: unknown, options?: BroadcastOptions): BroadcastReport; /** Optional settings for {@link registerHibernatableSocket} / * {@link acceptPresenceSocket}. */ interface RegisterOptions { /** * Hibernation tags for the socket — the same strings `ctx.getWebSockets(tag)` * filters on, so a grain can fan out to a subset (e.g. a team, a channel). */ readonly tags?: readonly string[]; /** * A per-socket value to persist via `server.serializeAttachment` so it * survives DO eviction (e.g. the player/session id the grain re-reads in * `webSocketMessage`/`webSocketClose`). Omitted ⇒ no attachment written. */ readonly attachment?: A; } /** * The subset of `WebSocket` {@link registerHibernatableSocket} writes to — the * attachment serializer. A real server `WebSocket` satisfies it; a test supplies * a fake that records the serialized attachment. */ interface AttachableSocket { serializeAttachment(value: unknown): void; } /** * Register an already-created `server` socket on the DO via the Cloudflare * **Hibernation API**: `ctx.acceptWebSocket(server, tags)` hands the socket to * the runtime (it survives eviction and re-delivers inbound frames to the DO's * `webSocketMessage` lifecycle method), and — when an `attachment` is supplied — * persists it via `server.serializeAttachment` so it survives the wake. * * Pure over the `ctx` + socket seam (no `WebSocketPair` construction), so the * registration logic — that accept is called with the right tags, that the * attachment is serialized iff present — is unit-testable with fakes. * {@link acceptPresenceSocket} is the thin wrapper that also builds the pair. */ declare function registerHibernatableSocket(ctx: PresenceCtx, server: S, options?: RegisterOptions): void; /** What {@link acceptPresenceSocket} hands back: the live server end (to send * initial frames on) and the 101 upgrade `Response` (to return from `fetch`). */ interface PresenceUpgrade { /** The server end of the pair — send the welcome / initial snapshot on it. */ readonly server: WebSocket; /** The 101 Switching-Protocols upgrade response carrying the client end. */ readonly response: Response; } /** * Accept a client WebSocket upgrade on a native DO and register it for * hibernation. Builds the `WebSocketPair`, registers the server end via * {@link registerHibernatableSocket} (tags + optional attachment), and returns * the `server` socket plus the 101 upgrade {@link PresenceUpgrade.response}. * * The caller's `fetch` collapses to: send any initial frames on `server` * (welcome, current roster/snapshot), then `return upgrade.response`. This lifts * the `new WebSocketPair()` + `ctx.acceptWebSocket` + `serializeAttachment` + * `new Response(null, { status: 101, webSocket })` boilerplate a presence grain * hand-rolls. * * NOTE: `WebSocketPair` is a runtime-only global (no workerd in unit tests), so * this assembly is exercised by TYPE here; its registration seam is unit-tested * via {@link registerHibernatableSocket}. * * @example * ```ts * import { acceptPresenceSocket, type PresenceCtx } from "@demlik/tea/do"; * * declare const room: { snapshot(): unknown }; * * class Lobby { * constructor(readonly ctx: PresenceCtx) {} * * async fetch(request: Request): Promise { * if (request.headers.get("Upgrade") !== "websocket") { * return new Response("expected a websocket upgrade", { status: 426 }); * } * const playerId = new URL(request.url).searchParams.get("player"); * const welcome = { _tag: "welcome", playerId }; * const { server, response } = acceptPresenceSocket(this.ctx, { * attachment: { playerId }, * }); * server.send(JSON.stringify(welcome)); * server.send(JSON.stringify(room.snapshot())); * return response; * } * } * ``` */ declare function acceptPresenceSocket(ctx: PresenceCtx, options?: RegisterOptions): PresenceUpgrade; /** * The live connection count for a presence grain — `ctx.getWebSockets(tag) * .length`, repopulated by the runtime after a wake. Pass a `tag` to count only * the sockets registered under it. The trivial roster-size lift a presence / * game grain reaches for (vortex's `connectionCount`). */ declare function presenceCount(ctx: PresenceCtx, tag?: string): number; /** * @packageDocumentation * @demlik/tea/do — Durable Object adapter for `@demlik/tea`. * * The integration is built on ONE transport model and one durability primitive: * * 1. `doStore(storage, parse, key?)` — `Store` impl backed by * `DurableObjectStorage`. JSON-stringifies on save, JSON-parses on load * and returns `unknown` (invariant-8 boundary); the substrate then calls * `migrate(raw)` (which forwards to `parse`) to turn it into `S`, `null` * or a refusal. Returns `null` (typed as `unknown`) when the key is * absent. Structural JSON malformation throws at load, and `run()`'s boot * path turns that into a `StoreRefusedError` on `ready`. A shape * mismatch is `parse`'s to answer with `refuse(reason)` (#316). * * 2. `deferredGateway` + `createAgentHost` (from `./host`) — THE transport for * a DO-hosted agent. A `createAgent().toMachine()` machine owns exactly one * Sub type, `DeadlinesSub` (the agent's own retry + watchdog timers); it has * no DO-native Sub variant to compose, and it needs none. The gateway owns * each deferred tool round-trip as a Promise the interpret cell awaits: * - Inbound WebSocket frames are bridged straight into `gateway.settle(...)` * from the DO's `webSocketMessage` lifecycle method — a direct dispatch, * NOT a Sub. * - The per-tool deadline is a `setTimeout` inside the gateway, NOT a DO * alarm. * One model: the transport lives outside the Sub system, bridged into * `dispatch` by the gateway. See `./host`'s module doc for the full rationale * and `.patterns/tea/durable-actors.md` for the host-layer north star. * * (Historical note: this module previously also shipped `do_ws` / `do_alarm` * Subs + a `doSubscribe` registry. Because `toMachine` fixes the agent machine's * Sub type to `DeadlinesSub`, those Subs could never union into an agent host's * Sub set — they were structurally unusable by the flagship consumer and had no * callers. They were dropped in favor of the gateway as the single transport.) */ /** * Options for {@link doStore}. Mirrors the optional-bag shape * `doEventSourcedStore` already uses for its `parse`/`keys`, so the two DO * stores read alike. */ interface DoStoreOptions { /** Storage key the snapshot cell lives at. Defaults to `@@state`. */ readonly key?: string; /** * The serialize half of the boundary (#182) — the INVERSE of `doStore`'s * `parse`. Maps the live `S` to a JSON-safe carrier before `JSON.stringify`, * so a Model holding a `Map`/`Set`/`Date` (which `JSON.stringify` would * silently flatten) round-trips: `parse` reconstructs the rich `S` from the * carrier on load. Omit for a plain-JSON Model (the identity default — the * `Record`-not-`Map` constraint, unchanged). When present, `parse` MUST * accept whatever `serialize` produces. */ readonly serialize?: (state: S) => unknown; /** * Refuse a second live writer (#143). With `{ fenced: true }` the returned * store is a `FencedStore`: the version lives in its own storage cell * (`@@version`) and the compare-and-swap runs inside * `storage.transaction`, so the read, the compare and the two writes are one * atomic unit. Inside a single DO the platform already guarantees one writer; * fencing is what refuses a SECOND grain — a stale zombie isolate mid-migration, * or a second DO id pointed at the same state by a routing bug. A run on a * fenced store must be given an `onError` (see `StoreAndOnError`). */ readonly fenced?: true; } /** * `Store` over `DurableObjectStorage`. * * `parse` is REQUIRED because DO storage is a real serialization boundary — * the bytes that come back through `JSON.parse` are structurally `unknown`, * and the caller (the DO that owns `S`) is the only party with enough * information to validate the shape. `parse` returns `S` for a shape it * recognizes, `null` when nothing was saved (the substrate boots `init` with * `loaded = null`), and `refuse(reason)` for saved bytes it cannot read. * `parse` must NOT throw per the `Store.migrate` contract; a shape * mismatch is a value (a refusal), not a panic. * * Structural malformations (the stored cell isn't even JSON) still throw at * `load()` — that's an infrastructure error, distinct from a schema * mismatch. Either way `runtime.ready` rejects with `StoreRefusedError` * before `init` runs, so nothing is saved over the old bytes. * * Concrete bite this closes: when a `State` variant is renamed between * deploys, the DO's new code previously received a value typed as the new * `S` that held a runtime string from the old `S` — silent undefined * behavior in `init`/`update`. After this, the boundary parse refuses the * old shape and the DO fails to start instead of running on it or saving * a fresh state over it. * * Serialization sharp edge (#182): `save` JSON-serializes the Model, and * `JSON.stringify` does NOT survive a `Map`/`Set`/`Date` (a `Map` stringifies * to `{}`, silently losing every entry). A Model that wants a `Map` (the * natural "roster keyed by id") therefore supplies a `serialize` hook — the * INVERSE of `parse` — so the boundary owns both directions: `serialize` turns * the live `S` into a JSON-safe carrier on the way out, `parse` reconstructs * the rich `S` from that carrier on the way back in. They are a matched pair: * `parse(JSON.parse(JSON.stringify(serialize(state))))` must round-trip to a * value equal to `state`. Omit `serialize` and the Model must stay plain-JSON * (the `Record`-not-`Map` constraint the default imposes, unchanged). * * @param parse - boundary parse, the deserialize half (`unknown -> S | null`, * or `refuse(reason)` for bytes it cannot read). * @param keyOrOptions - either the storage key (legacy positional form, * defaults to `@@state`) or a {@link DoStoreOptions} bag carrying `key` * and/or the `serialize` hook. A bare string is treated as `{ key }`. * * Either form is a `DeletableStore`: `delete()` removes the state cell and * its `@@version` cell in one `storage.delete` call. * * Options whose `fenced` is known only at runtime, such as a value typed * {@link DoStoreOptions}, return a store that may be fenced, so a run on it must * be given an `onError` (see `StoreAndOnError`). */ declare function doStore(storage: DurableObjectStorage, parse: (raw: unknown) => Migrated, keyOrOptions: DoStoreOptions & { readonly fenced: true; }): FencedStore & DeletableStore; declare function doStore(storage: DurableObjectStorage, parse: (raw: unknown) => Migrated, keyOrOptions?: string | (DoStoreOptions & { readonly fenced?: never; })): DeletableStore; declare function doStore(storage: DurableObjectStorage, parse: (raw: unknown) => Migrated, keyOrOptions?: string | DoStoreOptions): DeletableStore | (FencedStore & DeletableStore); export { type AgentHost, type AgentHostConfig, type AgentHostWiring, type AlarmStorage, type AttachableSocket, type BroadcastOptions, type BroadcastReport, type DeferResumeHook, type DeferStepHostConfig, type DeferredGateway, type DeferredStepOutcome, type DeferredStepResponse, type DoStoreOptions, type DurableCommandCarrier, type DurableTimer, type DurableTimerConfig, EffectConfirmed, EffectOwed, type EventLogHead, type EventLogRange, type EventLogReader, type EventLogReaderOptions, type EventSourcedOptions, type EventSourcedStore, type EvidenceEncoding, type ExecuteStep, type ExecutedStep, type ExecutedSteps, type FrameEvidence, type FrameReadOptions, type FrameRefusal, type HibernatableCtx, HostOverlapError, type LogFormat, type NextStep, PendingEffectsRecorder, type PersistedEvent, type PresenceCtx, type PresenceSocket, type PresenceUpgrade, type Projection, type ProjectionErrorContext, type ProjectionId, type ProjectionOnError, type ProjectionRegistry, type ProjectionRunner, type ProjectionUpdate, type RecordingBreak, type RegisterOptions, type RestoreAttempt, RestoreInterruptedError, type ResumePort, type RunStepLoopConfig, type SseHub, type StepCtx, type StepEngine, type StepHostConfig, type StepLoopCmd, type StepLoopMsg, type StepLoopOutcome, type StepLoopState, type StepOutcome, type StepRequest, type StepResponse, type StepResult, type StepTransport, type StepWorking, type StoredEvent, type StoredEventRange, type StoredEventRefusal, type StoredFrame, WS_READY_STATE_OPEN, acceptCommandSocket, acceptDurableCommandSocket, acceptPresenceSocket, agentIsResumable, autoBoot, bootResume, broadcast, broadcastFrame, broadcastHibernatable, constantTimeEqual, createAgentHost, deferredGateway, doEventLogReader, doEventSourcedStore, doStore, driveProjections, durableCommandCarrier, durableDeferredGateway, durableTimer, mintRunToken, presenceCount, projectionIdString, projectionRegistry, rebuildProjection, registerHibernatableSocket, reissueSurvivingEffects, runProjection, runStepLoop, sseFromAgentEvents, sseHub, sseProjection, stepHost, stepLoopMachine };