import type { Tool, ToolCall } from '../../types.js'; import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js'; const READ_DEMAND = new Map([['Read', 240_000], ['WebFetch', 240_000], ['Snip', DEFAULT_MAX_RESULT_SIZE_CHARS]]); export const usesReadBudget = (name: string) => READ_DEMAND.has(name); /** Approximate character allowance, not a guarantee of token-window safety. * Request preparation must still check and compact the next model request. */ export function createReadBudget(remainingTokens: number) { let available = Math.max(0, Math.floor(remainingTokens * 0.5)); const perRead = Math.min(1_000_000, Math.max(1000, Math.floor(available / 2))); return (requested = Math.min(240_000, perRead)) => { const granted = Math.min(Math.max(0, requested), perRead, available); available -= granted; return granted; }; } /** * 先只给决策屏障之前的调用分配额度。Advisor 若明确暂缓, * 调度器再按实际可执行的只读后缀,重新分配本批尚未领取的额度。 */ const DEFERRAL_BARRIERS = new Set(['AskUserQuestion', 'Advisor']); /** Allocate once in model-call order, independent of asynchronous gate timing. * Smaller explicit requests release their share to the remaining callers. */ export function planReadBudgets( remainingTokens: number, calls: readonly ToolCall[], tools: readonly Tool[], ): Map { const demands = new Map(); for (const call of calls) { if (DEFERRAL_BARRIERS.has(call.function.name)) break; const defaultDemand = READ_DEMAND.get(call.function.name); if (defaultDemand === undefined) continue; const tool = tools.find((item) => item.name === call.function.name); if (!tool) continue; try { const result = tool.inputSchema.safeParse(JSON.parse(call.function.arguments)); if (!result.success) continue; const args = result.data as { max_chars?: number }; // 保留原始需求、不做 perRead 预截断:显式小额度释放出的份额必须能被 // 同批其他读取方吸收,最终授予量由下方 available 的均分循环决定。 demands.set(call, args.max_chars ?? defaultDemand); } catch { // Invalid calls are rejected by the normal tool boundary, not budgeted. } } let available = Math.max(0, Math.floor(remainingTokens * 0.5)); const result = new Map(); const entries = [...demands.entries()]; // If the minimum window cannot be shared, prioritize model-call order. const eligible = Math.min(entries.length, Math.floor(available / 1000)); for (const [call] of entries.slice(eligible)) result.set(call, 0); let pending = entries.slice(0, eligible); while (pending.length) { const share = Math.floor(available / pending.length); const satisfied = pending.filter(([, demand]) => demand <= share); if (satisfied.length) { for (const [call, demand] of satisfied) { result.set(call, demand); available -= demand; } pending = pending.filter(([, demand]) => demand > share); continue; } for (const [index, [call]] of pending.entries()) { result.set(call, share + (index < available % pending.length ? 1 : 0)); } break; } return result; }