import { TraceContext } from "autotel"; //#region src/guard.d.ts /** What a rule does when it crosses its threshold. */ export type GuardAction = 'warn' | 'stop'; /** Usage contribution for a single step. */ export interface GuardUsage { /** * Estimated USD cost for this step. Pair with * {@link import('./cost.js').estimateLLMCost} to compute it from token usage. */ costUsd?: number; /** Input (prompt) tokens for this step. */ inputTokens?: number; /** Output (completion) tokens for this step. */ outputTokens?: number; } /** A single supervised step: an LLM call, a tool call, a delegation, … */ export interface GenAiGuardStep { /** * Step kind. `tool` increments the tool-call counter; any value is allowed. */ kind?: 'llm' | 'tool' | 'agent' | 'workflow' | (string & {}); /** Operation or tool name — used together with {@link signature} for loops. */ name?: string; /** * Stable signature of the call inputs (e.g. `JSON.stringify(args)`). Two * steps with the same `name` + `signature` count as identical for spin-loop * detection. Hash or truncate it yourself if the raw args are large. */ signature?: string; /** Whether this step failed. Drives error-loop detection. */ error?: boolean; /** Cost / token contribution to the running totals. */ usage?: GuardUsage; } /** Read-only snapshot of the accumulated session state. */ export interface GuardState { /** Epoch ms when the guard was created. */ readonly startedAt: number; /** Epoch ms at evaluation time. */ readonly now: number; /** Wall-clock ms since {@link startedAt}. */ readonly elapsedMs: number; /** Accumulated estimated cost in USD. */ readonly costUsd: number; /** Accumulated input tokens. */ readonly inputTokens: number; /** Accumulated output tokens. */ readonly outputTokens: number; /** Total steps recorded. */ readonly stepCount: number; /** Steps with `kind === 'tool'`. */ readonly toolCallCount: number; /** Steps with `error === true`. */ readonly errorCount: number; /** Bounded recent history (newest last) for loop detection. */ readonly history: ReadonlyArray<{ key: string | undefined; error: boolean; }>; } /** A fired rule. */ export interface GuardViolation { /** Rule name, e.g. `cost-ceiling:$5`. */ rule: string; /** Whether the run continued (`warn`) or was halted (`stop`). */ action: GuardAction; /** Human-readable explanation. */ message: string; /** The observed value that crossed the threshold. */ observed: number; /** The configured threshold. */ limit: number; } /** A guard rule: inspect the state after a step and optionally fire. */ export interface GenAiGuardRule { /** Stable identifier, surfaced on {@link GuardViolation.rule}. */ name: string; /** Default {@link GuardAction} when the rule fires. Defaults to `stop`. */ action?: GuardAction; /** * Evaluate against the post-step state and the step just recorded (absent on * a bare {@link GenAiGuard.check}). Return a partial violation to fire, or * `undefined` to pass. */ evaluate: (state: GuardState, step: GenAiGuardStep | undefined) => { message: string; observed: number; limit: number; } | undefined; } /** Minimal telemetry sink — the subset of {@link TraceContext} the guard uses. */ export type GuardSink = Pick; /** What happens when a `stop` rule fires. */ export type GuardStopBehavior = /** Abort the signal and throw a structured error (default). */ 'throw' | /** Abort the signal but do not throw — inspect `guard.stopped` yourself. */ 'abort' | /** Record the violation only; neither abort nor throw. */ 'silent'; export interface GenAiGuardOptions { /** Rules to evaluate after each step. */ rules: GenAiGuardRule[]; /** What to do when a `stop` rule fires. Defaults to `throw`. */ onStop?: GuardStopBehavior; /** * Max recent steps retained for loop detection. Defaults to 256; raise it if * a spin-loop rule uses a larger window. */ historyLimit?: number; /** Clock injection point, for tests. Defaults to {@link Date.now}. */ now?: () => number; } /** A live guard supervising an agent run. */ export interface GenAiGuard { /** * Record a step, accumulate its usage, and evaluate every rule. Returns the * violations that fired _this call_ (each rule fires at most once). When a * `stop` rule fires, aborts {@link signal} and — unless `onStop` is `abort` / * `silent` — throws a structured `GEN_AI_GUARD_STOP` error. */ record(step: GenAiGuardStep, ctx?: GuardSink): GuardViolation[]; /** * Re-evaluate the rules without recording a step. Useful for time-based * rules (e.g. a timeout) between LLM calls. */ check(ctx?: GuardSink): GuardViolation[]; /** Current accumulated state. */ readonly state: GuardState; /** Fires once a `stop` rule has crossed its threshold. */ readonly signal: AbortSignal; /** `true` after a `stop` rule has fired. */ readonly stopped: boolean; /** Every violation fired so far, in order. */ readonly violations: ReadonlyArray; } /** Stop / warn when accumulated cost exceeds `limitUsd`. */ export declare function costCeiling(limitUsd: number, action?: GuardAction): GenAiGuardRule; /** Stop / warn when accumulated input + output tokens exceed `limit`. */ export declare function tokenCeiling(limit: number, action?: GuardAction): GenAiGuardRule; /** Stop / warn when the number of tool calls exceeds `limit`. */ export declare function maxToolCalls(limit: number, action?: GuardAction): GenAiGuardRule; /** Stop / warn when the total number of steps exceeds `limit`. */ export declare function maxSteps(limit: number, action?: GuardAction): GenAiGuardRule; /** Stop / warn when wall-clock time since start exceeds `limitMs`. */ export declare function maxDuration(limitMs: number, action?: GuardAction): GenAiGuardRule; /** * Stop / warn on a spin loop: the same step (`name` + `signature`) repeated * `count` or more times within the last `window` steps. Steps without a `name` * are ignored (no identity to compare). */ export declare function spinLoop(options: { count: number; window: number; }, action?: GuardAction): GenAiGuardRule; /** Stop / warn on `count` or more consecutive failing steps. */ export declare function errorLoop(options: { count: number; }, action?: GuardAction): GenAiGuardRule; /** * Approximate context-window sizes (in input tokens) for common models. * Matched exactly first, then by longest key prefix. Override via the `limit` * option on {@link contextBudget}. */ export declare const CONTEXT_LIMITS: Record; /** * Stop / warn when cumulative input tokens reach `threshold` (default 0.9) of * the model's context window. Provide an explicit `limit`, or a `model` to look * one up from {@link CONTEXT_LIMITS}. */ export declare function contextBudget(options: { model?: string; limit?: number; threshold?: number; }, action?: GuardAction): GenAiGuardRule; /** * Parse a comma-separated shorthand rule string into {@link GenAiGuardRule}s. * All parsed rules default to the `stop` action — pass `defaultAction: 'warn'` * to warn instead, or build typed rules directly for per-rule actions. * * Supported tokens: * - `budget:$5` / `cost:$5` — {@link costCeiling} * - `tokens:100k` — {@link tokenCeiling} (`k`/`m`/`b` suffixes) * - `loop:3/10` — {@link spinLoop} (count / window) * - `errors:3` — {@link errorLoop} * - `max-tools:50` — {@link maxToolCalls} * - `max-steps:100` — {@link maxSteps} * - `timeout:30m` — {@link maxDuration} (`ms`/`s`/`m`/`h`, default seconds) * - `context:0.9` / `context:0.9@gpt-4o` — {@link contextBudget} */ export declare function parseGuardRules(shorthand: string, options?: { defaultAction?: GuardAction; }): GenAiGuardRule[]; /** * Create a guard that supervises an in-process agent run against `rules`. */ export declare function createGenAiGuard(options: GenAiGuardOptions): GenAiGuard; export interface GenAiBudgetOptions { /** Hard cost ceiling in USD — a `stop` rule. */ maxCostUsd?: number; /** Soft cost threshold in USD — a `warn` rule. */ warnAtUsd?: number; /** Hard token ceiling (input + output) — a `stop` rule. */ maxTokens?: number; /** Hard tool-call ceiling — a `stop` rule. */ maxToolCalls?: number; /** Hard wall-clock ceiling in ms — a `stop` rule. */ maxDurationMs?: number; /** What to do when a `stop` rule fires. Defaults to `throw`. */ onStop?: GuardStopBehavior; /** Clock injection point, for tests. */ now?: () => number; } /** * Convenience preset that wires the common cost / token / tool-call / duration * ceilings into a {@link createGenAiGuard}. Returns the same {@link GenAiGuard}. */ export declare function createGenAiBudget(options: GenAiBudgetOptions): GenAiGuard; //#endregion