Skip to content

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.

fix(agent): C83 catch silent near-identical tool calls and brake run cost

purplef8d5f70853f8
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 312fe415..31cddd7e 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -71,7 +71,7 @@ import { COMPUTER_USE_TOOL_NAME, onlyTheTaskForTheScreen, withComputerUsePrompt
import { memoryPairForRun } from '../lib/computer/memory-policy'
import { getModelMaxTokens, estimateTokens } from '../lib/context-compaction'
import { buildRequestMessages, trimWorkingHistory } from '../lib/context-decay'
-import { budgetBesideTheCatalog, effectiveSendWindow, sendWindowFor } from '../lib/send-window'
+import { budgetBesideTheCatalog, effectiveSendWindow, isPaidProvider, sendWindowFor } from '../lib/send-window'
import { sendsToALanBackend } from '../lib/lan-openai-slot'
import { speaksOpenAIProtocol } from '../api/providers/compat-id'
import { useSendSizeStore } from '../stores/sendSizeStore'
@@ -138,6 +138,7 @@ import { fitRequestForPhone, measuredRequest, phoneFitApplies, phoneResultChars,
import { toolFailureNote } from '../lib/tool-failure-note'
import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'
import { AgentLoopGuard } from '../lib/agent-loop-guard'
+import { AgentCostBrake } from '../lib/agent-cost-brake'
import { budgetFromSettings } from '../api/agents/budget'
import type { ChatMessage, ToolCall, ToolCallProgress, ToolDefinition } from '../api/providers/types'
import type { WorkflowEngineCallbacks } from '../types/agent-workflows'
@@ -1689,6 +1690,11 @@ export function useAgentChat() {
// rightly weakened. Windowed batch repeats, per-epoch identical reads and
// repeated narration now watch this loop too.
const loopGuard = new AgentLoopGuard({ enabled: useSettingsStore.getState().settings.agentLoopGuard !== false })
+ // C83: what the run has cost so far, on providers that bill per token.
+ const costBrake = new AgentCostBrake({
+ paid: isPaidProvider(providerId, sendsToALanBackend(providerId, activeModel)),
+ loopGuardEnabled: useSettingsStore.getState().settings.agentLoopGuard !== false,
+ })
// The closing line a turn gets when the model itself said nothing usable.
// Read from the live counters at call time, so both the normal end of the
// run and the swallowed multimodal refusal below produce the same text.
@@ -2330,6 +2336,7 @@ export function useAgentChat() {
})
}
requestUsage.add(turn)
+ costBrake.record(turn.promptEvalCount)
// Native thinking field (Ollama; LU Cloud reasoning_content)
if (turn.thinking) turnThinking = turn.thinking
@@ -2423,6 +2430,7 @@ export function useAgentChat() {
// abschneiden, und dann steht hier ebenfalls kein Werkzeugaufruf.
turnFinishReason = hermesTurn.finishReason
requestUsage.add(hermesTurn)
+ costBrake.record(hermesTurn.promptEvalCount)
notePhoneCount(hermesTurn.promptEvalCount)
if (hermesTurn.thinking) {
turnThinking = turnThinking
@@ -3011,6 +3019,24 @@ export function useAgentChat() {
})
break
}
+ // C83: the cost brake looks at what the backend reported, not at the
+ // calls, so it holds even when every call honestly differs.
+ const brake = costBrake.take()
+ if (brake.action === 'halt') {
+ runState.content = (runState.content ? runState.content + '\n\n' : '') + `_(${brake.message})_`
+ scheduleUIUpdate()
+ addBlock(runState, convId!, assistantMessage.id, {
+ id: uuid(), phase: 'reflection', content: `⛔ ${brake.message}`, timestamp: Date.now(),
+ })
+ log.warn('agent.cost_brake_halt', { provider: providerId, inputTokens: costBrake.inputTokens })
+ break
+ }
+ if (brake.action === 'warn') {
+ addBlock(runState, convId!, assistantMessage.id, {
+ id: uuid(), phase: 'reflection', content: `⚠ ${brake.message}`, timestamp: Date.now(),
+ })
+ log.info('agent.cost_brake_warn', { provider: providerId, inputTokens: costBrake.inputTokens })
+ }
const pendingSteer = batchVerdict.action === 'steer' ? batchVerdict.message : null
if (pendingSteer) {
addBlock(runState, convId!, assistantMessage.id, {
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index ceef54a5..6aaa73fc 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -101,13 +101,14 @@ import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS }
import { getModelMaxTokens, estimateTokens } from '../lib/context-compaction'
import { capToLearnedWindow, contextOverflowOf, learnSendWindow, shrunkSendWindow } from './codex/context-overflow'
import { buildRequestMessages, trimWorkingHistory, decayRestoredToolResult, isToolResult } from '../lib/context-decay'
-import { effectiveSendWindow, sendWindowFor } from '../lib/send-window'
+import { effectiveSendWindow, isPaidProvider, sendWindowFor } from '../lib/send-window'
import { sendsToALanBackend } from '../lib/lan-openai-slot'
import { useSendSizeStore } from '../stores/sendSizeStore'
import { resolveAgentNumCtx } from '../lib/agent-num-ctx'
import { platformPromptLine, hostClockLine } from '../lib/host-platform'
import { ensureBuiltinAgentCtx } from '../api/builtin-ensure'
import { AgentLoopGuard } from '../lib/agent-loop-guard'
+import { AgentCostBrake } from '../lib/agent-cost-brake'
import { applyAllStagedChanges, waitForStagedReview } from '../lib/staged-apply'
import { turnCaps } from '../lib/remote-turn-caps'
import { useMemoryStore } from '../stores/memoryStore'
@@ -1278,6 +1279,11 @@ export function useCodex() {
// it forever while the budget allowed 200 iterations of the loop
// (Morgan's 5-minute file_read loop, 2026-07-26).
const loopGuard = new AgentLoopGuard({ enabled: useSettingsStore.getState().settings.agentLoopGuard !== false })
+ // C83: what the run has cost so far, on providers that bill per token.
+ const costBrake = new AgentCostBrake({
+ paid: isPaidProvider(providerId, sendsToALanBackend(providerId, activeModel)),
+ loopGuardEnabled: useSettingsStore.getState().settings.agentLoopGuard !== false,
+ })
// Which read produced which result message. The request builder reports
// back the results it sent CAPPED, and this map turns those messages
// into the loop-guard keys that must not be counted as a repeat (plan
@@ -1759,6 +1765,7 @@ export function useCodex() {
turnFinishReason = turn.doneReason
reportTurnUsage(convId!, assistantMsg.id, turn)
requestUsage.add(turn)
+ costBrake.record(turn.promptEvalCount)
diagLog('streamWithTools-return', {
iter: i,
toolCallsCount: toolCalls.length,
@@ -1816,6 +1823,7 @@ export function useCodex() {
turnFinishReason = turn.finishReason
reportTurnUsage(convId!, assistantMsg.id, turn)
requestUsage.add(turn)
+ costBrake.record(turn.promptEvalCount)
// GH #147: a model on LU Cloud wrote its calls into the text
// (!function_call:{"call": "file_read", ...}). This path never
// looked, so the run stopped on prose. A call from the text counts
@@ -1954,6 +1962,7 @@ export function useCodex() {
// Gleiche Stelle wie in useAgentChat.
turnFinishReason = hermesTurn.finishReason
requestUsage.add(hermesTurn)
+ costBrake.record(hermesTurn.promptEvalCount)
if (keepThinking && hermesTurn.thinking) {
thinkingContent += (thinkingContent ? '\n\n' : '') + hermesTurn.thinking
useChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, thinkingContent)
@@ -2287,6 +2296,19 @@ export function useCodex() {
})
break
}
+ // C83: the cost brake looks at what the backend reported, not at the
+ // calls, so it holds even when every call honestly differs.
+ const brake = costBrake.take()
+ if (brake.action === 'halt') {
+ diagLog('cost-brake-halt', { iter: i, inputTokens: costBrake.inputTokens })
+ useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + `\n\n_(${brake.message})_`)
+ addBlock({ id: uuid(), phase: 'reflection', content: `⛔ ${brake.message}`, timestamp: Date.now() })
+ break
+ }
+ if (brake.action === 'warn') {
+ diagLog('cost-brake-warn', { iter: i, inputTokens: costBrake.inputTokens })
+ addBlock({ id: uuid(), phase: 'reflection', content: `⚠ ${brake.message}`, timestamp: Date.now() })
+ }
// Steer is appended AFTER this iteration's assistant+tool messages
// (audit F2). Pushed here it landed chronologically BEFORE the calls
// it complains about, so the history read "do not repeat this" and
diff --git a/src/lib/__tests__/c83-agent-loop-credits.test.ts b/src/lib/__tests__/c83-agent-loop-credits.test.ts
new file mode 100644
index 00000000..43bdeda2
--- /dev/null
+++ b/src/lib/__tests__/c83-agent-loop-credits.test.ts
@@ -0,0 +1,184 @@
+/**
+ * C83: an agent loop ate a user's credits.
+ *
+ * tid2110, 10.11.2026 09-10Z, LU Cloud direct/deepseek-v4.1-flash: 233 tool
+ * calls in one run, one every ~4 s, no text from the model at all, and every
+ * request carried 420-447k tokens of input. The arguments were 487-492
+ * characters long and never byte-identical, so the guard (3 identical calls)
+ * never fired. ~214k credits were refunded by hand.
+ *
+ * The incident's exact arguments are not in our logs, only their shape, so
+ * the calls below are rebuilt to it: one tool, ~490 characters of arguments,
+ * a few characters wobbling from call to call.
+ *
+ * Run: npx vitest run src/lib/__tests__/c83-agent-loop-credits.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { AgentLoopGuard, argSimilarity } from '../agent-loop-guard'
+import { AgentCostBrake, LARGE_REQUEST_TOKENS, RUN_HALT_TOKENS } from '../agent-cost-brake'
+
+/** One call of the incident's shape: the same script, a wobbling detail. */
+function incidentArgs(i: number): string {
+ const variants = ['data', 'result', 'output', 'rows']
+ const code =
+ `import json, os\n` +
+ `path = os.path.join(os.getcwd(), "report_${i % 3}.json")\n` +
+ `with open(path, "r", encoding="utf-8") as f:\n` +
+ ` ${variants[i % variants.length]} = json.load(f)\n` +
+ `items = [x for x in ${variants[i % variants.length]}.get("items", []) if x.get("status") == "open"]\n` +
+ `summary = {"count": len(items), "first": items[0] if items else None, "last": items[-1] if items else None}\n` +
+ `print(json.dumps(summary, indent=2, ensure_ascii=False))\n` +
+ `# check ${i % 2 ? 'again' : 'anew'} whether the export finished\n`
+ return JSON.stringify({ language: 'python', code, timeout: 60 })
+}
+
+/** The model's text per step: none at all, as in the incident. */
+const SILENT = ''
+
+describe('C83: the incident shape', () => {
+ it('rebuilt arguments really are ~490 characters and never identical', () => {
+ const args = Array.from({ length: 12 }, (_, i) => incidentArgs(i))
+ for (const a of args) expect(a.length).toBeGreaterThanOrEqual(480)
+ for (const a of args) expect(a.length).toBeLessThanOrEqual(500)
+ expect(new Set(args.slice(0, 2)).size).toBe(2)
+ expect(argSimilarity(args[0], args[1])).toBeGreaterThan(0.85)
+ })
+
+ it('the guard steers on the 5th silent near-copy and halts on the 8th, not the 233rd', () => {
+ const g = new AgentLoopGuard()
+ const verdicts = Array.from({ length: 233 }, (_, i) => {
+ g.recordNarration(SILENT)
+ return g.recordBatch([{ name: 'code_execute', args: incidentArgs(i) }])
+ })
+ const firstSteer = verdicts.findIndex((v) => v.action === 'steer')
+ const firstHalt = verdicts.findIndex((v) => v.action === 'halt')
+ expect(firstSteer).toBe(4)
+ expect(firstHalt).toBe(7)
+ const halt = verdicts[firstHalt]
+ expect(halt.action === 'halt' && halt.reason).toMatch(/8 nearly identical code_execute calls in a row/)
+ })
+
+ it('a model that still writes something new each step is not stopped by the near-copy detector', () => {
+ const g = new AgentLoopGuard()
+ const lines = [
+ 'The first report is still empty, I will look again after the export.',
+ 'Now the second report has 4 open items, checking the third one next.',
+ 'Third report loaded. Totals do not match yet, comparing with the list.',
+ 'Found the mismatch: two items were counted twice. Checking the fix.',
+ 'The fix holds for report 0. Running the same check on report 1 now.',
+ 'Report 1 matches too. Last one, report 2, then I write the summary.',
+ 'All three reports match. One final read of report 0 to confirm totals.',
+ 'Confirmed. Everything matches; writing the summary for you below.',
+ ]
+ const actions = lines.map((line, i) => {
+ g.recordNarration(line)
+ return g.recordBatch([{ name: 'code_execute', args: incidentArgs(i) }]).action
+ })
+ expect(actions).not.toContain('halt')
+ expect(actions).not.toContain('steer')
+ })
+
+ it('the C44 switch still turns it off', () => {
+ const g = new AgentLoopGuard({ enabled: false })
+ for (let i = 0; i < 233; i++) {
+ g.recordNarration(SILENT)
+ expect(g.recordBatch([{ name: 'code_execute', args: incidentArgs(i) }]).action).toBe('ok')
+ }
+ })
+})
+
+describe('C83: no false alarms from detector 8', () => {
+ it('paging through a file (only the offset changes) is not a loop', () => {
+ const g = new AgentLoopGuard()
+ for (let i = 0; i < 12; i++) {
+ g.recordNarration(SILENT)
+ const v = g.recordBatch([{ name: 'file_read', args: JSON.stringify({ path: 'src/big-module.ts', offset: i * 200, limit: 200 }) }])
+ expect(v.action).toBe('ok')
+ }
+ })
+
+ it('edit → test → edit → test alternates tools and never counts', () => {
+ const g = new AgentLoopGuard()
+ for (let i = 0; i < 10; i++) {
+ g.recordNarration(SILENT)
+ expect(g.recordBatch([{ name: 'file_edit', args: JSON.stringify({ path: 'src/a.ts', old: `x = ${i}`, new: `x = ${i + 1}` }) }]).action).not.toBe('halt')
+ g.recordNarration(SILENT)
+ expect(g.recordBatch([{ name: 'shell_execute', args: JSON.stringify({ command: 'npm test' }) }]).action).not.toBe('halt')
+ }
+ })
+
+ it('clearly different arguments to the same tool are separate steps', () => {
+ const g = new AgentLoopGuard()
+ const files = ['README.md', 'src/main.ts', 'package.json', 'docs/guide/setup.md', 'tests/unit/a.spec.ts', 'scripts/release.sh', 'src-tauri/Cargo.toml', '.github/workflows/ci.yml', 'vite.config.ts']
+ for (const path of files) {
+ g.recordNarration(SILENT)
+ expect(g.recordBatch([{ name: 'file_write', args: JSON.stringify({ path, content: `contents of ${path}` }) }]).action).toBe('ok')
+ }
+ })
+
+ it('web searches keep their own, wider ladder', () => {
+ const g = new AgentLoopGuard()
+ const actions = Array.from({ length: 6 }, (_, i) => {
+ g.recordNarration(SILENT)
+ return g.recordBatch([{ name: 'web_search', args: JSON.stringify({ query: `deepseek flash pricing per token ${i}` }) }]).action
+ })
+ expect(actions.slice(0, 5)).toEqual(['ok', 'ok', 'ok', 'ok', 'ok'])
+ expect(actions[5]).toBe('steer')
+ })
+})
+
+describe('C83: the cost brake', () => {
+ const incidentInput = (i: number) => 420_000 + ((i * 7919) % 27_000)
+
+ it('the incident (420-447k per call) warns on the first call and halts within 8 calls', () => {
+ const b = new AgentCostBrake({ paid: true })
+ const verdicts = Array.from({ length: 233 }, (_, i) => {
+ b.record(incidentInput(i))
+ return b.take()
+ })
+ expect(verdicts[0].action).toBe('warn')
+ expect(verdicts[0].action === 'warn' && verdicts[0].message).toMatch(/Large request: this step sent 4\d\dk tokens/)
+ const firstHalt = verdicts.findIndex((v) => v.action === 'halt')
+ expect(firstHalt).toBeGreaterThan(0)
+ expect(firstHalt).toBeLessThan(8)
+ const h = verdicts[firstHalt]
+ expect(h.action === 'halt' && h.message).toMatch(/Stopped to protect your credits: this run has sent 3\.\dM tokens/)
+ expect(h.action === 'halt' && h.message).toMatch(/Send a new message to go on/)
+ })
+
+ it('a normal paid run (32k send window, 60 steps) is never stopped', () => {
+ const b = new AgentCostBrake({ paid: true })
+ for (let i = 0; i < 60; i++) {
+ b.record(30_000)
+ expect(b.take().action).toBe('ok')
+ }
+ expect(b.inputTokens).toBe(1_800_000)
+ })
+
+ it('local and LAN models cost nothing per token and are never braked', () => {
+ const b = new AgentCostBrake({ paid: false })
+ for (let i = 0; i < 50; i++) {
+ b.record(500_000)
+ expect(b.take().action).toBe('ok')
+ }
+ })
+
+ it('with the loop guard switched off (C44) the brake only tells, once', () => {
+ const b = new AgentCostBrake({ paid: true, loopGuardEnabled: false })
+ const actions = Array.from({ length: 20 }, () => {
+ b.record(LARGE_REQUEST_TOKENS + 10_000)
+ return b.take().action
+ })
+ expect(actions).not.toContain('halt')
+ expect(actions.filter((a) => a === 'warn')).toHaveLength(2) // large request + passed the limit
+ })
+
+ it('calls without a reported count add nothing, the brake never guesses', () => {
+ const b = new AgentCostBrake({ paid: true })
+ for (let i = 0; i < 100; i++) b.record(undefined)
+ b.record(0)
+ expect(b.inputTokens).toBe(0)
+ expect(b.take().action).toBe('ok')
+ expect(RUN_HALT_TOKENS).toBe(3_000_000)
+ })
+})
diff --git a/src/lib/__tests__/loop-guard-failing-rounds.test.ts b/src/lib/__tests__/loop-guard-failing-rounds.test.ts
index cf5a9b93..7a6eee17 100644
--- a/src/lib/__tests__/loop-guard-failing-rounds.test.ts
+++ b/src/lib/__tests__/loop-guard-failing-rounds.test.ts
@@ -49,10 +49,19 @@ describe('the icacls run from the R26 measurement', () => {
]
it('NEGATIVE CONTROL: the call-shape detectors never fire on it', () => {
+ // The model wrote a new line before every attempt in the measurement, so
+ // detector 8 (silent near-copies, C83) stays out of it as well.
const g = new AgentLoopGuard()
- for (const args of REAL_ARGS) {
+ REAL_ARGS.forEach((args, i) => {
+ g.recordNarration(`Trying permission variant number ${i + 1} on the sandbox folder.`)
expect(g.recordBatch([{ name: 'shell_execute', args }]).action).toBe('ok')
- }
+ })
+ })
+
+ it('silent, the same six calls meet detector 8 on the fifth (C83)', () => {
+ const g = new AgentLoopGuard()
+ const actions = REAL_ARGS.map((args) => g.recordBatch([{ name: 'shell_execute', args }]).action)
+ expect(actions).toEqual(['ok', 'ok', 'ok', 'ok', 'steer', 'ok'])
})
it('but the result detector halts on the sixth failing round', () => {
diff --git a/src/lib/agent-cost-brake.ts b/src/lib/agent-cost-brake.ts
new file mode 100644
index 00000000..bf42321d
--- /dev/null
+++ b/src/lib/agent-cost-brake.ts
@@ -0,0 +1,108 @@
+/**
+ * Cost brake for one agent run (C83).
+ *
+ * tid2110, 10.11.2026, LU Cloud direct/deepseek-v4.1-flash: 233 tool calls
+ * in one run, one every ~4 s, and every single request carried 420-447k
+ * tokens of input. Around 214k credits were gone before the user looked.
+ * The loop guard now catches near-copies of the same call (detector 8), but
+ * a run can also burn money with calls that honestly differ. This brake
+ * looks only at what the backend REPORTED the run sent, whatever the calls
+ * were:
+ *
+ * - One request at or above LARGE_REQUEST_TOKENS gets a notice once per run:
+ * each further step re-reads that much again.
+ * - The run's summed input reaching RUN_HALT_TOKENS ends the run, with a
+ * plain sentence that says how much it sent and that a new message goes
+ * on from here.
+ *
+ * Only providers that bill (isPaidProvider) are braked; a model on this
+ * machine or in the LAN costs nothing per token. The loop guard switch (C44,
+ * Settings → Agent Permissions) is respected: with the guard off, the brake
+ * never ends a run, it only says once that the limit has been passed.
+ */
+
+export const LARGE_REQUEST_TOKENS = 400_000
+export const RUN_HALT_TOKENS = 3_000_000
+
+export type CostBrakeVerdict =
+ | { action: 'ok' }
+ | { action: 'warn'; message: string }
+ | { action: 'halt'; reason: string; message: string }
+
+const fmtTokens = (n: number): string =>
+ n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : `${Math.round(n / 1000)}k`
+
+export class AgentCostBrake {
+ private readonly paid: boolean
+ private readonly mayHalt: boolean
+ private readonly largeAt: number
+ private readonly haltAt: number
+ private sum = 0
+ private calls = 0
+ private largeWarned = false
+ private sumWarned = false
+ private pending: CostBrakeVerdict = { action: 'ok' }
+
+ constructor(opts: { paid: boolean; loopGuardEnabled?: boolean; largeRequestTokens?: number; runHaltTokens?: number }) {
+ this.paid = opts.paid
+ this.mayHalt = opts.loopGuardEnabled !== false
+ this.largeAt = opts.largeRequestTokens ?? LARGE_REQUEST_TOKENS
+ this.haltAt = opts.runHaltTokens ?? RUN_HALT_TOKENS
+ }
+
+ /** Input tokens summed over this run so far, as reported by the backend. */
+ get inputTokens(): number {
+ return this.sum
+ }
+
+ /**
+ * One model call's reported input. A call without a count adds nothing:
+ * the brake never guesses, the same rule as the usage line under an answer.
+ */
+ record(promptTokens: number | undefined): void {
+ if (!this.paid) return
+ const n = typeof promptTokens === 'number' && Number.isFinite(promptTokens) && promptTokens > 0 ? Math.round(promptTokens) : 0
+ if (n === 0) return
+ this.sum += n
+ this.calls++
+ if (this.sum >= this.haltAt) {
+ if (this.mayHalt) {
+ this.pending = {
+ action: 'halt',
+ reason: `cost brake: this run sent ${fmtTokens(this.sum)} tokens of input in ${this.calls} model calls (limit ${fmtTokens(this.haltAt)})`,
+ message:
+ `Stopped to protect your credits: this run has sent ${fmtTokens(this.sum)} tokens to the model in ${this.calls} steps, ` +
+ `the latest step alone ${fmtTokens(n)}. Every step re-reads the whole conversation, so long runs get expensive fast. ` +
+ 'Send a new message to go on, or start a new chat to begin with a small context.',
+ }
+ return
+ }
+ if (!this.sumWarned) {
+ this.sumWarned = true
+ this.pending = {
+ action: 'warn',
+ message:
+ `This run has now sent ${fmtTokens(this.sum)} tokens to the model in ${this.calls} steps. ` +
+ 'The loop guard is switched off, so it keeps going until you press Stop.',
+ }
+ return
+ }
+ }
+ if (n >= this.largeAt && !this.largeWarned) {
+ this.largeWarned = true
+ this.pending = {
+ action: 'warn',
+ message:
+ `Large request: this step sent ${fmtTokens(n)} tokens to the model. Every further step sends about as much again, ` +
+ 'and that is what you pay for. A new chat, or Compact, makes the next steps much cheaper.',
+ }
+ }
+ }
+
+ /** The verdict since the last take(), then cleared. Halt stays sticky. */
+ take(): CostBrakeVerdict {
+ const v = this.pending
+ if (v.action !== 'halt') this.pending = { action: 'ok' }
+ return v
+ }
+}
diff --git a/src/lib/agent-loop-guard.ts b/src/lib/agent-loop-guard.ts
index 6cac7a4c..e09f2ab2 100644
--- a/src/lib/agent-loop-guard.ts
+++ b/src/lib/agent-loop-guard.ts
@@ -63,6 +63,17 @@
* status and counted as neither success nor failure, so it reset detector
* 5 and never fed detector 6. Steer at 3 per command, halt at 6. A
* declined call also no longer counts as a success anywhere.
+ *
+ * 8. Near-identical silent batches (C83, tid2110 10.11.2026): 233 tool
+ * calls of one tool, one every ~4 s, no text at all, each request
+ * 420-447k tokens of input on a paid model. The arguments were 487-492
+ * characters and never byte-identical, so detectors 1-3 never saw a
+ * repeat. This one compares each batch with the one before it: same
+ * tool, arguments at least NEAR_SIMILARITY alike (character bigrams),
+ * and no new text from the model in between. Steer at NEAR_STEER_AT
+ * such batches in a row, halt at NEAR_HALT_AT. A read that only pages
+ * on (the arguments differ in numbers alone) is not counted, and any
+ * new text, a different tool or clearly different arguments start over.
*/
/*
@@ -134,6 +145,52 @@ const SEARCH_TOOLS = new Set<string>(['web_search'])
const SEARCH_STEER_AT = 6
const SEARCH_HALT_AT = 12
+/**
+ * Detector 8 (C83). Five silent near-copies in a row get one word, eight end
+ * the run. In the incident that is 8 calls instead of 233.
+ */
+const NEAR_SIMILARITY = 0.85
+const NEAR_STEER_AT = 5
+const NEAR_HALT_AT = 8
+
+/** Lower-cased, whitespace folded: the form two near-copies are compared in. */
+function normArgs(args: string): string {
+ return args.toLowerCase().replace(/\s+/g, ' ').trim()
+}
+
+function bigrams(s: string): Map<string, number> {
+ const m = new Map<string, number>()
+ for (let i = 0; i < s.length - 1; i++) {
+ const g = s.slice(i, i + 2)
+ m.set(g, (m.get(g) ?? 0) + 1)
+ }
+ return m
+}
+
+/**
+ * Sørensen–Dice over character bigrams, 0..1. Linear in the length, so a
+ * pair of 500-character argument strings costs nothing per step.
+ */
+export function argSimilarity(a: string, b: string): number {
+ const x = normArgs(a)
+ const y = normArgs(b)
+ if (x === y) return 1
+ if (x.length < 2 || y.length < 2) return 0
+ const ga = bigrams(x)
+ const gb = bigrams(y)
+ let both = 0
+ for (const [g, n] of ga) {
+ const m = gb.get(g)
+ if (m) both += Math.min(n, m)
+ }
+ return (2 * both) / (x.length - 1 + (y.length - 1))
+}
+
+/** Arguments that differ in numbers alone: an offset, a page, a line range. */
+function onlyNumbersDiffer(a: string, b: string): boolean {
+ return a !== b && a.replace(/\d+/g, '#') === b.replace(/\d+/g, '#')
+}
+
/** Tools whose args carry a shell command whose first token names the work. */
const EXEC_TOOLS = new Set<string>(['shell_execute', 'shell_execute_background'])
@@ -203,6 +260,17 @@ export class AgentLoopGuard {
/** Detector 7: how often in a row the user declined the same command or tool. */
private declinedStreaks = new Map<string, number>()
private declinedSteeredKeys = new Set<string>()
+ /** Detector 8: the batch before, and how many silent near-copies in a row. */
+ private prevBatch: Array<{ name: string; args: string }> | null = null
+ private nearStreak = 0
+ private nearSteered = false
+ /**
+ * What recordNarration saw for the step now being recorded: true when the
+ * model wrote nothing new (no text, or the same text as the step before).
+ * Null when recordNarration was not called for it, which counts as silent:
+ * the guard can only judge the text it is shown.
+ */
+ private stepSilent: boolean | null = null
/**
* Record one iteration's tool-call batch BEFORE executing it. `args` must
@@ -259,6 +327,8 @@ export class AgentLoopGuard {
this.searchStreak = 0
this.searchSteered = false
}
+ const near = this.recordNear(calls)
+ if (near.action === 'halt') return near
const keys = calls.map((c) => `${c.name}|${c.args}`)
const sig = [...keys].sort().join('||')
const trimmed = opts.trimmedReadKeys
@@ -343,7 +413,65 @@ export class AgentLoopGuard {
this.readCounts.clear()
this.pureWindow = []
}
- return steer ?? { action: 'ok' }
+ return steer ?? (near.action === 'steer' ? near : { action: 'ok' })
+ }
+
+ /**
+ * Detector 8: is this batch a silent near-copy of the one before it? Every
+ * call must have a partner in the previous batch with the same tool and
+ * arguments at least NEAR_SIMILARITY alike. Byte-identical partners count
+ * too, so an exact repeat that slips past detector 1 (A, A', A, A') still
+ * lands here.
+ */
+ private recordNear(calls: Array<{ name: string; args: string }>): LoopGuardVerdict {
+ const silent = this.stepSilent !== false
+ this.stepSilent = null
+ // Searches differ by a word on purpose and have their own ladder above.
+ if (calls.every((c) => SEARCH_TOOLS.has(c.name))) {
+ this.prevBatch = null
+ this.nearStreak = 0
+ this.nearSteered = false
+ return { action: 'ok' }
+ }
+ const prev = this.prevBatch
+ this.prevBatch = calls.map((c) => ({ name: c.name, args: c.args }))
+ const alike =
+ silent &&
+ prev !== null &&
+ calls.every((c) =>
+ prev.some(
+ (p) =>
+ p.name === c.name &&
+ !(READ_ONLY_TOOLS.has(c.name) && onlyNumbersDiffer(normArgs(p.args), normArgs(c.args))) &&
+ argSimilarity(p.args, c.args) >= NEAR_SIMILARITY,
+ ),
+ )
+ if (!alike) {
+ // The first batch of a new streak is its first member.
+ this.nearStreak = 1
+ this.nearSteered = false
+ return { action: 'ok' }
+ }
+ this.nearStreak++
+ const names = [...new Set(calls.map((c) => c.name))].join(', ')
+ if (this.nearStreak >= NEAR_HALT_AT) {
+ return {
+ action: 'halt',
+ reason: `${this.nearStreak} nearly identical ${names} calls in a row with no new text from the model`,
+ }
+ }
+ if (this.nearStreak >= NEAR_STEER_AT && !this.nearSteered) {
+ this.nearSteered = true
+ return {
+ action: 'steer',
+ message:
+ `You have now sent ${this.nearStreak} nearly identical ${names} calls in a row without writing anything. ` +
+ 'Changing a few characters does not make it a new step: the results will not change either. ' +
+ 'Stop calling it. Say in one or two sentences what you found and what is blocking you, then either take a clearly different step or give your final answer. ' +
+ 'The same call again ends the run.',
+ }
+ }
+ return { action: 'ok' }
}
/**
@@ -463,6 +591,8 @@ export class AgentLoopGuard {
recordNarration(text: string): LoopGuardVerdict {
if (!this.enabled) return { action: 'ok' }
const norm = text.trim().replace(/\s+/g, ' ').toLowerCase()
+ // Detector 8 (C83): text the step before did not already have is news.
+ this.stepSilent = norm.length < MIN_NARRATION_LEN || norm === this.lastNarration
if (norm.length < MIN_NARRATION_LEN) {
this.lastNarration = ''
this.narrationSeen = 0