The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
Phase 5a: tool-executor with parallel scheduling + sideEffectKey (v2.4.0)
PurpleDoubleD2f5b99ae1f5c
diff --git a/src/api/agents/__tests__/side-effect-key.test.ts b/src/api/agents/__tests__/side-effect-key.test.tsnew file mode 100644index 00000000..04b279ed--- /dev/null+++ b/src/api/agents/__tests__/side-effect-key.test.ts@@ -0,0 +1,59 @@+import { describe, it, expect } from 'vitest'+import { deriveSideEffectKey } from '../side-effect-key'++describe('side-effect-key', () => {+ it('returns undefined for pure reads (parallel-safe)', () => {+ expect(deriveSideEffectKey('file_read', { path: 'x' })).toBeUndefined()+ expect(deriveSideEffectKey('file_list', { path: 'x' })).toBeUndefined()+ expect(deriveSideEffectKey('file_search', { path: 'x', pattern: 'y' })).toBeUndefined()+ expect(deriveSideEffectKey('web_search', { query: 'x' })).toBeUndefined()+ expect(deriveSideEffectKey('web_fetch', { url: 'x' })).toBeUndefined()+ expect(deriveSideEffectKey('system_info', {})).toBeUndefined()+ expect(deriveSideEffectKey('process_list', {})).toBeUndefined()+ expect(deriveSideEffectKey('get_current_time', {})).toBeUndefined()+ expect(deriveSideEffectKey('screenshot', {})).toBeUndefined()+ })++ it('returns path-specific key for file_write', () => {+ const k1 = deriveSideEffectKey('file_write', { path: '/tmp/a.txt', content: '' })+ const k2 = deriveSideEffectKey('file_write', { path: '/tmp/b.txt', content: '' })+ expect(k1).not.toBe(k2)+ expect(k1?.startsWith('file_write:')).toBe(true)+ })++ it('collapses different-case Windows paths to the same key', () => {+ const k1 = deriveSideEffectKey('file_write', { path: 'C:\\Users\\me\\a.txt', content: '' })+ const k2 = deriveSideEffectKey('file_write', { path: 'c:/users/me/a.txt', content: '' })+ expect(k1).toBe(k2)+ })++ it('collapses trailing slash + double slash', () => {+ const k1 = deriveSideEffectKey('file_write', { path: '/tmp/a/', content: '' })+ const k2 = deriveSideEffectKey('file_write', { path: '/tmp//a', content: '' })+ expect(k1).toBe(k2)+ })++ it('preserves case on Unix paths', () => {+ const k1 = deriveSideEffectKey('file_write', { path: '/tmp/Foo.txt', content: '' })+ const k2 = deriveSideEffectKey('file_write', { path: '/tmp/foo.txt', content: '' })+ expect(k1).not.toBe(k2)+ })++ it('shell_execute and code_execute share the "exec" queue', () => {+ expect(deriveSideEffectKey('shell_execute', { command: 'ls' })).toBe('exec')+ expect(deriveSideEffectKey('code_execute', { code: '1' })).toBe('exec')+ })++ it('image_generate and run_workflow share the "comfyui" queue', () => {+ expect(deriveSideEffectKey('image_generate', { prompt: 'x' })).toBe('comfyui')+ expect(deriveSideEffectKey('run_workflow', { name: 'x' })).toBe('comfyui')+ })++ it('unknown tools default to no key (fully parallel)', () => {+ expect(deriveSideEffectKey('custom_tool', {})).toBeUndefined()+ })++ it('file_write without path falls back to unknown sentinel', () => {+ expect(deriveSideEffectKey('file_write', {})).toBe('file_write:unknown')+ })+})diff --git a/src/api/agents/__tests__/tool-executor.test.ts b/src/api/agents/__tests__/tool-executor.test.tsnew file mode 100644index 00000000..4690fb77--- /dev/null+++ b/src/api/agents/__tests__/tool-executor.test.ts@@ -0,0 +1,300 @@+import { describe, it, expect, vi } from 'vitest'+import {+ executeParallel,+ type ExecutorRuntime,+ type ExecutionRequest,+ type AuditHook,+ applyResultToToolCall,+} from '../tool-executor'+import type { AgentToolCall } from '../../../types/agent-mode'++const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))++const makeRuntime = (+ overrides: Partial<ExecutorRuntime> & {+ tools?: Record<string, { inputSchema?: any; executor: (args: any) => Promise<string> }>+ } = {}+): ExecutorRuntime => {+ const tools = overrides.tools ?? {}+ return {+ getTool: overrides.getTool ?? ((name: string) => (name in tools ? { name, inputSchema: tools[name].inputSchema } : undefined)),+ execute:+ overrides.execute ??+ (async (name: string, args: Record<string, any>) => {+ if (!(name in tools)) throw new Error(`no executor for ${name}`)+ return tools[name].executor(args)+ }),+ awaitApproval: overrides.awaitApproval,+ lookupCache: overrides.lookupCache,+ recordAudit: overrides.recordAudit,+ explainError: overrides.explainError,+ }+}++const req = (id: string, toolName: string, args: Record<string, any> = {}): ExecutionRequest => ({+ id,+ toolName,+ args,+})++describe('tool-executor — basic dispatch', () => {+ it('returns empty array on no requests', async () => {+ const out = await executeParallel([], makeRuntime())+ expect(out).toEqual([])+ })++ it('routes unknown tool to failure with "Unknown tool" error', async () => {+ const out = await executeParallel([req('1', 'nope')], makeRuntime())+ expect(out[0].status).toBe('failed')+ expect(out[0].error).toMatch(/Unknown tool/)+ })++ it('dispatches a single tool and records start + complete audit', async () => {+ const audit: AuditHook[] = []+ const runtime = makeRuntime({+ tools: { greet: { executor: async () => 'hi' } },+ recordAudit: (e) => audit.push(e),+ })+ const out = await executeParallel([req('1', 'greet')], runtime)+ expect(out[0].status).toBe('completed')+ expect(out[0].result).toBe('hi')+ expect(audit.map((a) => a.kind)).toEqual(['start', 'complete'])+ })++ it('preserves input order in result array regardless of completion order', async () => {+ const runtime = makeRuntime({+ tools: {+ slow: { executor: async () => { await sleep(30); return 'slow' } },+ fast: { executor: async () => 'fast' },+ },+ })+ const out = await executeParallel(+ [req('a', 'slow'), req('b', 'fast'), req('c', 'slow')],+ runtime+ )+ expect(out.map((r) => r.id)).toEqual(['a', 'b', 'c'])+ })+})++describe('tool-executor — parallelism', () => {+ it('runs no-side-effect tools concurrently', async () => {+ const runtime = makeRuntime({+ tools: {+ a: { executor: async () => { await sleep(40); return 'a' } },+ b: { executor: async () => { await sleep(40); return 'b' } },+ c: { executor: async () => { await sleep(40); return 'c' } },+ },+ })+ const t0 = Date.now()+ const out = await executeParallel([req('1', 'a'), req('2', 'b'), req('3', 'c')], runtime)+ const elapsed = Date.now() - t0+ // Serial would be ~120 ms; parallel finishes well under 100 ms.+ expect(elapsed).toBeLessThan(100)+ expect(out.every((r) => r.status === 'completed')).toBe(true)+ })++ it('serializes calls sharing a sideEffectKey (e.g. shell_execute)', async () => {+ // shell_execute maps to the "exec" queue.+ const order: string[] = []+ const runtime = makeRuntime({+ tools: {+ shell_execute: {+ executor: async (args: any) => {+ order.push(`start:${args.tag}`)+ await sleep(30)+ order.push(`end:${args.tag}`)+ return `done:${args.tag}`+ },+ },+ },+ })+ const out = await executeParallel(+ [+ req('1', 'shell_execute', { command: 'a', tag: 'a' }),+ req('2', 'shell_execute', { command: 'b', tag: 'b' }),+ ],+ runtime+ )+ expect(out.every((r) => r.status === 'completed')).toBe(true)+ // Serial: a must finish before b starts.+ expect(order).toEqual(['start:a', 'end:a', 'start:b', 'end:b'])+ })++ it('serializes two file_write to same path but not to different paths', async () => {+ const order: string[] = []+ const runtime = makeRuntime({+ tools: {+ file_write: {+ executor: async (args: any) => {+ order.push(`start:${args.path}`)+ await sleep(30)+ order.push(`end:${args.path}`)+ return 'ok'+ },+ },+ },+ })+ const t0 = Date.now()+ await executeParallel(+ [+ req('1', 'file_write', { path: '/tmp/a', content: '' }),+ req('2', 'file_write', { path: '/tmp/a', content: '' }), // same path — serial+ req('3', 'file_write', { path: '/tmp/b', content: '' }), // different — parallel w/ group A+ ],+ runtime+ )+ const elapsed = Date.now() - t0+ // Two serial writes to /tmp/a (~60 ms) run in parallel with one write to /tmp/b (~30 ms).+ // Total should be ~60 ms, well under 90 ms (full serial).+ expect(elapsed).toBeLessThan(90)+ // The two /tmp/a ops must be serial.+ const aEvents = order.filter((s) => s.endsWith('/tmp/a'))+ expect(aEvents).toEqual(['start:/tmp/a', 'end:/tmp/a', 'start:/tmp/a', 'end:/tmp/a'])+ })+})++describe('tool-executor — failures', () => {+ it('one failing sibling does not abort the others', async () => {+ const runtime = makeRuntime({+ tools: {+ ok: { executor: async () => 'yay' },+ boom: {+ executor: async () => {+ throw new Error('kaboom')+ },+ },+ },+ })+ const out = await executeParallel(+ [req('a', 'ok'), req('b', 'boom'), req('c', 'ok')],+ runtime+ )+ expect(out[0].status).toBe('completed')+ expect(out[1].status).toBe('failed')+ expect(out[1].error).toMatch(/kaboom/)+ expect(out[2].status).toBe('completed')+ })++ it('validation failure short-circuits dispatch with structured error', async () => {+ const runtime = makeRuntime({+ tools: {+ needs_arg: {+ inputSchema: {+ type: 'object',+ properties: { x: { type: 'string' } },+ required: ['x'],+ },+ executor: async () => 'unreachable',+ },+ },+ })+ const out = await executeParallel([req('1', 'needs_arg', {})], runtime)+ expect(out[0].status).toBe('failed')+ expect(out[0].schemaValidated).toBe(false)+ expect(out[0].validationError).toMatch(/x/)+ expect(out[0].error).toMatch(/Invalid arguments/)+ })++ it('explainError attaches a hint to failure results', async () => {+ const runtime = makeRuntime({+ tools: {+ boom: {+ executor: async () => {+ throw new Error('ENOENT: no such file')+ },+ },+ },+ explainError: (_name, err) =>+ /ENOENT/.test(err) ? 'Path not found. Try file_list first.' : undefined,+ })+ const out = await executeParallel([req('1', 'boom')], runtime)+ expect(out[0].errorHint).toMatch(/file_list/)+ })+})++describe('tool-executor — cache + approval', () => {+ it('returns cached result without invoking executor', async () => {+ const exec = vi.fn(async () => 'fresh')+ const runtime = makeRuntime({+ tools: { t: { executor: exec } },+ lookupCache: () => 'from-cache',+ })+ const out = await executeParallel([req('1', 't')], runtime)+ expect(out[0].status).toBe('cached')+ expect(out[0].result).toBe('from-cache')+ expect(out[0].cacheHit).toBe(true)+ expect(exec).not.toHaveBeenCalled()+ })++ it('rejected approval marks call rejected, skips dispatch', async () => {+ const exec = vi.fn(async () => 'fresh')+ const runtime = makeRuntime({+ tools: { t: { executor: exec } },+ awaitApproval: async () => false,+ })+ const out = await executeParallel([req('1', 't')], runtime)+ expect(out[0].status).toBe('rejected')+ expect(exec).not.toHaveBeenCalled()+ })+})++describe('tool-executor — abort', () => {+ it('aborted requests resolve as rejected without dispatching', async () => {+ const exec = vi.fn(async () => 'fresh')+ const runtime = makeRuntime({ tools: { t: { executor: exec } } })+ const controller = new AbortController()+ controller.abort()+ const out = await executeParallel([req('1', 't')], runtime, { abortSignal: controller.signal })+ expect(out[0].status).toBe('rejected')+ expect(exec).not.toHaveBeenCalled()+ })+})++describe('tool-executor — applyResultToToolCall', () => {+ it('maps ExecutionResult back onto AgentToolCall fields', () => {+ const call: AgentToolCall = {+ id: '1',+ toolName: 't',+ args: {},+ status: 'pending_approval',+ timestamp: 0,+ }+ applyResultToToolCall(call, {+ id: '1',+ toolName: 't',+ status: 'completed',+ result: 'ok',+ dispatchedArgs: {},+ argsHash: 'h',+ sideEffectKey: undefined,+ startedAt: 10,+ completedAt: 20,+ durationMs: 10,+ cacheHit: false,+ schemaValidated: true,+ })+ expect(call.status).toBe('completed')+ expect(call.result).toBe('ok')+ expect(call.duration).toBe(10)+ expect(call.schemaValidated).toBe(true)+ })++ it('translates cached result into cached status', () => {+ const call: AgentToolCall = { id: '1', toolName: 't', args: {}, status: 'pending_approval', timestamp: 0 }+ applyResultToToolCall(call, {+ id: '1',+ toolName: 't',+ status: 'cached',+ result: 'cached',+ dispatchedArgs: {},+ argsHash: 'h',+ startedAt: 0,+ completedAt: 0,+ durationMs: 0,+ cacheHit: true,+ schemaValidated: true,+ })+ expect(call.status).toBe('cached')+ expect(call.cacheHit).toBe(true)+ })+})diff --git a/src/api/agents/side-effect-key.ts b/src/api/agents/side-effect-key.tsnew file mode 100644index 00000000..3cf23841--- /dev/null+++ b/src/api/agents/side-effect-key.ts@@ -0,0 +1,58 @@+/**+ * Phase 5 (v2.4.0) — Side-effect key derivation.+ *+ * When a ReAct turn emits multiple tool calls, we want to run them+ * concurrently for speed, BUT two calls that touch the same shared+ * resource must be serialized. The scheduler groups calls by+ * sideEffectKey and runs one group in parallel but within-group in+ * sequence.+ *+ * - Pure reads (file_read, web_fetch, web_search, system_info,+ * process_list, file_list, file_search, get_current_time,+ * screenshot) → no key (fully parallel-safe).+ *+ * - file_write → key is `file_write:<normalized-path>`. Two writes to+ * the SAME path serialize; writes to DIFFERENT paths remain parallel.+ *+ * - shell_execute, code_execute → key 'exec'. We do not know what a+ * shell command touches, so batch all exec-class calls onto a single+ * queue.+ *+ * - image_generate, run_workflow → key 'comfyui'. ComfyUI serializes+ * internally and workflows do heavy I/O; running in parallel provides+ * no win and competes for the GPU.+ */++export function deriveSideEffectKey(+ toolName: string,+ args: Record<string, any>+): string | undefined {+ switch (toolName) {+ case 'file_write': {+ const path = typeof args?.path === 'string' ? normalizePath(args.path) : ''+ return path ? `file_write:${path}` : 'file_write:unknown'+ }+ case 'shell_execute':+ case 'code_execute':+ return 'exec'+ case 'image_generate':+ case 'run_workflow':+ return 'comfyui'+ default:+ // file_read, file_list, file_search, web_search, web_fetch,+ // system_info, process_list, get_current_time, screenshot.+ return undefined+ }+}++function normalizePath(p: string): string {+ // Windows paths case-insensitively; Unix paths case-sensitively. Keep+ // behaviour conservative: lowercase on Windows, preserve on Unix.+ const isWindowsLike = /^[A-Za-z]:[\\\/]/.test(p) || p.startsWith('\\\\')+ let out = p.trim().replace(/\\/g, '/')+ // Collapse trailing slash so "./foo" and "./foo/" collide.+ out = out.replace(/\/+$/, '')+ // Collapse double slashes.+ out = out.replace(/\/{2,}/g, '/')+ return isWindowsLike ? out.toLowerCase() : out+}diff --git a/src/api/agents/tool-executor.ts b/src/api/agents/tool-executor.tsnew file mode 100644index 00000000..6a0b045f--- /dev/null+++ b/src/api/agents/tool-executor.ts@@ -0,0 +1,367 @@+/**+ * Phase 5 (v2.4.0) — Parallel tool executor.+ *+ * Replaces the serial for-loop in useAgentChat / useCodex / mobile ReAct+ * with a scheduler that:+ *+ * 1. Validates args via args-validator (Phase 4).+ * 2. Records dispatch to toolAuditStore (Phase 2).+ * 3. Groups calls by sideEffectKey (Phase 5) — same key serial, different+ * keys parallel. Pure reads (no key) run fully in parallel.+ * 4. Uses Promise.allSettled so one failure does not abort siblings.+ * 5. Reports per-call completion back to the caller via onComplete.+ *+ * The executor is deliberately framework-agnostic — no React, no Zustand+ * calls (stores are plumbed in via dependency injection). This keeps it+ * testable in node-env vitest and keeps the hook integration thin.+ */++import type { AgentToolCall } from '../../types/agent-mode'+import { deriveSideEffectKey } from './side-effect-key'+import { validateToolArgs, formatValidationErrors, type JsonSchema } from './args-validator'+import { stableArgsHash } from './block-helpers'++export interface ExecutorToolDef {+ name: string+ inputSchema?: JsonSchema+}++export interface ExecutionRequest {+ /** Unique id for this tool call, matches AgentToolCall.id. */+ id: string+ /** Tool name — must be registered in the executor's runtime. */+ toolName: string+ /** Raw args from the LLM. */+ args: Record<string, any>+ /** Optional parent id for sub-agent lineage. */+ parentToolCallId?: string+}++export interface ExecutionResult {+ id: string+ toolName: string+ status: 'completed' | 'failed' | 'rejected' | 'cached'+ /** String result (executor outputs). */+ result?: string+ error?: string+ /** Human-readable retry hint (filled by Phase 7 error-hints module). */+ errorHint?: string+ /** Validated + coerced args that were actually dispatched. */+ dispatchedArgs: Record<string, any>+ argsHash: string+ sideEffectKey?: string+ startedAt: number+ completedAt: number+ durationMs: number+ cacheHit: boolean+ /** True when args-validator accepted the args (or no schema was provided). */+ schemaValidated: boolean+ /** When validation failed, the error text sent to the next LLM turn. */+ validationError?: string+}++export type ExecutorFn = (args: Record<string, any>) => Promise<string>++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 & ((name: string, args: Record<string, any>) => Promise<string>)+ /** Optional — called before dispatch to gate on user approval. */+ awaitApproval?: (req: ExecutionRequest, tool: ExecutorToolDef) => Promise<boolean>+ /** 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+ /** Optional — error hint mapper (Phase 7). */+ explainError?: (toolName: string, error: string) => string | undefined+}++export type AuditHook =+ | {+ kind: 'start'+ id: string+ toolName: string+ args: Record<string, any>+ argsHash: string+ parentToolCallId?: string+ startedAt: number+ }+ | {+ kind: 'complete'+ id: string+ status: ExecutionResult['status']+ completedAt: number+ durationMs: number+ cacheHit: boolean+ resultPreview?: string+ error?: string+ errorHint?: string+ }++export interface ExecutorOptions {+ /** Fires when a call transitions to running. */+ onStart?: (req: ExecutionRequest) => void+ /** Fires when a call settles. */+ onComplete?: (res: ExecutionResult) => void+ /** Aborts remaining not-yet-started calls when flipped true. */+ abortSignal?: AbortSignal+}++/**+ * Run a batch of tool calls. Returns ordered results matching the input order.+ *+ * Scheduling:+ * - Calls with no sideEffectKey run in parallel.+ * - Calls sharing a key run serially within their group.+ * - Groups with different keys run in parallel with each other and with the+ * no-key pool.+ */+export async function executeParallel(+ requests: ExecutionRequest[],+ runtime: ExecutorRuntime,+ opts: ExecutorOptions = {}+): Promise<ExecutionResult[]> {+ if (requests.length === 0) return []++ // Tag each request with its side-effect key up front so tests can inspect+ // the schedule and the audit recorder sees consistent keys.+ const tagged = requests.map((req) => ({+ req,+ key: deriveSideEffectKey(req.toolName, req.args),+ }))++ // Index → result slot so we can preserve input order.+ const results: (ExecutionResult | undefined)[] = Array(requests.length).fill(undefined)++ // Group by key. `undefined` means "no shared key" — each goes to its own+ // solo group so it runs concurrently with everything else.+ const groups = new Map<string, number[]>()+ const soloIndices: number[] = []+ tagged.forEach((t, i) => {+ if (!t.key) {+ soloIndices.push(i)+ } else {+ const list = groups.get(t.key) ?? []+ list.push(i)+ groups.set(t.key, list)+ }+ })++ const runOne = async (index: number): Promise<void> => {+ if (opts.abortSignal?.aborted) {+ results[index] = abortedResult(tagged[index])+ opts.onComplete?.(results[index]!)+ return+ }+ const res = await runSingle(tagged[index].req, tagged[index].key, runtime, opts)+ results[index] = res+ opts.onComplete?.(res)+ }++ const solo = soloIndices.map(runOne)++ const grouped = [...groups.values()].map(async (indices) => {+ for (const i of indices) {+ await runOne(i)+ }+ })++ await Promise.all([...solo, ...grouped])+ return results.map((r, i) => r ?? abortedResult(tagged[i]))+}++async function runSingle(+ req: ExecutionRequest,+ sideEffectKey: string | undefined,+ runtime: ExecutorRuntime,+ opts: ExecutorOptions+): Promise<ExecutionResult> {+ const startedAt = Date.now()+ const argsHash = stableArgsHash(req.args ?? {})++ opts.onStart?.(req)+ runtime.recordAudit?.({+ kind: 'start',+ id: req.id,+ toolName: req.toolName,+ args: req.args,+ argsHash,+ parentToolCallId: req.parentToolCallId,+ startedAt,+ })++ const finalize = (partial: Omit<ExecutionResult, 'completedAt' | 'durationMs'>): ExecutionResult => {+ const completedAt = Date.now()+ const durationMs = completedAt - startedAt+ const result: ExecutionResult = { ...partial, completedAt, durationMs }+ runtime.recordAudit?.({+ kind: 'complete',+ id: req.id,+ status: result.status,+ completedAt,+ durationMs,+ cacheHit: result.cacheHit,+ resultPreview: result.result,+ error: result.error,+ errorHint: result.errorHint,+ })+ return result+ }++ const tool = runtime.getTool(req.toolName)+ if (!tool) {+ return finalize({+ id: req.id,+ toolName: req.toolName,+ status: 'failed',+ error: `Unknown tool: ${req.toolName}`,+ dispatchedArgs: req.args,+ argsHash,+ sideEffectKey,+ startedAt,+ cacheHit: false,+ schemaValidated: false,+ })+ }++ // Schema validate (Phase 4).+ let dispatchedArgs = req.args ?? {}+ let schemaValidated = true+ let validationError: string | undefined+ if (tool.inputSchema) {+ const v = validateToolArgs(req.args ?? {}, tool.inputSchema)+ if (!v.valid) {+ schemaValidated = false+ validationError = formatValidationErrors(v.errors)+ return finalize({+ id: req.id,+ toolName: req.toolName,+ status: 'failed',+ error: `Invalid arguments: ${validationError}`,+ errorHint: 'Re-issue the tool call with valid arguments matching the tool schema.',+ dispatchedArgs: req.args,+ argsHash,+ sideEffectKey,+ startedAt,+ cacheHit: false,+ schemaValidated: false,+ validationError,+ })+ }+ if (v.coerced) dispatchedArgs = v.coerced+ }++ // Cache lookup (Phase 6 integration point).+ const cached = runtime.lookupCache?.(req, argsHash)+ if (typeof cached === 'string') {+ return finalize({+ id: req.id,+ toolName: req.toolName,+ status: 'cached',+ result: cached,+ dispatchedArgs,+ argsHash,+ sideEffectKey,+ startedAt,+ cacheHit: true,+ schemaValidated,+ })+ }++ // 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,+ })+ }+ }++ // Dispatch.+ try {+ const result = await runtime.execute(req.toolName, dispatchedArgs)+ return finalize({+ id: req.id,+ toolName: req.toolName,+ status: 'completed',+ result,+ dispatchedArgs,+ argsHash,+ sideEffectKey,+ startedAt,+ cacheHit: false,+ schemaValidated,+ })+ } catch (err) {+ const errorText = err instanceof Error ? err.message : String(err)+ const hint = runtime.explainError?.(req.toolName, errorText)+ return finalize({+ id: req.id,+ toolName: req.toolName,+ status: 'failed',+ error: errorText,+ errorHint: hint,+ dispatchedArgs,+ argsHash,+ sideEffectKey,+ startedAt,+ cacheHit: false,+ schemaValidated,+ })+ }+}++function abortedResult(tagged: { req: ExecutionRequest; key?: string }): ExecutionResult {+ const now = Date.now()+ const argsHash = stableArgsHash(tagged.req.args ?? {})+ return {+ id: tagged.req.id,+ toolName: tagged.req.toolName,+ status: 'rejected',+ error: 'Aborted before dispatch',+ dispatchedArgs: tagged.req.args,+ argsHash,+ sideEffectKey: tagged.key,+ startedAt: now,+ completedAt: now,+ durationMs: 0,+ cacheHit: false,+ schemaValidated: false,+ }+}++/** Convenience: attach ExecutionResult fields back onto an AgentToolCall. */+export function applyResultToToolCall(call: AgentToolCall, result: ExecutionResult): AgentToolCall {+ call.status =+ result.status === 'completed'+ ? 'completed'+ : result.status === 'cached'+ ? 'cached'+ : result.status === 'rejected'+ ? 'rejected'+ : 'failed'+ if (result.result !== undefined) call.result = result.result+ if (result.error !== undefined) call.error = result.error+ if (result.errorHint !== undefined) call.errorHint = result.errorHint+ call.duration = result.durationMs+ call.startedAt = result.startedAt+ call.completedAt = result.completedAt+ call.cacheHit = result.cacheHit+ call.schemaValidated = result.schemaValidated+ call.sideEffectKey = result.sideEffectKey+ return call+}