From 32af25fc9980c505c16889b47e78feb7feafbc95 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 11 Dec 2025 13:17:29 +0530 Subject: [PATCH] feat: subagents --- extensions/cli/src/subagent/builtInAgents.ts | 83 ++++++++ extensions/cli/src/subagent/executor.ts | 213 +++++++++++++++++++ extensions/cli/src/subagent/types.ts | 15 ++ extensions/cli/src/tools/allBuiltIns.ts | 2 + extensions/cli/src/tools/index.tsx | 23 ++ extensions/cli/src/tools/task.ts | 115 ++++++++++ extensions/cli/src/ui/ToolResultSummary.tsx | 51 +++++ 7 files changed, 502 insertions(+) create mode 100644 extensions/cli/src/subagent/builtInAgents.ts create mode 100644 extensions/cli/src/subagent/executor.ts create mode 100644 extensions/cli/src/subagent/types.ts create mode 100644 extensions/cli/src/tools/task.ts diff --git a/extensions/cli/src/subagent/builtInAgents.ts b/extensions/cli/src/subagent/builtInAgents.ts new file mode 100644 index 000000000..ba6cab8e5 --- /dev/null +++ b/extensions/cli/src/subagent/builtInAgents.ts @@ -0,0 +1,83 @@ +import { AgentConfig } from "./types.js"; + +// todo - move this to the subagent directory + +/** + * Built-in agent configurations + */ +export const BUILT_IN_AGENTS: Record = { + general: { + name: "general", + displayName: "General Agent", + description: + "General-purpose agent for researching complex questions and executing multi-step tasks autonomously", + tools: { + // Enable all standard tools (refactor to use BUILTIN_TOOLS) + Read: true, + Write: true, + Edit: true, + multiEdit: true, + listFiles: true, + searchCode: true, + runTerminalCommand: true, + Fetch: true, + writeChecklist: true, + // Explicitly disable Task to prevent recursion + Task: false, + }, + // model: "haiku-4-5-latest", // if the model is not there, skip the task tool (check api key?) + systemPrompt: `You are a specialized task execution agent. + +Your role: +- Work autonomously to complete the given task +- Use available tools effectively +- Provide clear, concise results +- If you cannot complete the task, explain why clearly + +Important: +- Focus on the specific task at hand +- Avoid unnecessary explanations or preamble in your final response +- Return actionable results`, + }, +}; + +/** + * Get an agent by name + */ +export function getAgent(name: string): AgentConfig | null { + return BUILT_IN_AGENTS[name] || null; +} + +/** + * List all available subagents + */ +export function listSubagents(): AgentConfig[] { + return Object.values(BUILT_IN_AGENTS); +} + +/** + * Generate dynamic tool description listing available agents + */ +export function generateTaskToolDescription(): string { + const agents = listSubagents(); + const agentList = agents + .map((agent) => ` - ${agent.name}: ${agent.description}`) + .join("\n"); + + return `Launch a specialized agent to handle complex, multi-step tasks autonomously. + +Available agent types: +${agentList} + +When to use this tool: +- Complex research tasks requiring multiple file reads and searches +- Multi-step implementation tasks +- Tasks that benefit from autonomous execution +- When you need to parallelize independent work + +When NOT to use this tool: +- Simple single-file reads (use Read tool instead) +- Single searches (use searchCode tool instead) +- Tasks you can complete directly with available tools +- Trivial operations that don't require multiple steps`; +} diff --git a/extensions/cli/src/subagent/executor.ts b/extensions/cli/src/subagent/executor.ts new file mode 100644 index 000000000..40fbd1bc5 --- /dev/null +++ b/extensions/cli/src/subagent/executor.ts @@ -0,0 +1,213 @@ +import type { ChatHistoryItem } from "core"; + +import { services } from "../services/index.js"; +import { streamChatResponse } from "../stream/streamChatResponse.js"; +import { Tool } from "../tools/types.js"; +import { logger } from "../util/logger.js"; + +import { AgentConfig } from "./types.js"; + +/** + * Options for executing a subagent + */ +export interface SubAgentExecutionOptions { + agent: AgentConfig; + prompt: string; + description?: string; + parentSessionId: string; + abortController: AbortController; + onOutputUpdate?: (output: string) => void; +} + +/** + * Result from executing a subagent + */ +export interface SubAgentResult { + success: boolean; + response: string; + summary: string; + error?: string; +} + +/** + * Filter tools based on agent configuration + */ +function filterToolsByAgent(allTools: Tool[], agent: AgentConfig): Tool[] { + return allTools.filter((tool) => { + const toolName = tool.name; + // If tool is explicitly disabled in agent config, filter it out + return agent.tools[toolName] !== false; + }); +} + +/** + * Build system message for the agent + */ +async function buildAgentSystemMessage(agent: AgentConfig): Promise { + const baseMessage = services.systemMessage + ? await services.systemMessage.getSystemMessage( + services.toolPermissions.getState().currentMode, + ) + : ""; + + const agentPrompt = agent.systemPrompt || ""; + + // Combine base system message with agent-specific prompt + if (agentPrompt) { + return `${baseMessage}\n\n${agentPrompt}`; + } + + return baseMessage; +} + +/** + * Execute a subagent in a child session + */ +export async function executeSubAgent( + options: SubAgentExecutionOptions, +): Promise { + const { agent, prompt, description, abortController, onOutputUpdate } = + options; + + try { + logger.debug("Starting subagent execution", { + agent: agent.name, + description, + }); + + // Get model and LLM API from model service + const modelState = services.model.getState(); + const { model, llmApi } = modelState; + + if (!model || !llmApi) { + throw new Error("Model or LLM API not available"); + } + + logger.debug("debug1 model and llmapi", { model, llmApi }); + + // Get all available tools + const { getAllAvailableTools } = await import("../tools/index.js"); + const allTools = await getAllAvailableTools(true); // headless mode + + // Filter tools based on agent configuration + const allowedTools = filterToolsByAgent(allTools, agent); + + logger.debug("debug1 Filtered tools for agent", { + agent: agent.name, + toolCount: allowedTools.length, + tools: allowedTools.map((t) => t.name).filter((t) => t !== "Task"), + }); + + // Build agent system message + const systemMessage = await buildAgentSystemMessage(agent); + + // Store original system message function + const originalGetSystemMessage = services.systemMessage?.getSystemMessage; + + // Store original ChatHistoryService ready state + const chatHistorySvc = services.chatHistory; + const originalIsReady = + chatHistorySvc && typeof chatHistorySvc.isReady === "function" + ? chatHistorySvc.isReady + : undefined; + + // Override system message for this execution + if (services.systemMessage) { + services.systemMessage.getSystemMessage = async () => systemMessage; + } + + // Temporarily disable ChatHistoryService to prevent it from interfering with child session + if (chatHistorySvc && originalIsReady) { + chatHistorySvc.isReady = () => false; + } + + const userMessage = description + ? `Task: ${description}\n\n${prompt}` + : prompt; + + const chatHistory = [ + { + message: { + role: "user", + content: userMessage, + }, + contextItems: [], + }, + ] as ChatHistoryItem[]; + + try { + let accumulatedOutput = ""; + + // Execute the chat stream with child session + await streamChatResponse( + chatHistory, + model, + llmApi, + abortController, + { + onContent: (content: string) => { + accumulatedOutput += content; + if (onOutputUpdate) { + onOutputUpdate(accumulatedOutput); + } + }, + onToolResult: (result: string) => { + // todo: skip tool outputs - show tool names and params + accumulatedOutput += `\n\n${result}`; + if (onOutputUpdate) { + onOutputUpdate(accumulatedOutput); + } + }, + }, + false, // Not compacting + ); + + // The last message (mostly) contains the important output to be submitted back to the main agent + const lastMessage = chatHistory.at(-1); + const response = + typeof lastMessage?.message?.content === "string" + ? lastMessage.message.content + : ""; + + logger.debug("debug1 response was", { + response, + history: chatHistory, + }); + + const summary = response.substring(0, 150); // summary should be the last message only - this is not needed + + logger.debug("Subagent execution completed", { + agent: agent.name, + responseLength: response.length, + }); + + return { + success: true, + response, + summary: summary + (response.length > 150 ? "..." : ""), + }; + } finally { + // Restore original system message function + if (services.systemMessage && originalGetSystemMessage) { + services.systemMessage.getSystemMessage = originalGetSystemMessage; + } + + // Restore original ChatHistoryService ready state + if (chatHistorySvc && originalIsReady) { + chatHistorySvc.isReady = originalIsReady; + } + } + } catch (error: any) { + logger.error("Subagent execution failed", { + agent: agent.name, + error: error.message, + }); + + return { + success: false, + response: "", + summary: `Failed: ${error.message}`, + error: error.message, + }; + } +} diff --git a/extensions/cli/src/subagent/types.ts b/extensions/cli/src/subagent/types.ts new file mode 100644 index 000000000..e3575cef4 --- /dev/null +++ b/extensions/cli/src/subagent/types.ts @@ -0,0 +1,15 @@ +/** + * Configuration for a specialized agent + */ +export interface AgentConfig { + /** Unique identifier for the agent */ + name: string; + /** Human-readable display name */ + displayName: string; + /** Description of when to use this agent */ + description: string; + /** Tool configuration - which tools are available to this agent */ + tools: Record; + /** Optional custom system prompt for the agent */ + systemPrompt?: string; +} diff --git a/extensions/cli/src/tools/allBuiltIns.ts b/extensions/cli/src/tools/allBuiltIns.ts index 18a7e8eee..8f97d9922 100644 --- a/extensions/cli/src/tools/allBuiltIns.ts +++ b/extensions/cli/src/tools/allBuiltIns.ts @@ -7,6 +7,7 @@ import { readFileTool } from "./readFile.js"; import { reportFailureTool } from "./reportFailure.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; import { searchCodeTool } from "./searchCode.js"; +import { taskTool } from "./task.js"; import { uploadArtifactTool } from "./uploadArtifact.js"; import { writeChecklistTool } from "./writeChecklist.js"; import { writeFileTool } from "./writeFile.js"; @@ -22,6 +23,7 @@ export const ALL_BUILT_IN_TOOLS = [ runTerminalCommandTool, fetchTool, writeChecklistTool, + taskTool, exitTool, reportFailureTool, uploadArtifactTool, diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index cf3e1b1dd..83e172d2d 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -28,6 +28,7 @@ import { readFileTool } from "./readFile.js"; import { reportFailureTool } from "./reportFailure.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; import { checkIfRipgrepIsInstalled, searchCodeTool } from "./searchCode.js"; +import { taskTool } from "./task.js"; import { isBetaUploadArtifactToolEnabled } from "./toolsConfig.js"; import { type Tool, @@ -119,6 +120,27 @@ export async function getAllAvailableTools( tools.push(exitTool); } + // // Add Task tool for primary sessions only (not child sessions) + // // Check if current session is a child session by checking for parentSessionId + // const chatHistoryService = await serviceContainer.get( + // SERVICE_NAMES.CHAT_HISTORY, + // ); + + // // Get current session ID and load the session to check for parentSessionId + // const sessionId = chatHistoryService?.sessionId; + // let isChildSession = false; + // logger.debug("debug1 sessionId", { sessionId }); + // if (sessionId) { + // const { loadSessionById } = await import("../session.js"); + // const currentSession = loadSessionById(sessionId); + // isChildSession = currentSession?.parentSessionId !== undefined; + // } + + // Only add Task tool if this is NOT a child session (prevents recursion) + // if (!isChildSession) { + tools.push(taskTool); + // } + const mcpState = await serviceContainer.get( SERVICE_NAMES.MCP, ); @@ -211,6 +233,7 @@ export async function executeToolCall( // Preprocessed arg names may be different const result = await toolCall.tool.run( toolCall.preprocessResult?.args ?? toolCall.arguments, + { toolCallId: toolCall.id }, ); const duration = Date.now() - startTime; diff --git a/extensions/cli/src/tools/task.ts b/extensions/cli/src/tools/task.ts new file mode 100644 index 000000000..837e8bc42 --- /dev/null +++ b/extensions/cli/src/tools/task.ts @@ -0,0 +1,115 @@ +import { services } from "../services/index.js"; +import { + generateTaskToolDescription, + getAgent, +} from "../subagent/builtInAgents.js"; +import { executeSubAgent } from "../subagent/executor.js"; +import { logger } from "../util/logger.js"; + +import { Tool } from "./types.js"; + +export const taskTool: Tool = { + name: "Task", + displayName: "Task", + description: generateTaskToolDescription(), + readonly: false, + isBuiltIn: true, + + parameters: { + type: "object", + required: ["description", "prompt", "subagent_type"], + properties: { + description: { + type: "string", + description: "A short (3-5 words) description of the task", + }, + prompt: { + type: "string", + description: "The task for the agent to perform", + }, + // todo: change this to subagent name + subagent_type: { + type: "string", + description: + "The type of specialized agent to use for this task (e.g., 'general')", + }, + }, + }, + + preprocess: async (args) => { + const { description, subagent_type } = args; + + const agent = getAgent(subagent_type); + if (!agent) { + throw new Error( + `Unknown agent type: ${subagent_type}. Available agents: general`, + ); + } + + return { + args, + preview: [ + { + type: "text", + content: `Spawning ${agent.displayName} to: ${description}`, + }, + ], + }; + }, + + run: async (args, context?: { toolCallId: string }) => { + const { description, prompt, subagent_type } = args; + + logger.debug("debug1", { args, context }); + + // Get agent configuration + const agent = getAgent(subagent_type); + if (!agent) { + throw new Error(`Unknown agent type: ${subagent_type}`); + } + + // Get parent session ID from chat history service + const chatHistoryService = services.chatHistory; + const parentSessionId = chatHistoryService.getSessionId(); + + if (!parentSessionId) { + throw new Error("No active session found"); + } + + // Create abort controller for child execution + const abortController = new AbortController(); + + // Execute subagent with output streaming + const result = await executeSubAgent({ + agent, + prompt, + description, + parentSessionId, + abortController, + onOutputUpdate: context?.toolCallId + ? (output: string) => { + try { + services.chatHistory.addToolResult( + context.toolCallId, + output, + "calling", + ); + } catch { + // Ignore errors during streaming updates + } + } + : undefined, + }); + + const output = [ + result.response, + "", + `status: ${result.success ? "completed" : "failed"}`, + "", + ] + .filter(Boolean) + .join("\n"); + + return output; + }, +}; diff --git a/extensions/cli/src/ui/ToolResultSummary.tsx b/extensions/cli/src/ui/ToolResultSummary.tsx index 9e2de0824..70f2d12c6 100644 --- a/extensions/cli/src/ui/ToolResultSummary.tsx +++ b/extensions/cli/src/ui/ToolResultSummary.tsx @@ -115,6 +115,57 @@ const ToolResultSummary: React.FC = ({ } } + // show streaming output for task tool output + if (toolName === "Task") { + const metadataIndex = content.indexOf(""); + const actualOutput = + metadataIndex >= 0 ? content.slice(0, metadataIndex).trim() : content; + + if (!actualOutput) { + return ( + + ⎿ + Task executing... + + ); + } + + const outputLines = actualOutput.split("\n"); + const MAX_TASK_OUTPUT_LINES = 20; + + if (outputLines.length <= MAX_TASK_OUTPUT_LINES) { + return ( + + + ⎿ + Task output: + + + {actualOutput.trimEnd()} + + + ); + } else { + const lastLines = outputLines.slice(-MAX_TASK_OUTPUT_LINES).join("\n"); + return ( + + + ⎿ + Task output: + + + + ... +{outputLines.length - MAX_TASK_OUTPUT_LINES} lines + + + + {lastLines.trimEnd()} + + + ); + } + } + // Handle all other cases with text summary const getSummary = () => { // Check if this is a user cancellation first