import { countTextTokens } from './tokenCounter.js'; export type ContextFragmentKind = | 'runtime' | 'persona' | 'memory' | 'episode' | 'project' | 'skill' | 'plugin' | 'task' | 'diagnostic'; export type ContextAuthority = 'host' | 'constraint' | 'user-evidence' | 'untrusted-data'; export interface ContextFragment { id: string; kind: ContextFragmentKind; authority: ContextAuthority; priority: number; estimatedTokens: number; content: string; required?: boolean; clippable?: boolean; /** Whole evidence records: never detach a statement from its qualifications. */ recordList?: { header: string; entries: Array<{ id: string; text: string }> }; /** Constraints that must remain whole, even when this exceeds the soft budget. */ atomic?: boolean; } export interface ContextBudgetDiagnostics { budgetTokens: number; usedTokens: number; includedIds: string[]; omittedIds: string[]; clippedIds: string[]; } export interface ContextBundle { fragments: ContextFragment[]; text: string; diagnostics: ContextBudgetDiagnostics; } export const DEFAULT_TRANSIENT_BUDGET_TOKENS = 3_000; export function contextFragment( input: Omit & { estimatedTokens?: number }, ): ContextFragment { const content = input.content.trim(); return { ...input, content, estimatedTokens: input.estimatedTokens ?? countTextTokens(content), }; } const CLIP_MARKER = '\n[上下文片段因预算截断]'; /** * 按**渲染后**的 token 数收敛,而不是裸内容。 * * ⚠️ 曾经的实现拿裸内容 token 判预算、外层却用 `renderedTokens()`(JSON 转义 + 信封)验收, * 于是 `裸 token ≤ 预算 < 渲染 token` 这个窗口里 clip 会「认为放得下」原样返回,验收再不通过, * 片段就被整段丢进 `omittedIds` —— `clippable` 形同虚设(`clippedIds` 恒空)。 * 窗口宽度 = 转义膨胀量,所以 **Windows 上尤其致命**:技能目录里每个 `\` 都要转义成 `\\`, * 27 条技能的窗口从 POSIX 的 ~25 token 涨到 ~92 token,本仓库实测整份 `skills.catalog` * (2643 token)在还剩 1900+ token 预算时被整个扔掉,模型完全看不到任何 Skill。 * * 判据必须与验收同口径:这里直接对 `measure(候选内容)` 二分,measure 由调用方传入, * 保证「算的就是最终要花的」。 */ function clipToRenderedBudget( content: string, budgetTokens: number, measure: (candidate: string) => number, ): string { if (budgetTokens <= 0) return ''; if (measure(content) <= budgetTokens) return content; // Token counter is deliberately dependency-free. Binary search preserves its // exact mixed Chinese/ASCII estimate instead of falling back to chars/4. let low = 0; let high = content.length; while (low < high) { const mid = Math.ceil((low + high) / 2); const candidate = `${content.slice(0, mid).trimEnd()}${CLIP_MARKER}`; if (measure(candidate) <= budgetTokens) low = mid; else high = mid - 1; } if (low <= 0) return ''; return `${content.slice(0, low).trimEnd()}${CLIP_MARKER}`; } export function renderContextFragment(fragment: ContextFragment): string { const encoded = JSON.stringify(fragment.content) .replace(//g, '\\u003e') .replace(/&/g, '\\u0026'); return `\n${encoded}\n`; } function renderedTokens(fragment: ContextFragment): number { return countTextTokens(renderContextFragment(fragment)); } /** 片段之间的分隔符——记账时必须与最终 join 用的是同一个常量。 */ const FRAGMENT_SEPARATOR = '\n\n'; const SEPARATOR_TOKENS = countTextTokens(FRAGMENT_SEPARATOR); /** * Deterministic context budgeting. Required host facts are kept first; optional * fragments compete by priority, then original order. No LLM call is involved. */ export function assembleContextBundle( input: readonly ContextFragment[], budgetTokens = DEFAULT_TRANSIENT_BUDGET_TOKENS, ): ContextBundle { const fragments = input.filter((fragment) => fragment.content.length > 0); const indexed = fragments.map((fragment, index) => ({ fragment, index })); const ordered = indexed.sort((a, b) => Number(Boolean(b.fragment.required)) - Number(Boolean(a.fragment.required)) || b.fragment.priority - a.fragment.priority || a.index - b.index); const included: Array<{ fragment: ContextFragment; index: number }> = []; const omittedIds: string[] = []; const clippedIds: string[] = []; let remaining = Math.max(0, budgetTokens); for (const item of ordered) { const fragment = item.fragment; // 片段之间要用 SEPARATOR 拼接,那几个 token 也得记账,否则最终 text 会超出预算 // (usedTokens > budgetTokens 会让 loop.ts::transientFor 的余量判断失真)。 const separator = included.length > 0 ? SEPARATOR_TOKENS : 0; const budgetForItem = remaining - separator; const fullTokens = renderedTokens(fragment); if (fragment.atomic || fullTokens <= budgetForItem) { included.push(item); remaining -= fullTokens + separator; continue; } if ((fragment.required || fragment.clippable) && budgetForItem > 24) { // Measure the rendered envelope for both whole-record and prose clipping. let selectedRecords: ContextFragment['recordList']; const measure = (candidate: string) => renderedTokens({ ...fragment, content: candidate }); if (fragment.recordList) { const { header, entries } = fragment.recordList; const kept: typeof entries = []; for (const entry of entries) { const candidate = `${header}\n${[...kept, entry].map(record => record.text).join('\n')}${CLIP_MARKER}`; if (measure(candidate) <= budgetForItem) kept.push(entry); } selectedRecords = { header, entries: kept }; } const content = selectedRecords ? selectedRecords.entries.length ? `${selectedRecords.header}\n${selectedRecords.entries.map(record => record.text).join('\n')}${CLIP_MARKER}` : '' : clipToRenderedBudget( fragment.content, budgetForItem, measure, ); const clipped = contextFragment({ ...fragment, content, ...(selectedRecords ? { recordList: selectedRecords } : {}), }); const clippedTokens = renderedTokens(clipped); if (clipped.content && clippedTokens <= budgetForItem) { included.push({ fragment: clipped, index: item.index }); if (clipped.content !== fragment.content) clippedIds.push(fragment.id); remaining -= clippedTokens + separator; continue; } } omittedIds.push(fragment.id); } // Rendering follows semantic input order, not selection priority. included.sort((a, b) => a.index - b.index); const selected = included.map((item) => item.fragment); const text = selected.map(renderContextFragment).join(FRAGMENT_SEPARATOR); const usedTokens = countTextTokens(text); return { fragments: selected, text, diagnostics: { budgetTokens, usedTokens, includedIds: selected.map((fragment) => fragment.id), omittedIds, clippedIds, }, }; } export function resizeContextBundle(bundle: ContextBundle, budgetTokens: number): ContextBundle { return assembleContextBundle(bundle.fragments, budgetTokens); }