@sema-agent/core
Version:
Stateless, task-oriented AI agent core
594 lines (593 loc) • 46.2 kB
TypeScript
import type { TaskResult } from "./types.js";
import { type CorruptBodyForm } from "./store-contracts/read-back-shape-contract.js";
/**
* design/97 CORE-7 — one recorded `ctx.agent` result in a workflow's RESUME journal. Unlike the observation-only
* {@link WorkflowRunStore} (best-effort, swallowed on throw), the journal is LOAD-BEARING: a resume replays the
* longest unchanged PREFIX of these (keyed by the deterministic {@link workflowAgentCallKey}) and runs only the
* first changed/new call + everything after it live. Same script + same args → 100% cache hit.
*/
export type WorkflowJournalEntry = {
/** The agent's deterministic call key (`ordinal:specIdentityHash@position`, the position empty outside every pipeline
* item; no `@` in a key written before positions existed) — the replay match key. */
callKey: string;
/** The agent's TaskResult, replayed verbatim when a resume's call key matches at the same ordinal. */
result: TaskResult;
parked?: never;
stopped?: never;
} | {
callKey: string;
result?: never;
parked?: never;
/**
* #4760 — the ordinal's member was STOPPED by a stop of the member itself (the run's `stopAgent`, a stream handle's `stop`):
* the leg's result as it ended, and who stopped it. A resume reaching this ordinal with a matching call key replays it as
* stopped (`killed`, by that stopper — the script gets the same value back) and never runs it again. A different key from
* `result` for the reason `parked` is one: a reader from before this arm finds neither key it reads and refuses the whole
* resume (`WorkflowJournalIncompatibleError`) instead of running the stopped member again.
*/
stopped: {
readonly result: TaskResult;
readonly stoppedBy: string;
};
} | {
callKey: string;
result?: never;
stopped?: never;
/**
* The ordinal's leg is PARKED at a durable approval gate: the child's own paused `TaskResult`
* (its `terminal` carries the checkpoint token + gate, its `sessionId` the pinned session). A resume
* reaching this ordinal with a matching call key does NOT run the call live (the parked child's
* session is pinned under a pending checkpoint; a fresh spawn would duplicate it) — it drives the
* parked child's resume when the caller hands it a decision for the token, else re-parks. Deliberately
* a DIFFERENT key from `result`: a journal reader from before this entry kind existed finds no
* `result.terminal` and refuses the whole resume (`WorkflowJournalIncompatibleError`) instead of
* admitting a paused cause it would re-run live — one-way, loud, like every journal schema step.
*/
parked: TaskResult & {
terminal: Extract<TaskResult["terminal"], {
kind: "paused";
}>;
};
};
/** What {@link readWorkflowJournalEntry} answers: the entry, or the corrupt form the row takes plus a clause
* naming what is wrong with it (worded to follow "journal entry #N"; it quotes no stored value). */
export type WorkflowJournalEntryReading = {
entry: WorkflowJournalEntry;
} | {
corrupt: CorruptBodyForm;
why: string;
};
/**
* The ONE reading of a journal row read back from a store: which arm it is, and whether the arm carries what a
* resume reads from it — an object result, or a paused terminal with its checkpoint token (the payload's other
* members, `sessionId` / `gate` / `stats` among them, are not judged here). `raw` is the DECODED LOGICAL ROW — an object carrying
* `callKey` and exactly one of `result` / `parked`; how a backend encodes that row on its medium (a JSONL
* line with its own `scope` / `ordinal` members, a SQL column holding an envelope) is the backend's format
* and is decoded before this is asked. Members other than those three are not read and are not carried into
* the entry, which is minted fresh from them.
*
* Corrupt, by form:
* - `not-an-object` — the row is not an object;
* - `missing-required` — no `callKey`; neither arm; a parked arm whose result carries no `terminal`, or
* whose paused terminal carries no `token`;
* - `wrong-type` — a non-string `callKey`; BOTH arms (the union admits one); a `result` that is not an
* object; a `parked` that is not an object; a parked arm whose terminal is not `paused`, or whose token
* is not a non-empty string.
*
* The parked arm's paused terminal and its checkpoint token are judged here because the type requires them
* and the arm is load-bearing: a row that says it parked but holds no paused result with a token can neither
* be driven nor be replayed as a finished call, and answering it as either would let a resume run that
* ordinal again beside the child pinned under its pending checkpoint. Whether a COMPLETED result carries a
* terminal cause the engine can replay is the resume's own admission (a journal written before
* `TaskResult.terminal` is incompatible, not damaged).
*/
export declare function readWorkflowJournalEntry(raw: unknown): WorkflowJournalEntryReading;
/**
* Clamp an externally-supplied run identifier before it lands in a persisted field or an error message:
* `resumeFromRunId` is LLM-controlled text and a resume claim's `holder` is store-supplied, so neither may
* carry control characters / unbounded length into a record a human or a model reads.
*/
export declare function clampRunIdText(raw: string): string;
/** The code of {@link WorkflowJournalIncompatibleError} — the word the journal store kit asserts on a refused `load`. */
export declare const JOURNAL_INCOMPATIBLE_ERROR_CODE = "workflow.journal_incompatible";
/** A resume journal entry the resume cannot admit is INCOMPATIBLE, and the resume is refused before any work is
* dispatched: a row whose result carries no terminal cause (a journal written before `TaskResult.terminal`), or
* a row {@link readWorkflowJournalEntry} reads as corrupt — refused by the engine's admission, or by a store's
* own `load` (the journal store kit holds a backend's refused `load` to this code). The alternative (letting the
* entry diverge into a live re-run) would execute the already-completed prefix again, side effects included.
*
* `entry` is the row as read: when the journal reader finds it corrupt, the message carries that reader's clause
* (fixed text that quotes no stored value), so no caller-supplied text reaches it; absent, or a row the reader
* admits, the clause is the missing terminal cause. A backend whose own medium holds a line that is not one of the
* run's records refuses with {@link WorkflowJournalIncompatibleError.ledgerLine}. `ordinal` is `-1` when the refusal
* names no entry ordinal: a row with no readable call key, or a ledger line. The run id is clamped here. */
export declare class WorkflowJournalIncompatibleError extends Error {
readonly ordinal: number;
readonly code = "workflow.journal_incompatible";
readonly fromRunId: string;
constructor(fromRunId: string, ordinal: number, entry?: unknown);
/** The refusal for line `line` (1-based) of a backend's ledger that is not one of the run's records, judged `form`
* by the backend's line reader: dropping it would leave whatever it held looking never journaled. */
static ledgerLine(fromRunId: string, line: number, form: CorruptBodyForm): WorkflowJournalIncompatibleError;
}
/**
* What a workflow run was launched with — written ONCE by the engine, before the script body runs, and read back by the
* engine's own continuation of that run (a person decided a card the run parked on after it ended): the resolved script,
* the merged args the script received, and the call's other arguments as the launching gate saw them (a named launch's
* `name`, a `scriptPath` …; the script body and the args live in their own members and are not repeated there, and a
* resume's `resumeFromRunId` is not one of them). The one home of "what this run was started with": the script store's
* per-run file is the model's draft and may be edited, so a continuation never reads it.
*/
export interface WorkflowLaunchRecord {
readonly script: string;
/** The merged args the script received; absent for an argless launch. */
readonly effectiveArgs?: unknown;
readonly callArgs: Readonly<Record<string, unknown>>;
/** The host's model and thinking level the run's agents inherit — public identifiers only: `model` is the catalog key that
* chose the model, or, with `modelPinned: true`, the id of a model the host was handed as an object (a pin, never resolved
* through the catalog). Fixed at launch: every continuation of the run seats its agents on these, never on what the session
* uses by then (a member left out = the launch had none, and the continuation seats none). Absent on a record written
* before the member existed: such a continuation reads the session's current ones. */
readonly host?: {
readonly model?: string;
readonly modelPinned?: true;
readonly thinking?: string;
};
/** The presentation face the run's agents inherit from the host ({@link WorkflowLaunchFace}) — fixed at launch like `host`.
* Absent on a record written before the member existed: such a continuation reads the session's current face. */
readonly face?: WorkflowLaunchFace;
}
/**
* The host's presentation face as the launching leg had it, before the deployment's baseline is folded over it: its deferred
* tools, the tools it keeps loaded, its model-gate restore selector and its lean switch (a member left out = the host had none).
* What a workflow's agents inherit of how tools are presented to them — not what they may do: the deployment's baseline, the
* allowed models, the caps, the clamps and the posture are read when each run starts, and a change there refuses a continuation.
*/
export interface WorkflowLaunchFace {
readonly deferTools?: readonly string[];
readonly alwaysLoadTools?: readonly string[];
readonly restoreGatedTools?: readonly string[] | true;
readonly promptLean?: boolean;
}
/** A member read back in a shape it is never written in: its path in the record (`face.promptLean`). */
type LaunchDefect = {
readonly defect: string;
};
/**
* The one reading of a launch record read back from a store: the record (a fresh copy of its members), or the first member that
* is not the shape it is written in — `record` when the value is not a record at all. An absent member is absent; a member
* present as `null` (or any other shape) is that member's defect, never read as absent: a record read with a member dropped would
* seat a continuation on something its launch did not have. `effectiveArgs` is the script's own value and takes any shape.
*/
export declare function readLaunchRecordVerdict(raw: unknown): {
readonly record: WorkflowLaunchRecord;
} | LaunchDefect;
/** The record a store keeps for `raw` (its storage form, {@link launchRecordToKeep}), or `undefined` when `raw` is not one to keep —
* what a writer reads a record through before it keeps it, and what it keeps and compares a second write against
* ({@link sameLaunchRecord}). A reader of a KEPT record does not fold a defect into absence: it throws {@link WorkflowLaunchUnreadableError}. */
export declare function readWorkflowLaunchRecord(raw: unknown): WorkflowLaunchRecord | undefined;
/**
* {@link readWorkflowLaunchRecord} at a store's write door — the one reading every `recordLaunch` applies before it keeps or compares a record
* (both bundled stores read the record they are handed through it): the record to keep (its STORAGE form, as {@link readWorkflowLaunchRecord}
* answers), or a refusal.
*
* Throws an `Error` (no subclass, no `code`) whose message is `workflow journal: the launch record for <runId> is not one to keep — <why>`, where
* `<why>` names the member and, for a payload, the place and the kind of fault, never a value: `it is not a record` (the value is no record);
* `its effectiveArgs hold <fault> at effectiveArgs.<path>` (the same for `callArgs`; the place is `effectiveArgs` alone for a fault of the payload's own top
* level, and absent for containers nested deeper than the bound) — a payload value the store's JSON form cannot keep as it is: a number
* that is not finite, a hole or an undefined element in a list, a named member on a list, one object met twice (a shared reference), a `Date`, a
* function, a getter or any other object that is not plain data, or containers nested too deep — followed by the clause
* `— a value a store's JSON form cannot keep as it is`; or `its <member> is not the shape a launch record's is` (the script, the call arguments, the host or the face is
* not what a record carries; `<member>` is the first defective member, as {@link WorkflowLaunchUnreadableError.member} names one). `runId` is
* only said in the sentence. A store twin that writes the same record form calls this and lets what it throws through, so the refusal reads the same
* on every backend.
*/
export declare function launchRecordToKeepOrThrow(runId: string, raw: unknown): WorkflowLaunchRecord;
/** The `code` of {@link WorkflowLaunchUnreadableError}. */
export declare const WORKFLOW_LAUNCH_UNREADABLE_CODE = "workflow.launch_unreadable";
/**
* {@link WorkflowJournalStore.loadLaunch} on a record the store keeps that does not read back in the shape it was written in
* (a member present as `null` or of another shape, a file that does not parse): a fault of the record, never an absence — a
* continuation of the run is refused with the member named (`launch_unreadable`), and never seated on defaults. `member` = the
* record path of the first defective member (`host.thinking`, `face`, …; `record` when the value is not a record).
*/
export declare class WorkflowLaunchUnreadableError extends Error {
readonly runId: string;
readonly code = "workflow.launch_unreadable";
readonly member: string;
constructor(runId: string, raw: unknown);
}
/** What a continuation reads of a run's launch record: the record; `absent` (none kept under the scope); `defect` (the store keeps
* one that does not read back — its refusal, or an answer read through {@link readLaunchRecordVerdict}: the member named); or
* `failed` (the store threw otherwise — `cause.err` is the thrown value, unread here; a reader that tells it names its class
* only —, or did not answer within `boundMs`: no `cause`). */
export type KeptLaunchRead = {
readonly kind: "record";
readonly record: WorkflowLaunchRecord;
} | {
readonly kind: "absent";
} | {
readonly kind: "defect";
readonly member: string;
} | {
readonly kind: "failed";
readonly cause?: {
readonly err: unknown;
};
};
/** Read `runId`'s launch record the one way every continuation does (the engine's, and the model's own `resumeFromRunId`). It
* always settles: the store's value is read through the guarded readers (a revoked proxy, a getter that throws), and a reading that
* throws all the same answers `failed` with what it threw. */
export declare function readKeptLaunch(journal: WorkflowJournalStore & Required<Pick<WorkflowJournalStore, "loadLaunch">>, runId: string, scope: string, boundMs: number): Promise<KeptLaunchRead>;
/** The `code` of {@link WorkflowLaunchConflictError}. */
export declare const WORKFLOW_LAUNCH_CONFLICT_CODE = "workflow.launch_conflict";
/**
* A second {@link WorkflowJournalStore.recordLaunch} for a run whose launch record holds OTHER content: refused, the stored
* record kept. The same content again is no conflict (the write answers as the first did); only a different one is — a run is
* launched once, so two launch records for one run is a defect of the writer, never a newer value to take.
*/
export declare class WorkflowLaunchConflictError extends Error {
readonly runId: string;
readonly code = "workflow.launch_conflict";
constructor(runId: string);
}
/** The subject a launch record's oversize refusal names ({@link assertLaunchRecordFits}). */
export declare const LAUNCH_RECORD_SUBJECT = "launch record";
/**
* The size rule every {@link WorkflowJournalStore.recordLaunch} applies before it touches its medium — the journal's own
* per-entry cap ({@link MAX_JOURNAL_RESULT_BYTES}, UTF-8 bytes of the record's JSON), refused with the journal's own oversize
* refusal ({@link WorkflowJournalOversizeError}, code `workflow.journal_oversize`). A refused record is not written; the
* engine then runs the workflow without one (it never parks).
*/
export declare function assertLaunchRecordFits(record: WorkflowLaunchRecord): void;
/** Whether two launch records hold the same content (the canonical form of each): the write-once rule's "the same again". */
export declare function sameLaunchRecord(a: WorkflowLaunchRecord, b: WorkflowLaunchRecord): boolean;
/**
* The one door a workflow journal store passes where the engine receives it — `new Runner` (`RunnerDeps.workflowJournalStore`),
* the Workflow tool's mount (`RunWorkflowToolDeps.journalStore`) and `startWorkflow` (`RunWorkflowOptions.journalStore`): a store
* that takes resume claims ({@link WorkflowJournalStore.resumeClaim}) gives them back ({@link WorkflowJournalStore.releaseResumeClaim}).
* The engine gives a claim back when the run that took it ends; a store's expiry only frees one whose engine died holding it.
* A store with the first member and not the second is refused here (`config.invalid_argument`, the missing member named),
* never wired; a store with neither takes the engine's in-process table.
*/
export declare function assertJournalStoreGivesClaimsBack(store: unknown, seat: string): void;
/** Whether a journal store keeps launch records — both verbs, or none: a run launched where this answers `false` never
* parks (a card nothing could ever continue is never minted). */
export declare function journalKeepsLaunches(store: WorkflowJournalStore | undefined): store is WorkflowJournalStore & Required<Pick<WorkflowJournalStore, "recordLaunch" | "loadLaunch">>;
/** REF-D5: the resume-claim key triple — ONE shape for the interface pair and every implementation
* (it was re-inlined seven times; a key-field rename must red every leg at once). */
export interface ResumeClaimArgs {
/** The claim's key: the engine passes the ROOT of the resumed run's workflow tree (the run reached by following
* `resume.fromRunId` up), so one claim covers every run of the tree. An opaque id to the store, which keys by it verbatim. */
sourceRunId: string;
newRunId: string;
scope: string;
}
/** The longest remaining time a resume claim's answer can name: 24 hours, in milliseconds. */
export declare const RESUME_CLAIM_REMAINING_MS_MAX: number;
/** What a claim expiring at `expiresAt` has left at `now` (one clock), as the answer's member says it — `{ remainingMs }`, the whole
* millisecond up — or no member where no answer can say it: nothing left, or more than {@link RESUME_CLAIM_REMAINING_MS_MAX} (a clock
* stepped back past a day). The bundled stores' one reckoning. */
export declare function resumeClaimRemainingMember(expiresAt: number, now: number): {
remainingMs?: number;
};
/** What {@link WorkflowJournalStore.resumeClaim} answers — ONE shape for the interface and every implementation. */
export interface ResumeClaimAnswer {
granted: boolean;
/** On a refusal: the run id the claim is held for, when the store can attribute it. */
holder?: string;
/** How long the claim has left before the store's expiry frees it (if its holder never gives it back), in milliseconds by the
* STORE'S OWN clock: a safe integer from 1 to {@link RESUME_CLAIM_REMAINING_MS_MAX}, on a grant (the time the caller now holds)
* and on a refusal (the latest the refusal can stand). Answered only when the store can say. A remaining time, never an
* instant: no reader compares it with another machine's clock. The engine reads it on a refusal only, once, as it arrives —
* this machine's clock plus the remaining time, the latest instant the refusal names — and a refusal answering one that does
* not read (0 or less: refused while expired is a contradiction; not a safe integer; over the bound) names no instant and
* says the store's answer does not read. */
remainingMs?: number;
/** On a refusal because the key carries a permanent stop tombstone ({@link WorkflowJournalStore.stopResumeClaim}): who stopped
* the workflow tree. Reported explicitly by the store, never guessed by a caller from a prefix on `holder`. */
stopped?: {
readonly by: string;
};
}
/** Input to {@link WorkflowJournalStore.stopResumeClaim} (#5156 R1). */
export interface StopResumeClaimArgs {
/** The claim key (the workflow tree's root or tree id — opaque to the store, keyed verbatim as in {@link ResumeClaimArgs}). */
sourceRunId: string;
scope: string;
/** Non-empty identifier of who stopped the workflow tree (e.g. `"user"`, `"parent"`, `"system"`), echoed on
* {@link ResumeClaimAnswer.stopped}. */
stoppedBy: string;
/** When given, a binding claim currently held by THIS holder (arm (c): the caller's own in-process run, or a terminal run
* whose release failed) is rewritten into a tombstone in place; any other binding holder refuses without writing. */
holder?: string;
}
/** What {@link WorkflowJournalStore.stopResumeClaim} answers: `{ stopped: true }` once a tombstone stands on `(sourceRunId, scope)`,
* or `{ stopped: false, holder? }` when another binding holder owns the claim (nothing written). */
export type StopResumeClaimAnswer = {
readonly stopped: true;
} | {
readonly stopped: false;
readonly holder?: string;
};
/**
* The seam a resume reads/writes its journal through. Core ships {@link InMemoryWorkflowJournalStore}; a durable
* deployment provides a Postgres-backed one (service SVC-2) so a workflow survives a replica crash. The owner of
* a run is the sole writer of its journal.
*
* 🔐 `scope` (the TENANT/principal of the resuming run) is LOAD-BEARING for multi-tenant isolation (CORE-9 audit
* BLOCKER): an LLM controls the `resumeFromRunId`, so `load` MUST be constrained to the caller's scope — exactly
* as {@link WorkflowRunStore} puts scope in the WHERE of every method. A store implementation MUST return ONLY a
* run's journal whose recorded scope equals the requested `scope` (a cross-scope `resumeFromRunId` resolves to an
* EMPTY journal → the resume safely diverges to a live re-run, never disclosing another tenant's results).
*
* SESSION-axis RULING (ruled 2026-07-22):
* `load` is deliberately SCOPE-only, PERMANENTLY — same-scope callers from a different session may
* replay a run's journal. Rationale: (a) same-scope = same trust domain (the task-list store
* records the same posture) and a runId is engine-minted, not enumerable; (b) cross-session resume
* is `resumeFromRunId`'s CORE legitimate use — a fresh session picking up yesterday's run has a new
* taskId AND a new sessionId by construction, so ANY engine-side session/owner clamp on this face
* refuses exactly the contract the tool teaches (the prefix-replay pins are the regression
* proof; a γ-batch recheck attempt was reverted on them). Layering: the ENGINE owns the scope
* hard-wall (this WHERE); the SESSION acceptance arm belongs to the SERVING layer, which has a
* session-bound connection to adjudicate against (server 1.247's wire-face soft acceptance). This
* face diverges from poll/stop (scope+owner/session positive-match) BY DESIGN: they gate on the
* caller's CURRENT identity, resume asserts continuity with a PRIOR leg.
*/
export interface WorkflowJournalStore {
/** Entries for `runId` IF its recorded scope === `scope`, ASCENDING by ordinal; otherwise EMPTY (cross-scope). */
load(runId: string, scope: string): Promise<WorkflowJournalEntry[]>;
/** Record one agent's result under `(runId, scope)`. MUST be idempotent per `(runId, ordinal)` — a resumed run
* re-appends the cached results of its replayed prefix, so a second append for the same ordinal overwrites.
* The engine waits for the returned promise at most `RunWorkflowOptions.journalAppendTimeoutMs` (default 30 s);
* a store that has not answered by then is a store fault (`workflow.journal_append_timeout`), and the write is
* NOT cancelled — it may still land after the engine gave up on it, which idempotence makes harmless. */
append(runId: string, scope: string, entry: WorkflowJournalEntry): Promise<void>;
/** (CC diagnostics parity, additive): a HUMAN/MODEL-readable coordinate for this run's journal —
* the file store returns the on-disk jsonl path (CC "Read journal.jsonl" local form); a service store
* returns its API route (cloud form). `undefined`/absent ⇒ the completion notification's diagnostics
* line names no journal (the record behind its ref still carries every agent's row). Engine-facing string, never parsed. */
locator?(runId: string, scope: string): string | undefined;
/**
* Erase `runId`'s journal IF its recorded scope === `scope` (the {@link load} wall: a cross-scope call erases nothing) — the
* session-tree cascade's leg for a terminal run its session started ({@link import("./retention.js").RETENTION_CASCADE}).
* `true` = this call removed it; `false` = there was none under that scope. Idempotent; a store fault throws (a deletion
* face that cannot delete is loud). A later `load` of the id answers empty; the cascade deletes the run's record with it, and a
* resume from a run whose record is gone is refused before the load (`workflow.park_truth_unreadable`, `record_missing`). A resume
* claim naming the id holds ids only and is not this verb's (the claim's own release and sweep govern it). OPTIONAL: absent ⇒ this store's journals outlive their runs,
* and the deployment owns that gap.
*/
deleteRun?(runId: string, scope: string): Promise<boolean>;
/**
* Keep `runId`'s launch record under `scope`. WRITE ONCE: the engine is the one writer and writes it once per run, before
* the script body runs; a second record for the same id never replaces the first. A store fault throws (the engine then
* does not arm that run's parks). OPTIONAL with {@link loadLaunch} — both or neither ({@link journalKeepsLaunches}); a
* store with neither keeps no launch records, and a workflow run on it never parks.
*
* FORM: what is kept, compared and answered is the record's storage form ({@link readWorkflowLaunchRecord} — the form a JSON
* round trip hands back: a member holding `undefined` absent, `-0` as `0`); a record whose args hold a value JSON cannot keep as it
* is (a number that is not finite, a `Date`, a list hole …) is refused before the medium is touched, and the engine then runs the
* workflow without one.
* WRITE ONCE: the same record again (same scope, same content — {@link sameLaunchRecord} over the storage forms) answers as the first write did
* and changes nothing; a record with other content, or under another scope, is refused with
* {@link WorkflowLaunchConflictError} (`workflow.launch_conflict`) and the stored one kept. SIZE: a record over the journal's
* per-entry cap is refused before the medium is touched, with the journal's own oversize refusal
* ({@link assertLaunchRecordFits}: `workflow.journal_oversize`). RETENTION: kept no shorter than the same run's record in
* the run store — a sweep, truncation or compaction of the journal's ENTRIES must not take it (a card the run parked on
* stays decidable while the run is on record, and its continuation reads this record). Only this store's own
* {@link deleteRun} erases it — the journal's step of the session cascade (`RETENTION_CASCADE.workflowJournalStore`).
*/
recordLaunch?(runId: string, scope: string, launch: WorkflowLaunchRecord): Promise<void>;
/** The record {@link recordLaunch} kept for `runId` IF it was kept under `scope` (the {@link load} wall), exactly as it was
* written — an absent member stays absent, never `null`; `undefined` when there is none (never recorded, another scope,
* erased). A kept record that does not read back ({@link readLaunchRecordVerdict}) is refused with
* {@link WorkflowLaunchUnreadableError}, never answered `undefined`; the engine reads whatever is answered through the same
* verdict, so a store that answers a record with a `null` member gets the same refusal. */
loadLaunch?(runId: string, scope: string): Promise<WorkflowLaunchRecord | undefined>;
/**
* ADMISSION for a resume, so two concurrent
* `resumeFromRunId` legs off ONE source run cannot fork its execution.
*
* Why a store seam at all: the engine's own mutex is in-process only (`startWorkflow` refuses a duplicate
* `runId` and refuses resuming from a source still ACTIVE here). A resume mints a FRESH runId, so a second
* resume off the same source — from another process, replica, or a later session — trips neither guard: both
* legs replay the same prefix and then re-run the whole suffix LIVE, duplicating every side effect after it,
* each writing its own journal, neither ever seeing the other. The only place that fork is visible is the
* shared durable layer, i.e. here.
*
* OPTIONAL, and absence is a first-class state: a store that does NOT implement this has NO STORE-LEVEL lease
* semantics. A store without the hook is no longer completely
* unguarded, though — `runWorkflow`'s engine falls back to a process-local admission table for exactly this
* shape, so a same-process double `resumeFromRunId` off one source is still refused even against a store
* that never implements this member. That fallback cannot see a SECOND process, which is the one thing a
* real implementation is for — core's own {@link InMemoryWorkflowJournalStore} DOES implement this member
* (with in-process-only semantics; a single-process store cannot promise more), so the engine's fallback
* table is, in practice, only ever exercised by some OTHER store that omits the hook.
*
* A store that implements this member implements {@link releaseResumeClaim} too: one with this member alone is refused
* where the engine receives it ({@link assertJournalStoreGivesClaimsBack}), never wired.
*
* Contract:
* - `granted: true` ⇒ the caller (`newRunId`) now HOLDS the claim on `(sourceRunId, scope)` and owes exactly
* one {@link releaseResumeClaim} for it. The engine calls that at the run's terminal boundary — completed,
* failed, cancelled/aborted, or abandoned by a total-timeout — in a `finally`.
* - `granted: false` ⇒ someone else holds it. The engine REFUSES the resume with an explicit error rather
* than forking; `holder` (the holding leg's `newRunId`, when the store can attribute it) goes into that
* error text so an operator can find the run that is actually still going. `holder` is store-supplied text
* and is charset-clamped before it lands in a message. `remainingMs` (when the store can say) is how long its expiry
* leaves the claim standing, by the store's clock: the refusal names this machine's clock plus it as the latest moment the
* same resume goes through, for a holder that died holding it.
* - IDEMPOTENT for the same holder: a re-claim by the SAME `newRunId` on a claim it already holds MUST be
* granted (a retry must not deadlock a run against itself).
* - `scope` is the journal scope passed through VERBATIM. A claim is keyed by `(sourceRunId, scope)`,
* NOT by `sourceRunId` alone: a cross-scope caller already resolves to an EMPTY journal (the CORE-9 wall
* above) so it cannot fork anything, and letting it take a global claim would hand any tenant a
* denial-of-resume lever over another's runs. The engine's `sourceRunId` is the root of the resumed run's
* workflow tree ({@link ResumeClaimArgs.sourceRunId}): while one run of a tree holds the claim, no other
* run of that tree is started — the store keys by it as it keys by any id.
* - THROWING is a store failure, not a refusal — it propagates and fails the resume. Return `{granted:false}`
* to refuse.
* - A GRANT MEANS POSSESSION (RB-356①). `granted: true` may only be returned once
* the claim is RECORDED where every other contender will see it; a store that cannot tell whether it holds
* the claim must refuse, with `holder` omitted if it cannot attribute the winner. The asymmetry is the
* reason: an unearned refusal fails one resume loudly and is recoverable, an unearned grant forks a run
* and its duplicated side effects are not.
* - ACQUISITION MUST BE ATOMIC (RB-354). Contenders must never be able to observe a claim MID-ACQUISITION
* and read that state as "no claim" — an implementation that reserves the key first and fills the record
* in a second step needs the reservation itself to be the exclusion (SQL: one INSERT; core's file store:
* write a temp, then `link` it into place). Note this interacts with crash recovery: any rule of the form
* "an incomplete record is dead, take it over" is only safe if an in-flight acquisition can never look
* incomplete.
*
* TWO INVALIDATION DOMAINS, each covering what the other cannot — a store that takes claims carries both:
* 1. ENGINE release ({@link releaseResumeClaim}) — the normal path, prompt, covers every terminal outcome of a live
* engine. Required: a claim keys a whole workflow tree, so on a store that only expired claims every continuation
* of a workflow would wait out the claim of the one before it.
* 2. STORE TTL — only the backstop for an engine that DIED holding a claim (crash/kill/replica loss): it never
* reaches its `finally`, so only a store-side expiry can ever free that row. Server's SQL twins land this
* as the bake-store `idem_key UNIQUE` + TTL shape; core's in-memory and file stores carry the same TTL semantics.
* A store without expiry would wedge the tree's continuations for good once an engine died holding its claim.
* A store that can PROVE the holding engine gone may free its claim before the expiry (core's file store: a claim
* records the process that published it, judged by the one process-identity judgment); one that cannot tell keeps
* the expiry — freeing a claim on a guess is the fork this seam exists to prevent.
*/
resumeClaim?(input: ResumeClaimArgs): Promise<ResumeClaimAnswer>;
/**
* Release the claim {@link resumeClaim} granted to `newRunId` on `(sourceRunId, scope)`.
* Called by the engine at the resuming run's TERMINAL boundary (in a `finally`, so abort/error/abandon are
* covered), and ONLY when the matching claim was actually granted.
*
* MUST be idempotent and MUST NOT release a claim the caller does not hold: the claim may already be gone
* (TTL-reaped after a stall, then taken over by another leg), and unlinking the successor's claim would
* re-open exactly the fork this seam exists to prevent. A missing claim is a no-op, never an error.
*
* A throw here is swallowed by the engine — a release failure must never replace the run's real outcome, and
* the store's TTL is the standing backstop for the row it left behind.
*
* The engine's terminal boundary now BOUNDS this call (and its wait on
* the {@link resumeClaim} verdict) by a timeout — a store that hangs would otherwise keep the run's `done`
* promise pending forever, after the outcome is already decided. A release that outlives that bound is
* treated exactly like one that throws: swallowed, with the TTL as the backstop. Implementations should not
* rely on the engine waiting indefinitely for cleanup.
*/
releaseResumeClaim?(input: ResumeClaimArgs): Promise<void>;
/**
* Write a permanent stop tombstone on `(sourceRunId, scope)` in one compare-and-write (#5156 R1):
* - (a) row absent ⇒ write tombstone, answer `{ stopped: true }`;
* - (b) row no longer binds (expired, or holder process proven gone on a store that checks it) ⇒ replace with tombstone,
* answer `{ stopped: true }`;
* - (c) `holder` given and matches the current holder ⇒ rewrite in place into a tombstone (dropping any holder process),
* answer `{ stopped: true }`;
* - (d) already a tombstone ⇒ idempotent, preserve the existing tombstone as stored, answer `{ stopped: true }`;
* - held by another and still binding ⇒ write nothing, answer `{ stopped: false, holder }`.
*
* A tombstone never expires, is never taken over, is never deleted by {@link releaseResumeClaim} (for any holder string),
* sweep or {@link deleteRun}, and makes {@link resumeClaim} answer `{ granted: false, stopped: { by } }`.
* OPTIONAL: a store without this verb is legal.
*/
stopResumeClaim?(input: StopResumeClaimArgs): Promise<StopResumeClaimAnswer>;
}
export declare const MAX_JOURNAL_RESULT_BYTES: number;
/** True when a serialized journal result is too large to store (UTF-8 byte length over {@link MAX_JOURNAL_RESULT_BYTES}). */
export declare function oversizeJournalResult(serialized: string): boolean;
/** The ordinal a callKey (`<ordinal>:<hash>@<position>`; `<ordinal>:<hash>` before positions existed) was minted at — the journal's
* positional index, and the one reading of a run row's ordinal. The sole producer ({@link workflowAgentCallKey}) always
* emits a well-formed key with a leading `<int>:`; a MALFORMED key (no leading int) falls back to `0` rather than
* throwing — callers must not feed it arbitrary strings (audit note). */
export declare function callKeyOrdinal(callKey: string): number;
/** The errorCode a journal OVERSIZE TOMBSTONE carries — the resume path recognizes it to
* say WHY an ordinal never replays. `failed` + this code lands on the T2A-4 no-replay arm, so replay
* behavior is identical to the entry simply being absent (the pre-tombstone shape). */
export declare const JOURNAL_OVERSIZE_ERROR_CODE = "workflow.journal_oversize";
/**
* The refusal every {@link WorkflowJournalStore.append} answers an oversize entry with (#672): a stable
* `code` ({@link JOURNAL_OVERSIZE_ERROR_CODE} — the same word the engine's result-arm tombstone carries, so
* one code means "too big for the journal" on every face) and a message a person can act on (the bytes, the
* cap, the entry's callKey). A backend outside this package throws THIS class from its own `append` — the
* contract kit asserts the code only, so the class is the convenience, the code is the contract.
*/
export declare class WorkflowJournalOversizeError extends Error {
readonly callKey: string;
readonly bytes: number;
readonly cap: number;
readonly code = "workflow.journal_oversize";
constructor(callKey: string, bytes: number, cap?: number);
}
/**
* @contract workflow.journal_oversize.refused — every {@link WorkflowJournalStore.append} REFUSES an entry whose
* payload (the `parked` arm when present, else the `result` arm) serializes to more than
* {@link MAX_JOURNAL_RESULT_BYTES} UTF-8 bytes: it throws {@link WorkflowJournalOversizeError} and journals
* nothing, on BOTH arms alike — no backend degrades an oversize entry to a silent skip, and no backend
* judges the size by a rule of its own. A backend calls this first, before it touches its medium.
*
* Why a refusal and not the earlier skip (RB-168 "every backend degrades identically"): the skip was written
* for the `result` arm, where the engine measures the SAME serialization first and journals a small
* tombstone (RB-243) — a completed result never reaches this refusal. The `parked` arm (#642) is the child's
* whole paused TaskResult, which can exceed the cap; a park the journal dropped silently is a resume that
* runs the ordinal live beside the pinned child, and the write is the one moment the deployment can be told.
* A bad value answered with a default is the failure mode this repository refuses by default; the loud
* answer is the rule, the engine's tombstone the one place that pre-empts it.
*/
export declare function assertJournalEntryFits(entry: WorkflowJournalEntry): void;
/** Mint the tiny FAILED entry the ENGINE journals in place of an oversize result. The
* tombstone is minted in the engine, NOT in a store — a store REFUSES an oversize entry
* ({@link assertJournalEntryFits}) and never invents one; the engine measures the durable copy first, so
* the store sees the tombstone, not the payload. Never copies `result.result`/`structuredOutput` (the
* oversize payload); keeps taskId/sessionId/stats so the journal read-face still shows the session handle
* and the paid spend, and the leg's `continuesFrom` — where that leg left its session is a fact about the leg, not
* about the size of its payload. Its own serialization is a few hundred bytes — always under the cap (pinned). */
export declare function journalOversizeTombstone(result: TaskResult, bytes: number, replay?: "rerun" | "stopped"): TaskResult;
/**
* The TTL a resume claim {@link
* InMemoryWorkflowJournalStore} grants survives WITHOUT an engine release: the backstop for an engine that
* abandoned a granted claim without ever reaching the terminal `finally` that releases it (a bug, not the
* normal path — the normal path releases promptly). Same VALUE as the file store's `RESUME_CLAIM_TTL_MS`
* (`src/stores/file/workflow-journal-store.ts`) — kept as an independent constant rather than imported from
* it, because `core/` is upstream of `stores/file/` (the file store already imports FROM this module; the
* reverse would invert that layering) and an in-memory store's claims die with the process regardless, so the
* two constants have no shared-drift risk to guard against by literally sharing one declaration.
*/
export declare const IN_MEMORY_RESUME_CLAIM_TTL_MS: number;
/** In-process journal store (core default). A single-replica run; durable resume across crashes needs the
* service's Postgres store (SVC-2). Records each run's `scope` and enforces it on load (CORE-9 audit BLOCKER:
* a cross-scope resumeFromRunId resolves to an empty journal — no cross-tenant disclosure).
*
* Also carries a REAL {@link WorkflowJournalStore.resumeClaim}/{@link
* WorkflowJournalStore.releaseResumeClaim} implementation (this store used to be the canonical example of a
* store WITHOUT the seam — its own header said so). Left unimplemented, the DEFAULT deployment (no
* `journalStore` supplied, or this store supplied explicitly) had NO protection against two same-process
* `resumeFromRunId` calls off one source forking its execution — the class of bug RB-242 exists to close, and
* a dual-process probe found it wide open on the default path while the file store's half already
* worked. A single-process store's promise is necessarily single-process: this implementation gives no
* cross-process guarantee (there is no shared medium to publish a claim on), so a multi-process deployment
* still needs a store that IS durable/shared (the file or SQL stores) for the seam to mean anything beyond
* this one process. */
export declare class InMemoryWorkflowJournalStore implements WorkflowJournalStore {
private readonly runs;
/** RB-367 resume claims and #5156 R1 native tombstones, nested by scope then sourceRunId (rather than a single
* string-concatenated key) so untrusted-length `scope`/`sourceRunId` text (`sourceRunId` is `resumeFromRunId` — LLM-controlled)
* can never collide across the boundary between the two fields. Tombstones are a distinct variant — never a sentinel holder
* string — so `releaseResumeClaim` for any string can never delete one. */
private readonly resumeClaims;
private claimsForScope;
/** Contract parity with the file store: keyed by `(sourceRunId, scope)`; a tombstone always refuses with `stopped: { by }`;
* idempotent re-grant to the SAME holder; an unexpired claim held by someone else refuses (naming the holder); an expired or
* absent claim is free to take. Acquisition is a single synchronous Map read-then-write with no `await` between the check and
* the publish — there is no window (matching the atomicity RB-354 requires of a durable implementation) in which a concurrent
* caller could observe the key as free mid-acquire. Both answers say how long the claim has left by this process's clock (a
* re-claim by its holder starts the lease again). */
resumeClaim(input: ResumeClaimArgs): Promise<ResumeClaimAnswer>;
/** Release ONLY a claim `newRunId` still holds (a missing/foreign/already-taken-over claim or a tombstone is a
* no-op, never an error — matches the file store's contract). */
releaseResumeClaim(input: ResumeClaimArgs): Promise<void>;
/** #5156 R1 — compare-and-write a native tombstone on `(sourceRunId, scope)` (single synchronous Map step). */
stopResumeClaim(input: StopResumeClaimArgs): Promise<StopResumeClaimAnswer>;
deleteRun(runId: string, scope: string): Promise<boolean>;
/** Launch records by run id, each with the scope it was kept under. */
private readonly launches;
recordLaunch(runId: string, scope: string, launch: WorkflowLaunchRecord): Promise<void>;
loadLaunch(runId: string, scope: string): Promise<WorkflowLaunchRecord | undefined>;
load(runId: string, scope: string): Promise<WorkflowJournalEntry[]>;
append(runId: string, scope: string, entry: WorkflowJournalEntry): Promise<void>;
}
export {};