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 13: Sub-agent delegation via delegate_task tool (v2.4.0)

PurpleDoubleD14b8d559876f
diff --git a/src/api/__tests__/tool-description-parity.test.ts b/src/api/__tests__/tool-description-parity.test.ts
index 546b8f81..267711fc 100644
--- a/src/api/__tests__/tool-description-parity.test.ts
+++ b/src/api/__tests__/tool-description-parity.test.ts
@@ -141,9 +141,11 @@ describe('tool-description-parity — extraction sanity', () => {
})
// Tools intentionally absent on mobile because their executor relies on
-// desktop-only TypeScript code paths (WorkflowEngine for run_workflow).
-// Expanding this set requires wiring the Rust /remote-api/agent-tool dispatcher.
-const MOBILE_SKIP: ReadonlySet<string> = new Set<string>(['run_workflow'])
+// desktop-only TypeScript code paths. Expanding this set requires wiring
+// the Rust /remote-api/agent-tool dispatcher.
+// run_workflow → needs WorkflowEngine (TS)
+// delegate_task → needs sub-agent runner with provider access (TS)
+const MOBILE_SKIP: ReadonlySet<string> = new Set<string>(['run_workflow', 'delegate_task'])
describe('tool-description-parity — name sets', () => {
it('desktop and mobile expose the same set of tool names (modulo documented skips)', () => {
diff --git a/src/api/__tests__/tool-registry.test.ts b/src/api/__tests__/tool-registry.test.ts
index f197ff9f..0275e58a 100644
--- a/src/api/__tests__/tool-registry.test.ts
+++ b/src/api/__tests__/tool-registry.test.ts
@@ -9,8 +9,9 @@ import {
// ── AGENT_TOOL_DEFS ─────────────────────────────────────────────
describe('AGENT_TOOL_DEFS', () => {
- it('contains exactly 14 tool definitions', () => {
- expect(AGENT_TOOL_DEFS).toHaveLength(14)
+ it('contains exactly 15 tool definitions', () => {
+ // Phase 13 v2.4.0: delegate_task added as a builtin.
+ expect(AGENT_TOOL_DEFS).toHaveLength(15)
})
const expectedTools = [
@@ -53,11 +54,12 @@ describe('AGENT_TOOL_DEFS', () => {
expect(autoNames).toEqual(['get_current_time', 'process_list', 'system_info', 'web_fetch', 'web_search'])
})
- it('confirm-permission tools include file ops, code, shell, image, workflow, screenshot', () => {
+ it('confirm-permission tools include file ops, code, shell, image, workflow, screenshot, delegate_task', () => {
const confirmTools = AGENT_TOOL_DEFS.filter((t) => t.permission === 'confirm')
const confirmNames = confirmTools.map((t) => t.name).sort()
+ // Phase 13 v2.4.0: delegate_task added under workflow category (confirm default).
expect(confirmNames).toEqual([
- 'code_execute', 'file_list', 'file_read', 'file_search',
+ 'code_execute', 'delegate_task', 'file_list', 'file_read', 'file_search',
'file_write', 'image_generate', 'run_workflow', 'screenshot', 'shell_execute',
])
})
diff --git a/src/api/agents/__tests__/sub-agent.test.ts b/src/api/agents/__tests__/sub-agent.test.ts
new file mode 100644
index 00000000..a3eb8e37
--- /dev/null
+++ b/src/api/agents/__tests__/sub-agent.test.ts
@@ -0,0 +1,113 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import {
+ DELEGATE_TASK_TOOL_DEF,
+ SUB_AGENT_MAX_DEPTH,
+ SUB_AGENT_BUDGET,
+ buildDelegateExecutor,
+ _getDepth,
+ _setDepth,
+} from '../sub-agent'
+
+describe('sub-agent — tool definition', () => {
+ it('has the expected shape', () => {
+ expect(DELEGATE_TASK_TOOL_DEF.name).toBe('delegate_task')
+ expect(DELEGATE_TASK_TOOL_DEF.category).toBe('workflow')
+ expect(DELEGATE_TASK_TOOL_DEF.source).toBe('builtin')
+ expect(DELEGATE_TASK_TOOL_DEF.inputSchema.required).toContain('goal')
+ })
+
+ it('description contains the nesting warning', () => {
+ expect(DELEGATE_TASK_TOOL_DEF.description).toMatch(/nesting depth is 2/i)
+ })
+})
+
+describe('sub-agent — buildDelegateExecutor', () => {
+ beforeEach(() => {
+ _setDepth(0)
+ })
+
+ it('rejects calls without a goal argument', async () => {
+ const exec = buildDelegateExecutor(async () => 'unreachable')
+ const out = await exec({})
+ expect(out).toMatch(/requires a "goal" argument/i)
+ })
+
+ it('rejects whitespace-only goal', async () => {
+ const exec = buildDelegateExecutor(async () => 'unreachable')
+ const out = await exec({ goal: ' ' })
+ expect(out).toMatch(/requires a "goal" argument/i)
+ })
+
+ it('invokes runner with trimmed goal + context + fresh budget', async () => {
+ const runner = vi.fn(async (goal: string, context: string, { budget }: any) => {
+ expect(goal).toBe('do the thing')
+ expect(context).toBe('background notes')
+ expect(budget.snapshot()).toEqual({
+ toolCalls: 0,
+ iterations: 0,
+ caps: { ...SUB_AGENT_BUDGET },
+ })
+ return 'final answer'
+ })
+ const exec = buildDelegateExecutor(runner)
+ const out = await exec({ goal: ' do the thing ', context: ' background notes ' })
+ expect(out).toBe('final answer')
+ expect(runner).toHaveBeenCalledOnce()
+ })
+
+ it('depth resets after a successful run', async () => {
+ const runner = vi.fn(async () => 'ok')
+ const exec = buildDelegateExecutor(runner)
+ await exec({ goal: 'x' })
+ expect(_getDepth()).toBe(0)
+ })
+
+ it('depth resets even when runner throws', async () => {
+ const runner = vi.fn(async () => {
+ throw new Error('boom')
+ })
+ const exec = buildDelegateExecutor(runner)
+ const out = await exec({ goal: 'x' })
+ expect(out).toMatch(/Error: boom/)
+ expect(_getDepth()).toBe(0)
+ })
+
+ it('refuses once MAX_DEPTH is reached', async () => {
+ _setDepth(SUB_AGENT_MAX_DEPTH)
+ const runner = vi.fn(async () => 'should not run')
+ const exec = buildDelegateExecutor(runner)
+ const out = await exec({ goal: 'x' })
+ expect(out).toMatch(/Maximum sub-agent nesting depth/)
+ expect(runner).not.toHaveBeenCalled()
+ // And the tracker is not nudged by a refused call.
+ expect(_getDepth()).toBe(SUB_AGENT_MAX_DEPTH)
+ })
+
+ it('allows a call at depth = MAX_DEPTH - 1 (recursive boundary)', async () => {
+ _setDepth(SUB_AGENT_MAX_DEPTH - 1)
+ const runner = vi.fn(async () => 'ok')
+ const exec = buildDelegateExecutor(runner)
+ const out = await exec({ goal: 'x' })
+ expect(out).toBe('ok')
+ expect(_getDepth()).toBe(SUB_AGENT_MAX_DEPTH - 1)
+ })
+
+ it('serialises concurrent calls via shared depth counter (approximate)', async () => {
+ // Two simultaneous executors, each with its own goal. Both increment
+ // _depth on the way in; neither should see > 2 depth even when
+ // interleaved, because _depth is incremented synchronously before
+ // the async runner awaits.
+ let observedMax = 0
+ const runner = async () => {
+ observedMax = Math.max(observedMax, _getDepth())
+ await new Promise((r) => setTimeout(r, 5))
+ return 'done'
+ }
+ const exec = buildDelegateExecutor(runner)
+ await Promise.all([exec({ goal: 'a' }), exec({ goal: 'b' })])
+ // Two concurrent calls both pass the guard at depth 0 and 1, so the
+ // observed max is SUB_AGENT_MAX_DEPTH. A THIRD concurrent call would
+ // be refused before the runner fires.
+ expect(observedMax).toBeLessThanOrEqual(SUB_AGENT_MAX_DEPTH)
+ })
+})
diff --git a/src/api/agents/sub-agent.ts b/src/api/agents/sub-agent.ts
new file mode 100644
index 00000000..0549dec0
--- /dev/null
+++ b/src/api/agents/sub-agent.ts
@@ -0,0 +1,185 @@
+/**
+ * Phase 13 (v2.4.0) — Sub-agent delegation.
+ *
+ * Exposes a `delegate_task` builtin tool that spawns a nested ReAct loop
+ * with a sub-goal, its own isolated AgentBudget, and the same tool
+ * registry minus `delegate_task` itself (so a sub-agent cannot fork-bomb
+ * a tree of delegations).
+ *
+ * Depth is capped at 2 globally — a sub-agent that attempts to call
+ * delegate_task returns a refusal string. Combined with the tool-list
+ * filtering, the model has no syntactically valid path to recurse.
+ */
+
+import type { MCPToolDefinition } from '../mcp/types'
+import { executeParallel, type ExecutionRequest } from './tool-executor'
+import { AgentBudget } from './budget'
+import { explainError as explainToolError } from './error-hints'
+
+// NOTE: the toolRegistry import is done LAZILY inside defaultSubAgentRunner
+// to avoid a circular dependency with src/api/mcp/builtin-tools.ts, which
+// pulls DELEGATE_TASK_TOOL_DEF + buildDelegateExecutor from this file at
+// module init.
+
+/** Max sub-agent nesting depth. Incremented on every delegate_task call. */
+export const SUB_AGENT_MAX_DEPTH = 2
+
+/** Tight caps so a sub-agent cannot runaway inside the parent's budget. */
+export const SUB_AGENT_BUDGET = { maxToolCalls: 10, maxIterations: 5 } as const
+
+export const DELEGATE_TASK_TOOL_DEF: MCPToolDefinition = {
+ name: 'delegate_task',
+ description:
+ 'Spawn a focused sub-agent to work on a sub-goal autonomously. '
+ + 'USE for self-contained research or analysis tasks that would pollute the main conversation with tool-call chatter. '
+ + 'The sub-agent has its own tight budget (max 10 tool calls, 5 ReAct iterations) and returns a concise final answer. '
+ + 'DO NOT call from inside another delegate_task — max nesting depth is 2. '
+ + 'NOT a replacement for a regular tool call when one direct tool would do.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ goal: {
+ type: 'string',
+ description: 'One-sentence statement of what the sub-agent should accomplish.',
+ },
+ context: {
+ type: 'string',
+ description: 'Optional background information the sub-agent needs but should not search for.',
+ },
+ },
+ required: ['goal'],
+ },
+ category: 'workflow',
+ source: 'builtin',
+}
+
+/**
+ * Depth tracker — module-scoped so nested sub-agents across async
+ * boundaries stay bounded. Reset only by successful return or thrown
+ * error; see the try/finally in the executor.
+ */
+let _depth = 0
+
+/** Exposed for tests. */
+export function _getDepth(): number {
+ return _depth
+}
+/** Exposed for tests. */
+export function _setDepth(n: number): void {
+ _depth = n
+}
+
+export type SubAgentRunner = (
+ goal: string,
+ context: string,
+ options: { budget: AgentBudget }
+) => Promise<string>
+
+/**
+ * Default sub-agent runner. Pulls in the active provider + model via
+ * dynamic import to keep this module standalone and testable with a
+ * stub runner. The real hook wiring lives in buildDelegateExecutor().
+ */
+export async function defaultSubAgentRunner(
+ goal: string,
+ context: string,
+ options: { budget: AgentBudget }
+): Promise<string> {
+ const { useModelStore } = await import('../../stores/modelStore')
+ const { getProviderForModel } = await import('../providers')
+ const { toolRegistry } = await import('../mcp')
+ const activeModel = useModelStore.getState().activeModel
+ if (!activeModel) return 'Error: No active model configured.'
+ const { provider, modelId } = getProviderForModel(activeModel)
+
+ const tools: MCPToolDefinition[] = toolRegistry
+ .getAll()
+ .filter((t) => t.name !== DELEGATE_TASK_TOOL_DEF.name)
+
+ const llmTools = tools.map((t) => ({
+ type: 'function' as const,
+ function: { name: t.name, description: t.description, parameters: t.inputSchema },
+ }))
+
+ const messages: any[] = [
+ {
+ role: 'system',
+ content:
+ 'You are a focused sub-agent. Work autonomously toward the goal. '
+ + 'Be concise — return a direct final answer without filler. '
+ + 'Do NOT attempt to call delegate_task; it is not available to you.',
+ },
+ {
+ role: 'user',
+ content: context ? `Goal: ${goal}\n\nContext:\n${context}` : `Goal: ${goal}`,
+ },
+ ]
+
+ let finalContent = ''
+ for (let i = 0; i < SUB_AGENT_BUDGET.maxIterations; i++) {
+ options.budget.addIteration()
+ const ex = options.budget.exceeded()
+ if (ex.kind !== 'none') {
+ return `${options.budget.haltMessage()} ${finalContent || '(no partial answer)'}`
+ }
+ const turn = await provider.chatWithTools(modelId, messages, llmTools, {})
+ finalContent = turn.content || finalContent
+ if (!turn.toolCalls || turn.toolCalls.length === 0) break
+
+ options.budget.addToolCalls(turn.toolCalls.length)
+ const requests: ExecutionRequest[] = turn.toolCalls.map((tc, idx) => ({
+ id: `sub-${Date.now()}-${idx}`,
+ toolName: tc.function.name,
+ args: tc.function.arguments,
+ parentToolCallId: 'sub-agent',
+ }))
+ const registry = toolRegistry
+ const results = await executeParallel(requests, {
+ getTool: (name) => {
+ const td = registry.getToolByName(name)
+ return td ? { name: td.name, inputSchema: td.inputSchema } : undefined
+ },
+ execute: (name, args) => registry.execute(name, args),
+ explainError: (toolName, err) => explainToolError(toolName, err),
+ })
+
+ messages.push({ role: 'assistant', content: turn.content || '', tool_calls: turn.toolCalls })
+ for (const r of results) {
+ const tc = turn.toolCalls.find((t) => t.function.name === r.toolName)
+ messages.push({
+ role: 'tool',
+ content: r.result ?? r.error ?? '(no output)',
+ tool_call_id: tc?.id,
+ })
+ }
+ }
+
+ return finalContent || '(sub-agent produced no final answer)'
+}
+
+/**
+ * Build a tool executor suitable for toolRegistry.registerBuiltin. The
+ * runner is injectable so tests can stub the whole LLM round-trip.
+ */
+export function buildDelegateExecutor(
+ runner: SubAgentRunner = defaultSubAgentRunner
+): (args: Record<string, any>) => Promise<string> {
+ return async (args: Record<string, any>) => {
+ if (_depth >= SUB_AGENT_MAX_DEPTH) {
+ return 'Error: Maximum sub-agent nesting depth (2) reached. Continue the task yourself.'
+ }
+ const goal = typeof args.goal === 'string' ? args.goal.trim() : ''
+ if (!goal) return 'Error: delegate_task requires a "goal" argument.'
+ const context = typeof args.context === 'string' ? args.context.trim() : ''
+
+ _depth++
+ try {
+ const budget = new AgentBudget({ ...SUB_AGENT_BUDGET })
+ return await runner(goal, context, { budget })
+ } catch (err) {
+ return `Error: ${err instanceof Error ? err.message : String(err)}`
+ } finally {
+ _depth--
+ }
+ }
+}
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 2a3875f2..92cd125e 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -6,6 +6,7 @@ import { backendCall, fetchExternal } from '../backend'
import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
import { WorkflowEngine } from '../../lib/workflow-engine'
import type { StepResult } from '../../types/agent-workflows'
+import { DELEGATE_TASK_TOOL_DEF, buildDelegateExecutor } from '../agents/sub-agent'
// ── Tool Definitions ────────────────────────────────────────────
@@ -242,6 +243,9 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [
source: 'builtin',
},
+ // Sub-agent delegation (Phase 13 v2.4.0).
+ DELEGATE_TASK_TOOL_DEF,
+
// Local clock — so the agent never googles "what day is it".
{
name: 'get_current_time',
@@ -550,6 +554,7 @@ const EXECUTOR_MAP: Record<string, (args: Record<string, any>) => Promise<string
image_generate: executeImageGenerate,
run_workflow: executeRunWorkflow,
get_current_time: executeGetCurrentTime,
+ delegate_task: buildDelegateExecutor(),
}
export function registerBuiltinTools(registry: ToolRegistry) {