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.

Phase 10: Agent tool-call + iteration budget (v2.4.0)

PurpleDoubleD2110682d405b
diff --git a/src/api/agents/__tests__/budget.test.ts b/src/api/agents/__tests__/budget.test.ts
new file mode 100644
index 00000000..dfb273fd
--- /dev/null
+++ b/src/api/agents/__tests__/budget.test.ts
@@ -0,0 +1,79 @@
+import { describe, it, expect } from 'vitest'
+import { AgentBudget, budgetFromSettings } from '../budget'
+
+describe('AgentBudget', () => {
+ it('starts clean: exceeded() = none', () => {
+ const b = new AgentBudget({ maxToolCalls: 10, maxIterations: 5 })
+ expect(b.exceeded().kind).toBe('none')
+ expect(b.haltMessage()).toBe('')
+ })
+
+ it('detects tool-call cap hit', () => {
+ const b = new AgentBudget({ maxToolCalls: 3, maxIterations: 100 })
+ b.addToolCalls(3)
+ const ex = b.exceeded()
+ expect(ex.kind).toBe('tool_calls')
+ if (ex.kind === 'tool_calls') {
+ expect(ex.used).toBe(3)
+ expect(ex.cap).toBe(3)
+ }
+ expect(b.haltMessage()).toMatch(/tool-call budget reached/)
+ })
+
+ it('detects iteration cap hit (iterations checked first)', () => {
+ const b = new AgentBudget({ maxToolCalls: 100, maxIterations: 2 })
+ b.addIteration()
+ b.addIteration()
+ expect(b.exceeded().kind).toBe('iterations')
+ expect(b.haltMessage()).toMatch(/iteration cap/)
+ })
+
+ it('iteration cap reported when both would trigger', () => {
+ const b = new AgentBudget({ maxToolCalls: 1, maxIterations: 1 })
+ b.addToolCalls(5)
+ b.addIteration()
+ // Iteration cap is checked first by design — halts early on deeper runs.
+ expect(b.exceeded().kind).toBe('iterations')
+ })
+
+ it('addToolCalls accumulates across batches', () => {
+ const b = new AgentBudget({ maxToolCalls: 5, maxIterations: 100 })
+ b.addToolCalls(2)
+ b.addToolCalls(2)
+ expect(b.exceeded().kind).toBe('none')
+ b.addToolCalls(1)
+ expect(b.exceeded().kind).toBe('tool_calls')
+ })
+
+ it('ignores zero and negative additions', () => {
+ const b = new AgentBudget({ maxToolCalls: 1, maxIterations: 100 })
+ b.addToolCalls(0)
+ b.addToolCalls(-5)
+ expect(b.exceeded().kind).toBe('none')
+ })
+
+ it('cap = 0 means unlimited', () => {
+ const b = new AgentBudget({ maxToolCalls: 0, maxIterations: 0 })
+ b.addToolCalls(10_000)
+ for (let i = 0; i < 50; i++) b.addIteration()
+ expect(b.exceeded().kind).toBe('none')
+ })
+
+ it('snapshot reports current usage + caps', () => {
+ const b = new AgentBudget({ maxToolCalls: 10, maxIterations: 5 })
+ b.addToolCalls(3)
+ b.addIteration()
+ const snap = b.snapshot()
+ expect(snap).toEqual({
+ toolCalls: 3,
+ iterations: 1,
+ caps: { maxToolCalls: 10, maxIterations: 5 },
+ })
+ })
+
+ it('budgetFromSettings reads the two relevant fields', () => {
+ const b = budgetFromSettings({ agentMaxToolCalls: 7, agentMaxIterations: 3 })
+ b.addToolCalls(7)
+ expect(b.exceeded().kind).toBe('tool_calls')
+ })
+})
diff --git a/src/api/agents/budget.ts b/src/api/agents/budget.ts
new file mode 100644
index 00000000..8312dc85
--- /dev/null
+++ b/src/api/agents/budget.ts
@@ -0,0 +1,83 @@
+/**
+ * Phase 10 (v2.4.0) — Agent turn budget tracker.
+ *
+ * Hard cap on tool calls and ReAct iterations within a single user turn.
+ * Counts are global (not per-sub-agent-level) so a delegation fork-bomb
+ * cannot sneak past the cap by nesting.
+ *
+ * A budget is created at the start of each agent run. The hook increments
+ * on each batch of tool calls and each loop iteration; exceed() returns
+ * the first kind to exhaust, which the hook uses to synthesize a clean
+ * halt message for the user.
+ */
+
+export type BudgetExceed =
+ | { kind: 'none' }
+ | { kind: 'tool_calls'; used: number; cap: number }
+ | { kind: 'iterations'; used: number; cap: number }
+
+export interface BudgetCaps {
+ maxToolCalls: number
+ maxIterations: number
+}
+
+export class AgentBudget {
+ private toolCalls = 0
+ private iterations = 0
+
+ constructor(private caps: BudgetCaps) {}
+
+ /** Record N new tool calls (accepts batch). */
+ addToolCalls(n: number): void {
+ if (n > 0) this.toolCalls += n
+ }
+
+ /** Record one more ReAct loop iteration. */
+ addIteration(): void {
+ this.iterations += 1
+ }
+
+ /**
+ * Check whether any cap has been exceeded. A cap of 0 means "unlimited"
+ * — callers can opt out entirely by setting both to 0 (discouraged).
+ */
+ exceeded(): BudgetExceed {
+ if (this.caps.maxIterations > 0 && this.iterations >= this.caps.maxIterations) {
+ return { kind: 'iterations', used: this.iterations, cap: this.caps.maxIterations }
+ }
+ if (this.caps.maxToolCalls > 0 && this.toolCalls >= this.caps.maxToolCalls) {
+ return { kind: 'tool_calls', used: this.toolCalls, cap: this.caps.maxToolCalls }
+ }
+ return { kind: 'none' }
+ }
+
+ /**
+ * Convert an exceed to a user-facing halt message. Returns '' when the
+ * budget has not been exceeded.
+ */
+ haltMessage(): string {
+ const ex = this.exceeded()
+ if (ex.kind === 'none') return ''
+ if (ex.kind === 'tool_calls') {
+ return `[Agent halted: tool-call budget reached (${ex.used} / ${ex.cap}). Rephrase your request or raise the cap in Settings to continue.]`
+ }
+ // iterations
+ return `[Agent halted: ReAct loop iteration cap reached (${ex.used} / ${ex.cap}). Either the task is too broad or the model is looping — rephrase and retry.]`
+ }
+
+ /** Snapshot — useful for UI badges ("used 12 of 50 tool calls"). */
+ snapshot(): { toolCalls: number; iterations: number; caps: BudgetCaps } {
+ return { toolCalls: this.toolCalls, iterations: this.iterations, caps: { ...this.caps } }
+ }
+}
+
+/**
+ * Build a budget from user settings. Accepts the relevant fields only so
+ * tests do not need to construct a whole Settings object.
+ */
+export function budgetFromSettings(s: { agentMaxToolCalls: number; agentMaxIterations: number }): AgentBudget {
+ return new AgentBudget({
+ maxToolCalls: s.agentMaxToolCalls,
+ maxIterations: s.agentMaxIterations,
+ })
+}
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 9eef7846..477cc7a5 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -25,6 +25,7 @@ import { WorkflowEngine } from '../lib/workflow-engine'
import type { AgentBlock, AgentToolCall, OllamaChatMessage } from '../types/agent-mode'
import { selectRelevantTools, selectRelevantToolsAsync } from '../lib/tool-selection'
import { generateEmbeddings } from '../api/rag'
+import { budgetFromSettings } from '../api/agents/budget'
import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'
import type { StepResult, WorkflowEngineCallbacks } from '../types/agent-workflows'
import { executeParallel, applyResultToToolCall, type ExecutionRequest } from '../api/agents/tool-executor'
@@ -371,10 +372,25 @@ export function useAgentChat() {
// Phase 6: lock in the start-of-turn timestamp so the in-turn cache
// only serves results from calls made during THIS user prompt.
const turnStartMs = Date.now()
+ // Phase 10: hard caps on tool calls and loop iterations. Halts cleanly
+ // with a synthetic assistant message when the budget is exhausted —
+ // no wedged agent, no runaway token burn.
+ const budget = budgetFromSettings({
+ agentMaxToolCalls: settings.agentMaxToolCalls ?? 50,
+ agentMaxIterations: settings.agentMaxIterations ?? 25,
+ })
try {
// ── Agent Loop ──────────────────────────────────────────
while (runningRef.current && !abort.signal.aborted) {
+ budget.addIteration()
+ const exceed = budget.exceeded()
+ if (exceed.kind !== 'none') {
+ contentRef.current =
+ (contentRef.current ? contentRef.current + '\n\n' : '') + budget.haltMessage()
+ scheduleUIUpdate()
+ break
+ }
let toolCalls: ToolCall[] = []
let turnContent = ''
let turnThinking = ''
@@ -504,6 +520,7 @@ export function useAgentChat() {
type BatchEntry = { tc: typeof toolCalls[number]; ac: AgentToolCall; blockId: string }
const batch: BatchEntry[] = []
+ budget.addToolCalls(toolCalls.length)
for (const tc of toolCalls) {
const toolCallId = uuid()
const blockId = uuid()
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index db4a03ec..629c11b2 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -19,6 +19,7 @@ import { executeParallel, applyResultToToolCall, type ExecutionRequest } from '.
import { useToolAuditStore } from '../stores/toolAuditStore'
import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'
import { explainError as explainToolError } from '../api/agents/error-hints'
+import { budgetFromSettings } from '../api/agents/budget'
const CODEX_SYSTEM_PROMPT = `You are Codex, an autonomous coding agent inside Locally Uncensored. You execute coding tasks by reading files, writing code, and running shell commands. You MUST use tools to interact with the filesystem — never guess file contents.
@@ -156,10 +157,28 @@ export function useCodex() {
// Phase 6: pin turn start so in-turn cache scopes to this user prompt.
const turnStartMs = Date.now()
+ // Phase 10: Codex already capped at 20 iterations historically; the
+ // AgentBudget also tracks tool calls and the iteration cap pulled
+ // from settings. The legacy for-loop cap stays as the outer guard.
+ const budget = budgetFromSettings({
+ agentMaxToolCalls: settings.agentMaxToolCalls ?? 50,
+ agentMaxIterations: settings.agentMaxIterations ?? 25,
+ })
try {
- // Agent loop — max 20 iterations
+ // Agent loop — max 20 iterations (legacy cap) AND AgentBudget cap,
+ // whichever is tighter.
for (let i = 0; i < 20 && runningRef.current && !abort.signal.aborted; i++) {
+ budget.addIteration()
+ const bx = budget.exceeded()
+ if (bx.kind !== 'none') {
+ useChatStore.getState().updateMessageContent(
+ convId!,
+ assistantMsg.id,
+ (fullContent ? fullContent + '\n\n' : '') + budget.haltMessage()
+ )
+ break
+ }
let toolCalls: ToolCall[] = []
let turnContent = ''
@@ -260,6 +279,7 @@ export function useCodex() {
type BatchEntry = { tc: typeof toolCalls[number]; ac: AgentToolCall; blockId: string; injectedArgs: Record<string, any> }
const batch: BatchEntry[] = []
+ budget.addToolCalls(toolCalls.length)
for (const tc of toolCalls) {
const toolName = tc.function.name
const toolArgs = { ...tc.function.arguments }
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 7dd0ed15..121ec7fa 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -23,6 +23,9 @@ export const DEFAULT_SETTINGS: Settings = {
claudeCodeModel: '',
claudeCodeAutoApprove: false,
claudeCodePath: '',
+ // Agent budget (Phase 10 v2.4.0)
+ agentMaxToolCalls: 50,
+ agentMaxIterations: 25,
}
/** Caveman mode system prompt prefixes — credit: github.com/JuliusBrussee/caveman (MIT) */
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 94ee8f9f..3ee1bf6d 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -19,6 +19,11 @@ export interface Settings {
claudeCodeModel: string
claudeCodeAutoApprove: boolean
claudeCodePath: string
+ // Agent budget (Phase 10 v2.4.0) — hard caps that halt a runaway agent.
+ /** Hard cap on tool calls per user turn. 0 = unlimited (not recommended). */
+ agentMaxToolCalls: number
+ /** Hard cap on ReAct loop iterations per user turn. 0 = unlimited. */
+ agentMaxIterations: number
}
export interface Persona {