UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

176 lines (175 loc) • 13.5 kB
/** * The run's usage account for the model calls made BESIDE the main loop — the compaction summarizer, the permission * classifier, a mod's `$.model.complete`, the advisor tool: the lanes, what a reply tells the account, the one door a lane books * through, and the ONE function behind it. The lane table says which `Stats` line keeps a lane's cost besides `costMicroUsd` * (every lane folds into the total — it is the budget coordinate and the reported figure); it is total over the lanes by its * fence, so another lane is a row here, not a second accounting function. */ import type { AssistantMessage, AssistantMessageDiagnostic, Model, Usage } from "../../internal/llm.js"; import type { FastModeCall } from "../../brain/fast-mode.js"; import type { ServedReading } from "../../brain/model-lane.js"; import { type ModelPricing, type PriceTable } from "../pricing.js"; import { type ConfigRefusalInput } from "../config-refusal-input.js"; import type { AssertAllKeysHandled } from "../ask-origin.js"; import type { Brain, RunnerDeps, TaskSpec } from "../types.js"; import type { Stats } from "./assemble-result.js"; import { type ResourceLedger } from "../checkpoint-store.js"; import type { SpendAccount } from "../spend-account.js"; /** Whose model call it is: the compaction summarizer, the permission classifier, a mod's `$.model.complete`, the advisor * tool's consultation of its advisor model, a manager's judgment of a worker's card (`TaskSpec.managerApproves`, booked on * the worker's leg). The word rides every side-call trace row (`brain.call.lane`). */ export type SideCallLane = "compaction" | "classifier" | "mod" | "advisor" | "manager"; /** The lane a model call of the leg is booked on: the main loop's turn, or a side-call lane. */ export type UsageLane = "main" | SideCallLane; /** The `Stats` line a lane's cost is also kept in: compaction is its own partition line (the engine's upkeep); the * classifier, the mods and the advisor share the side-call line (calls the run's own agent caused, so they stay inside the * root agent's cost). */ export declare const SIDE_CALL_LANE_TOTAL: { readonly compaction: "compactionMicroUsd"; readonly classifier: "sideCallMicroUsd"; readonly mod: "sideCallMicroUsd"; readonly advisor: "sideCallMicroUsd"; readonly manager: "sideCallMicroUsd"; }; export type LaneTotalCoversEverySideCallLane = AssertAllKeysHandled<Exclude<SideCallLane, keyof typeof SIDE_CALL_LANE_TOTAL>>; /** How an unpriced call's model reached the run: the run's own model (`main`), a hop of the requested model's fallback chain, the * near-budget degrade target, a side-call lane's model, or a call of a run this run started (`below`, at any depth). */ export type UnpricedVia = UsageLane | "degrade" | "below" | { readonly fallbackOf: string; }; /** * Why one settled call has no cost figure, as a refusal says it — one sentence per cause, each naming the model, how it reached * the run and what to change: a call served at fast speed on a table that declares no fast tier (`tableExists`), or a model with no * price table at all, by the path that brought it in. */ export declare function unpricedCallCause(modelId: string, tableExists: boolean, via: UnpricedVia): string; /** Mark the run's spend unpriced: the one writer of `unpricedSpend`, and of the first cause beside it. */ export declare function noteUnpricedSpend(telemetry: { unpricedSpend: boolean; unpricedCause?: string | undefined; }, cause: string): void; /** * THE run's own money ceiling, as a refusal names it: its window (`TaskSpec.limits.maxCostUsd`), else its total * (`resourceSuspend.totalBudgetUsd`, or what a resumed chain's ledger has left of it). `undefined` ⇒ the run sets none. The * task-start doors read it (a ceiling over a model that cannot be priced is refused there, so `Runner.judgeTaskStart` says so too); * {@link moneyCeilingOver} reads it first. */ export declare function ownMoneyCeiling(spec: Pick<TaskSpec, "limits" | "resourceSuspend">, ledger: ResourceLedger | undefined): string | undefined; /** THE money ceiling of a run this run spends from, as a refusal names it: `under` — the account node the run hangs under — or a * node above it has one (`undefined` for a root, or no such ceiling). {@link moneyCeilingOver} reads it after the run's own. */ export declare function enclosingMoneyCeiling(under: SpendAccount | undefined): string | undefined; /** * THE money ceiling a run's spend with no cost figure is judged against, as the refusal names it: the run's own * ({@link ownMoneyCeiling}), else the ceiling of any run it spends from ({@link enclosingMoneyCeiling}). `undefined` ⇒ no money * ceiling holds the run, and such spend is only disclosed. Read at each turn's end (a call settled with no cost figure ⇒ stopped * then); before the first request its two halves are asked where each exists ({@link unpricedModelRefusal}). */ export declare function moneyCeilingOver(spec: Pick<TaskSpec, "limits" | "resourceSuspend">, ledger: ResourceLedger | undefined, under: SpendAccount | undefined): string | undefined; /** * THE refusal, before a run's first request, of a money ceiling (`held`, as a refusal names it) over a run's own model the * ceiling cannot count — `undefined` with no ceiling (the table is then not read: a garbage one stays report-only) or a table that * counts it. No price table (neither a RunnerDeps.pricing entry nor a Model.cost declaration) ⇒ nothing the run sends can be * counted; a table with an unevaluable rate (NaN prices a turn at zero, a negative one below zero) ⇒ the ceiling would never fill * while every disclosure face reads "priced". Both `config.limit_invalid`. One function, each ceiling asked once where it exists: * the run's own ({@link ownMoneyCeiling}) at the task-start doors, an enclosing run's ({@link enclosingMoneyCeiling}) in prepare * on the node the run hangs under and in `Runner.judgeTaskStart` on the node of the seat a host hands on — so both answer alike. */ export declare function unpricedModelRefusal(held: string | undefined, model: Model, pricing: RunnerDeps["pricing"], modelInput: ConfigRefusalInput): (Error & { code: string; }) | undefined; /** The input a refusal about a model's price table is about (`config-refusal-input.ts`): the deployment's entry for the model, else what * the model declares of itself — the input the model came from (`modelInput`); a model with no table at all is about the model too. */ export declare function priceTableInput(table: PriceTable, modelInput: ConfigRefusalInput): ConfigRefusalInput; /** The refusal of spend a money ceiling cannot count (`config.limit_invalid`): `held` from {@link moneyCeilingOver}, `why` the * unpriced cause; `when` — before the first request (nothing was sent) or at the end of the turn the spend settled in. */ export declare function uncountedSpendRefusal(held: string, why: string, when: "start" | "turn"): Error & { code: string; }; /** The run's money figure as a ceiling reads it: `costMicroUsd`, or — once any spend settled unpriced — why there is none. Every * money ceiling (the usage window's charge, the task's `maxCostUsd` stop) asks here. */ export declare function costFigureOf(telemetry: { unpricedSpend: boolean; unpricedCause?: string | undefined; }, costMicroUsd: number): number | { readonly unpricedBecause: string; }; /** A side call's reply as the account reads it: the provider's usage (absent ⇒ none reported), the marks of what is unknown, * and the diagnostics in which the model lane says which hop answered and which hops it left behind (each billed at its own * model). */ export interface SideCallReply { readonly usage?: Usage; readonly usageMissing?: true; readonly stopReason?: string; readonly partialFinalized?: boolean; readonly diagnostics?: AssistantMessageDiagnostic[]; } /** The leg's one door onto the run's usage account: every side call's reply is booked through it, once. */ export type SideCallBook = (lane: SideCallLane, model: Model, reply: SideCallReply | undefined) => void; /** The leg's seats a side call is priced and traced on — everything the call needs that `stats` does not carry. */ export interface SideCallAccount { /** The run's telemetry: a call on an unpriced model taints `unpricedSpend`; the trace row goes to its tracer. */ telemetry: { unpricedSpend: boolean; unpricedCause?: string | undefined; readonly tracer: TaskSpec["tracer"]; readonly taskId: string; }; /** The deployment's price table, read at the call (a swapped deps seat reaches legs already running). */ pricing: () => RunnerDeps["pricing"]; /** The telemetry lane's price-table door, consulted for every table a side call adopts. */ noteUnevaluablePriceTable: (p: ModelPricing) => void; /** Where a reply is read for the leg's `model.fallback` seat — a walked reply, or one whose walk sent no hop, is announced, and the * requested model's own answer ends what the seat told of its walks (`reply`: the call's reply, absent when it made none); absent ⇒ not read. */ noteFallback?: (lane: SideCallLane, requested: Model, reading: ServedReading, reply: SideCallReply | undefined) => void; } /** What one billed call tells the account beyond its usage: the model it is priced at and the marks of what is unknown. */ export interface SideCallCall { model: Model; account: SideCallAccount; usageMissing?: true; stopReason?: string; } /** * THE one place a model call made beside the main loop reaches the run's account: the compaction summarizer, the * permission classifier and a mod's `$.model.complete` all land here, each with its lane. The call is accounted exactly * like a main-loop call (re-priced in core from the deployment's table and the model's cache family, integer * micro-USD, never the brain's own `usage.cost`), so the reported total, the budget gate at the next turn end and the * trace agree about what the run spent. Latency and first-token time are not modeled (there are no per-delta hooks here). * * `usage` absent — the reply reported none — marks the leg's stats `usageMissing` (the totals are then a lower bound: * unknown is not free). A reply the brain itself marked `usageMissing` does the same for its zero-filled usage. Either way the * lane is left out of the cache-hit rate; the cache members fold through the one cache account (`./cache-hit-account.ts`). */ export declare function recordSideCallUsage(stats: Stats, usage: Usage | undefined, lane: SideCallLane, call: SideCallCall): void; type SideCallRowTelemetry = { readonly tracer: TaskSpec["tracer"]; readonly taskId: string; }; /** The prompt-suggestion pass's row: its reply priced by the same function as the booked lanes, emitted by the builder above, * and booked nowhere (the pass's spend is the result's separate `stats.suggestions` line). */ export declare function emitSuggestionsRow(telemetry: SideCallRowTelemetry, reply: AssistantMessage, model: Model, pricing: RunnerDeps["pricing"]): void; /** * The accounted brain of a DERIVED LEG — a model call made beside the main loop on the leg's behalf (the compaction summary, * the advisor consultation): every reply is booked through `book` exactly once, under `lane`, and the call runs behind a * NO-OP status sink. Both arms obey the same law, whichever one the caller uses. * * The shield: a derived call fires inside the leg's `runWithStatusSink` scope (the compaction hook from `turn_boundary` * within `harness.prompt`, the advisor from a tool call), so a 429/retry on it must not surface as a `status` event on the * user's turn (status-sink.ts / TaskEvent.status). Its reply never reaches the leg's harness `message_end`, so it cannot * restate the leg's reasoning posture either. * * `complete` is ALWAYS provided (brainToRuntime prefers it), so the booking is awaited INLINE on both the native-complete and * derived-from-stream paths, and the message is returned UNCHANGED (its `errorKind` is what the summary path's * budget-escalation recovery reads). `stream` opens the inner stream inside the same scopes (the provider work it starts runs * in them) and books the stream's final message when it settles: the inner `result()` settles once, whether the caller awaits * it or only iterates, and the returned stream's `result()` is that booked settlement — a booking that throws rejects it rather * than vanishing. A stream that ends without a final message books nothing; its caller owes the lower-bound mark. `brainOf` * is read per call (a swapped deployment brain reaches legs already running). `fastModeOf`, when given, is the session's * fast-mode handle each call carries (a request of the session's conversation asks as the session does, as the reference's * forks copy their caller's options, (cli321.js:287049) "w=n?.options??e.options"); read per call, so it follows the session. */ export declare function derivedLegBrain(brainOf: () => Brain, lane: SideCallLane, book: SideCallBook, fastModeOf?: () => FastModeCall | undefined): Brain; /** The leg's door: `recordSideCallUsage` bound to the leg's `stats` and account, reading what the reply itself says — its * marks, and its bills (`billsOf`: every hop the model lane left behind, then the reply, each at its own model). */ export declare function sideCallBookOf(stats: Stats, account: SideCallAccount): SideCallBook; export {};