import type { Message, Provider, Tool } from '../types.js'; import { getCompactThreshold } from './compact.js'; import { countMessagesTokens, countTextTokens, estimateToolsTokens } from './tokenCounter.js'; import { budgetClassForToolName } from '../tools/capabilities.js'; export interface ContextBudgetPlan { contextWindow: number; inputLimit: number; reservedOutput: number; historyTokens: number; toolTokens: number; transientTokens: number; multimodalTokens: number; totalInputTokens: number; overBudget: boolean; } /** The same effective threshold is used for preflight, switching and display. */ export function modelInputLimit(provider: Provider): number { const configured = provider.source === 'gateway' ? undefined : provider.maxTokens; const output = typeof configured === 'number' && Number.isFinite(configured) ? Math.max(0, Math.floor(configured)) : 0; return Math.min(getCompactThreshold(provider), Math.max(0, provider.contextWindow - output)); } export function buildContextBudgetPlan(input: { provider: Provider; history: readonly Message[]; tools: readonly Tool[]; transientContext?: string; multimodalTokens?: number; }): ContextBudgetPlan { const inputLimit = modelInputLimit(input.provider); const historyTokens = countMessagesTokens(input.history as Message[]); const toolTokens = estimateToolsTokens(input.tools as Tool[]); const transientTokens = countTextTokens(input.transientContext ?? ''); const multimodalTokens = input.multimodalTokens ?? 0; const totalInputTokens = historyTokens + toolTokens + transientTokens + multimodalTokens; return { contextWindow: input.provider.contextWindow, inputLimit, reservedOutput: Math.max(0, input.provider.contextWindow - inputLimit), historyTokens, toolTokens, transientTokens, multimodalTokens, totalInputTokens, overBudget: totalInputTokens > inputLimit, }; } export interface EmergencyToolFit { tools: Tool[]; removedNames: string[]; plan: ContextBudgetPlan; } // Agent first (largest schema); the advisor goes last because it is cheap and is the // capability that matters most when the request is already under pressure. const AUXILIARY_REMOVAL_ORDER = ['Agent', 'Advisor']; /** * Last-resort schema reduction. Normal requests keep the full catalog; this is * used only after history compaction still cannot fit the provider window. */ export function fitToolsForEmergency(input: { provider: Provider; history: readonly Message[]; tools: readonly Tool[]; transientContext?: string; multimodalTokens?: number; requiredNames?: ReadonlySet; }): EmergencyToolFit { let tools = [...input.tools]; let plan = buildContextBudgetPlan({ ...input, tools }); if (!plan.overBudget) return { tools, removedNames: [], plan }; const required = input.requiredNames ?? new Set(); const auxiliaryRank = new Map(AUXILIARY_REMOVAL_ORDER.map((name, index) => [name, index])); const candidates = tools .filter((tool) => !required.has(tool.name) && budgetClassForToolName(tool.name) === 'auxiliary') .sort((a, b) => { const rankA = auxiliaryRank.get(a.name); const rankB = auxiliaryRank.get(b.name); if (rankA !== undefined || rankB !== undefined) { return (rankA ?? Number.MAX_SAFE_INTEGER) - (rankB ?? Number.MAX_SAFE_INTEGER); } return estimateToolsTokens([b]) - estimateToolsTokens([a]); }); const removedNames: string[] = []; for (const candidate of candidates) { if (!plan.overBudget || tools.length <= 1) break; tools = tools.filter((tool) => tool.name !== candidate.name); removedNames.push(candidate.name); plan = buildContextBudgetPlan({ ...input, tools }); } return { tools, removedNames, plan }; }