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.

feat(agent): credit brake per task and per hour, visible; read-only shell repeats count; limits locked from the agent (CA)

purpledf0ea301113f
diff --git a/src/components/chat/ChatNotices.tsx b/src/components/chat/ChatNotices.tsx
index 2e810c79..ea6dc89c 100644
--- a/src/components/chat/ChatNotices.tsx
+++ b/src/components/chat/ChatNotices.tsx
@@ -11,7 +11,7 @@
* fuer Anmerkungen und Fehler vorschreibt: eine Zeile, kein Kasten, ruhiges
* Grau oder Rot, und ein x, das sie wegnimmt.
*/
-import { AlertCircle, AtSign, Binary, Bot, Download, FileText, FolderOpen, ImageOff, Images, Paperclip, RotateCcw, Scissors } from 'lucide-react'
+import { AlertCircle, AtSign, Binary, Coins, Bot, Download, FileText, FolderOpen, ImageOff, Images, Paperclip, RotateCcw, Scissors } from 'lucide-react'
import { Hinweis } from '../ui/Hinweis'
import { useChatNoticeStore, CONVERSATION_BOUND, type ChatNoticeId } from '../../stores/chatNoticeStore'
import { COMPOSER_MAX_W } from './composer-width'
@@ -35,6 +35,7 @@ const ICON: Record<ChatNoticeId, typeof Paperclip> = {
'file-mention': AtSign,
rewind: RotateCcw,
'agent-start-failed': AlertCircle,
+ 'cost-brake': Coins,
}
diff --git a/src/components/settings/CreditLimitSettings.tsx b/src/components/settings/CreditLimitSettings.tsx
new file mode 100644
index 00000000..33c9d609
--- /dev/null
+++ b/src/components/settings/CreditLimitSettings.tsx
@@ -0,0 +1,45 @@
+// The two credit limits of agent runs (CA, 14.11.2026; lib/agent-cost-brake.ts).
+//
+// Customers lost hundreds of thousands of credits to agent runs nobody was
+// watching. A run now pauses at a limit per task and at a limit per hour,
+// says how much it used, and goes on when the user sends "continue".
+
+import { useSettingsStore } from '../../stores/settingsStore'
+import { HOUR_CREDIT_LIMIT, RUN_CREDIT_LIMIT } from '../../lib/agent-cost-brake'
+
+const RUN_CHOICES = [25_000, 50_000, 100_000, 250_000, 500_000, 0]
+const HOUR_CHOICES = [100_000, 250_000, 500_000, 1_000_000, 0]
+
+const label = (n: number) => (n === 0 ? 'No limit' : `${n.toLocaleString('en-US')} credits`)
+
+function Row({ id, title, value, choices, onPick }: { id: string; title: string; value: number; choices: number[]; onPick: (n: number) => void }) {
+ return (
+ <div className="flex items-center justify-between gap-3 py-0.5">
+ <label htmlFor={id} className="t-control text-gray-700 dark:text-gray-300">{title}</label>
+ <select
+ id={id}
+ data-testid={id}
+ value={value}
+ onChange={(e) => onPick(Number(e.target.value))}
+ className="t-micro px-1.5 py-0.5 rounded bg-transparent border border-gray-300 dark:border-white/15 text-gray-700 dark:text-gray-300 focus:outline-none"
+ >
+ {choices.map((n) => <option key={n} value={n}>{label(n)}</option>)}
+ </select>
+ </div>
+ )
+}
+
+export function CreditLimitSettings() {
+ const run = useSettingsStore((s) => s.settings.agentRunCreditLimit ?? RUN_CREDIT_LIMIT)
+ const hour = useSettingsStore((s) => s.settings.agentHourCreditLimit ?? HOUR_CREDIT_LIMIT)
+ const update = useSettingsStore((s) => s.updateSettings)
+ return (
+ <div className="pt-1" data-testid="credit-limits">
+ <Row id="credit-limit-task" title="Pause a task at" value={run} choices={RUN_CHOICES} onPick={(n) => update({ agentRunCreditLimit: n })} />
+ <Row id="credit-limit-hour" title="Pause all agent runs per hour at" value={hour} choices={HOUR_CHOICES} onPick={(n) => update({ agentHourCreditLimit: n })} />
+ <div className="t-micro text-gray-500 dark:text-gray-500 leading-relaxed pt-0.5">
+ LU Cloud only. The agent pauses, says how many credits it used, and goes on when you send &quot;continue&quot;. A Hosted plan has 900,000 credits a month.
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index 5d0849bf..7b6415a8 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -1,4 +1,5 @@
import { SkillsSettings } from './SkillsSettings'
+import { CreditLimitSettings } from './CreditLimitSettings'
import { CommandRulesSettings } from './CommandRulesSettings'
import { useState, useEffect, useLayoutEffect, useRef, type ReactNode, type ChangeEvent } from 'react'
import { withDetail } from '../../lib/error-text'
@@ -2466,6 +2467,7 @@ export function SettingsPage() {
<div className="t-micro text-gray-500 dark:text-gray-500 leading-relaxed pt-0.5">
Stops an agent run that keeps repeating the same steps (&quot;Loop guard halted the run&quot;). Off: the run goes on until its step limit or until you press Stop.
</div>
+ <CreditLimitSettings />
{/* C59 A2: the compact profile for local models, on by default. */}
<InlineToggle
label="Short tool list for local models"
diff --git a/src/hooks/__tests__/c83-the-incident-run-ends.test.ts b/src/hooks/__tests__/c83-the-incident-run-ends.test.ts
index 8f099573..26b2cf73 100644
--- a/src/hooks/__tests__/c83-the-incident-run-ends.test.ts
+++ b/src/hooks/__tests__/c83-the-incident-run-ends.test.ts
@@ -133,7 +133,7 @@ describe('C83: the incident run, end to end', () => {
expect(requests).toBeLessThanOrEqual(8)
expect(notes.some((n) => /^⚠ Large request: this step sent 4\d\dk tokens/.test(n))).toBe(true)
expect(notes.some((n) => /^⛔ Stopped to protect your credits/.test(n))).toBe(true)
- expect(answer.content).toMatch(/Stopped to protect your credits: this run has sent 3\.\dM tokens/)
+ expect(answer.content).toMatch(/Stopped to protect your credits: this run has sent 2\.\dM tokens/)
})
it('without usage numbers: the near-copy detector ends it on the 8th', { timeout: 60_000 }, async () => {
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 01bfd99c..6c43bb07 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -1,4 +1,5 @@
import { stripSourcesMarker } from '../lib/web-evidence'
+import { billingOf, creditRatesOf } from '../lib/agent-core/credit-rates'
import { canonicalArgs, repeatLabel, skippedRepeatsNote } from '../lib/agent-core/repeat-note'
import { replayableReasoning } from '../lib/agent-core/reasoning-replay'
import { useRef, useState, useCallback, useEffect } from 'react'
@@ -1714,6 +1715,11 @@ export function useAgentChat() {
const costBrake = new AgentCostBrake({
paid: isPaidProvider(providerId, sendsToALanBackend(providerId, activeModel)),
loopGuardEnabled: useSettingsStore.getState().settings.agentLoopGuard !== false,
+ // CA (14.11.2026): credits per task and per hour, priced from the
+ // model's declared rates (LU Cloud catalogue).
+ rates: creditRatesOf(activeModel),
+ runCreditLimit: useSettingsStore.getState().settings.agentRunCreditLimit,
+ hourCreditLimit: useSettingsStore.getState().settings.agentHourCreditLimit,
})
// 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
@@ -2381,7 +2387,7 @@ export function useAgentChat() {
})
}
requestUsage.add(turn)
- costBrake.record(turn.promptEvalCount)
+ costBrake.record(turn.promptEvalCount, { output: turn.evalCount, billing: billingOf(turn) })
// Native thinking field (Ollama; LU Cloud reasoning_content)
if (turn.thinking) turnThinking = turn.thinking
@@ -2475,7 +2481,7 @@ export function useAgentChat() {
// abschneiden, und dann steht hier ebenfalls kein Werkzeugaufruf.
turnFinishReason = hermesTurn.finishReason
requestUsage.add(hermesTurn)
- costBrake.record(hermesTurn.promptEvalCount)
+ costBrake.record(hermesTurn.promptEvalCount, { output: hermesTurn.evalCount, billing: billingOf(hermesTurn) })
notePhoneCount(hermesTurn.promptEvalCount)
if (hermesTurn.thinking) {
turnThinking = turnThinking
@@ -3062,6 +3068,7 @@ export function useAgentChat() {
id: uuid(), phase: 'reflection', content: `⛔ ${brake.message}`, timestamp: Date.now(),
})
log.warn('agent.cost_brake_halt', { provider: providerId, inputTokens: costBrake.inputTokens })
+ useChatNoticeStore.getState().show('cost-brake', brake.message, 'ruhig')
break
}
if (brake.action === 'warn') {
@@ -3069,6 +3076,8 @@ export function useAgentChat() {
id: uuid(), phase: 'reflection', content: `⚠ ${brake.message}`, timestamp: Date.now(),
})
log.info('agent.cost_brake_warn', { provider: providerId, inputTokens: costBrake.inputTokens })
+ // Visible where the user looks, not only inside the folded steps.
+ useChatNoticeStore.getState().show('cost-brake', brake.message, 'ruhig')
}
const pendingSteer = batchVerdict.action === 'steer' ? batchVerdict.message : null
if (pendingSteer) {
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index e4bd5c4d..04e8fb82 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -1,4 +1,5 @@
import { stripSourcesMarker } from '../lib/web-evidence'
+import { billingOf, creditRatesOf } from '../lib/agent-core/credit-rates'
import { replayableReasoning } from '../lib/agent-core/reasoning-replay'
import { NOT_IN_CODE_TAB } from '../lib/browser-tools'
import { useRef, useState, useCallback } from 'react'
@@ -1280,6 +1281,11 @@ export function useCodex() {
const costBrake = new AgentCostBrake({
paid: isPaidProvider(providerId, sendsToALanBackend(providerId, activeModel)),
loopGuardEnabled: useSettingsStore.getState().settings.agentLoopGuard !== false,
+ // CA (14.11.2026): credits per task and per hour, priced from the
+ // model's declared rates (LU Cloud catalogue).
+ rates: creditRatesOf(activeModel),
+ runCreditLimit: useSettingsStore.getState().settings.agentRunCreditLimit,
+ hourCreditLimit: useSettingsStore.getState().settings.agentHourCreditLimit,
})
// Which read produced which result message. The request builder reports
// back the results it sent CAPPED, and this map turns those messages
@@ -1776,7 +1782,7 @@ export function useCodex() {
turnFinishReason = turn.doneReason
reportTurnUsage(convId!, assistantMsg.id, turn)
requestUsage.add(turn)
- costBrake.record(turn.promptEvalCount)
+ costBrake.record(turn.promptEvalCount, { output: turn.evalCount, billing: billingOf(turn) })
diagLog('streamWithTools-return', {
iter: i,
toolCallsCount: toolCalls.length,
@@ -1835,7 +1841,7 @@ export function useCodex() {
turnFinishReason = turn.finishReason
reportTurnUsage(convId!, assistantMsg.id, turn)
requestUsage.add(turn)
- costBrake.record(turn.promptEvalCount)
+ costBrake.record(turn.promptEvalCount, { output: turn.evalCount, billing: billingOf(turn) })
// 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
@@ -1975,7 +1981,7 @@ export function useCodex() {
// Gleiche Stelle wie in useAgentChat.
turnFinishReason = hermesTurn.finishReason
requestUsage.add(hermesTurn)
- costBrake.record(hermesTurn.promptEvalCount)
+ costBrake.record(hermesTurn.promptEvalCount, { output: hermesTurn.evalCount, billing: billingOf(hermesTurn) })
if (keepThinking && hermesTurn.thinking) {
thinkingContent += (thinkingContent ? '\n\n' : '') + hermesTurn.thinking
useChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, thinkingContent)
@@ -2324,11 +2330,14 @@ export function useCodex() {
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() })
+ useChatNoticeStore.getState().show('cost-brake', brake.message, 'ruhig')
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() })
+ // Visible where the user looks, not only inside the folded steps.
+ useChatNoticeStore.getState().show('cost-brake', brake.message, 'ruhig')
}
// Steer is appended AFTER this iteration's assistant+tool messages
// (audit F2). Pushed here it landed chronologically BEFORE the calls
diff --git a/src/lib/__tests__/a-find-repeated-is-a-repeat.test.ts b/src/lib/__tests__/a-find-repeated-is-a-repeat.test.ts
new file mode 100644
index 00000000..f9987b2b
--- /dev/null
+++ b/src/lib/__tests__/a-find-repeated-is-a-repeat.test.ts
@@ -0,0 +1,76 @@
+/**
+ * CA (14.11.2026), measured with LU's own engine: the reports were not where
+ * the model looked, and it sent the same `find` nine times in 26 calls. Every
+ * shell call counted as a possible change and reset the read counter, so only
+ * four identical calls in a row ended it. Inspection-only commands count as
+ * reads now.
+ */
+import { describe, it, expect } from 'vitest'
+import { AgentLoopGuard, isInspectionShell } from '../agent-loop-guard'
+
+const sh = (command: string) => ({ name: 'shell_execute', args: JSON.stringify({ command, cwd: '/ws/LP1', timeout: 60000 }) })
+
+describe('isInspectionShell', () => {
+ it('reads', () => {
+ for (const c of [
+ 'find . -type f -name "*.json" 2>/dev/null',
+ 'find . -type d 2>/dev/null | head -20',
+ 'ls -la',
+ 'grep -rn "slugify" src | head',
+ 'cat package.json',
+ 'git status',
+ 'wc -l src/*.ts',
+ ]) expect(isInspectionShell(JSON.stringify({ command: c })), c).toBe(true)
+ })
+
+ it('anything that can write or chain is not a read', () => {
+ for (const c of [
+ 'find . -name "*.tmp" -delete',
+ 'find . -name "*.js" -exec rm {} +',
+ 'find . | xargs rm',
+ 'ls > listing.txt',
+ 'cat a.txt; rm b.txt',
+ 'ls && npm install',
+ 'echo $(whoami)',
+ 'mkdir -p data/reports && ls -la data/reports',
+ 'npm test',
+ 'sed -i s/a/b/ f.txt',
+ 'cat x | tee y',
+ ]) expect(isInspectionShell(JSON.stringify({ command: c })), c).toBe(false)
+ })
+})
+
+describe('the measured run', () => {
+ // The order of the real trace (loop-nachher-lokal LP2), shell calls only.
+ const TRACE = [
+ 'find . -type d -name "reports" 2>/dev/null',
+ 'find . -name "*.json" -type f 2>/dev/null',
+ 'ls -la',
+ 'find . -type d 2>/dev/null | head -20',
+ 'find . -type d -name "data" 2>/dev/null',
+ 'find . -type f -name "*.json" 2>/dev/null',
+ 'find . -type f \\( -name "*.json" -o -name "*report*" \\) 2>/dev/null',
+ 'find . -type d 2>/dev/null',
+ 'find . -type f -name "*.json" 2>/dev/null',
+ 'find . -type f -name "*.json" 2>/dev/null',
+ 'find . -type d -name "reports" 2>/dev/null',
+ 'find . -type d 2>/dev/null',
+ 'find . -type f -name "*.json" 2>/dev/null',
+ 'find . -type f -name "*.json" 2>/dev/null',
+ ]
+
+ it('steers at the third identical find and ends at the fifth, not after 25 calls', () => {
+ const g = new AgentLoopGuard()
+ const verdicts: string[] = []
+ for (const c of TRACE) {
+ const v = g.recordBatch([sh(c)])
+ verdicts.push(v.action)
+ if (v.action === 'halt') break
+ }
+ // The json find is at 5, 8, 9, 12 and 13: steer at its third; the halt comes
+ // by its fifth at the latest (the window detector may end it a step sooner).
+ expect(verdicts.indexOf('steer')).toBe(9)
+ expect(verdicts[verdicts.length - 1]).toBe('halt')
+ expect(verdicts.length).toBeLessThanOrEqual(14)
+ })
+})
diff --git a/src/lib/__tests__/c83-agent-loop-credits.test.ts b/src/lib/__tests__/c83-agent-loop-credits.test.ts
index b3890f47..894c38da 100644
--- a/src/lib/__tests__/c83-agent-loop-credits.test.ts
+++ b/src/lib/__tests__/c83-agent-loop-credits.test.ts
@@ -142,7 +142,7 @@ describe('C83: the cost brake', () => {
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(/Stopped to protect your credits: this run has sent 2\.\dM tokens/)
expect(h.action === 'halt' && h.message).toMatch(/Send a new message to go on/)
})
@@ -165,7 +165,7 @@ describe('C83: the cost brake', () => {
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 }, () => {
+ const actions = Array.from({ length: 40 }, () => {
b.record(LARGE_REQUEST_TOKENS + 10_000)
return b.take().action
})
@@ -179,6 +179,7 @@ describe('C83: the cost brake', () => {
b.record(0)
expect(b.inputTokens).toBe(0)
expect(b.take().action).toBe('ok')
- expect(RUN_HALT_TOKENS).toBe(3_000_000)
+ // CA (14.11.2026): 3M let the incidents of that week through.
+ expect(RUN_HALT_TOKENS).toBe(2_000_000)
})
})
diff --git a/src/lib/__tests__/credits-pause-a-task-and-an-hour.test.ts b/src/lib/__tests__/credits-pause-a-task-and-an-hour.test.ts
new file mode 100644
index 00000000..7a05fd3c
--- /dev/null
+++ b/src/lib/__tests__/credits-pause-a-task-and-an-hour.test.ts
@@ -0,0 +1,78 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * CA (14.11.2026): nine paying customers lost credits to agent runs nobody
+ * watched. A task now pauses at a credit limit and all agent runs together at
+ * an hourly one, priced from the model's declared rates.
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { AgentCostBrake, HOUR_CREDIT_LIMIT, RUN_CREDIT_LIMIT } from '../agent-cost-brake'
+import { _resetCreditLedger, hourCredits } from '../agent-core/credit-ledger'
+
+// direct/deepseek-v4.1-flash-like price: a 30k step costs ~600 credits.
+const RATES = { inputPerMillion: 20_000, outputPerMillion: 60_000 }
+
+beforeEach(() => _resetCreditLedger())
+afterEach(() => _resetCreditLedger())
+
+describe('per task', () => {
+ it('a normal step is well under the limit and says nothing', () => {
+ const b = new AgentCostBrake({ paid: true, rates: RATES })
+ b.record(30_000, { output: 300, billing: 'credits' })
+ expect(b.take().action).toBe('ok')
+ expect(b.creditsUsed).toBe(618)
+ })
+
+ it('tells at half, pauses at the limit, with the amount in credits and euros', () => {
+ const b = new AgentCostBrake({ paid: true, rates: RATES, runCreditLimit: 10_000, hourCreditLimit: 0 })
+ const seen: string[] = []
+ for (let i = 0; i < 40; i++) {
+ b.record(30_000, { output: 300, billing: 'credits' })
+ const v = b.take()
+ if (v.action !== 'ok') seen.push(`${v.action}: ${v.message}`)
+ if (v.action === 'halt') break
+ }
+ expect(seen[0]).toMatch(/^warn: This task has used up to \d,000 credits so far \(under 1 €\)\. It pauses at 10,000\./)
+ expect(seen[seen.length - 1]).toMatch(/^halt: Paused to protect your credits: this task has used up to 1\d,000 credits \(under 1 €\)/)
+ expect(seen[seen.length - 1]).toMatch(/Send "continue"/)
+ })
+
+ it('a Flash step on the free allowance costs no credits', () => {
+ const b = new AgentCostBrake({ paid: true, rates: RATES, runCreditLimit: 1_000 })
+ for (let i = 0; i < 20; i++) b.record(30_000, { output: 300, billing: 'flash' })
+ expect(b.creditsUsed).toBe(0)
+ expect(b.take().action).toBe('ok')
+ })
+
+ it('without a declared price it counts tokens only, as before', () => {
+ const b = new AgentCostBrake({ paid: true })
+ b.record(30_000, { output: 300 })
+ expect(b.creditsUsed).toBe(0)
+ })
+
+ it('0 switches the task limit off', () => {
+ const b = new AgentCostBrake({ paid: true, rates: RATES, runCreditLimit: 0, hourCreditLimit: 0 })
+ for (let i = 0; i < 60; i++) { b.record(30_000, { billing: 'credits' }); expect(b.take().action).toBe('ok') }
+ })
+
+ it('the defaults', () => {
+ expect(RUN_CREDIT_LIMIT).toBe(100_000)
+ expect(HOUR_CREDIT_LIMIT).toBe(250_000)
+ })
+})
+
+describe('per hour, across runs', () => {
+ it('many short runs together pause once, then the user decides', () => {
+ const verdicts: string[] = []
+ for (let run = 0; run < 20; run++) {
+ const b = new AgentCostBrake({ paid: true, rates: RATES, runCreditLimit: 0, hourCreditLimit: 20_000 })
+ for (let i = 0; i < 5; i++) {
+ b.record(30_000, { billing: 'credits' })
+ const v = b.take()
+ if (v.action === 'halt') { verdicts.push(`run ${run}`); break }
+ }
+ }
+ expect(verdicts).toHaveLength(1)
+ expect(hourCredits()).toBeGreaterThan(20_000)
+ })
+})
diff --git a/src/lib/agent-core/credit-ledger.ts b/src/lib/agent-core/credit-ledger.ts
new file mode 100644
index 00000000..55d55269
--- /dev/null
+++ b/src/lib/agent-core/credit-ledger.ts
@@ -0,0 +1,69 @@
+/**
+ * Credits agent runs used in the last hour, across runs and chats (CA,
+ * 14.11.2026).
+ *
+ * The per-run brake cannot see a customer who starts run after run: in the
+ * support logs of that week one account sent 627 requests in 102 minutes,
+ * a few hundred per run. This ledger keeps an upper-bound estimate of the
+ * credits every paid agent step used, for one rolling hour, and survives a
+ * restart (localStorage, wrapped: a failing store only means a fresh hour).
+ */
+const KEY = 'lu-agent-credit-hour'
+const HOUR_MS = 60 * 60 * 1000
+
+interface Entry { at: number; credits: number }
+interface State { entries: Entry[]; pausedAt: number | null }
+
+function load(): State {
+ try {
+ const raw = globalThis.localStorage?.getItem(KEY)
+ if (!raw) return { entries: [], pausedAt: null }
+ const s = JSON.parse(raw) as Partial<State>
+ return {
+ entries: Array.isArray(s.entries) ? s.entries.filter((e) => typeof e?.at === 'number' && typeof e?.credits === 'number') : [],
+ pausedAt: typeof s.pausedAt === 'number' ? s.pausedAt : null,
+ }
+ } catch {
+ return { entries: [], pausedAt: null }
+ }
+}
+
+function save(s: State): void {
+ try { globalThis.localStorage?.setItem(KEY, JSON.stringify(s)) } catch { /* a fresh hour is the safe failure */ }
+}
+
+function prune(s: State, now: number): State {
+ return { entries: s.entries.filter((e) => now - e.at < HOUR_MS), pausedAt: s.pausedAt !== null && now - s.pausedAt < HOUR_MS ? s.pausedAt : null }
+}
+
+/** Add one step's credits; returns the sum over the last hour. */
+export function addHourCredits(credits: number, now: number = Date.now()): number {
+ const s = prune(load(), now)
+ if (credits > 0) s.entries.push({ at: now, credits })
+ save(s)
+ return s.entries.reduce((a, e) => a + e.credits, 0)
+}
+
+/** Sum over the last hour, without adding. */
+export function hourCredits(now: number = Date.now()): number {
+ return prune(load(), now).entries.reduce((a, e) => a + e.credits, 0)
+}
+
+/**
+ * The hourly pause fires once per hour: after it, the user's next message is
+ * the go-ahead, and the next pause comes an hour later at the earliest.
+ */
+export function hourPauseDue(now: number = Date.now()): boolean {
+ return prune(load(), now).pausedAt === null
+}
+
+export function markHourPause(now: number = Date.now()): void {
+ const s = prune(load(), now)
+ s.pausedAt = now
+ save(s)
+}
+
+/** Tests only. */
+export function _resetCreditLedger(): void {
+ try { globalThis.localStorage?.removeItem(KEY) } catch { /* nothing to reset */ }
+}
diff --git a/src/lib/agent-core/credit-rates.ts b/src/lib/agent-core/credit-rates.ts
new file mode 100644
index 00000000..48571e7e
--- /dev/null
+++ b/src/lib/agent-core/credit-rates.ts
@@ -0,0 +1,21 @@
+/**
+ * The credit price a model's catalogue entry declares (LU Cloud), for the
+ * cost brake. Null for every model without one: the brake then counts tokens
+ * only, as before.
+ */
+import { useModelStore } from '../../stores/modelStore'
+import type { CreditRates } from '../../api/providers/types'
+
+export function creditRatesOf(model: string | null | undefined): CreditRates | null {
+ if (!model) return null
+ const meta = useModelStore.getState().models.find((m) => m.name === model) as { creditRates?: CreditRates } | undefined
+ const r = meta?.creditRates
+ if (!r || typeof r.inputPerMillion !== 'number' || typeof r.outputPerMillion !== 'number') return null
+ return r
+}
+
+/** How LU Cloud billed one step ('flash' cost no credits), from any turn shape. */
+export function billingOf(turn: unknown): 'flash' | 'credits' | undefined {
+ const b = turn && typeof turn === 'object' ? (turn as { billing?: unknown }).billing : undefined
+ return b === 'flash' || b === 'credits' ? b : undefined
+}
diff --git a/src/lib/agent-cost-brake.ts b/src/lib/agent-cost-brake.ts
index 2b47c27c..23cd57f3 100644
--- a/src/lib/agent-cost-brake.ts
+++ b/src/lib/agent-cost-brake.ts
@@ -1,3 +1,6 @@
+import type { CreditRates } from '../api/providers/types'
+import { HOSTED_CREDITS_PER_EUR } from './cloud-pitch'
+import { addHourCredits, hourPauseDue, markHourPause } from './agent-core/credit-ledger'
/**
* Cost brake for one agent run (C83).
*
@@ -21,14 +24,35 @@
* 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
+// CA (14.11.2026): 400k and 3M let the incidents of that week through. The
+// send cap keeps a paid step at 32k now, so a step past 64k is unusual and
+// worth a word, and 2M input per run is ~60 full steps at the cap.
+export const LARGE_REQUEST_TOKENS = 64_000
+export const RUN_HALT_TOKENS = 2_000_000
+
+/**
+ * Credits (CA, 14.11.2026). Where the model's catalogue entry declares its
+ * credit price (LU Cloud), every step is priced from the tokens the backend
+ * reported: an upper bound, because cached input is billed for less and the
+ * app does not learn by how much. One task may use up to RUN_CREDIT_LIMIT
+ * before it pauses and asks; all agent runs together up to HOUR_CREDIT_LIMIT
+ * in a rolling hour. Half of the run limit gets a visible notice.
+ * For scale: a Hosted plan carries 900,000 credits a month.
+ */
+export const RUN_CREDIT_LIMIT = 100_000
+export const HOUR_CREDIT_LIMIT = 250_000
export type CostBrakeVerdict =
| { action: 'ok' }
| { action: 'warn'; message: string }
| { action: 'halt'; reason: string; message: string }
+const fmtCredits = (n: number): string => (Math.round(n / 1000) * 1000).toLocaleString('en-US')
+const euros = (credits: number): string => {
+ const e = credits / HOSTED_CREDITS_PER_EUR
+ return e < 1 ? 'under 1 €' : `about ${e < 10 ? e.toFixed(1) : Math.round(e)} €`
+}
+
const fmtTokens = (n: number): string =>
n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : `${Math.round(n / 1000)}k`
@@ -42,12 +66,35 @@ export class AgentCostBrake {
private largeWarned = false
private sumWarned = false
private pending: CostBrakeVerdict = { action: 'ok' }
+ private readonly rates: CreditRates | null
+ private readonly runCreditLimit: number
+ private readonly hourCreditLimit: number
+ private credits = 0
+ private halfWarned = false
- constructor(opts: { paid: boolean; loopGuardEnabled?: boolean; largeRequestTokens?: number; runHaltTokens?: number }) {
+ constructor(opts: {
+ paid: boolean
+ loopGuardEnabled?: boolean
+ largeRequestTokens?: number
+ runHaltTokens?: number
+ /** The model's declared credit price (LU Cloud catalogue). */
+ rates?: CreditRates | null
+ /** 0 switches the credit limit off. */
+ runCreditLimit?: number
+ hourCreditLimit?: number
+ }) {
this.paid = opts.paid
this.mayHalt = opts.loopGuardEnabled !== false
this.largeAt = opts.largeRequestTokens ?? LARGE_REQUEST_TOKENS
this.haltAt = opts.runHaltTokens ?? RUN_HALT_TOKENS
+ this.rates = opts.rates && opts.rates.inputPerMillion >= 0 && opts.rates.outputPerMillion >= 0 ? opts.rates : null
+ this.runCreditLimit = opts.runCreditLimit ?? RUN_CREDIT_LIMIT
+ this.hourCreditLimit = opts.hourCreditLimit ?? HOUR_CREDIT_LIMIT
+ }
+
+ /** Credits this run used so far, upper bound; 0 without a declared price. */
+ get creditsUsed(): number {
+ return Math.round(this.credits)
}
/** Input tokens summed over this run so far, as reported by the backend. */
@@ -59,12 +106,48 @@ export class AgentCostBrake {
* 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 {
+ record(promptTokens: number | undefined, extra: { output?: number; billing?: 'flash' | 'credits' } = {}): 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++
+ // Credits, where the price is known and the step was billed in credits
+ // (a Flash step on the free allowance costs none).
+ if (this.rates && extra.billing !== 'flash') {
+ const out = typeof extra.output === 'number' && extra.output > 0 ? extra.output : 0
+ const step = (n * this.rates.inputPerMillion + out * this.rates.outputPerMillion) / 1_000_000
+ this.credits += step
+ const hour = addHourCredits(step)
+ if (this.mayHalt && this.runCreditLimit > 0 && this.credits >= this.runCreditLimit) {
+ this.pending = {
+ action: 'halt',
+ reason: `cost brake: this task used up to ${fmtCredits(this.credits)} credits in ${this.calls} steps (limit ${fmtCredits(this.runCreditLimit)})`,
+ message:
+ `Paused to protect your credits: this task has used up to ${fmtCredits(this.credits)} credits (${euros(this.credits)}) in ${this.calls} steps. ` +
+ 'Send "continue" to go on with the next ' + fmtCredits(this.runCreditLimit) + ', or change the limit in Settings → Agent.',
+ }
+ return
+ }
+ if (this.mayHalt && this.hourCreditLimit > 0 && hour >= this.hourCreditLimit && hourPauseDue()) {
+ markHourPause()
+ this.pending = {
+ action: 'halt',
+ reason: `cost brake: agent runs used up to ${fmtCredits(hour)} credits in the last hour (limit ${fmtCredits(this.hourCreditLimit)})`,
+ message:
+ `Paused to protect your credits: agent runs have used up to ${fmtCredits(hour)} credits (${euros(hour)}) in the last hour. ` +
+ 'Send "continue" to go on; the next pause comes in an hour at the earliest. The limit is in Settings → Agent.',
+ }
+ return
+ }
+ if (this.runCreditLimit > 0 && !this.halfWarned && this.credits >= this.runCreditLimit / 2) {
+ this.halfWarned = true
+ this.pending = {
+ action: 'warn',
+ message: `This task has used up to ${fmtCredits(this.credits)} credits so far (${euros(this.credits)}). It pauses at ${fmtCredits(this.runCreditLimit)}.`,
+ }
+ }
+ }
if (this.sum >= this.haltAt) {
if (this.mayHalt) {
this.pending = {
diff --git a/src/lib/agent-loop-guard.ts b/src/lib/agent-loop-guard.ts
index adbee509..4d0b6c68 100644
--- a/src/lib/agent-loop-guard.ts
+++ b/src/lib/agent-loop-guard.ts
@@ -224,6 +224,40 @@ const READ_ONLY_TOOLS = new Set<string>([
'git_diff',
])
+/**
+ * A shell command that only looks (CA, 14.11.2026). Measured in a real run
+ * with LU's own engine: the data was not where the model looked, and it sent
+ * `find . -type f -name "*.json" 2>/dev/null` nine times in 26 calls. Every
+ * shell call counted as "may have changed something", which reset the read
+ * counter each time, so only four identical calls IN A ROW ended it. A command
+ * built from inspection programs only, with no way to write, now counts as a
+ * read here. This list is for counting repeats, never for permission: what
+ * runs without asking is decided elsewhere (command-rules, Ask mode).
+ */
+const INSPECT_FIRST = /^(find|ls|cat|grep|rg|head|tail|wc|pwd|stat|file|du|tree|which|git\s+(status|log|diff|show|blame))(\s|$)/
+const INSPECT_PIPE = /^(head|tail|wc|sort|uniq|grep|rg|cut)(\s|$)/
+const NEVER_INSPECT = /;|&&|\|\||`|\$\(|<\(|\s-exec(dir)?\b|\s-delete\b|\s-ok\b|\bxargs\b|\btee\b|\s-i\b|--output/
+
+export function isInspectionShell(argsJson: string): boolean {
+ let command = ''
+ try {
+ const a = JSON.parse(argsJson) as { command?: unknown }
+ command = typeof a?.command === 'string' ? a.command : ''
+ } catch {
+ return false
+ }
+ const c = command.replace(/\s2>\s*\/dev\/null/g, ' ').replace(/\s2>&1/g, ' ').trim()
+ if (!c || NEVER_INSPECT.test(c) || />/.test(c)) return false
+ const parts = c.split('|').map((x) => x.trim())
+ if (parts.some((x) => !x)) return false
+ return INSPECT_FIRST.test(parts[0]) && parts.slice(1).every((x) => INSPECT_PIPE.test(x))
+}
+
+/** A call that only reads, for counting repeats. */
+function isReadCall(c: { name: string; args: string }): boolean {
+ return READ_ONLY_TOOLS.has(c.name) || (c.name === 'shell_execute' && isInspectionShell(c.args))
+}
+
export class AgentLoopGuard {
/** Off (Settings → Agent Permissions, C44): every verdict is `ok`, the run
* goes on until its step and tool call limits or the user's Stop. */
@@ -341,7 +375,7 @@ export class AgentLoopGuard {
const sig = [...keys].sort().join('||')
const trimmed = opts.trimmedReadKeys
const isTrimmed = (k: string) => trimmed?.has(k) ?? false
- const batchHasTrimmedRead = keys.some((k, i) => READ_ONLY_TOOLS.has(calls[i].name) && isTrimmed(k))
+ const batchHasTrimmedRead = keys.some((k, i) => isReadCall(calls[i]) && isTrimmed(k))
// (1) Back-to-back identical batches, any tool class.
if (sig === this.lastSig) {
@@ -359,7 +393,7 @@ export class AgentLoopGuard {
return { action: 'steer', message: repeatSteer(calls.map((c) => c.name), this.consecutive, 'in a row') }
}
- const hasMutation = calls.some((c) => !READ_ONLY_TOOLS.has(c.name))
+ const hasMutation = calls.some((c) => !isReadCall(c))
// (2) Windowed repeats among pure-read batches (alternation). A batch that
// re-reads something the builder capped is not part of that pattern and is
@@ -384,7 +418,7 @@ export class AgentLoopGuard {
// (3) Identical read calls within the epoch.
let steer: LoopGuardVerdict | null = null
for (let i = 0; i < calls.length; i++) {
- if (!READ_ONLY_TOOLS.has(calls[i].name)) continue
+ if (!isReadCall(calls[i])) continue
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
diff --git a/src/lib/settings-catalog.ts b/src/lib/settings-catalog.ts
index 047a7b8f..1cff5f37 100644
--- a/src/lib/settings-catalog.ts
+++ b/src/lib/settings-catalog.ts
@@ -430,7 +430,7 @@ export const CATALOG: readonly CatalogEntry[] = [
// ── Locked ──────────────────────────────────────────────────────
export type LockedCategory =
- | 'computer-control' | 'remote-access' | 'permissions' | 'keys' | 'paths' | 'plugins' | 'persona-text'
+ | 'computer-control' | 'remote-access' | 'permissions' | 'keys' | 'paths' | 'plugins' | 'persona-text' | 'spending'
interface LockRule {
category: LockedCategory
@@ -478,6 +478,12 @@ export const LOCK_RULES: readonly LockRule[] = [
names: ['personas', 'systemPrompt', 'personaPrompt', 'characterCard'],
pattern: /systemprompt|personaprompt|personatext|charactercard|instruction/,
},
+ {
+ // CA (14.11.2026): an agent must never raise its own spending limit.
+ category: 'spending', what: 'Credit limits of agent runs', where: 'Settings → Agent',
+ names: ['agentRunCreditLimit', 'agentHourCreditLimit', 'creditLimit', 'spendingLimit'],
+ pattern: /credit(limit)?|spending|budget|costbrake/,
+ },
]
/** Internal values the model never sees. */
diff --git a/src/stores/chatNoticeStore.ts b/src/stores/chatNoticeStore.ts
index e2f0d871..93991114 100644
--- a/src/stores/chatNoticeStore.ts
+++ b/src/stores/chatNoticeStore.ts
@@ -34,7 +34,7 @@ import { useChatStore } from './chatStore'
/** Die Zeilen, die es gibt. Kein freier Schluessel: eine Aufzaehlung laesst
* sich nachzaehlen, ein String-Schluessel waechst unbemerkt. */
-export type ChatNoticeId = 'document-belongs-in-docs' | 'model-cannot-see-images' | 'image-attach' | 'file-attach' | 'binary-summary-only' | 'file-cut' | 'agent-outside-workspace' | 'agent-for-local-files' | 'create-save' | 'file-mention' | 'rewind' | 'agent-start-failed'
+export type ChatNoticeId = 'document-belongs-in-docs' | 'model-cannot-see-images' | 'image-attach' | 'file-attach' | 'binary-summary-only' | 'file-cut' | 'agent-outside-workspace' | 'agent-for-local-files' | 'create-save' | 'file-mention' | 'rewind' | 'agent-start-failed' | 'cost-brake'
export interface ChatNotice {
id: ChatNoticeId
diff --git a/src/types/settings.ts b/src/types/settings.ts
index c0f3a582..533345a9 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -189,6 +189,11 @@ export interface Settings {
/** The agent loop guard (lib/agent-loop-guard.ts): steers and halts a run
* that repeats itself. On unless switched off (C44, Discord 05.11.2026). */
agentLoopGuard?: boolean
+ /** CA (14.11.2026): credits one agent task may use before it pauses and
+ * asks (LU Cloud, lib/agent-cost-brake.ts). 0 = no limit. */
+ agentRunCreditLimit?: number
+ /** Credits all agent runs together may use in a rolling hour. 0 = no limit. */
+ agentHourCreditLimit?: number
/** Local models up to ~35B get a short tool list with one-line
* descriptions plus tool_search (lib/agent-profile.ts, C59). On unless
* switched off; Small-Model Mode still wins. */