@sema-agent/core
Version:
Stateless, task-oriented AI agent core
233 lines (232 loc) • 14.2 kB
TypeScript
/**
* The spend account: ONE tree of nodes that every ceiling on model spend is a ceiling of. A node is one run (a workflow run
* included); it hangs under the run that started it or woke it. Each node holds what its own requests settled, what its
* whole subtree settled, and what its subtree has reserved for requests still in flight. A run's `limits.maxTokens` /
* `maxCostUsd` window, a workflow's `budget`, a member's `childMaxTokens`, a composition's whole-task allowance — each is the
* ceiling of exactly one node, compared against that node's SUBTREE, so "how much did this tree spend" has one answer.
*
* Every real model request reserves before it is sent (`admit`): estimated input plus the output ceiling the request will
* carry, on its own node and on every ancestor that has a ceiling. A request that does not fit has its output ceiling narrowed
* to what is left; one that would be narrowed under the floor waits for an in-flight reservation on the node that holds it to
* settle, and is refused when there is none. Settling replaces the reservation with what the provider reported; a request
* whose usage never arrived (aborted, dropped) settles at its whole reservation — the account never gives back an amount that
* may still be being spent.
*
* Closing: a node closes when its run reaches its terminal. A closed node refuses its own requests and those of descendants
* that hang under it by a TASK link; a descendant under a SESSION link (a session-scoped background child, a revived cycle) is
* not bound to the run's end and keeps spending from it, under the same ceilings.
*/
declare const SPEND_SEAT: unique symbol;
/** The opaque handle a run gives its tools (`ToolExecuteContext.spendSeat`): a delegating tool hands it on to the run it starts
* (`RunInternals.spendParent.seat`), so that run's requests spend from this run's account. Nothing else can be done with it. */
export interface SpendSeat {
readonly [SPEND_SEAT]: true;
}
/** The account a seat stands for; `undefined` for anything that is not a seat the engine handed out. */
export declare function spendAccountOf(seat: unknown): SpendAccount | undefined;
/** The two ceiling axes. */
export type SpendAxis = "tokens" | "cost";
/** How a node hangs under its parent: `task` — bound to the parent run's end; `session` — outlives it. */
export type SpendLink = "task" | "session";
/** Where a run (or a workflow) hangs on the account of the run that started it: that run's seat, handed on as it is (typed as the
* tool's `ToolExecuteContext.spendSeat` is, so it is handed on without a check; an absent one — a tool driven outside a Runner task
* has none — is refused like any other value that is not a seat), and the link. */
export interface SpendParent {
readonly seat: SpendSeat | undefined;
readonly link: SpendLink;
}
/**
* Judge where a run or a workflow will spend from, now, and answer the mint of its node, made when the caller calls it: a child of
* the account `parent.seat` stands for, by `parent.link`; a root of its own account when there is no parent. A `seat` that is not a
* seat the engine handed out, or a `link` outside the two, is refused here (`config.invalid_argument`, `detail.field` = the member)
* — never read as "no parent", which would put the work outside every ceiling of the run it belongs to.
*/
export declare function spendNodeMint(parent: SpendParent | undefined, member: string): () => SpendAccount;
/** The judgment {@link spendNodeMint} mints by, read without minting: the account the work will hang under and by which link
* (`undefined` — no parent, a root), or the same refusal. */
export declare function spendParentOf(parent: SpendParent | undefined, member: string): {
readonly account: SpendAccount;
readonly link: SpendLink;
} | undefined;
/** One node's ceilings: tokens (input + output) and micro-USD. Absent ⇒ no ceiling on that axis. */
export interface SpendCeiling {
readonly tokens?: number;
readonly costMicroUsd?: number;
}
/** Why a request was refused, and by which node: `heldBy` says whether raising the requesting run's own ceiling would help. */
export interface SpendStop {
readonly axis: SpendAxis;
/** The ceiling that held (tokens or micro-USD by axis); for a closed node, the node's ceiling on the axis or 0. */
readonly limit: number;
/** What the holding node's subtree had settled when the request was refused (same unit as `limit`). */
readonly observed: number;
readonly heldBy: "own" | "ancestor";
/** `ceiling` — the request did not fit; `closed` — the run the request belongs to (or a task-bound ancestor) had ended. */
readonly reason: "ceiling" | "closed";
}
/** What one request asks the account for. */
export interface SpendAsk {
/** Estimated input tokens of the request as it will be sent. */
readonly inputTokens: number;
/** The output ceiling the request would carry unconstrained. */
readonly outputTokens: number;
/** Micro-USD per input token at the most expensive input column of the tier the request asks for (0 when unpriced). */
readonly inputMicroUsdPerToken: number;
/** Micro-USD per output token at that tier (0 when unpriced). */
readonly outputMicroUsdPerToken: number;
}
/** The output floor a narrowed request may not go under: below it the request waits or is refused. */
export declare const SPEND_OUTPUT_FLOOR_TOKENS = 1024;
/** The output ceiling a request reserves when neither the call nor its model states one (and carries on the wire when its
* chain is constrained): the token and cost axes read the same figure, so they cannot disagree about the same request. */
export declare const SPEND_DEFAULT_OUTPUT_TOKENS = 4096;
/** A call that settled with no cost figure: its model, and whether that model has a price table (with one, it was served at a
* speed the table declares no rates for). */
export interface UnpricedCall {
readonly modelId: string;
readonly tableExists: boolean;
}
/** One admitted request's hold on the account, settled exactly once. */
export interface SpendTicket {
/** The output ceiling the request must carry on the wire. */
readonly outputTokens: number;
/** The account narrowed the request's output ceiling to fit (the request must say so, `maxTokensDynamic`). */
readonly narrowed: boolean;
/** Some node on the request's chain has a ceiling (the request carries its reserved output ceiling on the wire). */
readonly constrained: boolean;
/** When narrowed: the stop the narrowing node states (read when the request used its whole narrowed ceiling). */
readonly narrowedBy?: () => SpendStop;
/** Replace the reservation with what the provider reported. `unpriced` — the call settled with no cost figure (the cost figure is
* a lower bound), and why. `inputTokens` — the input the provider billed, when it said: the next request presents at least that
* much ({@link SpendAccount.fill}). */
settle(actual: {
readonly tokens: number;
readonly costMicroUsd: number;
readonly unpriced?: UnpricedCall;
readonly inputTokens?: number;
}): void;
/** Settle at the whole reservation (the usage never arrived). `unpriced` — as for {@link settle}: the call has no cost figure, so
* the reservation's cost is no upper bound on it (a model with no price table reserves at no cost). */
settleAtReservation(unpriced?: UnpricedCall): void;
}
export type SpendAdmission = {
readonly kind: "admit";
readonly ticket: SpendTicket;
} | {
readonly kind: "refuse";
readonly stop: SpendStop;
};
/**
* Whether `reason` — the reason a caller aborted its request's signal with — ended that request's wait for room on the account
* (so the request was never sent). A caller whose own deadline cut the request reads here whether the deadline cut a model that
* was slow or a request the account had not let through: the second is the account's refusal, not the model's lateness.
*/
export declare function cutWaitingForRoom(reason: unknown): boolean;
interface Amount {
tokens: number;
costMicroUsd: number;
}
/** A node of the spend account. Construct roots with {@link SpendAccount.root}, children with {@link SpendAccount.child}. */
export declare class SpendAccount implements SpendSeat {
readonly parent: SpendAccount | undefined;
readonly link: SpendLink | undefined;
/** The seat's brand (type only): a node is the seat the engine hands out for it. */
readonly [SPEND_SEAT]: true;
private ceiling;
private closed;
/** Settled by this node's own requests. */
private readonly own;
/** Settled by the whole subtree (own included). */
private readonly subtree;
/** Reserved by in-flight requests of the whole subtree. */
private readonly reserved;
/** Descendant nodes (runs) ever attached under this node. */
private descendants;
/** The first call of a descendant that settled with no cost figure (this node's own calls are its run's to read). */
private firstUnpricedBelow;
/** Requests of the subtree that are waiting for a reservation on this node to settle. */
private readonly waiters;
/** The first refusal this node's own requests met (the run reads it to end on the budget). */
private firstStop;
/** This node's last request as it asked (its estimated input, its output floor, its prices): the size {@link fill} gives the next one. */
private lastAsk;
/** Served input per estimated input token, per model id (≥ 1), as this node's requests last settled — the meter scales the next
* estimate by it. A node starts from its parent's figures as they stand when it is made, so a run's first request is estimated
* the way the run that started it already learned to. */
readonly inputScale: Map<string, number>;
private constructor();
/** A root node: a run nobody started (a host's top-level run, a host-driven workflow). */
static root(): SpendAccount;
/** A child node under this one (a run this run started or woke). */
child(link: SpendLink): SpendAccount;
/** Set this node's ceilings (a run sets them once its window is computed, before its first request). */
setCeiling(ceiling: SpendCeiling): void;
/** This node's ceilings as set. */
get ceilings(): SpendCeiling;
/** Close the node: its run reached its terminal. Waiters re-evaluate (and are refused). */
close(): void;
get isClosed(): boolean;
/** The first refusal this node's own requests met, if any. */
get stop(): SpendStop | undefined;
/** Record a stop on this node (a refusal, or the meter when a request it narrowed used its whole narrowed ceiling). The
* latest one stands: it is the one whose refusal the run's last turn ended on. */
noteStop(stop: SpendStop): void;
/** One turn of this node's run ended (the subtree's turn count, for the nested figure). */
noteTurn(): void;
/** What this node's own requests settled. */
get ownSettled(): Readonly<Amount & {
turns: number;
}>;
/** What the subtree settled (own included). */
get subtreeSettled(): Readonly<Amount & {
turns: number;
}>;
/** What the subtree has reserved in flight. */
get inFlight(): Readonly<Amount>;
/** The figure the result's `stats.nested` reports: everything under this node, its own requests excluded; `undefined`
* when no descendant was ever attached. `anyUnpriced` — some descendant's spend had no cost figure, so `costMicroUsd` is a
* subtotal (the priced part). */
nested(): {
tokens: number;
turns: number;
tasks: number;
costMicroUsd: number;
anyUnpriced: boolean;
} | undefined;
/** The first call under this node — of a run it started, at any depth — that settled with no cost figure: what a money ceiling on
* this node's chain cannot count, read at its run's turn ends. */
get unpricedBelow(): UnpricedCall | undefined;
/** Room left on `axis` at this node's ceiling (settled and in-flight subtracted), or `undefined` with no ceiling on it. */
remaining(axis: SpendAxis): number | undefined;
/**
* How full the tightest ceiling on this node's chain is, in the one reading the account refuses by: what the ceiling's subtree
* settled and holds in flight, plus this node's next request at the least the account would send it with (sized as its last
* request: its estimated input, or what the provider billed it as input when that is more, and the output floor), over the
* ceiling. At 1 that request stops fitting and is refused, so a
* warning read off this figure (the limit-approach notice) always comes before the refusal it warns of. `undefined` before
* this node's first request, or with no positive ceiling on its chain.
*/
fill(): {
readonly axis: SpendAxis;
readonly ratio: number;
} | undefined;
/** This node or one above it has a money ceiling: what a run hanging under this node spends is held by it. */
moneyCeilingOnChain(): boolean;
/** Some node on this node's chain has a ceiling. */
constrained(): boolean;
/** The node on this node's chain whose end binds this node's requests: refusal when one is closed. */
private closedHolder;
/** Decide one request now: admitted (maybe narrowed), refused, or `wait` on the node that holds it. */
private decide;
/**
* Admit one request: synchronous when the account can decide now (`admit` / `refuse`), a promise when the request must wait
* for an in-flight reservation to settle. A wait ends on settle, close, or `signal` (aborted ⇒ refused as closed would be:
* the caller is gone). A refusal is recorded as this node's stop.
*/
admit(ask: SpendAsk, signal?: AbortSignal): SpendAdmission | Promise<SpendAdmission>;
private recorded;
private reserve;
/** Wake every waiter on this node's chain (a settle or a close changed what fits). */
private wakeChain;
}
export {};