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.

tech(AGT-1): Sub-Agent erbt Freigabe, Audit und Abbruch — kein unbeaufsichtigtes Delegieren mehr

David4a228035398a
diff --git a/src/api/agent-context.ts b/src/api/agent-context.ts
index 1a1327ea..14af0ffe 100644
--- a/src/api/agent-context.ts
+++ b/src/api/agent-context.ts
@@ -73,6 +73,17 @@ export interface AgentRunContext {
*/
mode: string | null
artifacts: CapturedArtifact[]
+ /**
+ * Stop button of the run that owns this context (audit AGT-1).
+ *
+ * The hook creates its AbortController after beginAgentRun, so it assigns
+ * this afterwards. Everything a NESTED loop starts — today that is
+ * delegate_task's sub-agent — reads it from here, because a sub-agent that
+ * keeps running tools after the user pressed Stop is the same bug as a tool
+ * batch that keeps dispatching after Stop. Undefined on surfaces that do not
+ * thread yet; those simply cannot be interrupted mid-delegation.
+ */
+ abortSignal?: AbortSignal
}
interface AgentCtxState {
diff --git a/src/api/agents/__tests__/sub-agent.test.ts b/src/api/agents/__tests__/sub-agent.test.ts
index 4f76c3e8..63e27294 100644
--- a/src/api/agents/__tests__/sub-agent.test.ts
+++ b/src/api/agents/__tests__/sub-agent.test.ts
@@ -1,12 +1,73 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
+
+// ── Doubles for the modules defaultSubAgentRunner pulls in lazily ─────
+//
+// The runner resolves provider, registry, permissions and audit store at call
+// time, so the whole delegated ReAct loop is drivable from here: the provider
+// double decides what tool calls the sub-agent emits, the registry double
+// decides what the executor may run, and the permission double decides which
+// gate the call has to pass.
+
+const chatWithTools = vi.fn()
+const toolExecute = vi.fn(async () => 'tool output')
+const auditRecord = vi.fn(() => 'audit-1')
+const auditComplete = vi.fn()
+let permLevel: 'auto' | 'confirm' | 'blocked' = 'auto'
+
+const SHELL_DEF = {
+ name: 'shell_execute',
+ description: 'run a command',
+ inputSchema: {
+ type: 'object',
+ properties: { command: { type: 'string' } },
+ required: ['command'],
+ },
+ category: 'system',
+ source: 'builtin',
+}
+
+vi.mock('../../../stores/modelStore', () => ({
+ useModelStore: { getState: () => ({ activeModel: 'ollama::qwen' }) },
+}))
+
+vi.mock('../../providers', () => ({
+ getProviderForModel: (name: string) => ({
+ provider: { chatWithTools },
+ modelId: name.includes('::') ? name.split('::')[1] : name,
+ }),
+}))
+
+vi.mock('../../mcp', () => ({
+ toolRegistry: {
+ getAll: () => [SHELL_DEF],
+ resolveExecutable: (name: string) => (name === 'shell_execute' ? SHELL_DEF : undefined),
+ execute: (...args: any[]) => toolExecute(...(args as [])),
+ getPermissionLevelWithOverrides: () => permLevel,
+ },
+}))
+
+vi.mock('../../../stores/permissionStore', () => ({
+ usePermissionStore: {
+ getState: () => ({ getEffectivePermissions: () => ({}), perToolOverrides: {} }),
+ },
+}))
+
+vi.mock('../../../stores/toolAuditStore', () => ({
+ useToolAuditStore: { getState: () => ({ record: auditRecord, complete: auditComplete }) },
+}))
+
import {
DELEGATE_TASK_TOOL_DEF,
SUB_AGENT_MAX_PARALLEL,
SUB_AGENT_BUDGET,
buildDelegateExecutor,
+ defaultSubAgentRunner,
_getDepth,
_setDepth,
} from '../sub-agent'
+import { AgentBudget } from '../budget'
+import type { AgentRunContext } from '../../agent-context'
+import { dequeueApproval, headApproval, resetApprovals } from '../../../lib/approval-queue'
describe('sub-agent — tool definition', () => {
it('has the expected shape', () => {
@@ -146,3 +207,183 @@ describe('sub-agent — buildDelegateExecutor', () => {
expect(await exec({ goal: 'x' })).toBe('ok')
})
})
+
+// ── AGT-1: the delegated loop inherits the parent run's gates ──────────
+//
+// Before 2.6.7 defaultSubAgentRunner called executeParallel with getTool +
+// execute + explainError and nothing else, so a sub-agent ran the whole
+// registry — shell_execute, file_write, file_edit, all 'confirm' by default —
+// with no approval prompt, no audit entry and no way to stop it. These pin the
+// three gates it now has to pass.
+
+const makeRun = (over: Partial<AgentRunContext> = {}): AgentRunContext => ({
+ token: 'run-test',
+ chatId: null,
+ conversationId: 'conv-1',
+ workspace: null,
+ artifactMode: false,
+ readOnlyShellTurn: false,
+ mode: null,
+ artifacts: [],
+ ...over,
+})
+
+/** Script the provider: one tool-calling turn, then a plain final answer. */
+function scriptOneToolCall(): void {
+ chatWithTools
+ .mockResolvedValueOnce({
+ content: '',
+ toolCalls: [{ id: 'tc1', function: { name: 'shell_execute', arguments: { command: 'ls' } } }],
+ })
+ .mockResolvedValueOnce({ content: 'done', toolCalls: [] })
+}
+
+/** The message array the sub-agent sent on its Nth provider turn (0-based). */
+const messagesOfTurn = (n: number): any[] => chatWithTools.mock.calls[n][1] as any[]
+const lastToolMessage = (n: number): string => {
+ const msgs = messagesOfTurn(n)
+ return String(msgs[msgs.length - 1]?.content ?? '')
+}
+
+const tick = () => new Promise((r) => setTimeout(r, 0))
+
+async function waitForPrompt(convId: string) {
+ for (let i = 0; i < 100; i++) {
+ const head = headApproval(convId)
+ if (head) return head
+ await tick()
+ }
+ throw new Error('no approval was raised')
+}
+
+const runSub = (run?: AgentRunContext) =>
+ defaultSubAgentRunner('do it', '', { budget: new AgentBudget({ ...SUB_AGENT_BUDGET }), run })
+
+describe('sub-agent — approval gate (AGT-1)', () => {
+ beforeEach(() => {
+ _setDepth(0)
+ permLevel = 'auto'
+ chatWithTools.mockReset()
+ toolExecute.mockReset()
+ toolExecute.mockResolvedValue('tool output')
+ auditRecord.mockClear()
+ auditComplete.mockClear()
+ resetApprovals()
+ })
+
+ it('a confirm-level tool call raises an approval instead of dispatching', async () => {
+ permLevel = 'confirm'
+ scriptOneToolCall()
+ const p = runSub(makeRun())
+
+ const head = await waitForPrompt('conv-1')
+ expect(head.toolName).toBe('shell_execute')
+ expect(head.args).toEqual({ command: 'ls' })
+ // Still waiting on the user — nothing has run.
+ expect(toolExecute).not.toHaveBeenCalled()
+
+ dequeueApproval('conv-1')!.resolve(false)
+ await p
+ expect(toolExecute).not.toHaveBeenCalled()
+ expect(lastToolMessage(1)).toMatch(/rejected/i)
+ })
+
+ it('an approved confirm-level call dispatches once the user says yes', async () => {
+ permLevel = 'confirm'
+ scriptOneToolCall()
+ const p = runSub(makeRun())
+
+ await waitForPrompt('conv-1')
+ dequeueApproval('conv-1')!.resolve(true)
+ expect(await p).toBe('done')
+ expect(toolExecute).toHaveBeenCalledOnce()
+ expect(lastToolMessage(1)).toBe('tool output')
+ })
+
+ it('auto-level tools run unprompted (the gate is a gate, not a wall)', async () => {
+ permLevel = 'auto'
+ scriptOneToolCall()
+ expect(await runSub(makeRun())).toBe('done')
+ expect(headApproval('conv-1')).toBeNull()
+ expect(toolExecute).toHaveBeenCalledOnce()
+ })
+
+ it('blocked tools are refused without asking anyone', async () => {
+ permLevel = 'blocked'
+ scriptOneToolCall()
+ await runSub(makeRun())
+ expect(headApproval('conv-1')).toBeNull()
+ expect(toolExecute).not.toHaveBeenCalled()
+ expect(lastToolMessage(1)).toMatch(/Blocked: shell_execute is not permitted/)
+ })
+
+ it('fails closed when the delegation has no conversation to ask in', async () => {
+ permLevel = 'confirm'
+ scriptOneToolCall()
+ await runSub(undefined)
+ expect(toolExecute).not.toHaveBeenCalled()
+ expect(lastToolMessage(1)).toMatch(/no conversation to ask in/)
+ })
+
+ it('records every delegated call in the parent conversation audit trail', async () => {
+ permLevel = 'auto'
+ scriptOneToolCall()
+ await runSub(makeRun())
+ expect(auditRecord).toHaveBeenCalledOnce()
+ expect(auditRecord.mock.calls[0][0]).toMatchObject({
+ convId: 'conv-1',
+ toolName: 'shell_execute',
+ parentToolCallId: 'sub-agent',
+ })
+ expect(auditComplete).toHaveBeenCalledOnce()
+ })
+})
+
+describe('sub-agent — abort signal (AGT-1)', () => {
+ beforeEach(() => {
+ _setDepth(0)
+ permLevel = 'auto'
+ chatWithTools.mockReset()
+ toolExecute.mockReset()
+ toolExecute.mockResolvedValue('tool output')
+ resetApprovals()
+ })
+
+ it('Stop during the model turn keeps the batch from dispatching', async () => {
+ const ctrl = new AbortController()
+ chatWithTools.mockImplementationOnce(async () => {
+ ctrl.abort() // user hits Stop while the sub-agent is thinking
+ return {
+ content: '',
+ toolCalls: [{ id: 'tc1', function: { name: 'shell_execute', arguments: { command: 'ls' } } }],
+ }
+ })
+ const out = await runSub(makeRun({ abortSignal: ctrl.signal }))
+ expect(toolExecute).not.toHaveBeenCalled()
+ expect(out).toMatch(/stopped by the user/)
+ // And it did not start another ReAct iteration after the abort.
+ expect(chatWithTools).toHaveBeenCalledOnce()
+ })
+
+ it('Stop answers a tool call that is waiting for approval', async () => {
+ permLevel = 'confirm'
+ const ctrl = new AbortController()
+ scriptOneToolCall()
+ const p = runSub(makeRun({ abortSignal: ctrl.signal }))
+
+ await waitForPrompt('conv-1')
+ ctrl.abort()
+ const out = await p
+ expect(toolExecute).not.toHaveBeenCalled()
+ expect(headApproval('conv-1')).toBeNull()
+ expect(out).toMatch(/stopped by the user/)
+ })
+
+ it('an already-aborted run never reaches the provider at all', async () => {
+ const ctrl = new AbortController()
+ ctrl.abort()
+ const out = await runSub(makeRun({ abortSignal: ctrl.signal }))
+ expect(chatWithTools).not.toHaveBeenCalled()
+ expect(out).toMatch(/stopped by the user/)
+ })
+})
diff --git a/src/api/agents/__tests__/tool-executor.test.ts b/src/api/agents/__tests__/tool-executor.test.ts
index c4c42d9c..2afb349c 100644
--- a/src/api/agents/__tests__/tool-executor.test.ts
+++ b/src/api/agents/__tests__/tool-executor.test.ts
@@ -5,6 +5,7 @@ import {
type ExecutionRequest,
type AuditHook,
applyResultToToolCall,
+ APPROVE_ALL,
} from '../tool-executor'
import type { AgentToolCall } from '../../../types/agent-mode'
@@ -24,7 +25,9 @@ const makeRuntime = (
if (!(name in tools)) throw new Error(`no executor for ${name}`)
return tools[name].executor(args)
}),
- awaitApproval: overrides.awaitApproval,
+ // Required field now (audit AGT-1) — a runtime cannot get an unattended
+ // dispatch by leaving it out, so the default has to be explicit.
+ awaitApproval: overrides.awaitApproval ?? APPROVE_ALL,
lookupCache: overrides.lookupCache,
recordAudit: overrides.recordAudit,
explainError: overrides.explainError,
@@ -226,6 +229,34 @@ describe('tool-executor — cache + approval', () => {
expect(exec).not.toHaveBeenCalled()
})
+ // AGT-1: the gate used to be optional, so a runtime that simply omitted it
+ // dispatched everything unattended — which is how the sub-agent ended up
+ // running shell_execute with no prompt. It is consulted on every call now,
+ // and a caller that wants no prompt has to say APPROVE_ALL out loud.
+ it('consults the gate for every call, including pure reads', async () => {
+ const seen: string[] = []
+ const runtime = makeRuntime({
+ tools: { a: { executor: async () => 'ra' }, b: { executor: async () => 'rb' } },
+ awaitApproval: async (r) => {
+ seen.push(r.toolName)
+ return true
+ },
+ })
+ const out = await executeParallel([req('1', 'a'), req('2', 'b')], runtime)
+ expect(out.map((r) => r.status)).toEqual(['completed', 'completed'])
+ expect(seen.sort()).toEqual(['a', 'b'])
+ })
+
+ it('APPROVE_ALL is a real gate that lets everything through', async () => {
+ const exec = vi.fn(async () => 'ran')
+ const out = await executeParallel([req('1', 't')], makeRuntime({
+ tools: { t: { executor: exec } },
+ awaitApproval: APPROVE_ALL,
+ }))
+ expect(out[0].status).toBe('completed')
+ expect(exec).toHaveBeenCalledOnce()
+ })
+
it('rejected approval marks call rejected, skips dispatch', async () => {
const exec = vi.fn(async () => 'fresh')
const runtime = makeRuntime({
diff --git a/src/api/agents/budget.ts b/src/api/agents/budget.ts
index 8312dc85..258f084f 100644
--- a/src/api/agents/budget.ts
+++ b/src/api/agents/budget.ts
@@ -1,9 +1,23 @@
/**
* 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.
+ * Hard cap on tool calls and ReAct iterations within a single LOOP.
+ *
+ * Counts are per-instance, not global. This comment used to claim the
+ * opposite — "global (not per-sub-agent-level) so a delegation fork-bomb
+ * cannot sneak past the cap by nesting" — and the code has never done that:
+ * buildDelegateExecutor in sub-agent.ts hands every delegation a fresh
+ * `new AgentBudget({ ...SUB_AGENT_BUDGET })`, so a sub-agent's 10 tool calls
+ * are counted against its own tight caps and never against the parent's.
+ *
+ * That is the intended design, not an oversight to be "fixed" by sharing one
+ * counter: the sub-agent caps (10 calls / 5 iterations) exist precisely to
+ * bound a delegation independently of how much budget the parent has left,
+ * and delegate_task advertises them to the model. Sharing the parent's budget
+ * would also make one runaway sub-agent silently starve its siblings. What
+ * actually bounds a delegation fan-out is SUB_AGENT_MAX_PARALLEL (4 in
+ * flight) plus the registry filter that hides delegate_task from a sub-agent
+ * — see the notes in sub-agent.ts. Fixed in 2.6.7 (audit AGT-1).
*
* 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
diff --git a/src/api/agents/sub-agent.ts b/src/api/agents/sub-agent.ts
index b60ddf9f..a7658ab7 100644
--- a/src/api/agents/sub-agent.ts
+++ b/src/api/agents/sub-agent.ts
@@ -13,7 +13,14 @@
import { settleThinking } from '../../lib/thinking-stripper'
import type { MCPToolDefinition } from '../mcp/types'
-import { executeParallel, type ExecutionRequest } from './tool-executor'
+import type { AgentToolCall } from '../../types/agent-mode'
+import type { ApprovalEntry } from '../../lib/approval-queue'
+import {
+ executeParallel,
+ type ExecutionRequest,
+ type ApprovalGate,
+ type AuditRecorder,
+} from './tool-executor'
import type { AgentRunContext } from '../agent-context'
import { AgentBudget } from './budget'
import { explainError as explainToolError } from './error-hints'
@@ -125,6 +132,143 @@ export function buildSubAgentSystemPrompt(
return `${stable}\n\n${platformLine}\n\n${clockLine}`
}
+/**
+ * The gates a delegated tool call has to pass. Same three the parent loop
+ * installs on its own executeParallel call, resolved for the sub-run.
+ */
+export interface SubAgentGates {
+ awaitApproval: ApprovalGate
+ recordAudit?: AuditRecorder
+ abortSignal?: AbortSignal
+ /**
+ * id → why the gate said no, for refusals that are NOT a user clicking
+ * reject. The executor's generic 'User rejected tool call' would otherwise
+ * tell the sub-agent's model a story that never happened.
+ */
+ refusals: Map<string, string>
+}
+
+/**
+ * Build the gates for one delegated run (audit AGT-1).
+ *
+ * A sub-agent runs a full ReAct loop over the whole tool registry minus
+ * delegate_task — shell_execute, file_write and file_edit included, all three
+ * 'confirm' by default. Until 2.6.7 it called executeParallel with getTool +
+ * execute + explainError and NOTHING else: no approval gate (the executor's
+ * was optional and therefore skipped), no audit trail, no abort signal. One
+ * approved delegate_task bought an unattended, unlogged, uninterruptible
+ * shell. Threading `run` (plan 2.6.6 C1) did not fix that: the run context
+ * carries the conversation, workspace, artifact and read-only flags, so it
+ * scopes WHERE a tool writes and whether shell_execute is read-only — it never
+ * asked the user anything.
+ *
+ * The gates are resolved here rather than handed down from the hook on
+ * purpose. All three live in module-scoped, conversation-keyed state (the
+ * approval FIFO, the audit store, the permission store), so the run's
+ * conversation id is enough to reach the SAME queue the parent loop uses —
+ * the pending approval surfaces in the same UI, the tool call lands in the
+ * same audit list. The parent's own awaitApproval closure could not be reused:
+ * it resolves a request id against the batch it was built for and answers
+ * "true" for anything it does not recognise, so a sub-agent's id would sail
+ * straight through it.
+ *
+ * Fail closed: with no conversation to ask in, a 'confirm' tool is refused
+ * rather than run.
+ */
+export async function buildSubAgentGates(run?: AgentRunContext): Promise<SubAgentGates> {
+ const convId = run?.conversationId ?? null
+ const abortSignal = run?.abortSignal
+ const refusals = new Map<string, string>()
+
+ const [{ toolRegistry }, { usePermissionStore }, approvals] = await Promise.all([
+ import('../mcp'),
+ import('../../stores/permissionStore'),
+ import('../../lib/approval-queue'),
+ ])
+
+ const awaitApproval: ApprovalGate = async (req) => {
+ if (abortSignal?.aborted) {
+ refusals.set(req.id, 'Aborted: the user stopped the run before this delegated tool call ran.')
+ return false
+ }
+ const perm = usePermissionStore.getState()
+ const level = toolRegistry.getPermissionLevelWithOverrides(
+ req.toolName,
+ perm.getEffectivePermissions(convId ?? undefined),
+ perm.perToolOverrides,
+ )
+ if (level === 'blocked') {
+ refusals.set(req.id, `Blocked: ${req.toolName} is not permitted in this conversation.`)
+ return false
+ }
+ if (level === 'auto') return true
+ // 'confirm' — the user decides, in the conversation that owns this run.
+ if (!convId) {
+ refusals.set(
+ req.id,
+ `Blocked: ${req.toolName} needs confirmation and this delegated run has no conversation to ask in.`,
+ )
+ return false
+ }
+ return new Promise<boolean>((resolve) => {
+ const toolCall: AgentToolCall = {
+ id: req.id,
+ toolName: req.toolName,
+ args: req.args,
+ status: 'pending_approval',
+ timestamp: Date.now(),
+ }
+ const entry: ApprovalEntry = { toolCall, resolve }
+ approvals.enqueueApproval(convId, entry)
+ // Stop has to answer a question nobody clicked, or the delegation (and
+ // with it the parent turn) waits forever — same lesson as audit A4.
+ abortSignal?.addEventListener(
+ 'abort',
+ () => {
+ if (approvals.removeApproval(convId, entry)) {
+ refusals.set(req.id, 'Aborted: the user stopped the run while this tool call awaited approval.')
+ resolve(false)
+ }
+ },
+ { once: true },
+ )
+ })
+ }
+
+ if (!convId) return { awaitApproval, abortSignal, refusals }
+
+ const { useToolAuditStore } = await import('../../stores/toolAuditStore')
+ const auditIds = new Map<string, string>()
+ const recordAudit: AuditRecorder = (entry) => {
+ if (entry.kind === 'start') {
+ auditIds.set(
+ entry.id,
+ useToolAuditStore.getState().record({
+ convId,
+ toolCallId: entry.id,
+ toolName: entry.toolName,
+ args: entry.args,
+ startedAt: entry.startedAt,
+ parentToolCallId: entry.parentToolCallId,
+ }),
+ )
+ return
+ }
+ const aid = auditIds.get(entry.id)
+ if (!aid) return
+ useToolAuditStore.getState().complete(aid, {
+ status: entry.status,
+ completedAt: entry.completedAt,
+ resultPreview: entry.resultPreview,
+ error: entry.error,
+ errorHint: entry.errorHint,
+ cacheHit: entry.cacheHit,
+ })
+ }
+
+ return { awaitApproval, recordAudit, abortSignal, refusals }
+}
+
/**
* Default sub-agent runner. Pulls in the active provider + model via
* dynamic import to keep this module standalone and testable with a
@@ -162,8 +306,14 @@ export async function defaultSubAgentRunner(
},
]
+ // Approval + audit + Stop for every tool this sub-run fires (AGT-1).
+ const gates = await buildSubAgentGates(options.run)
+
let finalContent = ''
for (let i = 0; i < SUB_AGENT_BUDGET.maxIterations; i++) {
+ if (gates.abortSignal?.aborted) {
+ return finalContent || '(sub-agent stopped by the user)'
+ }
options.budget.addIteration()
const ex = options.budget.exceeded()
if (ex.kind !== 'none') {
@@ -189,12 +339,19 @@ export async function defaultSubAgentRunner(
run: options.run,
}))
const registry = toolRegistry
- const results = await executeParallel(requests, {
- getTool: (name) => registry.resolveExecutable(name),
- execute: (name: string, args: Record<string, any>, callRun?: AgentRunContext) =>
- registry.execute(name, args, 1, callRun),
- explainError: (toolName, err) => explainToolError(toolName, err),
- })
+ const results = await executeParallel(
+ requests,
+ {
+ getTool: (name) => registry.resolveExecutable(name),
+ execute: (name: string, args: Record<string, any>, callRun?: AgentRunContext) =>
+ registry.execute(name, args, 1, callRun),
+ explainError: (toolName, err) => explainToolError(toolName, err),
+ // The three gates the nested loop used to run without.
+ awaitApproval: gates.awaitApproval,
+ recordAudit: gates.recordAudit,
+ },
+ { abortSignal: gates.abortSignal },
+ )
messages.push({ role: 'assistant', content: turn.content || '', tool_calls: turn.toolCalls })
// Map each result back to its ORIGINATING call by index. executeParallel
@@ -208,7 +365,9 @@ export async function defaultSubAgentRunner(
results.forEach((r, i) => {
messages.push({
role: 'tool',
- content: r.result ?? r.error ?? '(no output)',
+ // A gate refusal explains itself; only a real user rejection falls
+ // through to the executor's own wording.
+ content: r.result ?? gates.refusals.get(r.id) ?? r.error ?? '(no output)',
tool_call_id: turn.toolCalls[i]?.id,
})
})
diff --git a/src/api/agents/tool-executor.ts b/src/api/agents/tool-executor.ts
index fff8c45a..e43be298 100644
--- a/src/api/agents/tool-executor.ts
+++ b/src/api/agents/tool-executor.ts
@@ -80,20 +80,46 @@ export type ExecutorFn = (
run?: AgentRunContext,
) => Promise<string>
+/**
+ * Pre-dispatch approval gate. Resolves true to let the call run, false to
+ * mark it 'rejected' without ever reaching the executor.
+ */
+export type ApprovalGate = (req: ExecutionRequest, tool: ExecutorToolDef) => Promise<boolean>
+
+/** Audit sink (Phase 2). Called once at dispatch and once at completion. */
+export type AuditRecorder = (entry: AuditHook) => void
+
+/**
+ * The one gate that is NOT optional: every caller must say, in writing, what
+ * happens before a tool runs.
+ *
+ * It used to be optional, and the omission was invisible — a runtime that
+ * simply left the field out ran shell_execute / file_write / file_edit
+ * unattended even though all three default to 'confirm'. That is exactly how
+ * the sub-agent's nested ReAct loop ended up with no approval prompt at all
+ * (audit AGT-1): nobody wrote `awaitApproval`, so nobody saw it missing.
+ * Making it required turns that silent hole into a compile error. A surface
+ * that genuinely runs unattended passes APPROVE_ALL and thereby says so.
+ */
+export const APPROVE_ALL: ApprovalGate = async () => true
+
export interface ExecutorRuntime {
/** Resolve a tool by name — returns undefined for unknown tools. */
getTool: (name: string) => ExecutorToolDef | undefined
/** Execute a registered tool against args; returns string result. */
execute: ExecutorFn
- /** Optional — called before dispatch to gate on user approval. */
- awaitApproval?: (req: ExecutionRequest, tool: ExecutorToolDef) => Promise<boolean>
+ /**
+ * REQUIRED — called before dispatch to gate on user approval. Pass
+ * APPROVE_ALL to opt out explicitly; there is no implicit opt-out.
+ */
+ awaitApproval: ApprovalGate
/** Optional — cache lookup pre-dispatch (Phase 6). Returns a cached result or undefined. */
lookupCache?: (
req: ExecutionRequest,
argsHash: string
) => string | undefined
/** Optional — audit recorder (Phase 2). Called at dispatch + completion. */
- recordAudit?: (entry: AuditHook) => void
+ recordAudit?: AuditRecorder
/** Optional — error hint mapper (Phase 7). */
explainError?: (toolName: string, error: string) => string | undefined
}
@@ -310,23 +336,22 @@ async function runSingle(
})
}
- // User approval (desktop only; mobile runtime has no approval gate).
- if (runtime.awaitApproval) {
- const approved = await runtime.awaitApproval(req, tool)
- if (!approved) {
- return finalize({
- id: req.id,
- toolName: req.toolName,
- status: 'rejected',
- error: 'User rejected tool call',
- dispatchedArgs,
- argsHash,
- sideEffectKey,
- startedAt,
- cacheHit: false,
- schemaValidated,
- })
- }
+ // User approval. Unconditional: a runtime that does not want a prompt says
+ // so with APPROVE_ALL, it does not get there by forgetting the field.
+ const approved = await runtime.awaitApproval(req, tool)
+ if (!approved) {
+ return finalize({
+ id: req.id,
+ toolName: req.toolName,
+ status: 'rejected',
+ error: 'User rejected tool call',
+ dispatchedArgs,
+ argsHash,
+ sideEffectKey,
+ startedAt,
+ cacheHit: false,
+ schemaValidated,
+ })
}
// Dispatch.
diff --git a/src/api/mcp/__tests__/tool-merge-redirect.test.ts b/src/api/mcp/__tests__/tool-merge-redirect.test.ts
index 36498f17..50cfec73 100644
--- a/src/api/mcp/__tests__/tool-merge-redirect.test.ts
+++ b/src/api/mcp/__tests__/tool-merge-redirect.test.ts
@@ -140,6 +140,9 @@ describe('retired names survive the step executor (executeParallel)', () => {
const runtime = {
getTool: (name: string) => registry.resolveExecutable(name),
execute: ((name: string, args: Record<string, any>) => registry.execute(name, args)) as any,
+ // awaitApproval is required (audit AGT-1); this fixture exercises the
+ // redirect path, not the gate.
+ awaitApproval: async () => true,
}
it('resolveExecutable: registered def, retired stub, unknown undefined', () => {
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 6905ddda..cb327e90 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -577,6 +577,10 @@ export function useAgentChat() {
// Setup
const abort = new AbortController()
abortRef.current = abort
+ // Hand Stop to everything this run starts, including the nested ReAct loop
+ // a delegate_task sub-agent runs (audit AGT-1). Assigned here rather than
+ // in beginAgentRun because the controller does not exist that early.
+ run.abortSignal = abort.signal
runningRef.current = true
setIsAgentRunning(true)
// Bind the generating flag to THIS conversation so the typing indicator
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 0f4b45cb..2a8bffc6 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -41,7 +41,7 @@ import { log } from '../lib/logger'
import type { AgentBlock, AgentToolCall } from '../types/agent-mode'
import { isThinkingCompatible, isPlainTextPlanner } from '../lib/model-compatibility'
import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'
-import { executeParallel, applyResultToToolCall, type ExecutionRequest } from '../api/agents/tool-executor'
+import { executeParallel, applyResultToToolCall, APPROVE_ALL, type ExecutionRequest } from '../api/agents/tool-executor'
import { useToolAuditStore } from '../stores/toolAuditStore'
import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'
import { explainError as explainToolError } from '../api/agents/error-hints'
@@ -731,6 +731,10 @@ export function useCodex() {
// Setup
const abort = new AbortController()
abortRef.current = abort
+ // Hand Stop to everything this run starts, including the nested ReAct loop
+ // a delegate_task sub-agent runs (audit AGT-1). Assigned here rather than
+ // in beginAgentRun because the controller does not exist that early.
+ run.abortSignal = abort.signal
runningRef.current = true
setIsRunning(true)
codexStore.setThreadStatus(convId, 'running')
@@ -2061,7 +2065,10 @@ export function useCodex() {
cloudReason: !settings.codexConfirmShell && codexMode !== 'ask' && providerId === 'lu-cloud',
}, abort.signal)
}
- : undefined,
+ // Unattended by choice, stated in writing: awaitApproval is a
+ // required field now (audit AGT-1), so "no prompt here" is a
+ // decision a reader can see instead of a field nobody filled in.
+ : APPROVE_ALL,
recordAudit: (entry) => {
if (!convId) return
if (entry.kind === 'start') {