@sema-agent/core
Version:
Stateless, task-oriented AI agent core
142 lines (141 loc) • 9.9 kB
TypeScript
/**
* The task LIMITS: the allowance axes a caller sets on one run (turns, tokens, cost, wall-clock, the
* tool-call and idle bounds, the per-model overrides). Its own module rather than a section of
* `task-spec.ts` because it is the one shape a caller edits without touching anything else in the
* spec. Layer 0 vocabulary; `types.ts` re-exports the name, so no consumer's import changes.
*/
import type { ModelRef } from "./model-seat.js";
/**
* design/164 — the task's complete limit surface (see {@link TaskSpec.limits}).
*
* **Window semantics.** `maxTokens` / `maxCostUsd` / `maxWalltimeMs` are PER-SLICE windows, not
* whole-task totals: a task that opted into {@link TaskSpec.resourceSuspend} suspends when a window is
* exhausted and its resume gets the NEXT window of the same size. Whole-task ceilings live on
* `resourceSuspend` (`totalTokens` / `totalBudgetUsd`) and are frozen on the ledger, so a resume can
* never refresh them.
*
* **Two-tier hit semantics.** When a window is exhausted:
* - no `resourceSuspend` (the default) ⇒ a LOUD TERMINAL: `status:"failed"` with
* `limits.max_tokens_exceeded` / `limits.max_cost_exceeded` / `limits.max_turns_exceeded` /
* `limits.max_walltime_exceeded`, salvaged text attached where there is any. This is the
* "must have a definite outcome by the deadline" shape — express it by NOT opting in.
* - `resourceSuspend` set and the durable infrastructure present ⇒ a resumable `suspended` checkpoint.
*
* **Priority.** Several axes may be armed at once; the first to trip stops the run. When more than one
* trips at the same turn boundary the attribution order is tokens > cost > turns > walltime.
*
* **One task, several legs.** The verification gate and the repair loop run one task as several `runTask` legs; they read
* the task's whole-task ceilings (these windows on a task that cannot suspend, the `resourceSuspend` totals on one that can)
* as the TASK's, and dispatch each later leg on what the legs before it left (`src/agents/composition-allowance.ts`).
* `runGoal` and the cascade keep a per-iteration / per-rung allowance.
*/
export interface TaskLimits {
/**
* Cumulative prompt+completion tokens this slice may spend. The PRIMARY budget axis. Unset ⇒ no token
* ceiling. Must be a finite, non-negative number (a bad value is a fail-loud config error, never folded
* to a default) — see the two-tier hit semantics on {@link TaskLimits}.
*/
maxTokens?: number;
/**
* Cumulative spend ceiling for this slice, in USD (it counts what `model.cost` or `RunnerDeps.pricing` prices).
* Unset ⇒ no cost ceiling. Money and tokens are two genuine mental models and both are kept; documentation
* leads with `maxTokens`. It holds this run and every run it starts: each model request is admitted before it
* is sent — its estimated input (the whole request, characters / 4, scaled by the billed-to-estimated ratio
* already learned for that model) plus its output ceiling, at the request's rates — and the settled total is
* checked again at each turn boundary.
*
* Spend it cannot count is refused, not let through (`config.limit_invalid`): a run whose own model has no price
* table (neither `Model.cost` nor a `RunnerDeps.pricing` entry) is refused before its first request, nothing
* sent (`Runner.judgeTaskStart` answers the same), and so is a run it starts on such a model; a call that
* settles with no cost figure later (an unpriced fallback hop, compaction model or degrade target; a
* fast-served call on a table without a fast tier) stops the run that made it at that turn's end, and every run
* above it that a money ceiling holds at the end of its own turn.
*
* NOTE: the estimate can be under what a provider bills (a tokenizer that reads more than characters / 4, before
* any request of that model has settled), so a run can end somewhat past its ceiling.
*/
maxCostUsd?: number;
/** Turn ceiling for this slice. Unset ⇒ no turn ceiling. `0` is the explicit "unbounded" sentinel
* (kept for callers that write it deliberately); any other non-positive / non-finite value is a
* fail-loud config error. */
maxTurns?: number;
/**
* Wall-clock ceiling for this slice, in MILLISECONDS. A PER-SLICE ACTIVE clock: it starts at the
* slice's first turn on the monotonic clock, suspended time does not count, and a resume opens a
* fresh window (a new process, a new anchor — no cross-process clock is ever compared). Unset ⇒ no
* wall-clock ceiling, which is the default: time answers "how long did it take", not "how much work
* is this allowed to be", so it is the axis of last resort.
*/
maxWalltimeMs?: number;
/**
* How long a ONE-SHOT submission's ending ({@link TaskSpec.oneShot}) waits for the loop-type background tasks it started (agents,
* continued agents, workflow runs), in MILLISECONDS, counted from the ending's first wait. Absent ⇒ 600 000 (the reference's
* default for the same wait). `0` ⇒ no ceiling of its own: the ending waits as long as the run's walltime window and its
* cancel allow (the reference's `0`). It takes effect only on a one-shot run (any other run has no such wait, so a deployment may
* set it on every task); beside `maxWalltimeMs` the two clocks run side by side and whichever comes first ends the wait.
*
* When it is reached the wait stops, the answer stands as the result and the run's end handles each task as it always does (a
* task-scoped agent stopped with the run, anything else left to its own lifetime) — and says so once, naming each task:
* `task.wait_ceiling_reached`.
*
* Refused (`config.limit_invalid`), never folded to the default: not a finite number; negative; above 2 147 483 647 (a timer
* cannot hold it).
*/
oneShotWaitCeilingMs?: number;
/**
* design/119 #2: per-REQUEST output-token cap (the provider `max_tokens` / `max_completion_tokens`
* field). NOT a budget — it bounds each model reply, while {@link maxTokens} bounds the whole slice.
* Unset ⇒ the brain falls back to `model.maxTokens` (both families; the OpenAI lane omits the
* wire field — provider default — only when `model.maxTokens` is also absent). A reply
* that hits it stops with `length` and the loop's truncated-output auto-continue takes over.
* HARD bound on Anthropic budget-thinking models too: a cap too small to host a legal thinking
* budget (< 2048) skips thinking for the request rather than silently raising the cap.
*/
maxOutputTokens?: number;
/**
* design/164 — the LIMIT-APPROACH notice. While any of `maxTokens`/`maxCostUsd`/`maxTurns`/`maxWalltimeMs` is
* armed, every model request after the tightest axis crosses a threshold carries ONE sentence at its end: the
* first threshold's ("start converging") or, once the second is crossed, the second's ("deliver now") —
* chosen by the threshold crossed, so a first reading already past the second threshold is "deliver now".
* The sentence is request-only: it is never written to the transcript and never makes a request of its own.
* Advisory — it never stops the run, and it never fires on a resource-suspend task (a slice boundary is not
* a delivery deadline). The turn axis takes part only for a declared `maxTurns` of 4 or more.
*
* Default ON whenever an axis is armed; `false` switches it off. `{ at: [first, second] }` overrides
* the thresholds (each a fraction in `(0, 1]`, first ≤ second).
*/
approachNotice?: false | {
at?: [number, number];
};
/** Cancel an in-flight stream the moment cumulative cost/tokens cross their window. Defaults to `true`
* when {@link maxCostUsd} is set (hard control), `false` otherwise. */
budgetStreamCancel?: boolean;
/**
* **Near-budget degradation** (design/21 §5C). When cumulative cost reaches `atCostFraction` of the
* effective cost window, **switch the active model to the cheaper `to`** for the rest of the task to
* stretch the remaining budget — accepting lower quality instead of stopping at the ceiling. One-way
* (never switches back); sets `TaskResult.degraded = { …, reason: "budget" }`. Requires
* {@link maxCostUsd} (the fraction is of it); ignored otherwise. This is the proactive, Runner-level
* complement to the reactive model lane (a catalog entry's `fallbacks` chain, walked per request).
*/
degrade?: {
to: ModelRef;
atCostFraction: number;
};
/**
* The OUTER wall on how long the engine waits for a single brain
* call, in ms. Default {@link import("../brain/timeout.js").BRAIN_CALL_GUARDRAIL_DEFAULT_MS}
* (one hour); `false` or `0` switches it off; any other non-positive / non-finite value is a
* config error (fail-loud, never folded to a default). Overrides `RunnerDeps.brainCallGuardrailMs`.
*
* This is a GUARDRAIL, not a budget: it answers "is the system hung", so unlike every axis above it
* is armed by default, and it does NOT depend on the brain cooperating — on expiry the engine aborts
* the signal it handed the brain AND stops awaiting the call, ending the task fail-loud with
* `errorCode` `"brain.call_guardrail_timeout"`. That is what makes it the backstop for a custom
* `Brain` that ignores `options.signal` or never settles.
*
* It is deliberately COARSE. A task that also sets {@link maxWalltimeMs} runs both clocks in parallel
* and the tighter one expires first — the guardrail only shows up when everything finer failed to bind.
*/
brainCallGuardrailMs?: import("../brain/timeout.js").BrainCallGuardrailKnob;
}