/**
 * The terminal cause — the ONE record of how a run ended (`TaskResult.terminal`), its closed kind set,
 * the one disposition table over that set (which cause a resume journal may replay) and the admission
 * read a journal entry's cause passes through. Layer 0 vocabulary, beside `gate-outcome.ts` (the record
 * of one gate pass) and `pause-registry.ts` (the pause gate × pending-action pairing a paused cause
 * points at): no runtime import above this layer, so any module may read the words.
 *
 * The plane-word projection a face that still speaks `status` needs lives in
 * `runner/terminal-projection.ts` — the one cause→plane derivation.
 */
import type { AssertAllKeysHandled } from "./ask-origin.js";
import type { ProviderCondition, ProviderConditionSource } from "../brain/provider-dialect.js";
import type { RequestRoute } from "../brain/request-route.js";
import type { ModelOutputInvalidCause, OutputLimit } from "../internal/llm.js";
/**
 * What became of the checkpoint row of a RESUMED leg that ended before its approved action started — the store's own outcome of
 * the claim's reversal, stated by the exit that compensated it. A CLOSED SET with one home, registered in `docs/CLOSED-SETS.md`:
 *  · `"reopened"` — pending again: the same token resumes it (also when the reopen threw and the row read afterwards shows it landed);
 *  · `"declined"` — the store refused to reopen it (the row is no longer the resolved row the leg claimed): read the row;
 *  · `"unknown"` — the reopen threw and the row does not show it landed: its state is unprovable from here.
 * Every carrier reads this one type: a failed result's `terminal.unstartedRow`, a resume's rejection before its leg started
 * (`CheckpointError.detail.unstartedRow`), and the engine's own outcome record (`UnstartedRow`, whose sentence is derived from the word).
 * A consumer holding a table over it is tsc-red on a new word until it places the word.
 */
export type UnstartedRowOutcome = "reopened" | "declined" | "unknown";
/**
 * Whether a leg's rewind moved the working tree, read off what its restore asked of the env (the witness of the restore's own
 * view, the one reading): `"none"` — no write, delete, change of mode or directory was asked of the tree (the leg never reached its
 * restore, or the restore was refused or failed before any file moved: its plan refused or failed, the history had no address);
 * `"some"` — at least one of them answered done; `"unknown"` — some were asked and none answered done (a write that failed may have
 * written part of a file). A CLOSED SET registered in `docs/CLOSED-SETS.md`; the member {@link TaskRewindSettlement.moved}.
 */
export type RewindMoved = "none" | "some" | "unknown";
/**
 * Where a leg's request left its session's conversation leaf (`TaskSpec.resumeAt` branches it at the session acquire): `"untouched"`
 * — the request moved no leaf (it asked no `resumeAt`, was refused before branching, or branched at the leaf it found);
 * `"put_back"` — it branched and the refused leg put the leaf back where the request found it; `"left_moved"` — the leaf stays off
 * where the request found it (the leg ran past its prepare on the branch, another writer moved the leaf past the request's own
 * entries, or the cleanup's bound expired before its write started). A CLOSED SET registered in `docs/CLOSED-SETS.md`.
 */
export type RewindBranch = "untouched" | "put_back" | "left_moved";
/**
 * What a leg that asked for a rewind did to the working tree and to its conversation ({@link RewindMoved}, {@link RewindBranch}) —
 * the two facts a host tells a person "what the disk and the conversation look like now" from, minted where each happens: `moved` by
 * the restore (the witness of what it asked of the env), `branch` by the acquire that branched and the cleanup that puts it back.
 * `branch` absent = not known: the put-back's read or its write threw, or its bound expired while the write was in flight (the
 * session store's write carries no cancellation). Carried on a `failed` or `blocked` terminal ({@link TerminalCause}) and on `Runner.rewindFiles`'
 * `rewind.restore_failed` detail (`branch: "untouched"` there: the verb moves no leaf).
 */
export interface TaskRewindSettlement {
    moved: RewindMoved;
    branch?: RewindBranch;
}
/**
 * WHY a run ended — ONE tagged cause, and the ONLY terminal record a {@link TaskResult} carries. The run
 * loop's terminal arbitration used to decide a `status` word plus seven optional plane fields one by one
 * across an if/else-if ladder over competing optional flags, and the legal combinations
 * ("`status:"suspended"` ⇔ a token is present", "a review pause and an approval pause are never both set")
 * lived only in that ladder's order. Here they are the SHAPE: a paused run carries its token; a completed
 * run cannot. Branch on `kind`; the five-word {@link TaskStatus} a cause reads as (a `paused` cause reads
 * its gate kind's registry row) is derived by {@link import("./runner/terminal-projection.js").terminalProjection},
 * the one cause→plane derivation, for the faces that still speak the word.
 *  - `completed` — the run finished (a person's clean halt included — see `TaskResult.haltedByUser`).
 *  - `failed` — a limit, a provider failure, an abort, an invalid output…
 *  - `blocked` — the run ended without doing the work, and `detail` says by whom: ABSENT = the AGENT reported,
 *    through `ReportBlocked`, that it cannot finish, and why; `detail.kind === "prompt_blocked_by_hook"` = a
 *    `userPromptSubmit` hook kept the prompt from being submitted (see {@link TerminalBlockedDetail}). A TERMINAL
 *    cause: the leg is over and it waits for nobody (nothing to resume, no token). The waiting-on-a-person
 *    states are the `paused` cause's two status words — `suspended` (a pre-action approval of a tool
 *    call) and `needs_review` (a review pause); the task-registry face spells both as `parked`.
 *  - `paused` — a durable pause committed a checkpoint and the run is resumable.
 * A `GateOutcome` is the record of ONE gate pass (per call); a `TerminalCause` is the record of ONE run
 * (per leg); a paused run's `gate` and the park row's `gate.kind` are the same word, joined by the token.
 */
export type TerminalCause = {
    kind: "completed";
    /**
     * A machine-readable account beside a completion, for the shapes that complete yet may be short
     * ({@link TerminalCompletedDetail}): `finish_reason_unknown` — the final turn's provider ended it with a stream-end
     * word the brain does not read (`AssistantMessage.finishReasonUnknown`); the turn was kept as the model left it, and
     * the run announced the word (`route.finish_reason_unknown`). `response_cut` — the final turn's answer stopped
     * arriving before the provider ended it and what had arrived was kept (`AssistantMessage.partialFinalized`).
     * PRESENCE: only when the final assistant message carried one of those seats and the run completed on it; every
     * other completion leaves it absent.
     */
    detail?: TerminalCompletedDetail;
} | {
    kind: "failed";
    /**
     * Machine-readable failure code when the failure carried one — e.g. a `SessionError.code` such as
     * `"conflict"` (a cross-instance write lost the optimistic lock), or a Node error code. Lets a
     * caller branch programmatically (e.g. evict a stale cache + retry on `"conflict"`) instead of
     * matching `message` strings. Absent only for the failures that never had one (an abort with no
     * limit axis, no assistant message produced).
     *
     * Terminal codes use a **dotted namespace** so a caller can prefix-match a whole class:
     * `"limits.max_tokens_exceeded"` / `"limits.max_cost_exceeded"` / `"limits.max_turns_exceeded"` /
     * `"limits.max_walltime_exceeded"` / `"config.limit_invalid"` (also mid-run: a money ceiling over spend that settled with no
     * cost figure, `TaskLimits.maxCostUsd`) / `"config.limit_unknown_key"` /
     * `"config.attachment_invalid"` (a mode-valued `TaskSpec.attachments` member outside its closed
     * set, refused at the same door as the limits) (e.g. `code.startsWith("limits.")`). Brain codes
     * (`auth`/`network`/`rate_limit`/…) and `"conflict"` remain flat.
     *
     * Two codes name the EXTERNAL stop causes — neither is a `limits.` code, because neither is an
     * allowance the task chose, and a caller that retries on `limits.*` should NOT treat these the same:
     * - `"env.lifetime_expired"` — the execution environment's platform lifetime ran out and the run
     *   could not be suspended durably — or, answered by the environment when the leg established it, before
     *   the run started. Retrying needs a NEW environment, not a smaller budget.
     * - `"usage.window_exhausted"` — a deployment usage-governance window is full (see
     *   `RunnerDeps.usageWindows`). Reported at task ENTRY (nothing ran) or after a suspend was
     *   impossible; the wait hint rides the thrown error's `retryAfterMs` (delivered through
     *   `RunnerDeps.onError`) and the message text. Retrying before the window frees is refused again.
     * Their config-time siblings are `"config.env_lifetime_invalid"` / `"config.usage_window_invalid"`.
     * A governance window with a MONEY ceiling adds two more, both of which say "the ceiling could not
     * be evaluated" rather than "the ceiling was reached" — neither is retryable without a config change:
     * - `"config.usage_window_unpriced"` — a `UsageWindow.maxCostUsd` over a run with no cost figure
     *   (no `RunnerDeps.pricing` entry and no `Model.cost`).
     * - `"usage_window.store_cost_unanswered"` — the wired ledger does not carry the money arm.
     * Two codes name a model whose output the loop could not use after its bounded retries — the run did not
     * finish its work, though its last turn reads like an ordinary one:
     * - `"model.malformed_tool_use_exhausted"` — every tool call of the model's turns kept arriving unparseable, or
     *   kept naming the same tool the run does not mount, and the retry budget is spent (nothing ran for them).
     * - `"model.truncated_output_exhausted"` — the model's answer kept ending on the output cap and the
     *   continue budget is spent (`result` holds the text it reached).
     * `"spend.account_closed"` — the run's next model request was not sent because the run its work belongs to (the run
     * that started it, by a task-bound link) had already ended and closed its spend account; no ceiling held, so raising a
     * limit does not help — the work has to be started again under a live run (`errorClassOf` reads `aborted`).
     * `"holder.superseded"` — the store refused one of the leg's session writes for the run's grant (`RunInternals.holder`): another
     * leg holds the run, or the run has ended. The leg stopped on that tick; do not retry it (`errorClassOf` reads `aborted`).
     * `"unexpected.suspended"` / `"unexpected.needs_review"` — a nested orchestrator stopped at a durable pause and
     * carries it on {@link nestedPause} (`mapNestedSuspend` states which orchestrators, and how the pause continues).
     */
    code?: string;
    /** Human-readable failure text. */
    message?: string;
    /**
     * A machine-readable account of the failure beside `code` — the fact the failure's mint point stated, projected
     * once ({@link TerminalFailureDetail}; branch on `detail.kind`, never on `message`):
     *  - `provider_rejected` — the provider REFUSED the request as sent (a 4xx answer) and that refusal named this
     *    result. `status` is the refusal's HTTP status (`TaskResult.apiFailure.status`, the same value); `code` the
     *    provider's own word (`AssistantMessage.apiErrorCode`); `route` the request's route. A run whose
     *    higher-ranked cause named the result, a 5xx, a connect / stream failure and an in-band error inside a 200
     *    carry none. A 401 / 403 (credentials) and a 429 (rate limit) are refusals too: branch on `status`.
     *  - `coded` — the run threw a coded error (this `code`) whose throw site stated a structured `detail`.
     *  - `model_output_invalid` — the model's final turn failed because its tool calls could not be executed.
     * PRESENCE: only when the arm that named this result has such a fact to project; absent otherwise.
     */
    detail?: TerminalFailureDetail;
    /**
     * The durable pause this failure STANDS IN FOR — set only by the nested hard boundary
     * (`mapNestedSuspend`, which states which orchestrators map and the entry that continues the pause): an
     * orchestrator's nested leg paused on a durable gate, so at ITS boundary the pause is a failure — but the
     * pause's own cause travels here verbatim so the host keeps the recovery capability (`nestedPause.token`).
     * Absent on every failure the engine itself assembles.
     */
    nestedPause?: PausedCause;
    /**
     * What a RESUMED leg that ended before its approved action started did to its checkpoint row ({@link UnstartedRowOutcome}).
     * Beside `code`, never folded into it: the code still names what ended the leg. PRESENCE: only on such a leg; a
     * fresh run, a leg that started its approved action and a delivered negative decision carry none.
     */
    unstartedRow?: UnstartedRowOutcome;
    /**
     * On a row that is pending again (`unstartedRow: "reopened"`): whether resuming it again with the same decision, nothing done in
     * between, can succeed — the failure's cause read by the one table the reopened sentence reads too (`resumeAgainMayCure`).
     * `true` = an infrastructure failure a retry can pass (or a cause not known); `false` = a retry fails the same way (the
     * transcript is missing or damaged, or the tool, the deployment — its configuration, or its execution environment refusing
     * itself — or the decision must change first), so the same decision is not retried automatically: a row whose reopen reason
     * takes a fresh decision (`tool_unavailable`, `config_refused`, `constraint_rejected`) waits for one — a wake or resource-limit
     * row has no decision to change, and is resumed again once the cause is corrected, or expired —; any other row is expired, or
     * resumed again once what its sentence names is restored. PRESENCE: exactly when `unstartedRow` is `"reopened"` and the row is this run's to
     * resume — the table has an answer for the failure's cause; absent otherwise, and absent on a row reopened for the run's current
     * holder (cause `superseded`, code `holder.superseded`: this run neither retries nor expires it).
     */
    resumeAgainMayCure?: boolean;
    /**
     * On a leg whose request asked for a rewind (`TaskSpec.resumeAt`, `rewindFilesTo` or `restoreFiles`), whatever `code` ended it —
     * a refusal of the rewind itself, a refusal after the restore landed, a failure of the run on the restored tree: whether the
     * working tree moved and where the conversation's leaf was left ({@link TaskRewindSettlement}). Beside `code`, never folded into
     * a code's own `detail`. PRESENCE: exactly on such a leg's failed terminal; absent on every other leg — and from an engine before
     * 7.71.0, where it reads as not known.
     */
    rewind?: TaskRewindSettlement;
} | {
    kind: "blocked";
    /**
     * Why the run ended without doing the work — one of two sources, told apart by {@link detail}. With no
     * `detail`: the agent's own words from its `ReportBlocked` call. With `detail.kind ===
     * "prompt_blocked_by_hook"`: the engine's sentence about the deployment's `userPromptSubmit` hook, framed
     * as a reminder for the model-facing lane (the hook's own words, when it gave some, sit inside the
     * frame). Terminal: the run is over and nobody is being waited on (contrast `paused`, whose token is the
     * resume capability).
     */
    reason: string;
    /**
     * WHO stopped the run, for the one shape a consumer offers its own way out of: `prompt_blocked_by_hook` —
     * the prompt was NOT submitted (the objective never became a message and the loop never started), so
     * changing it and sending again is meaningful; `cause` says which of the hook's four endings it was.
     * PRESENCE: only on that terminal. ABSENT means the agent reported `ReportBlocked` ("I cannot go on"), or an
     * engine from before this key — branch on `detail?.kind`, never on the prose in `reason`.
     */
    detail?: TerminalBlockedDetail;
    /**
     * On a leg whose request asked for a rewind, the same record a `failed` terminal states ({@link TaskRewindSettlement}): the
     * restore ran in prepare and the leg then ended blocked (a prompt hook refused the objective, the agent reported it could not go
     * on) — whether the working tree moved and where the conversation's leaf was left. PRESENCE: exactly on such a leg's blocked
     * terminal; absent on every other leg, and from an engine before 7.71.0.
     */
    rewind?: TaskRewindSettlement;
} | {
    kind: "paused";
    /**
     * WHICH pause — who/what must resume (e.g. `{kind:"human", reason, toolName}`), so the caller knows
     * what decision the checkpoint awaits and which resume outcome it takes (a `policy_ask` for an
     * approval gate; a `dry_run_review` on a `needs_review` gate; a `plan_review` on a `plan_review`
     * gate). Its kind's {@link import("./pause-registry.js").PAUSE_REGISTRY} row is what
     * {@link import("./runner/terminal-projection.js").terminalProjection} reads the status word from
     * (`"suspended"` for an approval / a resource slice / a platform pause, `"needs_review"` for a review).
     *
     * An approval gate's `reason` is the engine's account of the pause kind, not the question put to a person. The card's
     * question, its askers' own words, the origin word and the class pair are the row's `PendingAction.tool_approval` members
     * (`cardMessage`, `askReasons`, `origin`, `askClass` / `classes` — the values the live card carried): a surface rendering
     * the parked card reads that row by {@link token} (`CheckpointStore.get`), and the row's `checkpointId` is
     * {@link checkpointId}. The gate carries none of those members; what it does carry about the ask is its triage
     * descriptor (`riskDescriptor`: severity, axes, the action's summary, a probe's account when a probe tightened the call)
     * and, on a real-approval ask, the bit the resume reads (`realApproval`, with the ask's origin word).
     */
    gate: import("./checkpoint-store.js").CheckpointGate;
    /**
     * The durable-checkpoint token to resume this task with via `runner.resume(token, outcome)`.
     * Branded `CheckpointToken`; **never log it or put it in a URL** (it is the resume capability, §6).
     */
    token: import("./checkpoint-store.js").CheckpointToken;
    /**
     * The pause's NON-SECRET stable identity ({@link import("./checkpoint-store.js").Checkpoint.checkpointId})
     * — the display/correlation key a consumer may log or render where the token must not travel.
     * Absent on pre-identity checkpoints.
     */
    checkpointId?: string;
    /**
     * The id of the tool call that asked for this plan_review pause — the call that PRESENTED the plan (the
     * `ExitPlanMode` call for the first-party plan tool), so a card can join the pause to that call by id instead of
     * by adjacency. PRESENT only on a `plan_review` pause whose requester carried a call id; ABSENT on every other
     * pause and on a plan_review pause whose requester had none (a row a deployment minted itself, a revive context). It
     * is provenance, not a binding: the pause gates no call, so no `tool_approval` field rides beside it, and the
     * resume never reads it. Echo of the committed row's {@link import("./checkpoint-store.js").PendingAction}
     * `plan_review.requestedByCallId` — one write, at the park mint.
     */
    requestedByCallId?: string;
    /**
     * The digest of the plan SHOWN to the person at this plan_review pause: `sha256:` + the lowercase hex SHA-256 of the
     * UTF-8 bytes of the `plan` string on the `exit-plan-mode` card the requesting call's `tool_end` carried
     * (`structured.plan`), unnormalized and untruncated — so a reader digests the plan string it holds, before any
     * display normalization, and compares. It says what was shown, not who asked and not which gate. PRESENT only on a
     * `plan_review` pause whose requesting call's frame carried a plan card; ABSENT otherwise (a card left off the frame
     * for size included), which means "nothing to compare", never "an empty plan". Echo of the committed row's
     * {@link import("./checkpoint-store.js").PendingAction} `plan_review.planContentHash` — one write, at the park mint.
     */
    planContentHash?: string;
    /**
     * `true` when approving or editing this plan_review pause asks the leg to leave plan mode: the committed row recorded the
     * leg's declared mode at the pause as `plan`. ABSENT otherwise — never `false`: on every other pause, and on a `plan_review`
     * parked outside plan (a caller tool's `requestReview`, a leg switched out of plan after the call). A REQUEST, not an
     * outcome: the resumed leg asks for the word the resume re-passes (when it is not `plan`), else the one it had before plan,
     * else its default; a host's root leg leaves plan, while a delegated leg that can park (a background child, a workflow
     * member) stays clamped under its parent's mode. Read off the committed row by the same reader as
     * {@link import("./checkpoint-store.js").CheckpointSummary.approvalRequestsPlanExit}; the resume's mode request reads the
     * same answer (`approvalRequestsPlanExit`). Not stored on the row.
     */
    approvalRequestsPlanExit?: true;
    /**
     * HOW the paused task's remote workspace will come back, present whenever the pause captured a
     * remote workspace. The two modes bill and behave very differently:
     * - `"snapshot"` — the workspace VM was `suspendVM`-paused into a snapshot. Provider billing
     *   typically stops; in-memory process state is captured; resume restores it.
     * - `"park_only"` — the env declared itself non-suspendable (an SSH host / an ADB device), so
     *   NOTHING was paused: the machine keeps running (and keeps costing), any in-memory process state
     *   is at the target's mercy, and resume simply reconnects to the still-present workspace.
     *   Deliberate and honest (core does not fabricate a snapshot) — but a scheduler that assumes
     *   "paused ⇒ idle and free" must be able to see it.
     * ABSENT for a process-local pause (a static caller-owned env: no remote workspace was captured).
     * The same discriminant rides {@link import("./checkpoint-store.js").CheckpointSummary} for the
     * inbox/`listByScope` face.
     */
    restoreMode?: "snapshot" | "park_only";
};
/**
 * The machine-readable account a `completed` cause may carry ({@link TerminalCause}) — the shapes that complete yet may be
 * short, each read off the final assistant message. `kind` is closed (branch with a default arm; members join with a minor):
 *  - `finish_reason_unknown` — the final turn's provider ended it with a stream-end word the brain does not read; the turn
 *    was kept as the model left it.
 *  - `response_cut` — the final turn's answer stopped arriving before the provider ended it (the stream went silent past
 *    its idle window, or the connection closed under it) and what had arrived was kept as the answer
 *    (`AssistantMessage.partialFinalized`): the run's continuations of the cut answer ran out, or none could follow it.
 *    `result` holds what arrived; the answer may be incomplete.
 */
export type TerminalCompletedDetail = {
    kind: "finish_reason_unknown";
    /** The provider's stream-end word, in the provider echo shape (`?` when it had bytes outside it). */
    finishReasonUnknown: string;
} | {
    kind: "response_cut";
};
/**
 * The machine-readable account a `failed` cause may carry ({@link TerminalCause}) — the ONE projection of a fact the
 * failure's mint point already stated, carried as it was stated (a missing fact stays missing; nothing is re-derived
 * from the message). `kind` is closed:
 *  - `provider_rejected` — the provider REFUSED the request as sent (a 4xx answer) and that refusal named the result:
 *    the terminal message's refusal account (`apiErrorStatus` / `apiErrorCode` / the provider-condition verdict / the
 *    request's `apiErrorRoute`).
 *  - `coded` — a failure THROWN with a machine code whose throw site stated a structured `detail` beside it (e.g. a
 *    `CheckpointError`'s `{ reason }` on `resume.parent_constraint_mismatch`): that detail, as a JSON-plain snapshot.
 *    `terminal.code` is the same error's code.
 *  - `model_output_invalid` — the model's turn failed because its tool calls could not be executed: the terminal
 *    message's `modelOutputInvalid` account.
 * New members join with a minor; a consumer that branches on `kind` keeps a default arm.
 */
export type TerminalFailureDetail = {
    kind: "provider_rejected";
    /** The refusal's HTTP status, 400–499. */
    status: number;
    /** The provider's own word for the refusal (its error envelope's `error.code`, else `error.type`), when stated. */
    code?: string;
    /**
     * What the refusal says about the account — the engine's closed word for it (`PROVIDER_CONDITIONS`), judged off
     * the provider dialect table by where the request went: `quota_exhausted` (stop; someone must act or a window
     * must reset), `throttled` / `overloaded` / `unknown` (a retryable condition the retry budget ran out on, or the
     * provider's own `x-should-retry: false` stopped), `stop_other` (credentials, model access, the request itself).
     * The terminal's reading of the same verdict the call's retry frames carried. Present whenever the terminal
     * message states one (`AssistantMessage.providerCondition`); a host-minted message that did not judge leaves it
     * absent.
     */
    providerCondition?: ProviderCondition;
    /** Which evidence {@link providerCondition} rests on. Present exactly when it is. */
    providerConditionSource?: ProviderConditionSource;
    /** The terminal message's `providerResetAtMs`, carried beside a `quota_exhausted` condition. */
    providerResetAtMs?: number;
    /**
     * The provider's own sentence for the refusal — its error envelope's `error.message`, after the one pass over a remote's words: the
     * request's declared values and credential shapes masked, a URL or a multi-segment path withheld, one line, at most 240 code points. The
     * retry frames of the same call carry the same member. Present when the refusal's body ended and parsed as a provider envelope that states a
     * sentence; absent for a plain-text, torn, unended or empty body — the account says the provider stated no trusted sentence, never an empty one.
     */
    providerMessage?: string;
    /**
     * The route the refused request took (`AssistantMessage.apiErrorRoute`): where its credential came from, how it
     * rode, which knob named its root — the knob words of `ROUTE_CREDENTIAL_PAIRING`, never a key value or a URL.
     * Present whenever the terminal message states one (the first-party brains always do); a host-minted message that
     * states none leaves it absent.
     */
    route?: RequestRoute;
    /**
     * Which part of the request the refusal named, when the engine classified it off the provider's envelope at the brain
     * boundary — the terminal message's own `errorKind`, carried when it is one of {@link REFUSED_REQUEST_PARTS}:
     * `input_too_long` (the input alone exceeds the context limit), `image_unprocessable` (an image could not be
     * processed), `tool_schema_refused` (one tool's input schema; {@link tool} names it), `output_cap_too_large` (the
     * request's output cap is above what the model allows; nothing re-sends it — {@link outputCap} carries the two numbers
     * when the provider's sentence stated them), `media_items_refused` (too many or oversized media blocks; the request
     * media trim had no lower rung to re-send it at). Absent when the refusal named
     * no part this engine classifies — the account says nothing about it, and nothing is read from the provider's words.
     */
    errorKind?: RefusedRequestPart;
    /** With `errorKind: "tool_schema_refused"`: the tool whose input schema the provider refused (the message's
     *  `refusedTool`). A tool the engine could not send without its schema (not an MCP / A2A tool, or the transcript's bound
     *  of 8 reached) ends the run here; one it could is re-sent and never names a terminal. */
    tool?: string;
    /** With `errorKind: "output_cap_too_large"`: the output cap the request carried as the provider echoed it (`requested`) and
     *  the most the model allows (`allowed`), read off its sentence (the message's `refusedOutputCap`). Present only when both
     *  are exact integers with `requested > allowed >= 1` ({@link outputCapReportOf}); a host lowers its cap to `allowed`. */
    outputCap?: {
        readonly requested: number;
        readonly allowed: number;
    };
} | {
    kind: "coded";
    /**
     * The thrown error's own `detail`, as its throw site stated it — a snapshot of its JSON-plain members (strings,
     * finite numbers, booleans, null, and arrays / plain objects of those, bounded; a member of any other kind is left
     * out; bytes — an `ArrayBuffer` view, an index-keyed object — are never a record). An ARRAY is one fact: when a bound
     * (64 entries per container, 4096 characters per string, depth 4, 256 values and 16384 characters in all) leaves out any
     * element of it, or a member of an element record, the array is absent whole — never a shorter list or a cut row — and
     * what it had spent of the bounds goes back, so the members after it are judged as if it were not there (a record's
     * own members that do not fit are left out one by one, as before). A member under a credential
     * name (the env-credential judge's names: `password`, `apiKey`, `token` …) stands as the bare redaction mark (`REDACTION_MARKS.bare`), unread; every
     * other string leaf passes the secret-tier redaction (credential shapes masked; a path is kept — it rides this
     * structured seat, never `message`); a member whose key is not JSON-safe (visible ASCII 1–128, nothing the
     * redaction would mask) is left out. Read off the same link of the error's `cause` chain whose `code` became
     * `terminal.code`. PRESENCE: only when that link carried a plain-object `detail` with at least one such member, or one a bound
     * cut ({@link omitted}), or is a configuration refusal whose input the engine knows (below) — a code thrown with none of those
     * (or a higher-ranked terminal that named the result) leaves the whole account absent.
     *
     * One member is the engine's own, never the thrower's: `input` — on a `config.*` / `resume_at.*` refusal of a leg's prepare,
     * which input must change for the refusal to go away (`ConfigRefusalInput`: `taskConfig` the request, `deps` the deployment,
     * `inheritedGate` a resumed row's recorded gate). It comes first, costs none of the bounds above, and a member of that
     * name in the thrown `detail` is left out; read it with `configRefusalInputOf`.
     */
    detail: CodedFailureDetail;
    /**
     * The names of the thrown `detail`'s own members a bound above left out of `detail`, or cut into (an array dropped whole, a
     * record that lost a member, a string too long, a member the snapshot's totals had no room for), in the detail's member order
     * — so a member absent from `detail` reads as "too large to carry" when it is named here and as "not stated" when it is not.
     * Never counted against the bounds; at most 64 names — a detail with more own members than the entry bound admits is left out
     * whole and named by its first 64, the rest counted in {@link omittedMore}. A member left out for its kind (a function, bytes)
     * or for its key is not named. PRESENCE: exactly when a bound cut something; `detail` is then present even if no member fit (`{}`).
     * It sits on this arm of `terminal.detail` (`terminal.detail.omitted`), beside the account's own `detail` — not on the terminal.
     */
    omitted?: readonly string[];
    /**
     * How many more of the thrown `detail`'s own members a bound cut than {@link omitted} names (it names 64 at most): a member past
     * those is "too large to carry" too, unnamed. Counts only members whose key could have been named (a key left out for its shape,
     * or for carrying a credential, is in neither). PRESENCE: only when more than 64 such were cut.
     */
    omittedMore?: number;
} | {
    kind: "model_output_invalid";
    /** Which drop cause failed the turn (`MODEL_OUTPUT_INVALID_CAUSES`: `truncated` — a call not received in full, its
     *  arguments cut before they parsed or the call still open at a stream frame the brain could not read or place;
     *  `unnamed` — a call with no tool name). The same words the person's line for an incomplete tool turn carries in `detail.cause`. */
    cause: ModelOutputInvalidCause;
    /** With `truncated`: the output-cap facts the stream reported (the cap stop, the counted output, the request's
     *  cap) — what the brain's sentence words as its cap clause. */
    outputLimit?: OutputLimit;
};
/** The parts of a request a provider's refusal can name that the brain boundary classifies — the closed set of
 *  `provider_rejected.errorKind` ({@link TerminalFailureDetail}). New members join with a minor. */
export declare const REFUSED_REQUEST_PARTS: readonly ["input_too_long", "image_unprocessable", "tool_schema_refused", "output_cap_too_large", "media_items_refused"];
export type RefusedRequestPart = (typeof REFUSED_REQUEST_PARTS)[number];
/** The two numbers of an output cap refused as above the model's allowance: the cap the request carried, the most the model allows. */
export interface OutputCapReport {
    readonly requested: number;
    readonly allowed: number;
}
/** `v` as such a pair, copied, when it is one as the provider can state it — exact integers, `requested > allowed >= 1` — each
 *  member read once; else `undefined`. */
export declare function outputCapReportOf(v: unknown): OutputCapReport | undefined;
/** A JSON-plain value as a `coded` account carries it. */
export type CodedFailureDetailValue = string | number | boolean | null | readonly CodedFailureDetailValue[] | {
    readonly [key: string]: CodedFailureDetailValue;
};
/** The `coded` account's body: the thrown error's `detail` members ({@link TerminalFailureDetail}). */
export type CodedFailureDetail = {
    readonly [key: string]: CodedFailureDetailValue;
};
/**
 * The endings of a `userPromptSubmit` hook that keep a prompt from being submitted — the closed set of
 * {@link TerminalBlockedDetail.cause} words:
 * - `"block"` — the hook answered and refused the prompt (its words ride `hookReason`).
 * - `"crashed"` — the hook threw or rejected; the seat is fail-closed, a screen that failed has not cleared the prompt.
 * - `"timeout"` — the hook did not answer within its `timeoutMs` bound; fail-closed the same way.
 * - `"cancelled"` — the task was cancelled while the hook was still screening.
 */
export declare const PROMPT_BLOCK_CAUSES: readonly ["block", "crashed", "timeout", "cancelled"];
export type PromptBlockCause = (typeof PROMPT_BLOCK_CAUSES)[number];
/** Membership test for {@link PromptBlockCause}. */
export declare function isPromptBlockCause(v: unknown): v is PromptBlockCause;
/** The machine-readable account a `blocked` cause may carry ({@link TerminalCause}). `kind` is closed; one member. */
export interface TerminalBlockedDetail {
    kind: "prompt_blocked_by_hook";
    /** Which of the hook seat's endings kept the prompt back ({@link PROMPT_BLOCK_CAUSES}). */
    cause: PromptBlockCause;
    /**
     * The hook's own words for refusing the prompt, folded to one line, bounded, with the engine's envelope tags
     * defused — still the hook's text, so a consumer renders it as untrusted. PRESENT only on cause `"block"` and
     * only when the hook gave words; never carries the engine's reminder frame or its session mark (the framed
     * sentence is `reason`).
     */
    hookReason?: string;
}
/** The paused arm alone — the shape the run's committed-pause holder carries. */
/**
 * The one disposition table over `TerminalCause["kind"]`: which causes a resume journal may REPLAY
 * instead of re-running. Only a completed cause is a finished leg; every other cause means the leg has
 * work left (or failed) and a resume runs it live. The table is also the admission list for a journal
 * entry's cause at load: a kind absent here (a journal written before `TaskResult.terminal`, a corrupted
 * or version-skewed entry) is refused before anything is dispatched — it is never read as "not
 * completed, so run it again", which would replay the side effects of finished work.
 */
export declare const TERMINAL_CAUSE_IS_REPLAYABLE: {
    readonly completed: true;
    readonly failed: false;
    readonly blocked: false;
    readonly paused: false;
};
/** Compile-time fence: every `TerminalCause` kind has a row in the replay table (and, via `satisfies`, only those). */
export type ReplayTableCoversEveryTerminalCause = AssertAllKeysHandled<Exclude<TerminalCause["kind"], keyof typeof TERMINAL_CAUSE_IS_REPLAYABLE>>;
/** The admission read for a journaled cause: a closed-set member, by table row. */
export declare function isTerminalCauseKind(kind: unknown): kind is TerminalCause["kind"];
export type PausedCause = Extract<TerminalCause, {
    kind: "paused";
}>;
/**
 * The run's own cancellation as a thrown value — its ONE mint (the leg's entry before the first turn, and the restore
 * seat around its establishment call). It carries no `code` by design: a cancelled run's terminal is
 * `{ kind: "failed", message: "run aborted" }`, whatever step it was cancelled at.
 */
export declare function runAbortedError(): Error;
