Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): preserve attachment read budgets across approval and failover
Alfredo Lopez46bc25b0f5b3
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 679ca3bdb..05c8310a0 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.483",+ "version": "0.1.484","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.483",+ "version": "0.1.484","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 01f45cfd7..ea930d873 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.483",+ "version": "0.1.484","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/agent/__tests__/approval.test.ts b/mcp-host/src/agent/__tests__/approval.test.tsindex 41a202248..a21e734bc 100644--- a/mcp-host/src/agent/__tests__/approval.test.ts+++ b/mcp-host/src/agent/__tests__/approval.test.ts@@ -13,6 +13,7 @@ import { AgentStateMachine } from '../stateMachine'vi.mock('../../config', () => ({config: {devMode: true,+ contextMaxTokens: 100_000,enableApproval: true,enableNudge: false,nudgeMaxIterations: 3,diff --git a/mcp-host/src/agent/__tests__/attachmentContextWindow.test.ts b/mcp-host/src/agent/__tests__/attachmentContextWindow.test.tsnew file mode 100644index 000000000..0323bb45c--- /dev/null+++ b/mcp-host/src/agent/__tests__/attachmentContextWindow.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it, vi } from 'vitest'+import { attachmentContextWindow } from '../attachmentContextWindow'++describe('attachment budget across provider failover', () => {+ it('uses the exact fallback model catalog window, including a smaller non-default model', () => {+ const catalog = vi.fn((provider: string, model: string) => {+ if (provider === 'claude' && model === 'public-small-model') return 32_000+ if (provider === 'deepseek' && model === 'public-large-model') return 256_000+ return undefined+ })+ expect(+ attachmentContextWindow(+ 128_000,+ 'openai',+ [+ { provider: 'deepseek', model: 'public-large-model' },+ { provider: 'claude', model: 'public-small-model' },+ ],+ catalog,+ 100_000+ )+ ).toBe(32_000)+ expect(catalog).toHaveBeenCalledWith('claude', 'public-small-model')+ })++ it('keeps the session model window for same-provider credential failover', () => {+ const catalog = vi.fn(() => 1)+ expect(+ attachmentContextWindow(+ 128_000,+ 'openai',+ [{ provider: 'openai', model: 'inert-other-model', credentialSlot: 'other-slot' }],+ catalog,+ 100_000+ )+ ).toBe(128_000)+ expect(catalog).not.toHaveBeenCalled()+ })++ it('never widens the primary window and resolves missing metadata by the existing policy', () => {+ expect(+ attachmentContextWindow(+ 8_000,+ 'openai',+ [{ provider: 'claude', model: 'public-model' }],+ undefined,+ 100_000+ )+ ).toBe(8_000)+ expect(+ attachmentContextWindow(+ 128_000,+ 'openai',+ [{ provider: 'claude', model: 'public-model' }],+ undefined,+ 100_000+ )+ ).toBe(100_000)+ })++ it('rejects unusable catalog windows rather than enlarging or ignoring the bound', () => {+ for (const value of [0, -1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1]) {+ expect(() =>+ attachmentContextWindow(+ 128_000,+ 'openai',+ [{ provider: 'claude', model: 'public-model' }],+ () => value,+ 100_000+ )+ ).toThrow('positive safe integer')+ }+ })+})diff --git a/mcp-host/src/agent/__tests__/attachmentRead.failover.test.ts b/mcp-host/src/agent/__tests__/attachmentRead.failover.test.tsnew file mode 100644index 000000000..a9824ce0e--- /dev/null+++ b/mcp-host/src/agent/__tests__/attachmentRead.failover.test.ts@@ -0,0 +1,181 @@+import { afterEach, expect, it, vi } from 'vitest'+import { createHash } from 'node:crypto'+import { config as appConfig } from '../../config'+import { ConversationManager } from '../../core/conversation/conversation'+import { LlmError, LlmErrorCode } from '../../core/errors'+import { toolMessageBudgetTokens } from '../../core/extensions/contextManager'+import { SimpleEventEmitter } from '../../core/orchestration/eventEmitter'+import type { TokenCounter } from '../../core/tokenizer/tokenCounter'+import { type ChatMessage, FinishReason } from '../../core/types'+import { TaskLifecycle } from '../../lifecycle/taskLifecycle'+import { FailoverEngine } from '../../llm/failover/engine'+import type { LlmPolicy } from '../../llm/failover/types'+import type { SingleTurnProvider } from '../../llm/types'+import { McpManager } from '../../mcp/manager'+import type { Task } from '../../queue/types'+import { validateIncomingAttachments } from '../incomingAttachments'+import { TaskExecutor } from '../taskExecutor'++const saved = {+ enableApproval: appConfig.enableApproval,+ dynamicToolsEnabled: appConfig.dynamicToolsEnabled,+ tokenizerDryrun: appConfig.tokenizerDryrun,+}+afterEach(() => Object.assign(appConfig, saved))++it.each([true, false])(+ 'bounds the page for a smaller fallback tokenizer (fail before page: %s)',+ async failBeforePage => {+ Object.assign(appConfig, {+ enableApproval: false,+ dynamicToolsEnabled: false,+ tokenizerDryrun: true,+ })+ const bytes = Buffer.from('A'.repeat(65_535))+ const admitted = validateIncomingAttachments(+ [+ {+ id: 'file-1',+ kind: 'file',+ filename: 'public-dense.txt',+ mimeType: 'text/plain',+ detectedMediaType: 'text/plain',+ encoding: 'base64',+ sizeBytes: bytes.length,+ dataBase64: bytes.toString('base64'),+ digest: { algorithm: 'sha256', hex: createHash('sha256').update(bytes).digest('hex') },+ },+ ],+ { maxCount: 20, maxBytes: 1_000_000, maxFileBytes: 11_534_336, messageId: 'window-message' }+ )+ if (!admitted.ok) throw new Error('Invalid public file fixture')+ const usage = { input_tokens: 1, output_tokens: 1, total_tokens: 2 }+ const received: ChatMessage[][] = []+ let primaryCalls = 0+ const readResponse = () => ({+ content: null,+ usage,+ finish_reason: FinishReason.ToolUse,+ tool_calls: [+ {+ id: 'window-read',+ name: 'clerum__attachment_read',+ arguments: { attachmentId: 'file-1' },+ },+ ],+ })+ const unexpected = () => {+ throw new Error('Unexpected completion')+ }+ const primary: SingleTurnProvider = {+ getProviderType: () => 'openai',+ classifyError: unexpected,+ completeSingleTurn: unexpected,+ completeSingleTurnWithTools: vi.fn(async () => {+ primaryCalls += 1+ if (!failBeforePage && primaryCalls === 1) return readResponse()+ throw new LlmError('Public quota fixture', 'openai', LlmErrorCode.InsufficientQuota, false)+ }),+ }+ const fallback: SingleTurnProvider = {+ getProviderType: () => 'claude',+ classifyError: unexpected,+ completeSingleTurn: unexpected,+ completeSingleTurnWithTools: async messages => {+ received.push(structuredClone(messages))+ if (failBeforePage && received.length === 1) return readResponse()+ return {+ content: 'Page received',+ tool_calls: null,+ usage,+ finish_reason: FinishReason.Stop,+ }+ },+ }+ const fallbackCounter: TokenCounter = {+ providerName: 'claude',+ modelName: 'public-small-model',+ warmup: vi.fn(async () => {}),+ countSync: messages =>+ Math.ceil(messages.reduce((n, m) => n + (m.content?.length ?? 0), 0) / 2) + 6,+ count: vi.fn(async () => {+ throw new Error('Network counting is forbidden in page measurement')+ }),+ recordObservedUsage: () => {},+ lastObservedInputTokens: () => null,+ }+ Object.assign(fallback, { createTokenCounter: () => fallbackCounter })+ const policy: LlmPolicy = {+ cooldownSeconds: 300,+ triggerOn: ['insufficient_quota'],+ fallbacks: [{ provider: 'claude', model: 'public-small-model' }],+ }+ const catalog = vi.fn((provider: string, model: string) =>+ provider === 'claude' && model === 'public-small-model' ? 32_000 : undefined+ )+ const task: Task = {+ id: 'public-window-task',+ source: 'channel',+ status: 'pending',+ priority: 'normal',+ createdAt: new Date(),+ responseCallback: vi.fn(async () => {}),+ sourceMessage: {+ sender: 'authenticated-user',+ content: 'Read the file',+ channelType: 'rpc',+ channelId: 'isolated-channel',+ messageId: 'window-message',+ hostRef: 'fixture-host',+ timestamp: new Date().toISOString(),+ attachments: admitted.attachments,+ },+ conversationHistory: [{ role: 'user', content: 'Read the file', timestamp: new Date() }],+ }+ const lifecycle = new TaskLifecycle()+ lifecycle.register(task)+ const onFail = vi.fn()+ const executor = new TaskExecutor(task, {+ conversationManager: new ConversationManager(),+ llmProvider: primary,+ modelName: 'public-primary-model',+ contextWindowTokens: 128_000,+ mcpManager: new McpManager(),+ workspaceService: undefined,+ approvalConfig: undefined,+ config: {+ maxTaskDuration: 300_000,+ maxToolCallsPerTask: 10,+ autoStart: true,+ taskDelay: 0,+ approvalTimeout: 300_000,+ },+ coreEvents: new SimpleEventEmitter(),+ cronScheduler: null,+ taskLifecycle: lifecycle,+ onApprovalNeeded: vi.fn(),+ onComplete: vi.fn(),+ onFail,+ failover: {+ engine: new FailoverEngine(policy),+ policy,+ buildProvider: () => fallback,+ contextWindowForPair: catalog,+ },+ })+ await executor.run()+ expect(onFail).not.toHaveBeenCalled()+ expect(executor.executorState).toBe('completed')+ expect(primary.completeSingleTurnWithTools).toHaveBeenCalledTimes(failBeforePage ? 1 : 2)+ expect(received).toHaveLength(failBeforePage ? 2 : 1)+ const page = received+ .at(-1)!+ .find(message => message.role === 'tool' && message.tool_call_id === 'window-read')+ expect(page?.content).toContain('"kind":"text"')+ expect(page?.content).toContain('"truncated":true')+ expect(toolMessageBudgetTokens(page!, undefined, true)).toBeLessThanOrEqual(3_200)+ expect(fallbackCounter.countSync([page!])).toBeLessThanOrEqual(3_200)+ expect(fallbackCounter.count).not.toHaveBeenCalled()+ expect(catalog).toHaveBeenCalledWith('claude', 'public-small-model')+ }+)diff --git a/mcp-host/src/agent/__tests__/attachmentRead.integration.test.ts b/mcp-host/src/agent/__tests__/attachmentRead.integration.test.tsindex 1fc336c04..a2b05f2d3 100644--- a/mcp-host/src/agent/__tests__/attachmentRead.integration.test.ts+++ b/mcp-host/src/agent/__tests__/attachmentRead.integration.test.ts@@ -48,13 +48,21 @@ function lastUserText(messages: ChatMessage[]): string {return user.content ?? ''}-async function runTask(filename: string, mimeType: string, bytes: Buffer) {+async function runTask(+ filename: string,+ mimeType: string,+ bytes: Buffer,+ options: { contextWindowTokens?: number } = {}+) {const attachment = admittedFile(filename, mimeType, bytes)- return { ...(await runTaskWith(attachment)), attachment }+ return { ...(await runTaskWith(attachment, options)), attachment }}/** Without an attachment the double answers directly; with one it reads it first. */-async function runTaskWith(attachment: ReturnType<typeof admittedFile> | undefined) {+async function runTaskWith(+ attachment: ReturnType<typeof admittedFile> | undefined,+ options: { contextWindowTokens?: number } = {}+) {const call: ToolCall = {id: 'read-1',name: 'clerum__attachment_read',@@ -117,6 +125,9 @@ async function runTaskWith(attachment: ReturnType<typeof admittedFile> | undefinmcpManager: new McpManager(),workspaceService: undefined,modelName: 'test-model',+ ...(options.contextWindowTokens !== undefined+ ? { contextWindowTokens: options.contextWindowTokens }+ : {}),approvalConfig: undefined,config: {maxTaskDuration: 300000,@@ -138,6 +149,14 @@ async function runTaskWith(attachment: ReturnType<typeof admittedFile> | undefinreturn { attachment, call, deps, executor, providerCalls, task }}+/** The tool message content is the `<tool_output>` wrapper around the page JSON. */+function toolPayload(content: string): Record<string, unknown> {+ const bodyStart = content.indexOf('\n')+ const bodyEnd = content.lastIndexOf('\n</tool_output>')+ if (bodyStart < 0 || bodyEnd < 0) throw new Error('tool message is not wrapped')+ return JSON.parse(content.slice(bodyStart + 1, bodyEnd)) as Record<string, unknown>+}+describe('clerum__attachment_read through a complete task (#666)', () => {const saved = {enableApproval: appConfig.enableApproval,@@ -189,6 +208,43 @@ describe('clerum__attachment_read through a complete task (#666)', () => {expect(deps.onComplete).toHaveBeenCalledTimes(1)})+ it('bounds the emitted page with the explicit turn window and debits the shared ledger', async () => {+ Object.assign(appConfig, {+ enableApproval: false,+ dynamicToolsEnabled: false,+ promptCacheEnabled: true,+ })+ // window 25_000 → page 2_500 / turn 7_500 with the notice reserve covered,+ // so the page binds (limit=page_budget) and a 65 KiB dense file cannot be+ // emitted whole; under the default 100k window it would arrive complete.+ const fileBytes = 65_535+ const { call, deps, executor, providerCalls } = await runTask(+ 'dense.txt',+ 'text/plain',+ Buffer.from('A'.repeat(fileBytes)),+ { contextWindowTokens: 25_000 }+ )++ expect(deps.onFail).not.toHaveBeenCalled()+ expect(executor.executorState).toBe('completed')+ expect(providerCalls).toHaveLength(2)+ const result = providerCalls[1]!.messages.find(+ message => message.role === 'tool' && message.tool_call_id === call.id+ )+ expect(result?.content).toBeTruthy()+ const payload = toolPayload(result!.content)+ expect(payload.kind).toBe('text')+ expect(payload.truncated).toBe(true)+ expect(payload.limit).toBe('page_budget')+ const byteRange = payload.byteRange as { offset: number; length: number }+ expect(byteRange.offset).toBe(0)+ expect(byteRange.length).toBeGreaterThan(0)+ expect(byteRange.length).toBeLessThan(fileBytes)+ expect(typeof payload.nextOffset).toBe('number')+ expect(payload.nextOffset as number).toBeGreaterThan(0)+ expect(deps.onComplete).toHaveBeenCalledTimes(1)+ })+it('returns a binary result for a PDF, and the model never sees its bytes', async () => {Object.assign(appConfig, {enableApproval: false,diff --git a/mcp-host/src/agent/__tests__/coreEventBridge.test.ts b/mcp-host/src/agent/__tests__/coreEventBridge.test.tsindex 56e2e1bcc..686c371ac 100644--- a/mcp-host/src/agent/__tests__/coreEventBridge.test.ts+++ b/mcp-host/src/agent/__tests__/coreEventBridge.test.ts@@ -22,6 +22,7 @@ import { AgentStateMachine } from '../stateMachine'vi.mock('../../config', () => ({config: {devMode: true,+ contextMaxTokens: 100_000,enableApproval: true,enableNudge: false,nudgeMaxIterations: 3,diff --git a/mcp-host/src/agent/__tests__/cronApproval.test.ts b/mcp-host/src/agent/__tests__/cronApproval.test.tsindex 902eb2c32..ba1aeef96 100644--- a/mcp-host/src/agent/__tests__/cronApproval.test.ts+++ b/mcp-host/src/agent/__tests__/cronApproval.test.ts@@ -21,6 +21,7 @@ import { AgentStateMachine } from '../stateMachine'vi.mock('../../config', () => ({config: {devMode: true,+ contextMaxTokens: 100_000,enableApproval: true,enableNudge: false,nudgeMaxIterations: 3,diff --git a/mcp-host/src/agent/__tests__/singlePathAgent.test.ts b/mcp-host/src/agent/__tests__/singlePathAgent.test.tsindex 9cf3c7c71..4ce009459 100644--- a/mcp-host/src/agent/__tests__/singlePathAgent.test.ts+++ b/mcp-host/src/agent/__tests__/singlePathAgent.test.ts@@ -15,6 +15,7 @@ import { AgentStateMachine } from '../stateMachine'vi.mock('../../config', () => ({config: {devMode: true,+ contextMaxTokens: 100_000,enableApproval: true,enableNudge: false,nudgeMaxIterations: 3,diff --git a/mcp-host/src/agent/__tests__/statelessCronManageGate.wiring.test.ts b/mcp-host/src/agent/__tests__/statelessCronManageGate.wiring.test.tsindex 5acbc6105..f0569e1c1 100644--- a/mcp-host/src/agent/__tests__/statelessCronManageGate.wiring.test.ts+++ b/mcp-host/src/agent/__tests__/statelessCronManageGate.wiring.test.ts@@ -26,6 +26,7 @@ import { AgentStateMachine } from '../stateMachine'vi.mock('../../config', () => ({config: {devMode: true,+ contextMaxTokens: 100_000,enableApproval: true,// The lever under test: stateless lifecycle arms the cron×stateless gate.statelessLifecycle: true,diff --git a/mcp-host/src/agent/attachmentContextWindow.ts b/mcp-host/src/agent/attachmentContextWindow.tsnew file mode 100644index 000000000..3b79dd8c0--- /dev/null+++ b/mcp-host/src/agent/attachmentContextWindow.ts@@ -0,0 +1,32 @@+import type { FallbackEntry } from '../llm/failover/types'+import { resolveContextWindow } from '../llm/registryCore'++/** Budget pages for every model the same task can actually be sent to. */+export function attachmentContextWindow(+ primaryWindow: number,+ primaryProvider: string,+ fallbacks: readonly FallbackEntry[],+ catalogWindow: ((provider: string, model: string) => number | undefined) | undefined,+ envDefault: number+): number {+ assertWindow(primaryWindow)+ let minimum = primaryWindow+ for (const entry of fallbacks) {+ // R5.7 serves the session model for another key of the same provider.+ if (entry.provider === primaryProvider) continue+ const { contextWindowTokens } = resolveContextWindow(+ entry.provider,+ catalogWindow?.(entry.provider, entry.model),+ envDefault+ )+ assertWindow(contextWindowTokens)+ minimum = Math.min(minimum, contextWindowTokens)+ }+ return minimum+}++function assertWindow(value: number): void {+ if (!Number.isSafeInteger(value) || value <= 0) {+ throw new Error('Attachment context window must be a positive safe integer')+ }+}diff --git a/mcp-host/src/agent/taskExecutionBudget.ts b/mcp-host/src/agent/taskExecutionBudget.tsindex d9a2f40a2..c51055479 100644--- a/mcp-host/src/agent/taskExecutionBudget.ts+++ b/mcp-host/src/agent/taskExecutionBudget.ts@@ -1,3 +1,4 @@+import { readAttachmentReadLedgerSnapshot } from '../core/attachments/attachmentReadBudget'import type { TaskExecutionBudgetSnapshot } from '../core/types'import { VISUAL_INPUT_LIMITS, VisualInputBudget } from '../visualInput/policy'@@ -31,6 +32,11 @@ export function parseTaskExecutionBudget(value: unknown): TaskExecutionBudgetSna) {throw new Error('Invalid task execution budget')}+ // C15/C16 — this JSON column also carries the turn's attachment read ledger.+ // The whitelist rebuild below would drop it, and the cold path has no other+ // carrier, so an invalid value is dropped here and the restore boundary+ // fails closed instead of guessing spend.+ const attachmentReadLedger = readAttachmentReadLedgerSnapshot(snapshot.attachmentReadLedger)return {elapsedActiveMs: snapshot.elapsedActiveMs,iterationsUsed: snapshot.iterationsUsed,@@ -39,6 +45,7 @@ export function parseTaskExecutionBudget(value: unknown): TaskExecutionBudgetSna...(snapshot.visualReadBytes !== undefined? { visualReadBytes: snapshot.visualReadBytes }: {}),+ ...(attachmentReadLedger ? { attachmentReadLedger } : {}),}}diff --git a/mcp-host/src/agent/taskExecutor.ts b/mcp-host/src/agent/taskExecutor.tsindex 287b5db96..682436850 100644--- a/mcp-host/src/agent/taskExecutor.ts+++ b/mcp-host/src/agent/taskExecutor.ts@@ -14,6 +14,11 @@ import { maybeWrapFailover } from '../core/adapters/failoverLlmPort'import { maybeWrapHookedLlmPort } from '../core/adapters/hookedLlmPort'import { AdapterStaticContext, LlmPortAdapter } from '../core/adapters/llmPortAdapter'import { CompositeToolRegistry, McpToolRegistryAdapter } from '../core/adapters/toolRegistryAdapter'+import {+ AttachmentReadLedger,+ mergeAttachmentReadLedgerSnapshots,+ readAttachmentReadLedgerSnapshot,+} from '../core/attachments/attachmentReadBudget'import { compactConversation } from '../core/conversation/compaction'import { ConversationManager } from '../core/conversation/conversation'import { deriveAutoTitle } from '../core/conversation/sessionTitle'@@ -24,6 +29,7 @@ import {COMPACTION_PRESSURE_THRESHOLD,PressureContextManager,tierDecisionTokens,+ toolMessageBudgetTokens,} from '../core/extensions/contextManager'import {UnifiedApprovalGateController,@@ -113,6 +119,7 @@ import { resolveCronTaskSessionKey, serializeSessionKey } from '../session'import { GovernedRunReporter, UsageReporter } from '../usage/usageReporter.js'import { resolveProviderWorkflowCallerContext } from '../workflow/providerWorkflowCallerContextClient'import type { Workspace } from '../workspace/service'+import { attachmentContextWindow } from './attachmentContextWindow'import type { CronScheduler } from './cronScheduler'import { referencedFilesForTurnContext } from './fileReferenceResolver'import {@@ -288,6 +295,14 @@ export class TaskExecutor {private tokenCounter: TokenCounter | null = null/** #731 — the task's context window, resolved and logged once. */private contextWindow: number | null = null+ /**+ * C15/C16 — one turn-owned attachment read ledger per executor. The native+ * tool registry is memoized for the life of this executor, so the tool holds+ * THIS instance by reference and the ledger mutates in place: `reset()` only+ * after a successful `startTurn`, `restore()` on an approval resume that+ * continues the same turn.+ */+ private readonly attachmentReadLedger = new AttachmentReadLedger()/*** P2 token budgets (§5.2) — snapshot of the conversation's lifetime token* counters captured at task start, used as the per-task brake baseline.@@ -483,6 +498,10 @@ export class TaskExecutor {this.task.traceContext ?? null,autoTitle)+ // C15/C16 — a fresh turn starts with a zeroed attachment read ledger. The+ // reset runs only after `startTurn` resolved: a rejected write throws+ // above and must not hand the retried turn a fresh budget.+ this.attachmentReadLedger.reset()this.turnTiming?.addSessionLoadMs(Date.now() - sessionLoadStart)// P2 token budgets (§5.2) — capture the per-task brake baseline NOW, before@@ -693,6 +712,9 @@ export class TaskExecutor {() => this.buildLoopConfig({ skipContextManager: true }),this.abortController.signal)+ // Resume continues the same turn. Restore its independent budget before+ // executing the suspended tool; never derive spend from compacted text.+ this.restoreAttachmentReadLedger(approval)const suspendedCall = {id: approval.tool_call_id,name: approval.tool_name,@@ -1024,6 +1046,29 @@ export class TaskExecutor {return contextWindowTokens}+ /**+ * C15/C16 — restore the turn ledger from the approval's own snapshot. The+ * persisted value is authoritative and independent of message history, so+ * compaction and earlier turns cannot change it. A missing or invalid+ * snapshot fails closed: compacted history cannot prove that nothing was+ * spent. New approvals always carry even the valid zero snapshot.+ */+ private restoreAttachmentReadLedger(approval: PendingApproval): void {+ const persisted = readAttachmentReadLedgerSnapshot(approval.task_budget?.attachmentReadLedger)+ if (persisted) {+ // Warm resume must never decrease what the live turn already recorded.+ this.attachmentReadLedger.restore(+ mergeAttachmentReadLedgerSnapshots(this.attachmentReadLedger.snapshot(), persisted)+ )+ return+ }+ logger.warn(+ { component: 'TaskExecutor', taskId: this.taskId, reason: 'attachment_read_ledger_missing' },+ 'Approval has no usable attachment ledger; failing closed for the rest of the turn'+ )+ this.attachmentReadLedger.exhaust(this.contextMaxTokens())+ }+/*** #731 — the attempt contract's `maxMessages` for the provider, or* `undefined` when it has none. An unregistered provider type has no@@ -1234,7 +1279,15 @@ export class TaskExecutor {}case 'need_approval': {- result.approval.task_budget = this.executionBudget.pause()+ // C15/C16 — every pause (first, legacy re-pause, connect re-pause)+ // funnels through here, so the turn's attachment read ledger is stamped+ // inside the existing `task_budget` JSON column. Compaction cannot+ // lose it; no new column or migration is needed.+ const attachmentReadLedger = this.attachmentReadLedger.snapshot()+ result.approval.task_budget = {+ ...this.executionBudget.pause(),+ attachmentReadLedger,+ }// #666 R4-M2 — persist the sanitized source message so a cold restart// rebuilds the file-reference pins and attachment metadata. The inline// bytes (dataBase64) never persist.@@ -1473,6 +1526,15 @@ export class TaskExecutor {}const { registry, loopController, bridge } = await this.buildToolRegistry()+ const applicableToolCounters = registry+ .listDefinitions()+ .some(tool => tool.name === 'clerum__attachment_read')+ ? (effectiveLlmPort.getToolTokenCounters?.() ?? [tokenCounter])+ : [tokenCounter]+ const toolCounters = [...new Set(applicableToolCounters)]+ await Promise.all(+ toolCounters.filter(counter => counter !== tokenCounter).map(counter => counter.warmup())+ )// T2.2 — when the prompt-cache flag is ON and we have the dependencies// wired (PromptCache + WorkspaceService), build the tiered@@ -1591,6 +1653,14 @@ export class TaskExecutor {// oversized outputs and stamp `spillover_ref` on the result.loopConfig.spilloverStorage = this.deps.spilloverStorageloopConfig.taskId = this.taskId+ // C15/C16 — the exact synchronous measurement the bounded native readers+ // use for a result: the full tool message (framing + the larger applicable+ // provider/BPE estimate), never a content-only shortcut.+ // Page limits are enforced even when compaction is in tokenizer dry-run.+ // Use the largest applicable synchronous estimate for every destination;+ // emitted pages can survive a provider change in a later reasoning round.+ loopConfig.measureToolMessage = message =>+ Math.max(...toolCounters.map(counter => toolMessageBudgetTokens(message, counter, false)))// F3 (dynamic-tool-loading): context the `clerum__tool_call` bridge intercept// needs in `executeToolCalls`. Undefined when no McpManager is wired.loopConfig.bridge = bridge@@ -2064,6 +2134,15 @@ export class TaskExecutor {{maxBytes: appConfig.attachmentMaxBytes,secretEntriesProvider: this.deps.secretEntriesProvider,+ // Keep the ledger and bound pages for every model this task may serve.+ ledger: this.attachmentReadLedger,+ contextWindowTokens: attachmentContextWindow(+ this.contextMaxTokens(),+ this.deps.llmProvider.getProviderType(),+ this.deps.failover?.policy.fallbacks ?? [],+ this.deps.failover?.contextWindowForPair,+ appConfig.contextMaxTokens+ ),},this.deps.spilloverStorage,this.deps.sessionSearchService,diff --git a/mcp-host/src/agent/types.ts b/mcp-host/src/agent/types.tsindex a22d7f4c6..81a6657f0 100644--- a/mcp-host/src/agent/types.ts+++ b/mcp-host/src/agent/types.ts@@ -30,6 +30,8 @@ export interface ExecutorFailoverSupport {* all name the same pair.*/buildProvider: (entry: FallbackEntry) => SingleTurnProvider | null+ /** Same per-model catalog used by the primary resolver; no provider construction. */+ contextWindowForPair?: (provider: string, model: string) => number | undefined}/** Returns the current {@link ExecutorFailoverSupport}, or null when no policy. */diff --git a/mcp-host/src/core/adapters/failoverLlmPort.ts b/mcp-host/src/core/adapters/failoverLlmPort.tsindex 7c219b57f..23904260b 100644--- a/mcp-host/src/core/adapters/failoverLlmPort.ts+++ b/mcp-host/src/core/adapters/failoverLlmPort.ts@@ -91,6 +91,24 @@ class FailoverLlmPort implements LlmPort {return counter}+ getToolTokenCounters(): readonly TokenCounter[] {+ const counters = [this.getTokenCounter()]+ // File pages remain in the request when a later round changes provider.+ // Construct each configured adapter once so measurement uses its actual+ // model counter, without making a completion or countTokens request.+ for (const [index, entry] of this.o.policy.fallbacks.entries()) {+ const port = this.portFor({+ kind: 'fallback',+ index,+ provider: entry.provider,+ model: entry.model,+ })+ const counter = port?.getTokenCounter?.()+ if (counter) counters.push(counter)+ }+ return counters+ }+complete(request: CompletionRequest): Promise<CompletionResponse> {return this.run(port => port.complete(request), request.signal)}diff --git a/mcp-host/src/core/attachments/__tests__/attachmentReadBudget.test.ts b/mcp-host/src/core/attachments/__tests__/attachmentReadBudget.test.tsnew file mode 100644index 000000000..a7f9e00b4--- /dev/null+++ b/mcp-host/src/core/attachments/__tests__/attachmentReadBudget.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from 'vitest'+import {+ AttachmentReadLedger,+ attachmentReadBudgets,+ mergeAttachmentReadLedgerSnapshots,+ readAttachmentReadLedgerSnapshot,+} from '../attachmentReadBudget'++const zero = { reads: 0, spentTokens: 0, bytesRead: 0 }++describe('attachment turn ledger', () => {+ it('derives the 10% page and 30% turn limits', () => {+ expect(attachmentReadBudgets(10_000)).toEqual({ pageTokens: 1_000, turnTokens: 3_000 })+ for (const value of [0, -1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1]) {+ expect(() => attachmentReadBudgets(value)).toThrow()+ }+ })+ it('limits calls to 32 and reserves complete-message notices', () => {+ const ledger = new AttachmentReadLedger()+ expect(ledger.pageAllowance(10_000, 80)).toBe(360)+ for (let i = 0; i < 32; i++) expect(ledger.beginRead()).toBe(true)+ expect(ledger.beginRead()).toBe(false)+ expect(ledger.snapshot().reads).toBe(32)+ expect(ledger.pageAllowance(10_000, 80)).toBe(1_000)+ })+ it('charges successful emissions and refuses an over-budget debit without mutation', () => {+ const ledger = new AttachmentReadLedger()+ expect(() => ledger.debit(10_000, 1_001, 1)).toThrow()+ expect(ledger.snapshot()).toEqual(zero)+ for (let i = 0; i < 3; i++) ledger.debit(10_000, 1_000, 10)+ expect(() => ledger.debit(10_000, 1, 1)).toThrow()+ expect(ledger.snapshot()).toEqual({ reads: 0, spentTokens: 3_000, bytesRead: 30 })+ })+ it('retains actual spend above a smaller window when that window widens', () => {+ const ledger = new AttachmentReadLedger()+ ledger.restore({ reads: 5, spentTokens: 10_000, bytesRead: 40_000 })+ expect(ledger.canEmit(10_000, 1)).toBe(false)+ expect(ledger.canEmit(100_000, 1)).toBe(true)+ expect(ledger.snapshot().spentTokens).toBe(10_000)+ })+ it('exhaustion never lowers existing spend or byte count', () => {+ const ledger = new AttachmentReadLedger()+ ledger.restore({ reads: 5, spentTokens: 10_000, bytesRead: 40_000 })+ ledger.exhaust(10_000)+ expect(ledger.snapshot()).toEqual({ reads: 32, spentTokens: 10_000, bytesRead: 40_000 })+ expect(ledger.beginRead()).toBe(false)+ })+ it('rejects byte-count overflow before debiting tokens', () => {+ const ledger = new AttachmentReadLedger()+ const previous = { reads: 1, spentTokens: 10, bytesRead: Number.MAX_SAFE_INTEGER }+ ledger.restore(previous)+ expect(() => ledger.debit(10_000, 100, 1)).toThrow()+ expect(ledger.snapshot()).toEqual(previous)+ })+ it('rejects a missing counter instead of restoring undefined or zero', () => {+ const ledger = new AttachmentReadLedger()+ expect(() => ledger.restore({ reads: 1, spentTokens: 10 } as never)).toThrow()+ expect(ledger.snapshot()).toEqual(zero)+ })+ it('merges warm snapshots without reducing any spent counter', () => {+ expect(+ mergeAttachmentReadLedgerSnapshots(+ { reads: 12, spentTokens: 4_000, bytesRead: 30_000 },+ { reads: 2, spentTokens: 5_000, bytesRead: 1_000 }+ )+ ).toEqual({ reads: 12, spentTokens: 5_000, bytesRead: 30_000 })+ })+ it('reads persisted zero and over-window counts without clamping', () => {+ expect(readAttachmentReadLedgerSnapshot(zero)).toEqual(zero)+ expect(+ readAttachmentReadLedgerSnapshot({ reads: 32, spentTokens: 1_000_000, bytesRead: 99 })+ ).toEqual({ reads: 32, spentTokens: 1_000_000, bytesRead: 99 })+ for (const value of [+ undefined,+ null,+ {},+ [],+ { reads: 1 },+ { ...zero, reads: 33 },+ { ...zero, spentTokens: -1 },+ { ...zero, bytesRead: 1.5 },+ { ...zero, spentTokens: Number.MAX_SAFE_INTEGER + 1 },+ ]) {+ expect(readAttachmentReadLedgerSnapshot(value)).toBeNull()+ }+ })+})diff --git a/mcp-host/src/core/attachments/attachmentReadBudget.ts b/mcp-host/src/core/attachments/attachmentReadBudget.tsindex ab8216ea0..23d8d136b 100644--- a/mcp-host/src/core/attachments/attachmentReadBudget.ts+++ b/mcp-host/src/core/attachments/attachmentReadBudget.ts@@ -20,6 +20,45 @@ function boundedCount(value: number): boolean {return Number.isSafeInteger(value) && value >= 0}+/**+ * Strict reader for a persisted ledger snapshot. Returns null (never a guess,+ * never a partial value) unless every field is a safe non-negative integer and+ * the read count is within the hard cap. The spend is deliberately NOT clamped+ * to a window: a ledger that spent above the current envelope must stay+ * above it, so widening the window later cannot restore spent allowance.+ */+export function readAttachmentReadLedgerSnapshot(+ value: unknown+): AttachmentReadLedgerSnapshot | null {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return null+ const record = value as Record<string, unknown>+ const { reads, spentTokens, bytesRead } = record+ if (!boundedCount(reads as number) || !boundedCount(spentTokens as number)) return null+ if (!boundedCount(bytesRead as number)) return null+ if ((reads as number) > MAX_ATTACHMENT_READS_PER_TURN) return null+ return {+ reads: reads as number,+ spentTokens: spentTokens as number,+ bytesRead: bytesRead as number,+ }+}++/**+ * Monotone per-field maximum. The warm resume path merges the persisted+ * snapshot into the live ledger with this, so a stale or replayed approval can+ * never decrease reads or spend the running turn already recorded.+ */+export function mergeAttachmentReadLedgerSnapshots(+ live: AttachmentReadLedgerSnapshot,+ persisted: AttachmentReadLedgerSnapshot+): AttachmentReadLedgerSnapshot {+ return {+ reads: Math.max(live.reads, persisted.reads),+ spentTokens: Math.max(live.spentTokens, persisted.spentTokens),+ bytesRead: Math.max(live.bytesRead, persisted.bytesRead),+ }+}+/** Owned by one turn; registry memoization does not determine its lifetime. */export class AttachmentReadLedger {private state: AttachmentReadLedgerSnapshot = { reads: 0, spentTokens: 0, bytesRead: 0 }@@ -33,13 +72,23 @@ export class AttachmentReadLedger {}restore(snapshot: AttachmentReadLedgerSnapshot): void {- if (- !Object.values(snapshot).every(boundedCount) ||- snapshot.reads > MAX_ATTACHMENT_READS_PER_TURN- ) {- throw new Error('Invalid attachment read ledger snapshot')+ const parsed = readAttachmentReadLedgerSnapshot(snapshot)+ if (!parsed) throw new Error('Invalid attachment read ledger snapshot')+ this.state = parsed+ }++ /**+ * Fail-closed state for a turn whose spend cannot be trusted (a legacy or+ * corrupt snapshot). No further page can+ * be emitted, and no spend is guessed.+ */+ exhaust(windowTokens: number): void {+ const { turnTokens } = attachmentReadBudgets(windowTokens)+ this.state = {+ reads: MAX_ATTACHMENT_READS_PER_TURN,+ spentTokens: Math.max(this.state.spentTokens, turnTokens),+ bytesRead: this.state.bytesRead,}- this.state = { ...snapshot }}beginRead(): boolean {@@ -66,7 +115,12 @@ export class AttachmentReadLedger {}debit(windowTokens: number, cost: number, bytesRead: number): void {- if (!boundedCount(bytesRead) || !this.canEmit(windowTokens, cost)) {+ if (+ !boundedCount(bytesRead) ||+ !this.canEmit(windowTokens, cost) ||+ !Number.isSafeInteger(this.state.spentTokens + cost) ||+ !Number.isSafeInteger(this.state.bytesRead + bytesRead)+ ) {throw new Error('Attachment output cannot fit the remaining page/turn budget')}this.state.spentTokens += costdiff --git a/mcp-host/src/core/extensions/__tests__/approvalFlow.integration.test.ts b/mcp-host/src/core/extensions/__tests__/approvalFlow.integration.test.tsindex e55fbb1d7..3b837b0ca 100644--- a/mcp-host/src/core/extensions/__tests__/approvalFlow.integration.test.ts+++ b/mcp-host/src/core/extensions/__tests__/approvalFlow.integration.test.ts@@ -19,6 +19,7 @@ import type { ApprovalConfig } from '../approvalTypes'vi.mock('../../../config', () => ({config: {devMode: true,+ contextMaxTokens: 100_000,enableApproval: true,enableNudge: false,nudgeMaxIterations: 3,diff --git a/mcp-host/src/core/interfaces.ts b/mcp-host/src/core/interfaces.tsindex dd97a9c78..0600cac4a 100644--- a/mcp-host/src/core/interfaces.ts+++ b/mcp-host/src/core/interfaces.ts@@ -44,6 +44,8 @@ export interface LlmPort {* absent.*/getTokenCounter?(): TokenCounter+ /** Counters for all destinations that may receive this turn's paged output. */+ getToolTokenCounters?(): readonly TokenCounter[]}// ─── Reasoning ──────────────────────────────────────────────diff --git a/mcp-host/src/core/orchestration/__tests__/toolUseLoopSingleTool.attachmentRead.test.ts b/mcp-host/src/core/orchestration/__tests__/toolUseLoopSingleTool.attachmentRead.test.tsindex 935ca6066..a68189303 100644--- a/mcp-host/src/core/orchestration/__tests__/toolUseLoopSingleTool.attachmentRead.test.ts+++ b/mcp-host/src/core/orchestration/__tests__/toolUseLoopSingleTool.attachmentRead.test.ts@@ -12,6 +12,7 @@ import * as os from 'node:os'import * as path from 'node:path'import { validateIncomingAttachments } from '../../../agent/incomingAttachments'import type { IncomingMessage } from '../../../server'+import { AttachmentReadLedger } from '../../attachments/attachmentReadBudget'import type { Tool, ToolRegistry } from '../../interfaces'import { BasicSafety } from '../../safety/safety'import { DefaultToolOutputProcessor } from '../../safety/toolOutputProcessor'@@ -131,6 +132,10 @@ describe('executeSingleTool — clerum__attachment_read pages stay inline (#666,toolProgressInterval: 0,spilloverStorage: storage,taskId: TASK_ID,+ // C15/C16 — the bounded reader refuses to run without an exact+ // measurement; the loop always wires this in production.+ measureToolMessage: message =>+ Math.max(Math.ceil(Buffer.byteLength(message.content ?? '', 'utf8') / 4) + 4, 1),})}@@ -146,7 +151,10 @@ describe('executeSingleTool — clerum__attachment_read pages stay inline (#666,hostRef: 'host-1',attachments: [attachment],}- return new AttachmentReadTool(message, READ_LIMIT)+ return new AttachmentReadTool(message, READ_LIMIT, {+ contextWindowTokens: 100_000,+ ledger: new AttachmentReadLedger(),+ })}function eventTypes(): string[] {diff --git a/mcp-host/src/core/tools/__tests__/nativeToolRegistry.attachmentRead.test.ts b/mcp-host/src/core/tools/__tests__/nativeToolRegistry.attachmentRead.test.tsindex a6fad4b06..0e509ac3e 100644--- a/mcp-host/src/core/tools/__tests__/nativeToolRegistry.attachmentRead.test.ts+++ b/mcp-host/src/core/tools/__tests__/nativeToolRegistry.attachmentRead.test.ts@@ -6,6 +6,7 @@ import { describe, expect, it } from 'vitest'import { createHash } from 'node:crypto'import { validateIncomingAttachments } from '../../../agent/incomingAttachments'import type { IncomingMessage } from '../../../server'+import { AttachmentReadLedger } from '../../attachments/attachmentReadBudget'import type { NativeToolConfig } from '../../interfaces'import { SpilloverStorage } from '../../spillover'import type { Attachment } from '../../types'@@ -74,13 +75,25 @@ function toolNames(registry: NativeToolRegistry): string[] {return registry.listDefinitions().map(definition => definition.name)}+/** C15/C16 — the per-turn ledger and window a real caller always supplies. */+function attachmentOptions(+ ledger: AttachmentReadLedger = new AttachmentReadLedger(),+ contextWindowTokens = 100_000+) {+ return { maxBytes: 3_145_728, ledger, contextWindowTokens }+}+describe('NativeToolRegistry — clerum__attachment_read (#666)', () => {it('registers the tool for a message with a kind:file attachment', () => {const registry = new NativeToolRegistry(config,'conv-1',undefined,- message(attachments('file'))+ message(attachments('file')),+ undefined,+ undefined,+ undefined,+ attachmentOptions())expect(toolNames(registry)).toContain('clerum__attachment_read')expect(registry.get('clerum__attachment_read')!.parametersSchema()).toMatchObject({@@ -98,10 +111,23 @@ describe('NativeToolRegistry — clerum__attachment_read (#666)', () => {config,'conv-1',undefined,- message(attachments('file'))+ message(attachments('file')),+ undefined,+ undefined,+ undefined,+ attachmentOptions())expect(toolNames(control)).toContain('clerum__attachment_read')- const registry = new NativeToolRegistry(config, 'conv-1', undefined, source)+ const registry = new NativeToolRegistry(+ config,+ 'conv-1',+ undefined,+ source,+ undefined,+ undefined,+ undefined,+ attachmentOptions()+ )// Witness: the registry was built and presents its always-on native tools.expect(toolNames(registry)).toContain('file_read')expect(toolNames(registry)).not.toContain('clerum__attachment_read')@@ -110,12 +136,84 @@ describe('NativeToolRegistry — clerum__attachment_read (#666)', () => {it('refuses to build without the per-call limit when a file is attached', () => {const { attachmentTextReadMaxBytes: _omitted, ...withoutLimit } = config// Control: the same config builds when no file is attached.- expect(() => new NativeToolRegistry(withoutLimit, 'conv-1', undefined, message())).not.toThrow()expect(- () => new NativeToolRegistry(withoutLimit, 'conv-1', undefined, message(attachments('file')))+ () =>+ new NativeToolRegistry(+ withoutLimit,+ 'conv-1',+ undefined,+ message(),+ undefined,+ undefined,+ undefined,+ attachmentOptions()+ )+ ).not.toThrow()+ expect(+ () =>+ new NativeToolRegistry(+ withoutLimit,+ 'conv-1',+ undefined,+ message(attachments('file')),+ undefined,+ undefined,+ undefined,+ attachmentOptions()+ )).toThrow('NativeToolConfig.attachmentTextReadMaxBytes is required for file attachments')})+ it('refuses to register the tool without the turn ledger and window', () => {+ // Control: the full wiring registers it.+ expect(+ () =>+ new NativeToolRegistry(+ config,+ 'conv-1',+ undefined,+ message(attachments('file')),+ undefined,+ undefined,+ undefined,+ attachmentOptions()+ )+ ).not.toThrow()+ expect(+ () =>+ new NativeToolRegistry(+ config,+ 'conv-1',+ undefined,+ message(attachments('file')),+ undefined,+ undefined,+ undefined,+ { maxBytes: 3_145_728 }+ )+ ).toThrow(/ledger/)+ })++ it('wires the SAME turn ledger into the registered tool', async () => {+ const ledger = new AttachmentReadLedger()+ for (let i = 0; i < 32; i++) ledger.beginRead()+ const registry = new NativeToolRegistry(+ config,+ 'conv-1',+ undefined,+ message(attachments('file')),+ undefined,+ undefined,+ undefined,+ attachmentOptions(ledger)+ )+ const tool = registry.get('clerum__attachment_read')!+ const output = await tool.execute({ attachmentId: 'file-1' })+ // The pre-spent ledger is observable through the registry-built tool.+ expect(output.content).toContain('read_budget_exhausted')+ expect(output.is_error).toBe(false)+ })+it('registers a spillover-exempt tool whether or not the turn has spillover storage', () => {const storage = new SpilloverStorage({workspacePath: '/tmp',@@ -131,7 +229,7 @@ describe('NativeToolRegistry — clerum__attachment_read (#666)', () => {undefined,undefined,undefined,- undefined,+ attachmentOptions(),storage)// Witness: this turn can spill (the read-back tool is present).@@ -141,7 +239,16 @@ describe('NativeToolRegistry — clerum__attachment_read (#666)', () => {expect(spilling.description()).toContain('reader=text')expect(spilling.description()).not.toContain('spillover')- const inline = new NativeToolRegistry(config, 'conv-1', undefined, message(attachments('file')))+ const inline = new NativeToolRegistry(+ config,+ 'conv-1',+ undefined,+ message(attachments('file')),+ undefined,+ undefined,+ undefined,+ attachmentOptions()+ )expect(inline.get('clerum__spillover_read')).toBeNull()const reader = inline.get('clerum__attachment_read')!expect(reader.spilloverExempt?.()).toBe(true)diff --git a/mcp-host/src/core/tools/nativeToolRegistry.ts b/mcp-host/src/core/tools/nativeToolRegistry.tsindex 03af4ee12..e74e3e475 100644--- a/mcp-host/src/core/tools/nativeToolRegistry.ts+++ b/mcp-host/src/core/tools/nativeToolRegistry.ts@@ -19,6 +19,7 @@ import { getOutputDir, resolveInternalTools } from '../../workflow/internalToolsimport type { InternalToolDefinition } from '../../workflow/types'import { ScopedWorkspace } from '../../workspace/scopedWorkspace'import type { Workspace } from '../../workspace/service'+import type { AttachmentReadLedger } from '../attachments/attachmentReadBudget'import { type ExecutionContext, NativeToolConfig, Tool, ToolRegistry } from '../interfaces'import type { SessionSearchService } from '../sessionSearch'import type { SpilloverStorage } from '../spillover'@@ -163,6 +164,16 @@ export class NativeToolRegistry implements ToolRegistry {attachmentOptions?: {maxBytes?: numbersecretEntriesProvider?: () => Array<{ name: string; value: string }>+ /**+ * C15/C16 — the turn-owned read ledger. Required (with+ * `contextWindowTokens`) whenever a file attachment registers+ * `clerum__attachment_read`: the tool refuses to run without an exact+ * measurement and a bound, so a missing ledger must fail here, at+ * registration, instead of mid-turn.+ */+ ledger?: AttachmentReadLedger+ /** C15/C16 — effective context window the ledger derives its envelope from. */+ contextWindowTokens?: number},spilloverStorage?: SpilloverStorage,sessionSearchService?: SessionSearchService,@@ -278,10 +289,19 @@ export class NativeToolRegistry implements ToolRegistry {'NativeToolConfig.attachmentTextReadMaxBytes is required for file attachments')}+ const ledger = attachmentOptions?.ledger+ const contextWindowTokens = attachmentOptions?.contextWindowTokens+ if (!ledger || contextWindowTokens === undefined) {+ throw new Error(+ 'NativeToolConfig attachment read wiring requires a turn ledger and contextWindowTokens for file attachments'+ )+ }// The tool declares itself spillover-exempt: a page is bounded by// `maxBytes`, so the loop ships it inline whether or not this turn has// spillover storage (#678).- this.register(new AttachmentReadTool(sourceMessage, maxBytes))+ this.register(+ new AttachmentReadTool(sourceMessage, maxBytes, { contextWindowTokens, ledger })+ )}const envGetter = (key: string): string | undefined => {diff --git a/mcp-host/src/core/types.ts b/mcp-host/src/core/types.tsindex 4cbf766e8..68cf7b375 100644--- a/mcp-host/src/core/types.ts+++ b/mcp-host/src/core/types.ts@@ -9,6 +9,7 @@import type { FileReferenceDigest, FileReferenceV1 } from '@clerum/gfs-interaction-policy'import type { IncomingMessage as HostIncomingMessage } from '../server/types'import type { GfsImageSource } from '../visualInput/policy'+import type { AttachmentReadLedgerSnapshot } from './attachments/attachmentReadBudget'import type { SystemPromptParts } from './reasoning/systemPrompt'// ─── Message Types ──────────────────────────────────────────@@ -631,6 +632,11 @@ export interface TaskExecutionBudgetSnapshot {maxIterations: number/** Cumulative source-read work; payloads are not durable task budget data. */visualReadBytes?: number+ /**+ * C15/C16 — the turn's attachment read ledger, carried inside this existing+ * JSON column. Data-only counts; no file bytes, no content.+ */+ attachmentReadLedger?: AttachmentReadLedgerSnapshot}export interface PendingApproval {diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex 6cff510ab..953754fbf 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -530,9 +530,16 @@ function currentFailoverSupport(): {engine: FailoverEnginepolicy: LlmPolicybuildProvider: (entry: FallbackEntry) => SingleTurnProvider | null+ contextWindowForPair: (provider: string, model: string) => number | undefined} | null {if (!failoverEngine || !currentPolicy) return null- return { engine: failoverEngine, policy: currentPolicy, buildProvider: buildFallbackProvider }+ return {+ engine: failoverEngine,+ policy: currentPolicy,+ buildProvider: buildFallbackProvider,+ contextWindowForPair: (provider, model) =>+ contextWindowForModel(allowlistView(), provider, model),+ }}/**