@sema-agent/core
Version:
Stateless, task-oriented AI agent core
311 lines (310 loc) • 25 kB
TypeScript
/**
* HOW ONE MEMBER ENDED — the engine's reading of a member's ending, minted once by the run that holds the member (a workflow run
* for its agent calls; a parent leg for its foreground child; the task registry for a background agent), and the one object every
* face that speaks about the member reads: the member's record row, the completion frame and the deployment notifier, the value a
* script gets back, the parent's report card. Before this, each face counted its own way — a workflow's completion line counted the
* rows whose status said `completed`, a tool the deployment refused left no fact on any face, a call refused at the budget before
* its row existed was not counted at all, and of the leg's three refusal records only one rode the background lane.
*
* Three readings, one function each:
* - {@link memberOutcomeOf} — the member's word (the closed set {@link MEMBER_OUTCOMES}) and its refusals, from the leg's result and
* what the holder alone knows (it refused the call before launch, it asked for a structured result, it stopped the member);
* - {@link memberRefusalsOf} — the leg's refusal records projected into the member's one record (the only projection there is);
* - {@link memberCoverageOf} — the run-level reading derived from its rows: `incomplete` when a row did not complete or carries a
* refusal that left work undone (an ask nobody could answer, a person's no, a verdict that never landed, a person's halt),
* `partial` when the only refusals are tool calls something else refused, `complete` otherwise.
*
* Types and pure functions only (the untrusted-text fence the names in its sentences pass through is its one runtime import); the
* carriers import it, it imports no carrier.
*/
import type { RefusedAsk, RefusedToolCall, TaskResult, VerdictRefusal } from "./task-result.js";
import type { AssertAllKeysHandled } from "./ask-origin.js";
import type { BackgroundAgentSettledStatus } from "./background-agent-store.js";
/**
* The closed set of how a member ended. One word per member; facts that are not an ending (a refused tool call, an ask nobody could
* answer, where the result came from) ride beside it, never folded in.
* - `completed` — the member's leg finished and handed back what it was asked for.
* - `failed` — the leg failed; `code` carries the failure's own code whenever the failure had one. A workflow member its run
* ended without — the script returned or threw while the member still ran, and the run did not stop it — is `failed` under
* `workflow.agent_outlived_run`: the run had not stopped it when it ended (its deadline, a cancel or its caller's abort can still
* stop the leg afterwards; the row is not rewritten), and what it did after is not recorded on that run.
* - `schema_unmet` — the holder asked for a structured result and none was delivered (the model answered in prose, or its
* submission was refused at the gate — `refused.verdict` says which).
* - `budget_refused` — the holder refused the call at its budget before the member started.
* - `parked` — the member is durably paused on an approval and waits for a decision.
* - `blocked` — the member reported that it cannot finish (its own `ReportBlocked`), or a hook kept its prompt from being submitted.
* - `killed` — our side stopped the member: a stop of the agent itself (a host's, a parent's, a sweep's), or of the run that holds
* it (a workflow run's cancel, its caller's abort, its deadline — each aborts the members the run still runs; one parked on an
* approval stays `parked`, its approval still pending). `stoppedBy` names who: `system`
* for a deadline or a sweep, `parent` for the holder or its caller, `manager` for the model's `TaskStop`, `user` for a person's stop on the service wire.
* - `cancelled` — the member's own side cancelled it (a stop it did not get from us).
*/
export declare const MEMBER_OUTCOMES: readonly ["completed", "failed", "schema_unmet", "budget_refused", "parked", "blocked", "killed", "cancelled"];
export type MemberOutcomeWord = (typeof MEMBER_OUTCOMES)[number];
/** Membership test for {@link MemberOutcomeWord} — the word crosses process boundaries on the completion frames and the stored rows. */
export declare function isMemberOutcomeWord(v: unknown): v is MemberOutcomeWord;
/** What kind of member a row is. Grows by a word when a new holder mints rows (a peer task, a nested workflow). */
export declare const MEMBER_KINDS: readonly ["workflow_member", "subagent", "background_agent", "workflow", "peer_task"];
export type MemberKind = (typeof MEMBER_KINDS)[number];
/** The member kinds the task registry holds: a row of one of them is a member of the task its row names as the one that dispatched it
* (`parentTaskId`, written at registration by the agent tool, the workflow tool and the peer task lane alike) — one law for the three.
* The other kinds (a synchronous agent, a workflow's own member) have no registry row: their dispatching station reports them. */
export declare const REGISTRY_MEMBER_KINDS: readonly ["background_agent", "workflow", "peer_task"];
export type RegistryMemberKind = (typeof REGISTRY_MEMBER_KINDS)[number];
export declare function isRegistryMemberKind(kind: string): kind is RegistryMemberKind;
/**
* What ended the run whose end stopped a member (the closed set of {@link MemberOutcome.runEnd}`.cause`). The five stop words are the
* axes `task.interrupt_unconsumed` names in its `origin` — one vocabulary for "what stopped the run", read by one function:
* - `turn_end` — the run ended on its own (its last turn ended; its terminal says how it went), no stop or ceiling ended it;
* - `one_shot_ceiling` — a one-shot ending stopped waiting at its ceiling (`task.wait_ceiling_reached`);
* - `interrupt` — a person's stop (the interrupt verb, or a halt the run consumed — the one `haltedByUser` signs); `walltime` — the run's walltime window; `turns` — its turn cap; `budget` — its budget gate;
* `signal` — every other run-level abort (the task's own `signal`, a parent's cancel, a `destroy()`).
*/
export declare const RUN_END_CAUSES: readonly ["turn_end", "one_shot_ceiling", "interrupt", "walltime", "turns", "budget", "signal"];
export type RunEndCause = (typeof RUN_END_CAUSES)[number];
/** Membership test for {@link RunEndCause}. */
export declare function isRunEndCause(v: unknown): v is RunEndCause;
/** The run-level reading over its rows ({@link memberCoverageOf}). */
export declare const MEMBER_COVERAGES: readonly ["complete", "partial", "incomplete"];
export type MemberCoverage = (typeof MEMBER_COVERAGES)[number];
/** Membership test for {@link MemberCoverage}. */
export declare function isMemberCoverage(v: unknown): v is MemberCoverage;
/**
* How many entries of one refusal list a record lists. A leg refused hundreds of times would otherwise carry an unbounded list on
* every face that holds the record (the result, the completion frame, the stored row, the two listings); past this many the record
* keeps a count of the rest instead ({@link Listed.unlisted}). Measured: a refused call's entry is about 66 bytes of JSON (a full list
* about 1.4 KB); an ask nobody could answer carries its two way-out sentences, about 730 bytes (a full list of asks about 14.5 KB).
*/
export declare const REFUSALS_LISTED = 20;
/** A bounded list: the first {@link REFUSALS_LISTED} entries in order, and how many more there were. */
export interface Listed<T> {
readonly listed: readonly T[];
/** Entries past the listed ones — absent when every entry is listed (never `0`). */
readonly unlisted?: number;
}
/**
* The member's ONE refusal record: what it did not get done because something refused it. Present on a {@link MemberOutcome} only
* when at least one member is; each member present only when it has something to say.
*/
export interface MemberRefusals {
/** Asks nobody could answer, refused — the leg's {@link TaskResult.refusedAsks}, bounded. */
readonly unansweredAsks?: Listed<RefusedAsk>;
/** Calls a person refused (the gate's settlement `human_refused`). */
readonly deniedByPerson?: Listed<RefusedToolCall>;
/** Every other call the gate refused — a policy, a rule, a hook, the mode, the org, an answer that was a policy's or a window's. */
readonly toolCalls?: Listed<RefusedToolCall>;
/** The leg's verdict never landed — the leg's {@link TaskResult.verdictRefused}. */
readonly verdict?: VerdictRefusal;
/** A person's bare no ended the leg — the leg's {@link TaskResult.haltedOnUserRejection}. */
readonly haltedByPerson?: true;
/** The record a stored row kept does not read (its ending object, or the asks an earlier engine kept under their own key, changed
* in storage), or the row was written by an engine that kept no refusal record for it (a workflow row an earlier release wrote):
* what the member did not get done is not known — never read as nothing. */
readonly unreadable?: true;
}
/** How one member ended — see the module head. */
export interface MemberOutcome {
readonly kind: MemberKind;
readonly outcome: MemberOutcomeWord;
/** `failed`: the failure's own code, present whenever the failure had one. `budget_refused` / `schema_unmet`: the holder's code
* for the refusal. `blocked` / `killed` / `cancelled` / `parked` / `completed`: absent. */
readonly code?: string;
/** `killed` only, when the holder knows who stopped the member (the task registry's stop source). */
readonly stoppedBy?: string;
/** `killed` only, when the member was stopped by the END of the run that holds it (the run-end sweep of that run's task-scoped
* background agents): what ended that run. Absent on every other ending — a member stopped by anyone else, one that ended on its own,
* and one a parking leg's yield stopped before its teardown (a park is not the run's end). Being on an ending, it is always the
* "stopped with the run" fate. */
readonly runEnd?: {
readonly cause: RunEndCause;
};
/** Where the member's ending came from: this run (`live`), or a journal a resume served it from (`replayed`). An origin, not an
* ending — a replayed member carries the ending it was recorded with. */
readonly provenance: "live" | "replayed";
readonly refused?: MemberRefusals;
}
/** One row of a run's member ledger: the member's outcome under the holder's name for it. */
export interface MemberLedgerRow extends MemberOutcome {
readonly label: string;
/** The holder's stable key for the call (a workflow agent call's `callKey`), when it has one. */
readonly callKey?: string;
}
/**
* A run's member ledger: every member it holds, the run-level reading derived from them, and the counts by ending. `final` says
* whether this is the run's last word (its terminal) or a mid-run snapshot — a row may then still be running, which a final ledger
* never carries.
*/
export interface MemberLedger {
readonly final: boolean;
readonly coverage: MemberCoverage;
readonly counts: Readonly<Partial<Record<MemberOutcomeWord, number>>>;
readonly rows: readonly MemberLedgerRow[];
/** Calls the run refused because its roster was full (a workflow's `maxAgents`): they never joined it, so they have no row — the
* run counts them, once each. Present when at least one was; the coverage is then never `complete`. */
readonly refusedAtMemberCap?: number;
}
/**
* Does a value read as a {@link MemberOutcome} — the one check a face that received one from outside this process (a boxed frame, a
* stored row) applies before rendering it: its ending in the closed set, its origin word, its code and stopper strings, and a
* refusal record whose every list is a bounded list of entries naming a tool and a call (an ask one {@link isRefusedAsk} reads), whose verdict
* names its tool and counts its attempts, whose halt and unreadable marks are `true`. A key this build does not read is not judged (a later release may
* add one); `kind` is read as a string for the same reason. A value that passes is taken in through {@link sealMemberOutcome}.
*/
export declare function isMemberOutcome(v: unknown): v is MemberOutcome;
/** Does a value read as one {@link RefusedAsk} — a refused call's entry whose cause is one of the closed causes, its ways out strings. */
export declare function isRefusedAsk(e: unknown): e is RefusedAsk;
/** A non-empty list of {@link isRefusedAsk} entries — the shape the key an earlier engine kept refused asks under had (on a boxed
* frame, on a stored row); the one check either reader of that key applies. */
export declare function isRefusedAskList(v: unknown): v is RefusedAsk[];
/**
* The ONE way an outcome is held: a copy, frozen to its last record (the refusal record, each list, each entry, the verdict). The
* mint ({@link memberOutcomeOf}) returns through it, and so does every reader that takes one in from outside this process (a boxed
* frame, a stored row), so every carrier — the row, the frames, the notifier's ledger, the value a script got back, the error it
* caught — shares one object no holder can change: a script that rewrites its `member` changes nothing anyone else reads. The
* copy leaves the leg's own records (the result's lists) the leg's.
*/
export declare function sealMemberOutcome(o: MemberOutcome): MemberOutcome;
/** A ledger that came from outside the process (a boxed frame's `members`), held the way every ledger is: frozen to its last record. */
export declare function sealMemberLedger(l: MemberLedger): MemberLedger;
/** A list bounded at {@link REFUSALS_LISTED}, `unlisted` adding to any count the source already carried past its own list. */
export declare function listedOf<T>(items: readonly T[], alreadyUnlisted?: number): Listed<T> | undefined;
/** How many entries a bounded list stands for. */
export declare function listedCount(l: Listed<unknown> | undefined): number;
/**
* The leg's refusal records projected into the member's one record — the ONLY projection. Each call the gate refused lands in one
* place, by the sort its run gave it when its end was read ({@link RefusedToolCall.countedBy}): a call the leg's own records
* already count (an ask nobody could answer — that record says why nobody answered, and the way out; a call of a verdict that
* never landed — that record counts them) is theirs; a person's refusal (`human_refused`) is the person's; every other refused
* call is a tool call something refused. Past the listed calls, the run's counts are sorted the same way
* ({@link RefusedToolCalls.unlisted}).
*/
export declare function memberRefusalsOf(result: Pick<TaskResult, "refusedAsks" | "refusedToolCalls" | "verdictRefused" | "haltedOnUserRejection">): MemberRefusals | undefined;
/** The holder's codes for the two refusals it makes itself. */
export declare const MEMBER_BUDGET_REFUSED_CODE = "workflow.budget_exceeded";
export declare const MEMBER_SCHEMA_UNMET_CODE = "workflow.agent_schema";
/**
* The status word a holder's row settles on for an ending — the one projection from ending to row status: `completed` and
* `parked` are their own words, `killed` / `cancelled` are a background row's own words (a workflow row, which has neither, reads
* them `failed` — `workflowRowStatusOf`), every other ending is `failed`. A stored outcome whose projection is not its row's
* status is not that row's ending (an earlier cycle's, left by a revival that did not clear it).
*/
export declare function memberRowStatusOf(word: MemberOutcomeWord): "completed" | "parked" | "killed" | "cancelled" | "failed";
/**
* What the holder knows about a member, beside the leg's result. Exactly one shape per way a member ends:
* - `result` — the member's leg settled with this result. `schemaRequested`: the holder asked for a structured result, so a
* completion without one reads `schema_unmet`. `settled`: the status the holder's own record settled on, when the holder keeps
* one (the task registry: first writer wins; a workflow run that stopped the member) — `killed` is the ending whatever the leg's
* terminal said (`stoppedBy` from the record), and a `failed` record over a leg that completed reads `failed` under the record's
* code. `parked: false`: the holder does not park this leg (a paused result there reads `failed`).
* - `refused` — the holder refused the call at its budget before the member started.
* - `ended` — the holder settled the member without a result of the leg's (a status word the holder's own record carries).
*/
export type MemberFacts = {
readonly from: "result";
readonly result: TaskResult;
readonly schemaRequested?: boolean;
readonly settled?: {
readonly status: BackgroundAgentSettledStatus;
readonly code?: string;
readonly stoppedBy?: string;
readonly runEnd?: MemberOutcome["runEnd"];
};
readonly parked?: boolean;
} | {
readonly from: "refused";
readonly budget: true;
} | {
readonly from: "ended";
readonly status: "failed" | "killed" | "cancelled" | "completed" | "parked";
readonly code?: string;
readonly stoppedBy?: string;
readonly runEnd?: MemberOutcome["runEnd"];
readonly refused?: MemberRefusals;
};
/** The ONE mint of a member's outcome. `kind` / `provenance` are the holder's; `kind` is carried as {@link isMemberOutcome} reads it
* (a string — a later release's word passes through). The outcome comes back sealed ({@link sealMemberOutcome}). */
export declare function memberOutcomeOf(kind: MemberKind, provenance: "live" | "replayed", facts: MemberFacts): MemberOutcome;
/**
* A background agent row's outcome, as the task registry mints it at the settle that wins the row (first writer wins): the winning
* status and code, the row's stop attribution, and the leg's result when the settle brought one. A frame whose row is gone (or a
* settle that won nothing of its own) mints the same way over the status it speaks — the one function, never a second reading.
*/
export declare function backgroundAgentOutcomeOf(status: BackgroundAgentSettledStatus, errorCode: string | undefined, stoppedBy: string | undefined, leg: TaskResult | undefined, runEnd?: MemberOutcome["runEnd"]): MemberOutcome;
/** The report-card lines a member's refusals read as (a foreground child's card, a fork's card): `refused_asks:` (the asks nobody
* could answer — the line that always carried them) and `refused:` (everything else); none when nothing was refused. */
export declare function memberRefusalLines(o: Pick<MemberOutcome, "refused"> | undefined): string[];
/** The run-level reading over its rows — see the module head. A row that has no outcome yet (a mid-run snapshot) is not complete. */
export declare function memberCoverageOf(rows: ReadonlyArray<Pick<MemberOutcome, "outcome" | "refused"> | undefined>): MemberCoverage;
/** The counts by ending a ledger carries (rows with no outcome yet are not counted). */
export declare function memberCountsOf(rows: ReadonlyArray<Pick<MemberOutcome, "outcome"> | undefined>): Partial<Record<MemberOutcomeWord, number>>;
/** A run's member ledger over its rows (`outcome` absent on a row still running — only a non-final ledger may carry one), and the
* calls its full roster refused (`refusedAtMemberCap`, the run's count; a run that refused none passes `0`). */
export declare function memberLedgerOf(rows: ReadonlyArray<{
readonly label: string;
readonly callKey?: string;
readonly outcome?: MemberOutcome;
}>, final: boolean, refusedAtMemberCap?: number): MemberLedger;
/** The ending's clause in the engine's sentences — total over the closed set (a word with no row is a red build). */
declare const OUTCOME_CLAUSE: {
readonly completed: "completed";
readonly failed: "failed";
readonly schema_unmet: "did not deliver the structured result asked for";
readonly budget_refused: "refused at the workflow budget before it started";
readonly parked: "parked on an approval";
readonly blocked: "reported it cannot finish";
readonly killed: "stopped";
readonly cancelled: "cancelled";
};
/** Compile-time fence: `never` while every ending has a clause. */
export type MemberOutcomeClauseCoversEveryWord = AssertAllKeysHandled<Exclude<MemberOutcomeWord, keyof typeof OUTCOME_CLAUSE>>;
/**
* The refusal record as one engine sentence (empty when there is none): what the member did not get done, by kind, with the tool
* names of the listed calls. The face that speaks a member's refusals reads this, never its own list.
*/
export declare function memberRefusalsText(r: MemberRefusals | undefined): string;
/** The one text a leg's refused asks read as, wherever a parent reads them (the sub-agent report's `refused_asks:` line, the
* completion notification's `refused-asks` tag, the poll faces) — read off the asks alone: how many (the unlisted ones counted), each
* listed call's tool and why nobody answered it (the cause in a person's words, the notice's own table
* {@link ASK_UNRESOLVABLE_CAUSE_WORDS} — the cause word is the record's, never the line's), that they did not run, and the ways out the
* refusals named to the leg's model (a parent is a model too: where nobody on the leg could answer, the way out that names no person). */
export declare function refusedAsksText(refused: readonly RefusedAsk[], unlisted?: number): string;
/** A member's refusals as its parent reads them, in two texts off its ONE refusal record: the asks nobody could answer
* ({@link refusedAsksText}, the `refused_asks:` line / `refused-asks` tag that always carried them) and everything else it did not
* get done (the `refused:` line / `refused` tag, {@link memberRefusalsText}). Either is absent when it has nothing to say.
* {@link memberRefusalsText} words the whole record as one sentence (without the asks' causes or remedies) and is not a substitute. */
export declare function memberRefusalFaces(o: Pick<MemberOutcome, "refused"> | undefined): {
asks?: string;
rest?: string;
};
/** One member's ending as one engine sentence: the ending's clause, its code, who stopped it, then its refusals. */
export declare function memberOutcomeText(o: MemberOutcome): string;
/** Is this outcome the plain success a face says nothing extra about (completed, nothing refused)? */
export declare function isPlainCompletion(o: Pick<MemberOutcome, "outcome" | "refused"> | undefined): boolean;
/**
* The ledger's counting clause for a completion line: the rows that did not complete, by ending; then the refusals the rows carry,
* by kind; then the coverage word when the counts alone do not show the run is short (every row completed, yet something was
* refused). Empty for a run whose every row completed with nothing refused — that line stays the line it always was.
*/
export declare function memberLedgerClause(l: MemberLedger): string;
/**
* The ending of a stored row that states none of its own — the one reading of such a row: a row written before rows carried
* {@link MemberOutcome} (it kept only its refused asks, under their own key), a row whose own outcome is an earlier cycle's (its
* status says otherwise — see {@link memberRowStatusOf}), and a row whose own outcome does not read (`outcomeUnreadable`) — or whose
* engine kept no refusal record for it at all (a workflow row an earlier release wrote: `workflowMembersOf` passes
* `outcomeUnreadable`, since what it did not get done is not known either). The ending is the one its status words name; the old asks key, read by the frame decoder's predicate ({@link isRefusedAskList}; an
* empty list is none, as it always was), becomes the refusal record. A key that does not read — or an outcome that does not — leaves
* the record `unreadable`: the row still answers, never read as one with nothing refused. A store keeps what it was given; the face
* that serves a row reads it here, and says so when the record did not read (`agentOutcomeOf`, `workflowMembersOf`). The status
* words that name an ending are `completed`, `failed`, `killed`, `cancelled` and `parked` (each the ending of its own name; for a
* background row `parked` is live, and `agentOutcomeOf` asks only of its settled words; the frame decoder asks of whatever status
* an old boxed frame carries, whose writers never put `parked` there); any other word names none. The
* ending's origin is the row's own mark (`replayed: true` — a resume served it), as at the mint.
*/
export declare function outcomeOfLegacyRow(row: {
readonly status: string;
readonly errorCode?: string;
readonly stoppedBy?: string;
readonly refusedAsks?: unknown;
readonly replayed?: unknown;
}, kind: MemberKind, outcomeUnreadable?: boolean): MemberOutcome | undefined;
export {};