The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(agent): cloud reasoners get their own reasoning back between tool calls; capped re-reads stop cycling (CA loops)
purplef99e4dfd0ce0
diff --git a/src/api/agents/sub-agent.ts b/src/api/agents/sub-agent.tsindex 20f0d959..426a4d09 100644--- a/src/api/agents/sub-agent.ts+++ b/src/api/agents/sub-agent.ts@@ -11,6 +11,7 @@* filtering, the model has no syntactically valid path to recurse.*/+import { replayableReasoning } from '../../lib/agent-core/reasoning-replay'import { stripSourcesMarker } from '../../lib/web-evidence'import { settleThinking } from '../../lib/thinking-stripper'import { toolResultIsFailure } from '../../lib/tool-result-failure'@@ -618,7 +619,15 @@ export async function defaultSubAgentRunner(thinking: raw.thinking,tools,})- const turn = { ...raw, content: recovered.content, toolCalls: recovered.toolCalls }+ // Every call gets an id here, once. A call recovered from text or the+ // reasoning channel had none, and the wire format then made up a fresh+ // one on every request while its result went out with no id at all: the+ // model could not tie its call to its result (CA, cloud loops).+ const turn = {+ ...raw,+ content: recovered.content,+ toolCalls: recovered.toolCalls.map((tc, k) => (tc.id ? tc : { ...tc, id: `call_sub${i}_${k}` })),+ }// What a sub-agent returns becomes a TOOL RESULT in the parent's context,// so leaked reasoning floods the run it was supposed to shorten (2.6.7// Denk-Audit, Loch 11). Same settlement as every visible surface.@@ -701,7 +710,7 @@ export async function defaultSubAgentRunner(continue}- messages.push({ role: 'assistant', content: turn.content || '', tool_calls: turn.toolCalls })+ messages.push({ role: 'assistant', content: turn.content || '', tool_calls: turn.toolCalls, reasoning: replayableReasoning(raw.thinking) })// Map each result back to its ORIGINATING call by index. executeParallel// preserves input order (results[i] <-> requests[i] <-> turn.toolCalls[i]),// so zipping by index gives every tool message the correct tool_call_id,diff --git a/src/api/providers/__tests__/reasoning-goes-back-with-the-calls.test.ts b/src/api/providers/__tests__/reasoning-goes-back-with-the-calls.test.tsnew file mode 100644index 00000000..61ee9b6e--- /dev/null+++ b/src/api/providers/__tests__/reasoning-goes-back-with-the-calls.test.ts@@ -0,0 +1,95 @@+/**+ * CA, cloud loops (13.11.2026): an agent step's own reasoning goes back with+ * its tool calls as `reasoning_content`, where the provider asks for it (LU+ * Cloud), and nowhere else. lib/agent-core/reasoning-replay.ts says why.+ *+ * Driven through a real provider call with a stubbed fetch: the request body+ * is what the upstream model sees.+ */+import { describe, it, expect, vi, afterEach } from 'vitest'+import { OpenAIProvider } from '../openai-provider'+import type { ChatMessage, ProviderConfig } from '../types'+import { replayableReasoning, REPLAY_REASONING_CHARS } from '../../../lib/agent-core/reasoning-replay'++function config(replayReasoning?: boolean): ProviderConfig {+ return {+ id: 'openai', name: 'OpenAI', enabled: true,+ baseUrl: 'https://api.openai.com/v1', apiKey: 'sk-test', isLocal: false,+ ...(replayReasoning === undefined ? {} : { replayReasoning }),+ }+}++function okResponse(): Response {+ return new Response(JSON.stringify({ choices: [{ message: { content: 'done' }, finish_reason: 'stop' }] }), { status: 200 })+}++const RUN: ChatMessage[] = [+ { role: 'user', content: 'fix the parser' },+ {+ role: 'assistant', content: '', reasoning: 'The bug is in parse(); read src/parse.ts first.',+ tool_calls: [{ id: 'call_1', function: { name: 'file_read', arguments: { path: 'src/parse.ts' } } }],+ },+ { role: 'tool', content: 'export function parse() {}', tool_call_id: 'call_1' },+]++async function bodyOf(cfg: ProviderConfig): Promise<{ messages: Array<Record<string, unknown>> }> {+ const fetchMock = vi.fn().mockResolvedValue(okResponse())+ vi.stubGlobal('fetch', fetchMock)+ await new OpenAIProvider(cfg).chatWithTools('gpt-4o', RUN, [])+ return JSON.parse(fetchMock.mock.calls[0][1].body as string)+}++afterEach(() => vi.unstubAllGlobals())++describe('reasoning_content on the wire', () => {+ it('goes back with the step that made the call, where the provider asks for it', async () => {+ const body = await bodyOf(config(true))+ const step = body.messages.find((m) => m.role === 'assistant')!+ expect(step.reasoning_content).toBe('The bug is in parse(); read src/parse.ts first.')+ expect(step.tool_calls).toHaveLength(1)+ // Never on the other roles.+ expect(body.messages.filter((m) => 'reasoning_content' in m)).toHaveLength(1)+ })++ it('is not sent to a provider that did not ask for it', async () => {+ for (const cfg of [config(), config(false)]) {+ const body = await bodyOf(cfg)+ expect(body.messages.some((m) => 'reasoning_content' in m)).toBe(false)+ }+ })+})++describe('replayableReasoning', () => {+ it('nothing for nothing', () => {+ expect(replayableReasoning(undefined)).toBeUndefined()+ expect(replayableReasoning(' ')).toBeUndefined()+ })++ it('keeps a normal step whole', () => {+ expect(replayableReasoning(' plan: read, then edit ')).toBe('plan: read, then edit')+ })++ it('keeps the END of a very long one, where the decision is', () => {+ const long = 'x'.repeat(REPLAY_REASONING_CHARS) + 'DECISION: call file_edit'+ const out = replayableReasoning(long)!+ expect(out.length).toBeLessThanOrEqual(REPLAY_REASONING_CHARS + 4)+ expect(out.endsWith('DECISION: call file_edit')).toBe(true)+ expect(out.startsWith('[…]')).toBe(true)+ })+})++describe('LU Cloud asks for it', () => {+ it('its provider sets replayReasoning', async () => {+ const { readFileSync } = await import('node:fs')+ const src = readFileSync(new URL('../lu-cloud-provider.ts', import.meta.url), 'utf8')+ expect(src).toMatch(/replayReasoning: true/)+ })++ it('all three loops attach the step reasoning to the assistant turn with the calls', async () => {+ const { readFileSync } = await import('node:fs')+ const read = (p: string) => readFileSync(new URL(p, import.meta.url), 'utf8')+ expect(read('../../../hooks/useAgentChat.ts')).toMatch(/reasoning: replayableReasoning\(turnThinking\)/)+ expect(read('../../../hooks/useCodex.ts')).toMatch(/tool_calls: toolCalls, reasoning: replayableReasoning\(turnReasoning\)/)+ expect(read('../../agents/sub-agent.ts')).toMatch(/reasoning: replayableReasoning\(raw\.thinking\)/)+ })+})diff --git a/src/api/providers/lu-cloud-provider.ts b/src/api/providers/lu-cloud-provider.tsindex 3ce737f8..b798463f 100644--- a/src/api/providers/lu-cloud-provider.ts+++ b/src/api/providers/lu-cloud-provider.ts@@ -61,6 +61,9 @@ export class LuCloudProvider implements ProviderClient {baseUrl: `${CLOUD_BASE}/api/inference/v1`,apiKey: token,isLocal: false,+ // Its reasoners continue from their own reasoning between tool calls+ // (lib/agent-core/reasoning-replay.ts).+ replayReasoning: true,})}diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex 156d1a3d..2c86a2c3 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -102,6 +102,7 @@ export interface OpenAIRequestMessage {content: string | OpenAIContentPart[]tool_calls?: OpenAIRequestToolCall[]tool_call_id?: string+ reasoning_content?: string}export interface OpenAIChatRequest {@@ -2049,6 +2050,12 @@ export class OpenAIProvider implements ProviderClient {m.tool_call_id = msg.tool_call_id}+ // The step's own reasoning, where the provider asks for it+ // (lib/agent-core/reasoning-replay.ts).+ if (this.config.replayReasoning && msg.role === 'assistant' && msg.reasoning) {+ m.reasoning_content = msg.reasoning+ }+return m}diff --git a/src/api/providers/types.ts b/src/api/providers/types.tsindex c7e674d7..5ff3bfeb 100644--- a/src/api/providers/types.ts+++ b/src/api/providers/types.ts@@ -31,6 +31,10 @@ export interface ProviderConfig {baseUrl: string // e.g. "http://localhost:11434", "https://openrouter.ai/api/v1"apiKey: string // Encrypted in store. Empty string for local providers.isLocal: boolean // true for Ollama, LM Studio, vLLM, no API key needed+ // CA (13.11.2026): send an assistant step's own reasoning back as+ // `reasoning_content` (lib/agent-core/reasoning-replay.ts). Set by LU Cloud,+ // whose reasoners need it between tool calls. Undefined = not sent.+ replayReasoning?: boolean// Built-in engine (2.5.7): the app manages this OpenAI-compatible backend's// lifecycle itself (bundled llama-server on 127.0.0.1:8127). When true the UI// hides the URL/key inputs and the model list comes from `list_bundled_models`@@ -208,6 +212,10 @@ export interface ChatMessage {images?: { data: string; mimeType: string }[] // base64 image attachmentstool_calls?: ToolCall[]tool_call_id?: string // Required for OpenAI tool results+ /** The model's own reasoning on this assistant step, sent back as+ * `reasoning_content` where the provider asks for it (replayReasoning).+ * Set only by the agent loops for steps of the run that is going. */+ reasoning?: string}export interface ToolCall {diff --git a/src/hooks/__tests__/useCodex-loop-detection.test.ts b/src/hooks/__tests__/useCodex-loop-detection.test.tsindex 88f80ef2..ebff74f4 100644--- a/src/hooks/__tests__/useCodex-loop-detection.test.ts+++ b/src/hooks/__tests__/useCodex-loop-detection.test.ts@@ -48,7 +48,7 @@ describe('useCodex loop-detector (Bug #5 → AgentLoopGuard)', () => {// history read "do not repeat this" and then showed the model doing it.const idxHold = src.indexOf('pendingSteer = batchVerdict.message')const idxPush = src.indexOf("messages.push({ role: 'user', content: pendingSteer })")- const idxHistory = src.indexOf("messages.push({ role: 'assistant', content: turnContent || '', tool_calls: toolCalls })")+ const idxHistory = src.indexOf("messages.push({ role: 'assistant', content: turnContent || '', tool_calls: toolCalls, reasoning: replayableReasoning(turnReasoning) })")expect(idxHold).toBeGreaterThan(0)expect(idxHistory).toBeGreaterThan(idxHold)expect(idxPush).toBeGreaterThan(idxHistory)diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 7100d74b..a199f985 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -1,4 +1,5 @@import { stripSourcesMarker } from '../lib/web-evidence'+import { replayableReasoning } from '../lib/agent-core/reasoning-replay'import { useRef, useState, useCallback, useEffect } from 'react'import { frameFlush } from '../lib/frame-flush'import { useRunActivityStore, toolProgressActivity, waitBeforeRetry, readingActivity, endFirstWait, hiddenThoughtArrived, waitForChatCard } from '../stores/runActivityStore'@@ -1726,6 +1727,9 @@ export function useAgentChat() {// than a loop (plan A1, LOOP-GUARD). Keyed by the message object, which// works across all three transports.const guardKeyOfResult = new WeakMap<object, string>()+ // Reads fetched again after their result was capped: their newest result+ // stays whole from then on (context-decay keepWhole, CA cloud loops).+ const neededAgain = new Set<string>()const guardKeyFor = (tc: { function: { name: string; arguments?: unknown } }): string =>`${tc.function.name}|${JSON.stringify(tc.function.arguments ?? {})}`const NO_TRIMMED_KEYS: ReadonlySet<string> = new Set<string>()@@ -1959,6 +1963,7 @@ export function useAgentChat() {enabled: decayOn,hysteresis: decayOn,keyOf: (m) => guardKeyOfResult.get(m as unknown as object),+ keepWhole: neededAgain,})sendMessages = built.messagestrimmedReadKeys = new Set(built.trimmedKeys)@@ -3005,6 +3010,10 @@ export function useAgentChat() {// decay working as designed, not a loop (plan A1, LOOP-GUARD).{ trimmedReadKeys },)+ for (const tc of toolCalls) {+ const k = guardKeyFor(tc)+ if (trimmedReadKeys.has(k)) neededAgain.add(k)+ }// A plan the model keeps restating steers like a repeated batch does;// the batch's own verdict wins where it has one (A37).const batchVerdict = recordedVerdict.action === 'ok' ? narrationVerdict : recordedVerdict@@ -3459,6 +3468,9 @@ export function useAgentChat() {role: 'assistant',content: turnContent || '',tool_calls: toolCalls,+ // The step's own reasoning goes back with its calls where the+ // provider asks for it (lib/agent-core/reasoning-replay.ts).+ reasoning: replayableReasoning(turnThinking),})for (const { tc } of batch) {const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 52c33f0e..49b33329 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -1,4 +1,5 @@import { stripSourcesMarker } from '../lib/web-evidence'+import { replayableReasoning } from '../lib/agent-core/reasoning-replay'import { NOT_IN_CODE_TAB } from '../lib/browser-tools'import { useRef, useState, useCallback } from 'react'import { markCannotThink } from '../lib/model-compatibility'@@ -914,7 +915,14 @@ export function useCodex() {// the provider now flips through chat_template_kwargs. Asking for tags on// top of a template that already opened the thought is a double// instruction, and that is what loops a reasoner.+ //+ // And not for a model whose catalogue entry declares how it thinks+ // (`thinkMode`, every LU Cloud model): the provider switches its native+ // reasoning through reasoning_effort, and the tag request on top is the+ // same double instruction. Plain chat had this gate (useChat.ts), the Code+ // tab did not, and GLM on LU Cloud got both (CA, cloud loops, 13.11.2026).if (settings.thinkingEnabled && providerId !== 'ollama' && codexCanThink(activeModel)+ && codexThinkMode(activeModel) === undefined&& !isLocalModelByName(activeModel)) {systemPrompt += '\n\nBefore answering, reason through your thinking inside <think></think> tags. Your thinking will be hidden from the user. After thinking, provide your answer outside the tags.'}@@ -1280,6 +1288,9 @@ export function useCodex() {// transport shape and every reordering the builder does; a WeakMap so a// dropped message takes its entry with it.const guardKeyOfResult = new WeakMap<object, string>()+ // Reads fetched again after their result was capped: their newest result+ // stays whole from then on (context-decay keepWhole, CA cloud loops).+ const neededAgain = new Set<string>()const guardKeyFor = (tc: { function: { name: string; arguments: unknown } }): string =>`${tc.function.name}|${JSON.stringify(tc.function.arguments)}`const NO_TRIMMED_KEYS: ReadonlySet<string> = new Set<string>()@@ -1357,6 +1368,9 @@ export function useCodex() {}let toolCalls: ToolCall[] = []let turnContent = ''+ // The step's native reasoning, sent back with its calls where the+ // provider asks for it (lib/agent-core/reasoning-replay.ts).+ let turnReasoning = ''// Warum DIESER Zug endete. Nur `length` wird ausgewertet, und nur// unten in der Weiche ohne Werkzeugaufruf: ein abgeschnittener Zug// sah dort bis Fehler D genauso aus wie ein fertiges Modell.@@ -1469,6 +1483,7 @@ export function useCodex() {enabled: decayOn,hysteresis: decayOn,keyOf: (m) => guardKeyOfResult.get(m as unknown as object),+ keepWhole: neededAgain,})sendMessages = built.messagesstepPromptEstimate = built.promptTokens@@ -1770,6 +1785,7 @@ export function useCodex() {contentHead: turnContent.slice(0, 200),thinkingLen: turn.thinking?.length || 0,})+ turnReasoning = turn.thinking || ''if (keepThinking && turn.thinking) {thinkingContent += (thinkingContent ? '\n\n' : '') + turn.thinkinguseChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, thinkingContent)@@ -1831,6 +1847,7 @@ export function useCodex() {turnContent = recovered.contentif (recovered.source !== 'native' && recovered.source !== 'none') diagLog('calls-recovered', { from: recovered.source, count: toolCalls.length })}+ turnReasoning = turn.thinking || ''if (keepThinking && turn.thinking) {thinkingContent += (thinkingContent ? '\n\n' : '') + turn.thinkinguseChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, thinkingContent)@@ -2274,6 +2291,10 @@ export function useCodex() {// not a loop (plan A1, LOOP-GUARD).{ trimmedReadKeys },)+ for (const tc of toolCalls) {+ const k = guardKeyFor(tc)+ if (trimmedReadKeys.has(k)) neededAgain.add(k)+ }// A plan the model keeps restating steers like a repeated batch does;// the batch's own verdict wins where it has one (A37).const batchVerdict = recordedVerdict.action === 'ok' ? narrationVerdict : recordedVerdict@@ -2701,7 +2722,7 @@ export function useCodex() {))}} else if (speaksOpenAIProtocol(providerId) || providerId === 'anthropic') {- messages.push({ role: 'assistant', content: turnContent || '', tool_calls: toolCalls })+ messages.push({ role: 'assistant', content: turnContent || '', tool_calls: toolCalls, reasoning: replayableReasoning(turnReasoning) })for (const { tc } of batch) {const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!messages.push(rememberResult({ role: 'tool', content: resultTextFor(result), tool_call_id: tc.id }, tc))diff --git a/src/lib/__tests__/loop-guard-decay.test.ts b/src/lib/__tests__/loop-guard-decay.test.tsindex 8f848a8b..ebd26208 100644--- a/src/lib/__tests__/loop-guard-decay.test.ts+++ b/src/lib/__tests__/loop-guard-decay.test.ts@@ -67,14 +67,29 @@ describe('A1 loop guard: a read whose result was capped never counts', () => {expect(last.action === 'halt' && last.reason).toMatch(/identical arguments/)})- it('with the capped marker the same eight rounds never halt', () => {+ it('with the capped marker the first re-read is forgiven, the cycle after it is not (CA)', () => {+ // CA, cloud loops (13.11.2026): the loops now keep the newest result of a+ // read fetched again after a cap WHOLE (context-decay keepWhole), so a+ // second cap cannot come from age. Forgiving every lap let read, cap, read+ // run uncounted on a 32k cloud window. Once per read, then it counts.const guard = new AgentLoopGuard()const trimmed = new Set([keyOf('src/big.ts')])const verdicts: string[] = []for (let i = 0; i < 8; i++) {verdicts.push(guard.recordBatch(readPlusNoise('src/big.ts', i), { trimmedReadKeys: trimmed }).action)}- expect(verdicts).toEqual(new Array(8).fill('ok'))+ expect(verdicts.slice(0, 3)).toEqual(['ok', 'ok', 'ok'])+ expect(verdicts).toContain('steer')+ expect(verdicts[verdicts.length - 1]).toBe('halt')+ })++ it('a write in between forgives again: the bytes may have changed', () => {+ const guard = new AgentLoopGuard()+ const trimmed = new Set([keyOf('src/big.ts')])+ for (let round = 0; round < 4; round++) {+ expect(guard.recordBatch(readPlusNoise('src/big.ts', round), { trimmedReadKeys: trimmed }).action).toBe('ok')+ guard.recordBatch([{ name: 'file_write', args: `{"path":"src/big.ts","n":${round}}` }])+ }})})@@ -88,7 +103,7 @@ describe('A1 loop guard: the steer text never orders work against a stub', () =>expect(steer.action === 'steer' && steer.message).toContain('Use the result from before')})- it('never emits that sentence for a read the builder capped', () => {+ it('never emits that sentence for a read the builder capped (it points at a smaller read)', () => {const guard = new AgentLoopGuard()const trimmed = new Set([keyOf('a.ts')])const seen: string[] = []@@ -97,8 +112,10 @@ describe('A1 loop guard: the steer text never orders work against a stub', () =>// stays out of it; that one is the deliberate backstop, tested below.const v = guard.recordBatch(readPlusNoise('a.ts', i), { trimmedReadKeys: trimmed })if (v.action === 'steer') seen.push(v.message)+ if (v.action === 'halt') break}- expect(seen).toEqual([])+ expect(seen.join(' ')).not.toContain('Use the result from before')+ expect(seen.join(' ')).toMatch(/Read only the part you need/)})})diff --git a/src/lib/agent-core/reasoning-replay.ts b/src/lib/agent-core/reasoning-replay.tsnew file mode 100644index 00000000..a84a53f5--- /dev/null+++ b/src/lib/agent-core/reasoning-replay.ts@@ -0,0 +1,40 @@+/**+ * The model's own reasoning goes back with its tool calls (CA, cloud loops,+ * 13.11.2026).+ *+ * Users report cloud models that call the same tool again and again. One root+ * cause sat in the wire format: all three agent loops kept the reasoning of a+ * step only for the screen and sent the assistant turn back with content and+ * tool_calls alone. The reasoners on LU Cloud (GLM 5.x, DeepSeek V3.2/V4,+ * Kimi K3, Qwen 3.x) are built for interleaved thinking: their chat templates+ * render `reasoning_content` of the assistant turns after the last user+ * message, so the model continues from its own plan after a tool result.+ * DeepSeek's thinking-with-tools mode even requires it (its API answers 400+ * without it, api-docs.deepseek.com/guides/thinking_mode), and Z.AI's GLM+ * keeps a plan across tool calls only when the reasoning comes back+ * unchanged (docs.z.ai/guides/capabilities/thinking-mode). Without it every+ * step starts with no memory of why the last call was made, and re-reading+ * the same file is the rational move.+ *+ * What goes back: the reasoning of the steps of the run that is going, never+ * that of earlier user turns (history rebuilt from the store carries none, and+ * the templates drop it there anyway). Capped per step: a model that thought+ * for 100k characters must not turn every later request into a 100k-character+ * input bill. The END of the reasoning is kept, because that is where the+ * decision is.+ *+ * Only providers that ask for it send the field (ProviderConfig+ * `replayReasoning`, set by LU Cloud). An unknown message field is not+ * something every OpenAI-compatible server forgives.+ */++/** Per step, in characters (about 3k tokens). */+export const REPLAY_REASONING_CHARS = 12_000++/** The reasoning of one step as it goes back, or undefined when there is none. */+export function replayableReasoning(text: string | undefined | null): string | undefined {+ const t = (text ?? '').trim()+ if (!t) return undefined+ if (t.length <= REPLAY_REASONING_CHARS) return t+ return '[…]\n' + t.slice(t.length - REPLAY_REASONING_CHARS)+}diff --git a/src/lib/agent-loop-guard.ts b/src/lib/agent-loop-guard.tsindex b9484b8e..ba2fda17 100644--- a/src/lib/agent-loop-guard.ts+++ b/src/lib/agent-loop-guard.ts@@ -272,6 +272,9 @@ export class AgentLoopGuard {*/private stepSilent: boolean | null = null+ /** Reads whose capped result was already forgiven once (detector 3). */+ private trimForgiven = new Set<string>()+/*** Record one iteration's tool-call batch BEFORE executing it. `args` must* be the serialized (stringified) arguments so identity is byte-exact —@@ -377,11 +380,18 @@ export class AgentLoopGuard {let steer: LoopGuardVerdict | null = nullfor (let i = 0; i < calls.length; i++) {if (!READ_ONLY_TOOLS.has(calls[i].name)) continue- if (isTrimmed(keys[i])) {+ if (isTrimmed(keys[i]) && !this.trimForgiven.has(keys[i])) {// The result aged out of the prompt, so this read returns information// the model genuinely no longer has. Clear the counter rather than// just skipping it: the epoch before the cap says nothing about the// epoch after it.+ //+ // Once per read, not forever (CA, cloud loops, 13.11.2026). The loops+ // keep the newest result of a read that was fetched again whole+ // (context-decay `keepWhole`), so a second "it was capped" cannot+ // come from age any more. Forgiving every lap let read, cap, read run+ // uncounted, and on a 32k cloud window that lap is every few steps.+ this.trimForgiven.add(keys[i])this.readCounts.delete(keys[i])continue}@@ -397,10 +407,14 @@ export class AgentLoopGuard {this.steeredKeys.add(keys[i])steer = {action: 'steer',- message:- `You have now called ${calls[i].name} ${n} times with exactly the same arguments. ` +- 'Nothing changed in between, so the result is identical to the one you already have. ' +- 'Do NOT repeat this call again. Use the result from before, or take a DIFFERENT action that moves the task forward.',+ // A read whose result keeps coming back cut has no whole "result+ // from before" to point at. The honest way out is a smaller read.+ message: isTrimmed(keys[i])+ ? `You have now called ${calls[i].name} ${n} times with exactly the same arguments, and its result is cut every time because the conversation is long. ` ++ 'Do NOT fetch it whole again. Read only the part you need (a line range, or a search for the name you want), or finish the task with what you have.'+ : `You have now called ${calls[i].name} ${n} times with exactly the same arguments. ` ++ 'Nothing changed in between, so the result is identical to the one you already have. ' ++ 'Do NOT repeat this call again. Use the result from before, or take a DIFFERENT action that moves the task forward.',}}}@@ -411,6 +425,7 @@ export class AgentLoopGuard {// change is never punished. steeredKeys survives: one steer per unique// call is enough for the whole run.this.readCounts.clear()+ this.trimForgiven.clear()this.pureWindow = []}return steer ?? (near.action === 'steer' ? near : { action: 'ok' })diff --git a/src/lib/context-decay.ts b/src/lib/context-decay.tsindex 986f00b5..65568451 100644--- a/src/lib/context-decay.ts+++ b/src/lib/context-decay.ts@@ -200,6 +200,15 @@ export interface DecayOptions<T> {* legitimate and the guard must not count it (plan A1, LOOP-GUARD).*/keyOf?: (msg: T) => string | undefined+ /**+ * Reads the model fetched AGAIN after their result had been capped (CA,+ * cloud loops, 13.11.2026). The newest result of such a read stays whole:+ * the model has shown it needs those bytes, and capping them again only+ * starts the next read, cap, read cycle, each lap a full paid request. Needs+ * `keyOf`. The window trim (trimWorkingHistory) still applies, so a pinned+ * result can never push a request past its budget.+ */+ keepWhole?: ReadonlySet<string>}export interface DecayReport<T> {@@ -243,9 +252,22 @@ export function applyToolResultDecay<T extends DecayMessage>(let trimmedCount = 0let savedChars = 0const trimmedKeys: string[] = []+ // The newest result of every read that must stay whole.+ const pinned = new Set<number>()+ if (opts.keepWhole?.size && opts.keyOf) {+ const seen = new Set<string>()+ for (let i = messages.length - 1; i >= 0; i--) {+ if (!isToolResult(messages[i])) continue+ const key = opts.keyOf(messages[i])+ if (!key || seen.has(key)) continue+ seen.add(key)+ if (opts.keepWhole.has(key)) pinned.add(i)+ }+ }for (let i = 0; i < messages.length; i++) {const m = messages[i]if (!isToolResult(m)) continue+ if (pinned.has(i)) continue// The request under construction is iteration newest + 1.const age = newest + 1 - iters[i]if (age < afterIterations) continue