@sema-agent/core
Version:
Stateless, task-oriented AI agent core
363 lines (362 loc) • 22.5 kB
TypeScript
import { type MemberCoverage, type MemberOutcome, type MemberOutcomeWord } from "./member-outcome.js";
import { type SubagentActions } from "./actions-digest.js";
import type { TaskNotificationPayload } from "./task-notification.js";
/** The ledger's shape version — one, and it stays one while rows only gain members. */
export declare const RUN_LEDGER_VERSION = 1;
/** The key a host's result frame carries the ledger under on the wire (its projection of {@link TaskResult.runLedger}); exported so
* no consumer spells it by hand. */
export declare const RUN_LEDGER_WIRE_KEY = "_sema_run_ledger";
/** How long a member's self-report runs on a row (code points), after redaction. */
export declare const RUN_LEDGER_SELF_REPORT_MAX_CHARS = 400;
/**
* What the accepted checks say about a row (derived, one source: the checks the report tool accepted, each covering the reading of
* the row it was accepted against — a revived row's next cycle is not covered by a check of an earlier one):
* - `verified` — an accepted "verified" claim is about its reading;
* - `evidence` — no claim is about it, and an accepted claim cites its reading as evidence (a verification worker): not counted unverified;
* - `unverified` — it reported completed and neither of the above holds;
* - `n/a` — it has not completed (still running, or it ended any other way): there is no report of success to check.
*/
export declare const RUN_LEDGER_CHECKS: readonly ["verified", "evidence", "unverified", "n/a"];
export type RunLedgerCheck = (typeof RUN_LEDGER_CHECKS)[number];
/** One member the run dispatched — see the module head (an open record). */
export interface RunLedgerRow {
readonly taskId: string;
/** What kind of member (`background_agent`, `workflow`, `peer_task`, `subagent`); read as a string. */
readonly kind: string;
/** What it was dispatched to do — the description the dispatch carried (untrusted, one line, bounded). */
readonly label: string;
/** The name it was addressed by, when it has one. */
readonly name?: string;
readonly state: "running" | "settled";
/** The engine's reading of how it ended (absent while it runs). */
readonly outcome?: MemberOutcome;
/** Its own last words (untrusted, redacted, one line, bounded) — set beside {@link actions}, never trusted over them. */
readonly selfReport?: string;
/** What it did, by the engine's count. */
readonly actions?: SubagentActions;
readonly check: RunLedgerCheck;
/** A `verified` row only: what the latest accepted check about it found — `confirms`, `refutes` or `partial` (derived from the
* accepted conclusions, never written apart from them). A row a check refuted reads `check: "verified"` with `verdict: "refutes"`,
* so a reader never takes it for a row found true. */
readonly verdict?: RunLedgerVerdict;
/** A workflow row: how its own members ended (coverage and counts), so a failure one level down is counted. */
readonly members?: {
readonly coverage: MemberCoverage;
readonly counts: Readonly<Partial<Record<MemberOutcomeWord, number>>>;
};
/** When the run's lane heard it settle (epoch ms) — the instant a check of it must come after. */
readonly settledAt?: number;
}
/** What a verified check found about the row it is about. */
export type RunLedgerVerdict = "confirms" | "refutes" | "partial";
/** Why the book took a snapshot: a delivery through the report tool (its call id, when the call carried one), a leg that parked
* (the run is not over: a resumed leg continues the same book), or the run's end (the final ledger, `final: true`). */
export type RunLedgerTrigger = {
readonly kind: "report";
readonly toolCallId?: string;
} | {
readonly kind: "park";
} | {
readonly kind: "run_end";
};
/** One conclusion of an accepted report, as the ledger keeps it. */
export interface RunLedgerClaim {
readonly about: string;
readonly text: string;
readonly basis: "verified" | "relayed" | "inferred";
readonly verdict?: RunLedgerVerdict;
readonly evidence?: readonly string[];
}
/** The last report the run's model delivered through the report tool, as the ledger's plain text carries it. */
export interface RunLedgerReport {
readonly status: "normal" | "proactive";
readonly message: string;
readonly kind?: "start" | "interim" | "final";
readonly claims?: readonly RunLedgerClaim[];
}
/** See the module head. */
export interface RunLedger {
readonly v: typeof RUN_LEDGER_VERSION;
/** The leg that took this snapshot (`Prepared.runId`, THIS call of the engine) — absent only on a book no run bound (a
* library-built book). A resumed leg has its own id and continues the parked leg's {@link seq}. */
readonly runId?: string;
/** The snapshot's place in its book: 1, 2, 3 … — one more at every snapshot the book takes (each delivery through the report tool,
* a park, then the run's end), across every leg a park and its resume join, never reused and never by the wall clock. The larger
* `seq` is the later ledger, whatever order the copies arrive or replay in; the final ledger has the largest. */
readonly seq: number;
/** Why this snapshot was taken ({@link RunLedgerTrigger}); `kind: "run_end"` exactly when {@link final}. */
readonly trigger: RunLedgerTrigger;
/** The run's last word (its result) — or a snapshot taken while it ran, a parked leg's included. */
readonly final: boolean;
/** Rows still running. */
readonly open: number;
readonly coverage: MemberCoverage;
/** How the rows ended, by the holder's word ({@link MemberOutcomeWord}) — the one count the headline and the text speak. */
readonly counts: Readonly<Partial<Record<MemberOutcomeWord, number>>>;
/** Members the book listed or heard that its holder no longer hands back (a reclaimed registry row; a resume in another process —
* a durable store is not read) — counted, never listed as rows; present only when there are some, and then {@link coverage} is `incomplete`. */
readonly unreadable?: number;
/** Rows that reported completed with no accepted check about them (rows cited as evidence are not counted). */
readonly unverified: number;
/** Verified rows whose check did not confirm them (`verdict` `refutes` or `partial`). */
readonly contradicted: number;
/** Structured reports the report tool accepted. */
readonly reports: number;
readonly rows: readonly RunLedgerRow[];
/** The engine's one-line headline, computed from the counts above — never the model's. */
readonly headline: string;
/** The ledger in the engine's fixed sentences, for an outlet with no interface of its own. */
readonly text: string;
readonly lastReport?: RunLedgerReport;
/** The launch check's reading, when the run took one. */
readonly launch?: import("./manager-launch-check.js").ManagerLaunchCheck;
/** The saved team this leg ran (`TaskSpec.team`): its name, the catalog layer it was read from, and the hash of its file's text
* (`sha256:<hex>`, the catalog entry's `contentHash`) — absent on a run that names no team. */
readonly team?: {
readonly name: string;
readonly source: string;
readonly contentHash: string;
};
}
/** What a delegation tool reports of a member it settled inside its own call (a synchronous agent, a fork). */
export interface RunLedgerSettledMember {
readonly taskId: string;
readonly kind: string;
readonly label: string;
readonly name?: string;
readonly outcome: MemberOutcome;
readonly selfReport?: string;
readonly actions?: SubagentActions;
/** The delegation call it ran inside — the instant it began. */
readonly toolCallId?: string;
}
/** The seat a delegation tool sees on its ctx (`ToolExecuteContext.runLedgerBook`): report an in-call member; report that a call
* dispatched a registry member (the peer task lane, at registration) — the one occurrence whose answer can be that member's arrival. */
export interface RunLedgerSink {
memberSettled(m: RunLedgerSettledMember): void;
/** Optional on the type (a seat a host builds without it compiles as before): a seat without it records no answer as an arrival. */
memberDispatched?(taskId: string, toolCallId: string): void;
}
/** A member row as its holder (the task registry) hands it to a snapshot. */
export interface RunLedgerRegistryRow {
readonly taskId: string;
readonly kind: string;
readonly label?: string;
/** The name it was addressed by, when it has one. */
readonly name?: string;
readonly running: boolean;
/** How it ended, by its holder — absent while it runs. */
readonly outcome?: MemberOutcome;
/** A workflow row: how its own members ended, by the run's own member ledger (absent while the run runs). */
readonly members?: RunLedgerRow["members"];
/** The tool call that dispatched it — the instant a check it ran can have begun. */
readonly toolUseId?: string;
/** The holder's cycle number (background agent stop-cycle number; workflow = 1). Absent on a caller that omits it (reads the
* latest arrived cycle, else 1). */
readonly cycle?: number;
}
/** One report the report tool hands the book to judge and, when it passes, keep. */
export interface RunLedgerReportInput {
readonly status: "normal" | "proactive";
readonly message: string;
readonly report?: {
readonly kind?: "start" | "interim" | "final";
readonly claims?: readonly RunLedgerClaim[];
};
/** The report call's own id (it cannot be its own evidence). */
readonly toolCallId?: string;
}
/** The door for `TaskSpec.runLedger`: `true` or absent; any other value refuses loudly (`config.invalid_argument`) — a `false`
* would read as "declared" to a reader that tests presence, and a word nobody reads must not sit on the spec as if wired. */
export declare function assertRunLedgerDeclaration(v: unknown): void;
/** The door for `TaskSpec.managerApproves`: `true` or absent, and only beside a ledger declared on the SAME spec — `runLedger: true`,
* or `team` (a team's run is a ledger run by its recipe; a resume that keeps the manager restates its declaration) — any other
* value, or the switch without its ledger, refuses loudly (`config.invalid_argument`). */
export declare function assertManagerApprovesDeclaration(spec: {
readonly managerApproves?: unknown;
readonly runLedger?: unknown;
readonly team?: unknown;
}): void;
/** What a resumed leg says when the row it resumes was parked by a leg that kept no ledger and its spec declares one
* (`TaskResult.runLedgerNotKept`): the task keeps none — whether it keeps one is fixed by its first leg. */
export declare const RUN_LEDGER_NOT_KEPT_SENTENCE = "This task's first leg kept no member ledger, so this leg keeps none either: whether a task keeps one is fixed when the task starts (declare runLedger on its first leg).";
/**
* A leg's ledger identity — see the module head. `resumed`: the row this leg resumes (its book section as the row holds it), absent
* on a leg that resumes nothing (a first leg; a woken or forked leg, which goes through no park row and keeps a ledger only when its
* own spec declares one). `rowTaskId`: the registry row a delegation lane runs the leg as, which is its task id.
* - a resumed row with a section: the section's task id; a spec naming another task id refuses (`config.invalid_argument`);
* - a resumed row with none: no ledger — and, when the spec declares one, `notKept` (the result says so; no notice code);
* - a leg that resumes nothing and declares one: the row's id, else the host's task id when it is not the session id, else a
* minted `rl-…`.
* Read by the run's lane (the book it mints), by prepare (the spec it rebinds) and before a resume's claim (the refusal): every
* reader of a resumed leg gets the same answer, since nothing is minted there.
*/
export declare function runLedgerIdentityOf(spec: {
readonly taskId?: string | undefined;
readonly sessionId?: string | undefined;
readonly runLedger?: unknown;
}, resumed: {
readonly section: unknown;
} | undefined, rowTaskId: string | undefined): {
readonly taskId: string;
readonly parked?: RunLedgerParked;
} | {
readonly notKept: string;
} | undefined;
/** The book a leg keeps, by {@link runLedgerIdentityOf}: a new one for a first leg, the parked one continued for a resumed leg, none
* for a leg that keeps no ledger. */
export declare function runLedgerBookFor(spec: Parameters<typeof runLedgerIdentityOf>[0], resumed: Parameters<typeof runLedgerIdentityOf>[1], rowTaskId: string | undefined, now?: () => number): RunLedgerBook | undefined;
/** The spec a leg runs under once its ledger identity is read: a leg with a book declares it and runs as its task; any other leg
* declares none (a resumed row whose leg kept none included). */
export declare function withRunLedgerTask<S extends {
readonly taskId?: string | undefined;
readonly runLedger?: true | undefined;
}>(spec: S, book: RunLedgerBook | undefined): S;
/** A synchronous member row held by the book (its only holder), frozen across a park up to its cap. */
export interface RunLedgerSyncRow {
readonly taskId: string;
readonly kind: string;
readonly label?: string;
readonly name?: string;
readonly outcome: MemberOutcome;
readonly selfReport?: string;
readonly actions?: SubagentActions;
readonly settledAt: number;
readonly order: number;
readonly call?: string;
readonly began?: number;
}
/** Compact arrival mark of a holder-backed member (background agent or workflow): order metadata only, no selfReport or actions. */
export interface RunLedgerArrivalMark {
readonly taskId: string;
readonly cycle: number;
readonly order: number;
readonly settledAt: number;
readonly began?: number;
}
/** One tool call of the run's own leg: wall-clock start, book order, turn start, end order, and whether the id appeared twice. */
export interface RunLedgerHeardCall {
at: number;
started: number;
readonly turn: number;
ended?: number;
duplicate?: true;
}
/** An accepted claim as the book keeps it: with the reading `(taskId, cycle)` of each row it names when it was accepted. A check
* covers that cycle only: a row's later cycle is a reading no accepted check saw. */
export type RunLedgerKeptClaim = RunLedgerClaim & {
readonly readings: ReadonlyArray<readonly [taskId: string, cycle: number]>;
};
/** Counts of oldest entries dropped per class when a leg parked past its cap (absent when nothing was dropped). */
export interface RunLedgerTruncated {
readonly listed?: number;
readonly syncRows?: number;
readonly arrivals?: number;
readonly calls?: number;
readonly claims?: number;
}
/**
* The book as a parked row carries it (`CheckpointState.runLedger`, reader word `run_ledger`): only the book's own bounded facts —
* task id, listed member ids, synchronous rows, compact arrival marks, calls, accepted claims, counters, and per-class drop counts.
* Holder-backed members' pre-park `selfReport` and `actions` are not carried across a park. Read back by {@link readRunLedgerParked}
* alone — a section that does not read is a damaged row, refused before the claim, never an empty book.
*/
export interface RunLedgerParked {
readonly v: 1;
readonly taskId: string;
readonly listed: readonly string[];
readonly tick: number;
readonly turn: number;
readonly seq: number;
readonly reports: number;
readonly syncRows: readonly RunLedgerSyncRow[];
readonly arrivals: readonly RunLedgerArrivalMark[];
readonly calls: ReadonlyArray<{
readonly id: string;
} & RunLedgerHeardCall>;
readonly claims: readonly RunLedgerKeptClaim[];
readonly lastReport?: RunLedgerReport;
readonly truncated?: RunLedgerTruncated;
/** The saved team the task's first leg ran ({@link RunLedger.team}): a leg that resumes the row runs that team or none. */
readonly team?: NonNullable<RunLedger["team"]>;
}
/** A parked row's book section, read: the section, or `undefined` when it does not read as one this engine wrote (a damaged row). */
export declare function readRunLedgerParked(v: unknown): RunLedgerParked | undefined;
/** The book — see the module head. "Before" and "after" between the book's facts (a row reported, a call started or finished) are
* read off ONE counter, in the order the book heard them — never the wall clock, which two facts can share. */
export declare class RunLedgerBook implements RunLedgerSink {
#private;
/** The task the book belongs to ({@link runLedgerIdentityOf}) — absent only on a book no leg minted (a library-built book). */
readonly taskId: string | undefined;
/** A new book of task `taskId`, or — `parked`, a resumed leg's — the book its parked row froze, continued (its task is the
* section's; a `taskId` naming another refuses). */
constructor(now?: () => number, parked?: RunLedgerParked, taskId?: string);
/** The book as the parking leg's row carries it ({@link RunLedgerParked}) — read when the row is minted; the leg's own `park`
* snapshot, taken after, is number `seq`. Each class keeps its newest entries up to its cap and counts any cut in `truncated`. */
parkSection(): RunLedgerParked;
/** Bind the book to its run: the run's id ({@link RunLedger.runId}) and its holder's reading — every member row of this task, and
* one by its id (bound once, when the prepared leg is known). */
bind(runId: string, read: () => readonly RunLedgerRegistryRow[], member?: (taskId: string) => RunLedgerRegistryRow | undefined): void;
/** The model's next turn began (the harness's `turn_start`): what it reads from here on is everything the book heard so far. */
turnStarted(): void;
/** The launch check the run took. */
setLaunch(launch: import("./manager-launch-check.js").ManagerLaunchCheck): void;
/** The saved team the leg ran ({@link RunLedger.team}). */
setTeam(team: NonNullable<RunLedger["team"]>): void;
/** A frame on the run's own lane: a terminal frame of a member the task registry holds (a background agent, a workflow run, a peer
* task) records its arrival mark for `(taskId, cycle)` and — but a peer task's — keeps this leg's transient words and actions. The cycle is the frame's
* `seq` on a background agent's frame only (its stop-cycle number); every other kind has one cycle (a peer task's `seq` counts its
* frames). It settles nothing: how the member stands is its holder's. */
observeFrame(n: TaskNotificationPayload, terminal: boolean): void;
/** {@link RunLedgerSink.memberDispatched}: call `toolCallId` of this leg dispatched registry member `taskId`. */
memberDispatched(taskId: string, toolCallId: string): void;
/** {@link RunLedgerSink.memberSettled}: an in-call member (first report wins). */
memberSettled(m: RunLedgerSettledMember): void;
/** A tool call of the run's own leg started (the harness's `tool_execution_start`). An id already seen in this book is marked
* non-unique (refused when cited as evidence); its turn still updates so an endpoint reusing one id as its report call keeps its
* own turn reading. */
callStarted(toolCallId: string): void;
/** A parked tool call resumed after approval (`run-leg.ts`): continues the open call leg 1 already heard without marking it
* non-unique, keeping the turn that issued it while recording when execution actually began. */
callResumed(toolCallId: string): void;
/** A tool call of the run's own leg finished (the harness's `tool_execution_end`, or a resumed call's end) — from here on its result
* is the model's to read. `details`: the answer's own, as the model's turn reads it (after every hook). When this call dispatched a
* registry member and its answer names that member's ending (`task_id`, `status`), and the holder hands the member back settled
* with that word, dispatched by this call, the call's end is the member's arrival (see the module head). */
callEnded(toolCallId: string, details?: unknown): void;
/**
* Judge a report's conclusions against the book and, when every one passes, keep it. Reads the same {@link #rowNow} view a
* snapshot reads: a running row has no current reading (refused naming running and its cycle when known); a settled row at
* cycle N without an arrival mark for `(taskId, N)` is refused; a call id seen more than once is non-unique and refused when
* cited as evidence; a mark cut at park is refused naming truncation.
*/
acceptReport(input: RunLedgerReportInput): {
ok: true;
} | {
ok: false;
why: string;
};
/** The ledger now, taken for `trigger` — `run_end` is the run's last word (`final`), read as the holders stand (nothing a later
* sweep will do is read ahead). Each call is the next {@link RunLedger.seq}. */
snapshot(trigger: RunLedgerTrigger): RunLedger;
}
/** The ledger over its rows — the run-level reading, the headline and the text, all derived here. */
export declare function runLedgerOf(rows: readonly RunLedgerRow[], at: {
runId?: string;
seq: number;
trigger: RunLedgerTrigger;
unreadable?: number;
reports: number;
lastReport?: RunLedgerReport;
launch?: RunLedger["launch"];
team?: RunLedger["team"];
}): RunLedger;
/**
* The headline — computed from the ledger's counts, never written by a model: rows still running say the run is not finished;
* otherwise the coverage, how the rows that did not complete ended (each by its holder's word: `1 killed`, `2 failed`), the members
* the holder no longer hands back, the rows a check contradicted and the unverified rows. A final ledger with no accepted
* structured report says so.
*/
export declare function runLedgerHeadline(l: Pick<RunLedger, "final" | "open" | "coverage" | "counts" | "unreadable" | "unverified" | "contradicted" | "reports" | "rows">): string;
/** The ledger in fixed sentences (one line per fact; the untrusted strings already passed their fences). */
export declare function runLedgerText(l: Omit<RunLedger, "text">): string;