import { P as Postable, T as TellAnswer } from '../loop-CKqoteig.js'; import { b as Cmd, c as Sub, R as RunHandlers, M as Machine } from '../core-sEWVgnpI.js'; import { B as BootingRuntime, R as Runtime, C as CtxArg, a as StoreAndOnError, b as Supervision, T as TelemetrySink } from '../runtime-types-f231H8Gq.js'; import '@standard-schema/spec'; /** * @demlik/tea runtime — `run`: boot a machine and drive its serial dispatch loop * on Promises; `driveToDone`: run one to its terminal State. * * `run` is assembly. The loop itself is `src/internal/engine/loop.ts` — a small * core with no special case for any built-in, shared with the Effect engine — * and every built-in is an extension of it (`src/internal/engine/builtins.ts`), * built from `run`'s options in the order both engines share. */ /** The options of the Promise engine's `run`. */ type PromiseRunOptions = CtxArg & NoInfer> & StoreAndOnError & { /** * The clock that stamps `at` on a `Cmd.define`d effect's settled Msg at * the interpret edge, and on each `telemetry` event. Defaults to * `Date.now`. Inject a fixed one for a deterministic run; a `replay` log * carries its own `at`s and never reads this. */ clock?: () => number; /** * The SEMANTIC event projector. Maps one APPLIED transition `(msg, state)` * to zero-or-more public events of `E`; `[]` skips the transition. Maps the * machine's PRIVATE Msg vocabulary to NAMED events — the private names never * reach `on`'s `E` surface. Omit → `E = never` and `on` is uncallable. PURE. */ events?: (msg: M, state: S) => readonly E[]; /** * Declared policy for a reducer (`update`) throw. Always surfaced via * `onError` (`phase: "reduce"`); the strategy decides what the runtime does * next. Defaults to `"stop"`. See `Supervision`. */ supervision?: Supervision; /** * The run-terminality predicate — makes the run's outcome first-class. Fed to * `Runtime.result()` and `Runtime.done()`. PURE. Omit → never terminal. * * `done()` resolves with a saved terminal State. When a failure closes the * run short of one, it rejects with that failure, for waiting and later * callers: the save's own error, a `SubFailedError`, or what a reducer threw * under the `stop` strategy. A `stop()` with no failure leaves it pending. */ terminal?: (state: S) => boolean; /** * A sink handed `{ seq, msgType, at }` for every applied transition — * the observe-only telemetry `withTelemetry` used to add by wrapping the * machine (#268). Fire-and-forget; see {@link TelemetrySink}. */ telemetry?: TelemetrySink; /** * How long `stop()` waits for work it cannot interrupt before giving up * on it. Defaults to 5_000ms. It bounds two waits, one after the other: * the queue, where a Cmd handler may still be running, and then the * teardown work that returned a Promise (an async `release` in * `defineManagedResource`, an async Sub cleanup). * * `stop()` awaits those disposals so a host doing * `await runtime.stop(); env.evict()` cannot drop the isolate mid-release — * the leak the managed-resource battery exists to prevent, relocated to * shutdown. The bound is what keeps a handler that never returns, or a * release that never settles, from hanging the host: on expiry `stop()` * reports a `DrainTimeoutNotice` or a `DisposeTimeoutNotice` (warn-only, * like every `RuntimeDiscardNotice`) and resolves anyway, because `stop()` * resolving is a contract (ADR 0025). The Subs are still stopped and the * final save still runs, except that a run started with `boot: "restored"` * skips it while the State is the one the store is known to hold. A * handler `stop()` gave up on keeps running; what it returns later is * dropped. * * tea starts no store call after `stop()` has returned. A store call * already under way when `stop()` gave up is not cancelled and can * finish after `stop()` has returned. A fenced store refuses that late * save with `StoreConflictError`, and so does `doEventSourcedStore` once * a newer run has loaded its log. A custom plain store that waits before * it writes takes it over what a newer run saved, unless it checks at * its own write point. So a host that starts a new run on the same store * after a `stop()` that gave up needs one of the first two. A run * stopped while its `store.load()` was pending saves nothing when the * load returns: `ready` resolves with the loaded State, unsaved. */ disposeTimeoutMs?: number; /** * Stop the run from outside, for a host that holds the runtime itself. Once * `signal` aborts the runtime queues `cancel`'s Msg, starts no further Cmd and * stops waiting on the handler in flight, which a promise cannot recall; what * that handler returns later reaches no one. A signal that is already aborted, * or aborts while the store is loading, settles the cancel before `ready` * resolves, so a host reading `ready` sees a run that ended and resumes * nothing. `cancel` is chosen off the State, and PURE; it must land a State * the run does not resume from. A `cancel` that throws is reported to * `onError`. A pair, so a signal with no `cancel` cannot be written. Not * available with a store that keeps a log: `run` throws. * * `driveToDone` takes the same pair to stop a run it drives. */ cancellation?: { readonly signal: AbortSignal; readonly cancel: (state: S) => M; }; /** * How the run starts. Omit it and nothing changes: `init` folds the loaded * State, the engine saves what `init` returned, runs `init`'s Cmds, and * `stop()` saves the last State once more (ADR 0028). * * `"restored"` is for a host that already knows this start is a wake, not * a new process: a Durable Object woken by its next Msg, a request handler. * With a loaded State, `init` still folds it, but its Cmds are not run and * nothing is written at boot while `init` returns the loaded State itself. * A transition still saves before its Cmds run. `stop()` skips its save * only while the State is the one the store is known to hold (the loaded * State or the last one a save accepted), and a refused save clears that, * because the store may have written before it failed. So a start that * changed nothing writes nothing and, on a fenced store, takes no turn at * the fence. With nothing saved, `init(null)` runs, its Cmds run and its * State is saved. A store with a durable log, or no store, is not changed * by it (ADR 0039). */ boot?: "restored"; /** * Iteration cap for `idle()`'s quiescence wait. Defaults to 100_000. Test * seam only. Production code must not set it. * * @internal test-only */ __idleCap?: number; }; /** * The handle `run` returns: a {@link BootingRuntime} whose `ready` resolves to a * {@link Run}. It does not compile as `tell`'s argument: wait for `ready`. */ interface BootingRun extends BootingRuntime { ready: Promise>; } /** * What a {@link BootingRun}'s `ready` resolves to: a booted {@link Runtime} that * also carries the run's line, which is what `tell` asks for. A spread keeps the * line. An object built by hand cannot have one, because tea does not export its * key, so a {@link Runtime} that is not one of these does not compile as `tell`'s * argument. It fits anywhere a `Runtime` is asked for. */ interface Run extends Runtime, Postable { ready: Promise>; } /** * Start a machine on the Promise engine and return its runtime. Pass the Cmd * handlers, the Sub runners, `ctx` and an optional `Store`; the runtime is * returned at once and every method waits for boot. * * Throws at once, before anything is loaded, when the store is fenced at runtime * and no `onError` was passed, even when the store is typed plain `Store` * (ADR 0031). */ declare function run(machine: Machine, opts: PromiseRunOptions): BootingRun; /** * The outside-in stop, as a PAIR. A signal is only cancellation if something can * turn "aborted" into a transition this machine understands, and the kernel has * no built-in cancel Msg any more than it has a built-in terminal set — so the * `signal` and the `cancel` that reads it are one option, present together or * absent together. A discriminated union rather than two optional fields, on the * same reasoning as `AgentCompactionConfig`: a signal with no `cancel` is a stop * button wired to nothing, and that is a state worth making unrepresentable * rather than checking for. */ type DriveCancellation = { readonly signal?: undefined; readonly cancel?: undefined; } | { /** * Abort the run through this signal. On abort the drive dispatches * `cancel`'s Msg and resolves on the State that lands — it does NOT reject, * and a cancellation is never a `DriveFailedError`. Already aborted when * the drive is called → the cancel Msg goes in place of `start`, so the * run ends without the start's effects ever firing. */ readonly signal: AbortSignal; /** * The Msg that settles this machine as cancelled, chosen off the current * State exactly as `start` is. PURE. It must land a State `isTerminal` * holds for — the drive resolves on the terminal predicate, not on the * abort — and that State should be DURABLE, or a reload resumes the run * its caller stopped. */ readonly cancel: (state: S) => M; }; /** Options for `driveToDone`. */ type DriveToDoneOptions = DriveCancellation & { /** * Marks a terminal State as a FAILURE. A State this holds for ends the drive * like any terminal one — the runtime is stopped — but the drive REJECTS with * `DriveFailedError` carrying it instead of resolving. A failed State is * terminal by definition; it need not also satisfy `isTerminal`. Omit → the * drive never rejects on State, only on a runtime error. */ readonly failed?: (state: S) => boolean; }; /** * Drive a machine from `start` to its terminal State in one call, then tear the * runtime down. The one-shot shape every "run this machine to done" test and * caller boundary otherwise hand-wires as six steps — `await ready`, `observe`, * park a promise, `dispatch(start)`, `getState()`, `stop()` — with the observer * leak and the forgotten `stop` those six steps invite. * * Takes the handle `run()` returns (a `Runtime` extends it, so a booted one is * accepted too), awaits `ready`, dispatches `start`, and resolves with the first * State for which `isTerminal` holds. A machine that boots already terminal (a * rehydrated finished run) resolves on its boot State and `start` is never * dispatched — a finished run has nothing to set in motion. `start` may be a * function of the boot State instead of a Msg: a machine rehydrated MID-run * needs its resume Msg, not its start Msg, and only the boot State says which * (the agent's `agent_boot` vs `agent_start` is the case in point). The * observer is detached and `stop()` awaited on EVERY exit: resolve, `failed`, * a stall, a boot or dispatch throw, the quiescence cap. * * Use this for a deliberate host `start` Msg after boot. Subs have already * opened by then. A machine whose restored first move must precede their Msgs * returns its resume Cmds and in-flight State from init instead; do not also * use `start` to resume that same work. * * Rejections are typed, never silent: * - `DriveFailedError` when `opts.failed` marks the final State — the State * rides on `error.state`. * - `DriveStalledError` when `start`'s follow-up chain quiesces on a State * that is neither terminal nor `failed` and the runtime has no live Sub and * no Cmd in flight — nothing inside it can deliver another transition, so * waiting would be a hang with the runtime leaked. The stalled State rides * on `error.state`. A machine that CAN still move is not stalled: a live Sub * that delivers the terminal Msg after the dispatch * quiesces keeps the drive waiting, and it resolves on that State. What the * runtime cannot see — a dispatch from outside it after quiescence — does * not count as live; a machine that depends on one declares it as a Sub. A * stall that a Cmd handler's failure left rejects with that failure instead * (the bullet after next). * - `QuiescenceTimeoutError` when `start`'s follow-up chain never settles — * the SAME cap `dispatch` and `idle()` already reject on (invariant 6), not a * second clock. A livelocking machine surfaces as its own failure class. * - the Cmd handler failure that left the drive stalled, as the handler threw * it (the same object), in place of `DriveStalledError`. A failure with no * caller to reject at (a throw on a later hop, or any throw or contract * breach of a `Cmd.define`d handler) goes to `onError` by itself, and the * drive would then find nothing live and stall with the cause gone. So while * `dispatch(start)` runs, the drive holds such a failure, and decides it at * its one stall check, when that dispatch quiesces. A stall rejects with the * first held failure, and every other held failure goes to `onError`, in * order. A drive that resolves, or keeps waiting on a live Sub or Cmd, sends * every held failure to `onError` at once. After that check nothing is held: * a failure goes to `onError` as it happens, so each is heard once, under * its own phase, as soon as its outcome is known. A hand-written Cmd's throw * on the first hop rejects the drive at once, as `dispatch(start)` does; if * it lands after the drive resolved, `onError` hears it. A failure that is * not a handler's, such as a store that refuses a later hop's save, goes to * `onError` and the drive stalls as before. A run no one drives is * unchanged. * - the boot error, or whatever `dispatch(start)` rejects with, otherwise. * * `isTerminal` is caller-supplied, exactly as `run()`'s `terminal` option is — * the kernel has no built-in terminal-set concept and this does not add one. * * Cancellation is the same story: `{ signal, cancel }` stops the drive from * outside, and it settles the run rather than escaping it. On abort the drive * dispatches `cancel`'s Msg and RESOLVES on the terminal State that transition * lands — no rejection, no `DriveFailedError`, no `AbortError`. That is the whole * point of routing a stop through the Model: the outcome is durable, so a killed * process resumes reading a run that ended instead of restarting one someone * stopped. A cancel that THROWS is the one abort that rejects: it lands * no State, so its error is what the drive has to report — and that holds * whether the `cancel` function throws synchronously or the fold it produced * throws later, since both leave the run with no State to settle on. A State the * caller's `failed` predicate marks rejects on an abort exit exactly as it does * anywhere else. In-flight effects are not recalled — a promise cannot be cancelled — * so they settle to their own end and `stop()` drains them, up to * `disposeTimeoutMs`; * keeping their results off the public channels is the machine's own business. * Omit the pair and every path here behaves exactly as it did before. * * @param handle the handle `run(machine, opts)` returned. * @param start the Msg that sets the run in motion, or a function choosing * it off the boot State. PURE. * @param isTerminal the terminal predicate over the machine's State. PURE. * @param opts an optional `failed` predicate and an optional * `{ signal, cancel }` pair (see {@link DriveToDoneOptions}). */ declare function driveToDone(handle: BootingRuntime, start: M | ((booted: S) => M), isTerminal: (state: S) => boolean, opts?: DriveToDoneOptions): Promise; /** * Put `msg` on a run's line and return at once. The answer means queued, not * handled: the receiver's step has not run yet, and any result comes back later * as its own Msg. So two machines can tell each other from their Cmd handlers * and neither stops. `machine` is the machine `runtime` runs. * * The answer is `"queued"`, `"stopped"` for a run that is stopping or has * stopped, or `"no_cell"` when its current State has no cell for the Msg. Msgs * already in line have not folded yet, so a Msg that only a queued one makes * acceptable answers `"no_cell"`. * * `runtime` is what `ready` resolved to, or a spread of it. Those carry the run's * line, and the type asks for it, so a `Runtime` built by hand, a fake or * `noopRuntime` is a compile error. So is the handle `run` returned, with a store * or without one: wait for `ready`. A hand-built object cast past the type has no * line to put a Msg on, and `tell` throws there. * * What happens after `"queued"` is the receiver's. Two `tell`s from one sender * fold in the order they were sent. A failed save or a handler's throw goes to * the receiver's `onError`, never back to the sender. A Msg whose cell is gone * by its turn is dropped without a word, and a `stop()` that gives up drops * what is still in line and counts it, per Msg type, in its * `DrainTimeoutNotice`. * * Two hand-written `await runtime.dispatch(...)` calls into each other, one from * each machine's Cmd handler, still stop both machines: `dispatch` waits, and * tea has no lock-up detector. Use `tell` there. * * ```ts * const answer = tell(parent, parentRun, { _tag: "child_result", id }); * ``` */ declare function tell(machine: Machine, runtime: Run, msg: NoInfer): TellAnswer; export { type BootingRun, type DriveToDoneOptions, type PromiseRunOptions, type Run, TellAnswer, driveToDone, run, tell };