@sema-agent/core
Version:
Stateless, task-oriented AI agent core
183 lines (182 loc) • 15.7 kB
TypeScript
/**
* Why a resume could not run its approved action — ONE reading of the failure's code, shared by every
* consumer that has to act on it: the reopen compensation (which {@link ReopenReason} a consumed
* checkpoint returns to pending under) and the parked-resume receipt (the `cause` its caller branches on).
* The answer is read from the failure's CODE — a thrown value's `cause` chain, or a failed result's
* terminal code — never from its sentence; a code this table does not name reads as ABSENT (not known),
* which each consumer answers in its own documented way rather than with a guessed cause.
*
* · `environment` — the leg's infrastructure failed (the workspace restore, an abort, the engine's `env.lifetime_expired`, a
* deployment's `env.*` refusal once the decision was delivered or the row replays one): the decision is untouched, a retry replays it;
* · `session_gone` — the resumed agent's transcript session is missing;
* · `transcript_corrupt` — the resumed agent's transcript session is THERE but cannot be read as a session
* (`corrupt_session`): its log has no header its store wrote, or its entry tree does not hold together — a leaf,
* a parent or the entry its checkpoint was cut at that is not in the log, a parent chain that loops. A store outside
* this package that answers the same fact `invalid_session` reads the same way. Distinct from `session_gone`: the
* bytes exist, so deleting or restoring the transcript is the remedy, not re-creating a session;
* · `tool_unavailable` — the approved tool is not available to the resumed leg (gone, replaced by a
* different contract, or an inherited tool the drive cannot hand over): this approval cannot run, and a
* fresh decision resolves it;
* · `configuration` — the deployment refuses the resumed leg: its configuration (a `config.*` door, the
* pre-claim configuration screen, a re-supplied constraint chain that is missing or does not match its
* installation record) or its execution environment refusing itself before any decision was delivered or replayed on the row (a
* deployment's own `env.*` code): a retry under the same deployment fails the same way;
* · `decision_rejected` — the supplied decision does not fit the checkpoint (another gate's answer, an
* unsafe payload, an input the constraints refuse): correct the decision and resubmit. A refusal of the row itself
* (`checkpoint.invalid_outcome` carrying a `reason`) is not this: no decision cures it, and no cause names it;
* · `superseded` — the run's grant stopped being current after the resume's claim won (`holder.superseded`): the row is not this
* run's any more. This run does not resume it again, ask for a fresh decision, or expire it: it is the run's current holder's,
* whatever state it is in now (a row put back to pending is replayed by that holder). This is the one cause where "can resuming
* again cure it" is not this run's question, so {@link resumeAgainMayCure} has no answer for it.
*/
import type { AssertAllKeysHandled } from "./ask-origin.js";
import { type CorruptSessionForm } from "../internal/harness.js";
import type { Checkpoint, CheckpointStore, CheckpointToken } from "./checkpoint-store.js";
import type { TerminalFailureDetail, UnstartedRowOutcome } from "./terminal-cause.js";
/**
* design/80 D-1: why a consumed checkpoint was {@link import("./checkpoint-store.js").CheckpointStore.reopen | reopened}
* (resolved → pending). The reason drives re-resume validation (§3 invariant #1): an `env_failed` reopen is a SYSTEM
* RETRY of the ALREADY-APPROVED action — the re-resume MUST replay the persisted
* {@link import("./checkpoint-store.js").ResolvedOutcome} winner, never a new vote — while a `tool_unavailable` reopen
* (the action could not run, may now be invalid — P-7) lets a human RE-DECIDE with the tool present, so a fresh
* operator decision IS allowed.
*
* `constraint_rejected` (F-012 L3) carries the same FRESH-REDECISION semantics as `tool_unavailable`:
* a resolve was retracted because its decided INPUT failed a constraint re-adjudication (a frozen
* ancestor projection / resume-edit policy denied the approver's edit) — the ask itself is unconsumed,
* so the returned-to-pending row takes a fresh operator decision, never a forced replay of the
* rejected one. Core's own edit re-adjudication runs PRE-CAS (nothing to reopen there); this reason
* exists for a deployment lane that discovers the same rejection only after its own resolve landed
* and must return the row to pending without inventing an out-of-vocabulary reason.
*
* `config_refused` carries the same FRESH-REDECISION semantics: the deployment — its configuration, or its execution
* environment refusing itself — refused the resumed leg before its approved action started, so a retry under the same
* deployment fails the same way — it is not a system retry, and the row takes a fresh decision (or the same one again once
* the deployment is corrected). Which reason a failure reopens under is {@link reopenReasonOf}'s answer.
*/
export declare const REOPEN_REASONS: readonly ["env_failed", "tool_unavailable", "constraint_rejected", "config_refused"];
export type ReopenReason = (typeof REOPEN_REASONS)[number];
export declare const RESUME_STARTUP_CAUSES: readonly ["environment", "session_gone", "transcript_corrupt", "tool_unavailable", "configuration", "decision_rejected", "superseded"];
export type ResumeStartupCause = (typeof RESUME_STARTUP_CAUSES)[number];
/** The cause a resume failure's code names; `undefined` when the code is absent or the table does not
* name it. Every `config.*` code is a configuration door's refusal; every deployment's own `env.` code (spelled as
* `isDeploymentEnvCode` reads it) but the engine's `env.lifetime_expired` (a table row) is the deployment's execution environment
* refusing itself (its factory's throw, an answer at the leg's restore seat, its snapshot restore or its model shell's readiness):
* both read `configuration`. Another `env.`-prefixed string reads `environment`, as it did. The terminal code table files both
* namespaces under `WorkerErrorClass` `config` — that answers which class and what to change; this answers why the resume could
* not run. A leg's own failure is read by {@link unstartedFailureOf}, which also weighs delivery and the row's replay-only state.
*
* `refusal` — the refusal's own members, when the failure states them ({@link resumeRefusalDetailOf}): `checkpoint.invalid_outcome`
* carrying a `reason` is a refusal of the row itself (that code's one rule: its `reason` names a damaged row, its `field` a decision
* cell), so no decision is to be corrected and no cause names it — `undefined`, the row's own word riding `refusal.reason`. */
export declare function resumeStartupCauseOf(code: string | undefined, refusal?: ResumeRefusalDetail): ResumeStartupCause | undefined;
/**
* The members of a resume refusal's `detail` the parked-resume receipt carries beside its `cause` — the three a
* {@link import("./checkpoint-store.js").CheckpointError} states where its `code` alone does not say which input or which arm refused:
* `code` (on `checkpoint.config_refused`: prepare's own code, the word a fresh run of the same bad config reports), `field` (which
* input carries the refusal) and `reason` (which arm fired) — and the one a `corrupt_session` states, `form` (which way the transcript is
* damaged, a word of `CORRUPT_SESSION_FORMS`; a word outside that set is left out). Their words are those families' own; the receipt adds no word of its own.
*/
export declare const RESUME_REFUSAL_MEMBERS: readonly ["code", "field", "reason", "form"];
/** {@link RESUME_REFUSAL_MEMBERS} as the receipt carries them: each a string, each present only when the failure stated it. */
export type ResumeRefusalDetail = {
readonly [K in (typeof RESUME_REFUSAL_MEMBERS)[number]]?: string;
};
/**
* The refusal members a failed resume stated, read from the failure's coded account ({@link TerminalFailureDetail}, `kind: "coded"`:
* the `detail` its throw site stated) — never from its sentence. `undefined` when the failure carries no coded account or none of
* the members is a string in it (`form`: a word of the closed set).
*/
export declare function resumeRefusalDetailOf(account: TerminalFailureDetail | undefined): ResumeRefusalDetail | undefined;
declare const REOPEN_REASON_OF_CAUSE: {
readonly environment: "env_failed";
readonly session_gone: "env_failed";
readonly transcript_corrupt: "env_failed";
readonly tool_unavailable: "tool_unavailable";
readonly configuration: "config_refused";
readonly decision_rejected: "constraint_rejected";
readonly superseded: "env_failed";
};
export type ReopenReasonTableCoversEveryCause = AssertAllKeysHandled<Exclude<ResumeStartupCause, keyof typeof REOPEN_REASON_OF_CAUSE>>;
/**
* The reason a consumed checkpoint whose approved action never started returns to pending under. A failure
* whose cause is not known reopens as `env_failed`: the leg went away before the action ran, the human's
* decision is untouched, and the retry replays it.
*/
export declare function reopenReasonOf(cause: ResumeStartupCause | undefined): ReopenReason;
/** {@link RESUME_AGAIN_MAY_CURE}'s answer for `cause`; a cause not known (`undefined`) answers as the `env_failed` reopen it takes:
* yes. `undefined` for a cause whose row is not this run's (`superseded`): no answer, and no host move follows from one. */
export declare function resumeAgainMayCure(cause: ResumeStartupCause | undefined): boolean | undefined;
/** What a resume leg's failure says of itself, as the reopened sentence reads it: its cause, the transcript's form when the failure
* states one, and the session store the transcript is in (whose doors the way out of that form names). */
export interface UnstartedFailure {
readonly cause: ResumeStartupCause | undefined;
readonly form?: CorruptSessionForm;
readonly sessions?: object;
}
/** The {@link UnstartedFailure} of a resumed leg's failure — its code and coded account (read by {@link resumeStartupCauseOf} and
* {@link resumeRefusalDetailOf}, never from its sentence), over `sessions`. A deployment's `env.` refusal takes a fresh decision
* (`configuration`) only on a row that never replayed one: it reads `environment` (the row replays its decision) when the leg had
* delivered its decision (`decisionDelivered`) or the row it claimed was already a replay-only reopen (`cp.reopenReason`, the row as
* read before the claim) — a row once reopened replay-only stays replay-only. */
export declare function unstartedFailureOf(code: string | undefined, account: TerminalFailureDetail | undefined, sessions: object, resume: {
readonly decisionDelivered?: boolean;
readonly cp: Pick<Checkpoint, "reopenReason">;
} | undefined): UnstartedFailure;
/** The facts each {@link UnstartedRowOutcome} word carries in the engine's own record — a table over the one word set, total both ways. */
interface UnstartedRowFacts {
/** the reason the row was reopened under (pending again) */
readonly reopened: {
readonly reason: ReopenReason;
};
/** the store's `reopen` answered `false`: the row is no longer the resolved row this leg claimed — missing, expired, its decided
* action already disposed, or pending again — which the boolean does not say */
readonly declined: object;
/** what the reopen threw, when the row does not show it landed: the write may have committed and only its acknowledgement been
* lost, so the row's state cannot be proven from here */
readonly unknown: {
readonly thrown: unknown;
};
}
export type UnstartedRowFactsCoverEveryOutcome = AssertAllKeysHandled<Exclude<UnstartedRowOutcome, keyof UnstartedRowFacts> | Exclude<keyof UnstartedRowFacts, UnstartedRowOutcome>>;
/**
* What happened to a claimed row whose approved action never started — the one closed outcome every exit of such a leg reports
* (the thrown-prepare backstop, the returned-leg settle, the post-claim abort), its word ({@link UnstartedRowOutcome}, the one
* declaration every carrier reads) beside the facts that word carries ({@link UnstartedRowFacts}).
*/
export type UnstartedRow = {
[K in UnstartedRowOutcome]: {
readonly kind: K;
} & UnstartedRowFacts[K];
}[UnstartedRowOutcome];
/**
* THE compensation of a claimed leg whose approved action never started: the claim's reversal (`reopen`, bound to the row) asked once,
* under `reason`, and read into {@link UnstartedRow} — its answer, never a code sniffed off whatever it threw (a store's own error may
* carry any code, and a throw after a committed write is not a refusal). A reopen that threw is not an answer, so the row is asked
* (`claimedRowPending`, bound to the same row): only a row that shows the reopen landed is `reopened`. Any other reading — the row still
* claimed, claimed again by another resumer, gone, or unreadable — proves nothing about what this reopen did, and stays `unknown`.
* Every exit calls it; none re-reads the outcome another way.
*/
export declare function compensateUnstarted(reopen: (reason: ReopenReason) => Promise<"reopened" | "declined">, reason: ReopenReason, claimedRowPending: () => Promise<boolean>): Promise<UnstartedRow>;
/**
* THE one reading of what a claimed row's outcome leaves in place — the four things a retry of the row needs: the session's pin, the
* parked constraint entry, this process's record of the parked env, and the env a leg sent back to the row's workspace was minted.
* `true` when the row came back (`reopened`) or may have (`unknown` — destroying on state that cannot be proven is the refusal): all
* four stay. `false` when it did not (`declined`) or no compensation was asked (`undefined`: the action started, a negative decision
* was delivered, the leg completed or paused): each exit releases them as it always did. Both exits — the thrown one and the
* returned one — read this, over the answer their own compensation got.
*/
export declare function rowKeepsWhatItsRetryNeeds(row: UnstartedRowOutcome | undefined): boolean;
/**
* The row read {@link compensateUnstarted} asks after a reopen that threw, bound to the row the leg claimed: `true` only when the row
* reads `pending` at a generation past the one the claim won at (`claimed` is the row as the resume read it, before its claim) — the
* reopen having landed. A pending row at the claim's own generation is a read older than the claim, and proves nothing.
*/
export declare function claimedRowPendingOf(store: Pick<CheckpointStore, "get">, token: CheckpointToken, claimed: Pick<Checkpoint, "rev">): () => Promise<boolean>;
/** The sentence for {@link UnstartedRow} — one per outcome, the same on every exit; the exit puts its own lead before it. What
* never started and what the person gave are named by the kind of pause the claimed row was ({@link parkNounOf}): a wake is
* not an approval. Each says what happened, whether the pause is still waiting, and what to do — `declined` (the engine asked to put
* the pause back and was told it no longer is the one the resume took) and `unknown` (the attempt failed partway: it may or may not
* be waiting) differ in the one thing a reader must not do: ask for a new grant while the old one may still be usable. */
export declare function unstartedRowSentence(row: UnstartedRow, parked: Pick<Checkpoint, "pendingAction"> | undefined, failure?: UnstartedFailure): string;
export {};