/** * Bounds and guard functions for the planner chaining loop: the * `ChainingLoopConfig` limit contract (max tool calls, repeated-failure and * cumulative-token budgets), the typed * `TrajectoryLimitExceeded` error, and the assert/count helpers that stop a * runaway or stuck planner from burning a turn. */ import type { ActionFailureProvenance } from "../types/action-failure.js"; export interface ChainingLoopConfig { /** Explicit domain-call ceiling; discovery does not spend it. Unbounded by default. */ maxToolCalls: number; /** Maximum repeated failures for the same tool/error signature. */ maxRepeatedFailures: number; /** Maximum planner misses when Stage 1 requires a tool before failing fast. */ maxRequiredToolMisses: number; /** Maximum planner retries after it calls only tools unavailable this turn. */ maxUnavailableToolCallRetries: number; /** Maximum terminal-only planner turns that still evaluate to CONTINUE. */ maxTerminalOnlyContinuations: number; /** * Maximum planner iterations whose only non-terminal tool calls exactly * repeat a call that already SUCCEEDED this turn (same tool name + args). * Re-running an identical successful call cannot yield new information; a * model that keeps doing so is stuck (observed live: gpt-5.5 re-issuing the * same WEB_FETCH 17× until `maxTrajectoryPromptTokens` aborted the turn with * a generic apology). Once exceeded, the loop stops re-executing and forces * one terminal synthesis call so the user gets the answer already gathered. * This is the success-side analog of `maxRepeatedFailures`. */ maxRepeatedToolCalls: number; /** Optional successful recall-search ceiling; distinct searches are unbounded by default. */ maxMemorySearchRounds: number; /** Explicit model window for diagnostic estimates; provider errors remain authoritative. */ contextWindowTokens: number; /** Optional model label for diagnostics; context limits are explicit metadata. */ contextWindowModelName?: string; /** Token reserve kept free for model output and provider overhead. */ compactionReserveTokens: number; /** * @internal Tracks whether `compactionReserveTokens` came from the caller * rather than `DEFAULT_CHAINING_LOOP_CONFIG`. This lets the planner apply * the per-model derived reserve when only `contextWindowModelName` is set, * while still preserving explicit reserve overrides. */ compactionReserveTokensExplicit?: boolean; /** * Maximum cumulative prompt tokens summed across every planner-stage * model call within a single user turn. Once exceeded the loop aborts * with `TrajectoryLimitExceeded({kind:"trajectory_token_budget"})`, * bounding the worst-case cost of a runaway replan. * * The count tracks **gross prompt tokens** (cached + non-cached + cache * write) — the same number the provider would meter you on; cache reads * count too because they still consume context and walltime even if the * dollar cost is discounted. * * Set to `Number.POSITIVE_INFINITY` to disable the guard. The default * of 1.5M tokens is calibrated against observed trajectories: * - well-formed single-turn answers: 50k–250k cumulative tokens. * - normal multi-step tool chains: 400k–800k cumulative. * - the runaway replan that motivated this guard: 2.2M cumulative * (13 planner iterations growing monotonically until the model's * per-call window overflowed). * * 1.5M sits comfortably above legitimate traffic and well below the * runaway level — a turn that exceeds it is almost certainly stuck. */ maxTrajectoryPromptTokens: number; } export type TrajectoryLimitKind = "tool_calls" | "repeated_observations" | "memory_search_rounds" | "repeated_failures" | "required_tool_misses" | "unavailable_tool_calls" | "terminal_only_continuations" | "trajectory_token_budget"; export declare class TrajectoryLimitExceeded extends Error { readonly kind: TrajectoryLimitKind; readonly max: number; readonly observed: number; /** * Present only for `repeated_failures`, where the underlying tool failure * has a structured cause worth surfacing. Consumed by * `classifyStructuredFailureCause` in `services/message/fallback-reply.ts`. */ readonly failureProvenance?: ActionFailureProvenance; constructor(params: { kind: TrajectoryLimitKind; max: number; observed: number; message?: string; failureProvenance?: ActionFailureProvenance; }); } export declare function mergeChainingLoopConfig(config?: Partial): ChainingLoopConfig; export declare function assertTrajectoryLimit(params: { kind: TrajectoryLimitKind; max: number; observed: number; }): void; export interface FailureLike { toolName?: string; error?: unknown; success?: boolean; repeatKey?: string; /** * Structured cause carried up from the settled `ActionResult`. When a * repeated-failure abort is raised, this is what lets the fallback reply * say *why* the tool kept failing (a dead datastore, say) rather than * reporting generic planner exhaustion. */ failureProvenance?: ActionFailureProvenance; } export declare function assertRepeatedFailureLimit(params: { failures: readonly FailureLike[]; latestFailure: FailureLike; maxRepeatedFailures: number; }): void;