@sema-agent/core
Version:
Stateless, task-oriented AI agent core
155 lines (154 loc) • 12.8 kB
TypeScript
/**
* ONE TOOL CALL ATTEMPT, ONE RECORD — the occurrence.
*
* A tool call on one leg (one `toolCallId`, one attempt) has a single record here, and everything the engine
* says about the call is read off it: the `tool_start` / `tool_end` frames (projected in `tool-end-body.ts`), the
* `tool_progress` heartbeat (`tool-progress-lane.ts`), the trace row's `ok`, and the resumed leg's
* `executionOutcome` filing. The record has three parts:
*
* - the EXECUTION LIFE, monotonic: `announced` (the start frame is out) → `released` (the engine let the call go
* to its executor: the resumed leg right before it runs the tool body itself, a live leg at the gate's allow
* exit — the loop starts the body after it and the runner does not observe that moment) → `settled` or
* `interrupted`. A call that closes still `announced` was never let go: whatever the tool's body did, this call
* did not do it (`refusedBeforeRelease`, `tool-not-executed.ts`). The release is also the call's RUNNING origin
* (`releasedAt`): the nearest moment to the body's start the runner observes, and the one the progress lane counts
* from — an announced call is waiting on its gate, not running. Leaving a terminal state is an engine defect and throws;
* - the HOLDS, re-entrant: one count per {@link ToolGatePhase} word — every ask put to the person's seat for this call
* (`approval`: several rounds of one gate pass, a confirmation asked during the execution), every auto-mode
* classification of it in flight (`classifier`), every `classic.PreToolUse` screening of it in flight (`hook`). A
* count, never a bit, because the holds nest and overlap; one bracket for all three ({@link ToolOccurrenceTable.whileHeld}).
* The counts are the one gate-phase fact the frames read ({@link gatePhaseOf});
* - the GATE ROUNDS: one record per gate exit for this call, and one more when a station AFTER the gate refuses
* it (the shell read admission that re-establishes what the gate judged, a resumed leg's belts). The latest
* record is the call's disposition: a refusal after the gate is a refusal, never a tool failure under an
* `allowed` record.
*
* WHAT IS NOT HERE: frames, clocks of a lane, the deny observer. This module is the record and its transitions;
* the projections read it. A durable park that crosses legs is two occurrences on two tables (the parking leg's,
* the resumed leg's), joined by the checkpoint row the resumed leg was opened from: the resumed leg's occurrence for
* the held call names that row ({@link OccurrenceStart.resumesCheckpoint}) and both of its frames carry the name — the
* one join a consumer reads, minted where the resumed leg opens the held call.
*/
import type { ApprovalHeldCall } from "../agent-state.js";
import type { DeniedBy, GateOutcome } from "../gate-outcome.js";
import type { ToolGatePhase } from "../task-event.js";
import { type GateExitFacts } from "./gate-exit.js";
/** The one clock the occurrence's heartbeat facts are stamped on. MONOTONIC for the reason the progress lane
* states: every reading is subtracted from another, and a wall-clock step backwards would silence the beat. A
* host without `performance` falls back to the wall clock and inherits its rollback behaviour. */
export declare const occurrenceClock: () => number;
/** Where a call's execution life stands — see the module header for the order. */
export type OccurrenceLife = "announced" | "released" | "settled" | "interrupted";
/** What opens an occurrence: the facts its start frame carries. */
export interface OccurrenceStart {
readonly toolCallId: string;
/** The name the frames carry — the model's spelling on a live leg, the parked row's spelling on a resumed one. */
readonly spelledName: string;
/** The name of the tool the call dispatches to on the live roster — the name every gate station judged (absent when
* the station opening the record does not know it). */
readonly wireName?: string;
/** The tool's display label, when it differs from the name. */
readonly label?: string;
/** The arguments the start frame carries (for a recovered start: the call's own input as the transcript holds it). */
readonly args: unknown;
/** An extension's own call (`$.tool.call`): who asked for it — the frames carry it. Absent for a call a model message carried. */
readonly requestedBy?: import("../task-event.js").ExtensionRequester;
/** The held call a resumed leg runs: the id of the checkpoint row it was opened from — the frames carry it
* (`tool_start.resumesCheckpoint`). Absent on every other call, and on a held call whose row carries no id. */
readonly resumesCheckpoint?: string;
}
/** The record, as its readers see it. Written only through {@link ToolOccurrenceTable}. */
export interface ToolOccurrence extends OccurrenceStart {
/** 1 for the first attempt of this id on this table, counting re-announcements of a reused id. */
readonly attempt: number;
readonly life: OccurrenceLife;
/** How many holds of each kind are open on this call right now: `approval` — asks put to the person; `classifier` —
* auto-mode classifications in flight (the leg's own classifier, or an ancestor's frozen one judging it); `hook` —
* `classic.PreToolUse` screenings in flight (the leg's own registrations, or an inherited installation judging it). */
readonly holds: Readonly<Record<ToolGatePhase, number>>;
/** One outcome per gate exit, plus one per refusal after the gate; the last one is the call's disposition. */
readonly gateRounds: readonly GateOutcome[];
/** The input the latest gate exit decided on, as a FROZEN snapshot (absent when no gate saw the call). */
readonly finalInput?: unknown;
/** The call's start frame is out on this leg. */
readonly startEmitted: boolean;
/** When the engine let the call go, on {@link occurrenceClock} — the progress clock's one origin. Absent until the
* call is released: a call still at its gate is not running, so the lane counts no running time for it (a frame
* minted for it reads elapsed 0). Written once, by {@link ToolOccurrenceTable.release}. */
readonly releasedAt?: number;
/** The last moment anything was heard from the call (its release, a frame for it, or its return from a wait on the
* person). */
readonly lastHeardAt: number;
/** The heartbeat covers it. Cleared when the loop leaves the call behind at a turn end with no
* end of its own: the record stays (a later settlement must still know its start frame went out) but no beat
* describes it. */
readonly beating: boolean;
/** An extension at `tool.call` answered for the call in place of its body — its result, or its refusal — and named here:
* the body was never called (positive evidence the call did not run). Absent: no station answered in its place. */
readonly answeredInPlaceBy?: string;
/** The latest gate exit's record of a rewrite (`tool_end.rewrite`): the args it let the call go with and who replaced them,
* when they are not the ones it took. Each gate round writes it (a round without one clears it). */
readonly rewrite?: import("../task-event.js").ToolInputRewrite;
}
/** The table of one leg's occurrences — the record's only writer. */
export interface ToolOccurrenceTable {
/** The live (unsettled) attempt for this id, if any. */
get(toolCallId: string): ToolOccurrence | undefined;
/** Every live attempt, in the order they were opened. */
live(): readonly ToolOccurrence[];
/** Open a new attempt. A live earlier attempt for the same id is superseded: the loop left it behind without an
* end (a reused id can only be re-announced after its earlier call stopped producing events), and nothing can
* settle it any more. */
open(start: OccurrenceStart): ToolOccurrence;
/** The live attempt for this id, opened from `start` when there is none — a call the engine is told about
* before it was announced (a frame the loop's own start never preceded). */
ensure(start: OccurrenceStart): ToolOccurrence;
/** The call's start frame is out. */
noteStartEmitted(toolCallId: string): void;
/** The engine lets the call go to its executor — the one transition into `released`, whichever leg makes it. It also
* starts the call's progress clock and its silence clock: whatever came before (the gate, a person's answer) is not
* time the call spent running. */
release(toolCallId: string): void;
/** A gate exit for this call: its record and the input it decided on (frozen by the gate's exit). */
gateRound(toolCallId: string, outcome: GateOutcome, finalInput?: unknown, rewrite?: import("../task-event.js").ToolInputRewrite): void;
/** A station after the gate refused the call: one more gate record, minted as a veto of whatever the latest one
* settled (a person's yes stays on the settlement; the refusing layer is the disposition). `facts` is what the refusing
* station knows beside the layer word: the extension that refused, the literals its sentence quoted. Returns the record. */
refuse(toolCallId: string, layer: DeniedBy, facts?: Pick<GateExitFacts, "extension" | "echoed">): GateOutcome;
/** An extension at `tool.call` answered for the call before its body was called (the kernel's record says the body had
* not started): the body is never called for this attempt. Once per attempt; a second is an engine defect. */
answeredInPlace(toolCallId: string, by: string): void;
/** A hold of `phase` opens on this call: its count rises, and the returned release lowers it once (a second call is a
* no-op). The pair is bound to THIS attempt — a release after the call ended, or after a reused id re-opened, touches
* nothing — and a hold on a call this leg does not hold counts nothing: the wait belongs to whoever holds the call (the
* person, the classifier, the hook), and no bookkeeping here may turn its answer into a failure. The last `approval`
* release restarts the call's silence clock (it is back from the person); the other two leave it alone — a
* classification and a screening are work on the call, and the heartbeat keeps covering them. */
hold(toolCallId: string, phase: ToolGatePhase): () => void;
/** The one bracket every holder uses: the hold opens before `held` runs and releases when its value settles, either way.
* Returns `held`'s own value, so the holder awaits exactly what it awaited before; a synchronous value (anything that is
* not a promise) was no hold at all. */
whileHeld<T>(toolCallId: string, phase: ToolGatePhase, held: () => T): T;
/** A frame for the call went out: its silence clock restarts. */
heard(toolCallId: string): void;
/** The call ended: it leaves the table and the record is returned for the end projection. */
close(toolCallId: string, life: "settled" | "interrupted"): ToolOccurrence | undefined;
/** The heartbeat stops covering every live attempt (turn end, leg teardown). Records stay. */
quiesce(): void;
/** Called whenever an attempt opens (the heartbeat arms its timer). One listener — the leg's one lane. */
onOpen(listener: () => void): void;
}
/** Who holds the call at its gate right now (`tool_progress.gate`): the first word of {@link GATE_HOLD_ORDER} whose count is
* open, else nothing holds it. The one reading of the counts. */
export declare function gatePhaseOf(occ: ToolOccurrence): ToolGatePhase | undefined;
/** The calls this leg holds at its gate for an approver right now — the one reading of "who is waiting on an approver", oldest
* first: every call in flight whose `approval` count is open, as the approver was handed it (the tool the call dispatches to,
* `wireName`; a call made under an alias is judged and asked as the tool it runs) with its call id. The reader a background row
* keeps of its running leg (`RunInternals.reportApprovalHolds`) is this over the leg's table. */
export declare function approvalHeldCalls(table: Pick<ToolOccurrenceTable, "live">): readonly ApprovalHeldCall[];
/** The run driver's hand-up, once per leg: the row this leg runs as (the lane set `internals.reportApprovalHolds`) is handed the reader of the
* leg's own table ({@link approvalHeldCalls}). An observation seat — a throwing one is swallowed, it must never fault the run it describes. */
export declare function reportApprovalHoldsOf(internals: {
readonly reportApprovalHolds?: (read: () => readonly ApprovalHeldCall[]) => void;
} | undefined, table: Pick<ToolOccurrenceTable, "live">): void;
export declare function createToolOccurrenceTable(): ToolOccurrenceTable;