@sema-agent/core
Version:
Stateless, task-oriented AI agent core
196 lines (195 loc) • 14.2 kB
TypeScript
/**
* A background agent's CURRENT state — the one reading every read face renders.
*
* A parent model answers "how far along is it?" from what its read faces show. Three faces read a
* background agent: AgentTranscript (its recent steps), ListAgents (the roster) and the host task poll.
* Each one projects {@link readAgentState}'s result and renders it with {@link agentStateSummary} /
* {@link agentActivityClause} / {@link agentParkClause}; none derives status, activity time or park
* facts on its own, so the three cannot disagree about one agent at one instant.
*
* Sources:
* - the registry row — the live handle this engine process runs ({@link agentStateSourceOfHandle}), or the
* durable record when no live handle answers ({@link agentStateSourceOfRecord});
* - for a row whose status is `parked` only, the checkpoint the row names, read through the run's checkpoint
* seat (the same seat the Agent tool parks children into). The checkpoint is the ONE source of what the park
* waits on (its gate): a person's approval, or a resource limit — a scheduler's yield among them. The token is
* the resume capability and never leaves this module: a face renders the checkpoint's non-secret `checkpointId`,
* and only as the identity judge ({@link readGateIdentity}) clears it against this card's token.
* - for a row whose status is `running` only, the calls its leg holds at its gate for an approver
* ({@link AgentState.approvalWait}): the reader the leg handed its row (`RunInternals.reportApprovalHolds`) over the leg's own
* tool-occurrence table — the table the heartbeat and `tool_progress.gate` read. An answer given in-process is no checkpoint, so
* this is the one place that wait is stated.
*
* Absence is stated, never left silent: a missing activity time renders as "last activity unknown (…why)",
* and a parked row whose card cannot be read carries `park.state` `missing` / `unreadable` (and no gate). A face
* that goes quiet on a fact invites the reader to fill the gap with a guess.
*/
import type { SemaTaskStatus } from "./task-registry-shared.js";
import { type CheckpointSeat } from "./checkpoint-seat.js";
import type { CheckpointGate } from "./checkpoint-store.js";
import { type ResourceLimitReason } from "./resource-limit-reasons.js";
import { type CheckpointIdMissing } from "./checkpoint-identity.js";
import type { AssertAllKeysHandled } from "@sema-agent/primitives";
/** The park card's state: the checkpoint row's own `status`, plus `missing` (the row names no card, or
* the store holds none under its token) and `unreadable` (why is stated by {@link AgentPark.unreadableCause}:
* `no_seat`, `store_failed`, or `status_unknown`). The same five answers the parked-row reconciliation sweep
* gives the same question. */
export type AgentParkState = "pending" | "resolved" | "expired" | "missing" | "unreadable";
/** Why an `unreadable` park card could not be read: `no_seat` — this face was given no checkpoint store;
* `store_failed` — the checkpoint store threw on this read; `status_unknown` — the card was read, and its
* status word is one this engine version does not know (`pending`, `resolved`, `expired`). */
export declare const AGENT_PARK_UNREADABLE_CAUSES: readonly ["no_seat", "store_failed", "status_unknown"];
export type AgentParkUnreadableCause = (typeof AGENT_PARK_UNREADABLE_CAUSES)[number];
/** What a parked agent waits on — its checkpoint's gate, reduced to the non-secret kind (and, for a resource
* limit, the closed reason word; the other kinds' free-text reason never leaves the card). */
export type AgentParkGate = {
readonly kind: "resource_limit";
readonly reason: ResourceLimitReason;
} | {
readonly kind: Exclude<CheckpointGate["kind"], "resource_limit">;
};
/** The checkpoint a parked agent waits on. */
export interface AgentPark {
state: AgentParkState;
/** Why {@link state} is `unreadable` ({@link AGENT_PARK_UNREADABLE_CAUSES}): `no_seat` — this face was given no
* checkpoint store; `store_failed` — the checkpoint store threw on this read; `status_unknown` — the card was
* read, and its status word is one this engine version does not know. Present exactly when {@link state} is
* `unreadable`; absent otherwise. */
unreadableCause?: AgentParkUnreadableCause;
/** What the park waits on, read off the checkpoint. Present when the card was read and carries a known gate. */
gate?: AgentParkGate;
/** The checkpoint's non-secret identity (the card id a person sees in an approval inbox). Present when
* the card was read and the id it carries passes the identity judge ({@link readGateIdentity}, against this card's token). */
checkpointId?: string;
/** Why {@link checkpointId} is not here although the card was read: `absent` — the card carries no id (one parked before
* the member existed); `untrusted` — it carries one the judge refused. A card that was read carries exactly one of the two
* keys; a card that was not read (`missing`, or `unreadable` because there was no seat or the store threw) carries neither. */
checkpointIdMissing?: CheckpointIdMissing;
/** The card's SLA / abandonment deadline, epoch ms. Present when the card was read and carries one. */
deadline?: number;
}
/** Where the row was read from: the live handle this engine process runs, or the durable record (the
* process that wrote it may be another one, or gone). */
export type AgentStateRow = "live_row" | "durable_row";
/** One agent's state at {@link readAt}. Times are epoch ms; relative ages appear only in rendered text. */
export interface AgentState {
/** The registry row's own status word. A word outside {@link SemaTaskStatus} reads `unknown`. */
status: SemaTaskStatus | "unknown";
/** The instant this state was read (epoch ms) — the base every rendered age is computed from. */
readAt: number;
row: AgentStateRow;
/** The row's last recorded change (epoch ms). Live row: every state transition and every tool start /
* end of the direct child moves it. Durable row: when it parked (`parked`) or settled (terminal).
* ABSENT when the source holds no such time — a durable row still marked running (activity in another
* process is not observable here), or a row that never recorded one. */
lastActivityAt?: number;
/** Present exactly when {@link status} is `running` and the agent's leg holds a call at its gate for an approver that has not
* answered (the host's synchronous approver — a person at its prompt, or the deployment's policy). `tool` and `toolCallId` are the
* oldest such call's — the name the approver was handed (`AskRequest.toolName`, the tool the call dispatches to) and its call id,
* each cut at {@link APPROVAL_WAIT_FIELD_MAX} — and `count` is how many calls the leg holds. An answer an approver gives in-process
* leaves no checkpoint (`park` is for a durable park), so this is the one place the wait is stated. Absent on a durable record
* (another process's leg is not observable here) and whenever nothing is held. */
approvalWait?: {
readonly tool: string;
readonly toolCallId: string;
readonly count: number;
};
/** Present exactly when {@link status} is `parked`. */
park?: AgentPark;
}
/** One call a leg holds at its gate for an approver: the name the approver was handed and the call's id. */
export interface ApprovalHeldCall {
readonly toolCallId: string;
readonly tool: string;
}
/** The longest `tool` / `toolCallId` {@link AgentState.approvalWait} carries, in UTF-16 code units (a provider's call id is at most 128). */
export declare const APPROVAL_WAIT_FIELD_MAX = 128;
/** The row facts {@link readAgentState} reads. Built by the two projections below — never by a face. */
export interface AgentStateSource {
status: string;
row: AgentStateRow;
/** The row's handle and scope: how an operator notice about the row's card names the agent (never by the card's token). */
handle: string;
scope?: string;
lastActivityAt?: number;
parkedCheckpointToken?: string;
/** The calls the row's leg holds at its gate for an approver, oldest first, read once from the leg's own table when the source
* is built (see {@link agentStateSourceOfHandle}). Absent: none, or a source with no live leg. */
approvalHeld?: readonly ApprovalHeldCall[];
}
/** THE reading of "the calls this live row's leg holds at its gate for an approver right now": the reader the row's running leg
* handed it (`RunInternals.reportApprovalHolds`), called once, on a row that reads `running` (a parked or settled row's leg holds
* nothing). Empty when none is held or no leg reported. Two readers take it: the state faces ({@link agentStateSourceOfHandle}) and
* the stall reap of session-scoped agents, which does not collect a row whose leg holds a call for an approver. */
export declare function approvalHeldOfHandle(h: {
status: string;
approvalHolds?: () => readonly ApprovalHeldCall[];
}): readonly ApprovalHeldCall[];
/** The live handle's facts: `updatedAt` is moved by every state transition and by each direct-child tool
* lifecycle beat, so it is the row's last activity. The calls held for an approver are read once, at the instant the source is
* taken ({@link approvalHeldOfHandle}). */
export declare function agentStateSourceOfHandle(h: {
id: string;
scope?: string;
status: string;
updatedAt: number;
parkedCheckpointToken?: string;
approvalHolds?: () => readonly ApprovalHeldCall[];
}): AgentStateSource;
/** The durable record's facts. Its `updatedAt` is the writer's liveness lease renewal, not activity, so it
* is never read as such: a parked record answers with `parkedAt`, a terminal one with `settledAt`, and a
* record still marked running answers nothing. */
export declare function agentStateSourceOfRecord(r: {
handle: string;
scope: string;
status: string;
parkedAt?: number;
settledAt?: number;
parkedCheckpointToken?: string;
}): AgentStateSource;
/** The park a run has just committed, as the park face states it (#4317: the held call's `tool_end.park`): the card is `pending` (the
* run itself committed it), its gate as {@link parkGateOf} reads it, its id through the identity judge against its own token. No
* deadline: the run's committed pause does not carry the card's. */
export declare function committedParkOf(pause: {
readonly gate: unknown;
readonly token: string;
readonly checkpointId?: unknown;
}): AgentPark;
/**
* THE state of one background agent at `now`. Synchronous unless the row is parked on a card the seat can
* read — only that row takes an async frame (the store read); every other row is answered in place.
* The caller must already have passed the row through its face's access check: this reads the card the
* row names and authorizes nothing.
*/
export declare function readAgentState(src: AgentStateSource, seat: CheckpointSeat | undefined, now: number): AgentState | Promise<AgentState>;
/** `Ns` / `Nm` / `Nh` / `Nd` — a bounded age word; a negative span reads as `0s`. */
export declare function formatAgo(ms: number): string;
/** `last activity <age> ago`, or the reason the time is unknown. */
export declare function agentActivityClause(s: AgentState): string;
/** `<what it waits on> <card id> <state>[ (deadline in <age> | deadline passed <age> ago)]` — facts only; a pending
* yield adds when it continues (nobody decides it: its owner's next run does). */
export declare function agentParkClause(p: AgentPark, readAt: number): string;
declare const AGENT_PARK_UNREADABLE_SENTENCES: {
readonly no_seat: "This run keeps no record of parked steps, so whether the agent is waiting on a decision cannot be read here, and asking again will not change that; it may be waiting for an approval decision.";
readonly store_failed: "The record of the parked step could not be read just now (a later read may succeed, and if it keeps failing the record itself may be damaged); it may be waiting for an approval decision.";
readonly status_unknown: "The parked step carries a state this engine version does not know; it may be waiting for an approval decision.";
};
export type UnreadableSentencesCoverEveryCause = AssertAllKeysHandled<Exclude<AgentParkUnreadableCause, keyof typeof AGENT_PARK_UNREADABLE_SENTENCES>>;
/**
* The sentence under a parked agent's state line, read off the park card's gate — the same card, the same table, as the
* state line. A yield (`resource_limit` / `preempt`) is not an approval: the agent left with its owner and continues when its
* owner runs again. Any other resource limit says it paused at that limit. A card that cannot be read keeps the one
* possibility a reader must not lose — a person may be waiting to decide an approval: an `unreadable` card carrying
* {@link AgentPark.unreadableCause} states which of the three causes happened (`no_seat`, `store_failed`, `status_unknown`),
* while `missing`, an absent park, an `unreadable` card without the member, or a `pending` card with no known gate keeps
* the general blind sentence. A card that WAS read and is no longer pending (decided, or expired), whatever gate it carries
* or lacks, promises nothing about what happens next, as the state line's park clause promises no continuation for one: the
* sentence and the line read the card's state alike.
*/
export declare function agentParkSentence(p: AgentPark | undefined): string;
/** `awaiting approval for <tool> call <call id>[ (+N more)]` — the call the agent's leg holds at its gate for an approver, as the
* approver was handed it (values are display text: cut at 64 code points; the structured member carries the whole value). */
export declare function agentApprovalWaitClause(w: NonNullable<AgentState["approvalWait"]>): string;
/** The one-line state sentence: `<status> · <activity clause>[ · <park clause>][ · <approval wait clause>]`. */
export declare function agentStateSummary(s: AgentState): string;
export {};