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 01/33] 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 From a78be7c4117460a9057e178515a9970cc8840193 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 11 Dec 2025 13:27:46 +0530 Subject: [PATCH 02/33] support streaming into tool call output --- extensions/cli/src/tools/index.tsx | 19 ------------------- extensions/cli/src/tools/types.ts | 2 +- 2 files changed, 1 insertion(+), 20 deletions(-) diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index 83e172d2d..d0000ccf3 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -120,26 +120,7 @@ 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, diff --git a/extensions/cli/src/tools/types.ts b/extensions/cli/src/tools/types.ts index 5adb45a92..f7b1ad3f1 100644 --- a/extensions/cli/src/tools/types.ts +++ b/extensions/cli/src/tools/types.ts @@ -37,7 +37,7 @@ export interface Tool { description: string; parameters: ToolParametersSchema; preprocess?: (args: any) => Promise; - run: (args: any) => Promise; + run: (args: any, context?: { toolCallId: string }) => Promise; readonly?: boolean; // Indicates if the tool is readonly isBuiltIn: boolean; evaluateToolCallPolicy?: ( From 675378f1a330d0d4d2cbd8da73511b7e7c4d7d68 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 11 Dec 2025 13:31:19 +0530 Subject: [PATCH 03/33] rename `subagent_type` to `subagent_name` --- extensions/cli/src/subagent/executor.ts | 16 ++-------------- extensions/cli/src/tools/task.ts | 22 +++++++++++----------- 2 files changed, 13 insertions(+), 25 deletions(-) diff --git a/extensions/cli/src/subagent/executor.ts b/extensions/cli/src/subagent/executor.ts index 40fbd1bc5..5fc095951 100644 --- a/extensions/cli/src/subagent/executor.ts +++ b/extensions/cli/src/subagent/executor.ts @@ -13,7 +13,6 @@ import { AgentConfig } from "./types.js"; export interface SubAgentExecutionOptions { agent: AgentConfig; prompt: string; - description?: string; parentSessionId: string; abortController: AbortController; onOutputUpdate?: (output: string) => void; @@ -25,7 +24,6 @@ export interface SubAgentExecutionOptions { export interface SubAgentResult { success: boolean; response: string; - summary: string; error?: string; } @@ -66,13 +64,11 @@ async function buildAgentSystemMessage(agent: AgentConfig): Promise { export async function executeSubAgent( options: SubAgentExecutionOptions, ): Promise { - const { agent, prompt, description, abortController, onOutputUpdate } = - options; + const { agent, prompt, abortController, onOutputUpdate } = options; try { logger.debug("Starting subagent execution", { agent: agent.name, - description, }); // Get model and LLM API from model service @@ -121,15 +117,11 @@ export async function executeSubAgent( chatHistorySvc.isReady = () => false; } - const userMessage = description - ? `Task: ${description}\n\n${prompt}` - : prompt; - const chatHistory = [ { message: { role: "user", - content: userMessage, + content: prompt, }, contextItems: [], }, @@ -174,8 +166,6 @@ export async function executeSubAgent( 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, @@ -184,7 +174,6 @@ export async function executeSubAgent( return { success: true, response, - summary: summary + (response.length > 150 ? "..." : ""), }; } finally { // Restore original system message function @@ -206,7 +195,6 @@ export async function executeSubAgent( return { success: false, response: "", - summary: `Failed: ${error.message}`, error: error.message, }; } diff --git a/extensions/cli/src/tools/task.ts b/extensions/cli/src/tools/task.ts index 837e8bc42..ca5612dd1 100644 --- a/extensions/cli/src/tools/task.ts +++ b/extensions/cli/src/tools/task.ts @@ -17,7 +17,7 @@ export const taskTool: Tool = { parameters: { type: "object", - required: ["description", "prompt", "subagent_type"], + required: ["description", "prompt", "subagent_name"], properties: { description: { type: "string", @@ -27,8 +27,7 @@ export const taskTool: Tool = { type: "string", description: "The task for the agent to perform", }, - // todo: change this to subagent name - subagent_type: { + subagent_name: { type: "string", description: "The type of specialized agent to use for this task (e.g., 'general')", @@ -37,12 +36,12 @@ export const taskTool: Tool = { }, preprocess: async (args) => { - const { description, subagent_type } = args; + const { description, subagent_name } = args; - const agent = getAgent(subagent_type); + const agent = getAgent(subagent_name); if (!agent) { throw new Error( - `Unknown agent type: ${subagent_type}. Available agents: general`, + `Unknown agent type: ${subagent_name}. Available agents: general`, ); } @@ -58,14 +57,14 @@ export const taskTool: Tool = { }, run: async (args, context?: { toolCallId: string }) => { - const { description, prompt, subagent_type } = args; + const { prompt, subagent_name } = args; - logger.debug("debug1", { args, context }); + logger.debug("debug1 subagent args", { args, context }); // Get agent configuration - const agent = getAgent(subagent_type); + const agent = getAgent(subagent_name); if (!agent) { - throw new Error(`Unknown agent type: ${subagent_type}`); + throw new Error(`Unknown agent type: ${subagent_name}`); } // Get parent session ID from chat history service @@ -83,7 +82,6 @@ export const taskTool: Tool = { const result = await executeSubAgent({ agent, prompt, - description, parentSessionId, abortController, onOutputUpdate: context?.toolCallId @@ -101,6 +99,8 @@ export const taskTool: Tool = { : undefined, }); + logger.debug("debug1 subagent result->", { result }); + const output = [ result.response, "", From 1a06d692970300e84c7cd0d99c78f960cb233b9b Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 11 Dec 2025 13:40:02 +0530 Subject: [PATCH 04/33] refactor subagent namings --- extensions/cli/src/subagent/builtInAgents.ts | 10 +++++----- extensions/cli/src/subagent/executor.ts | 2 +- extensions/cli/src/tools/allBuiltIns.ts | 4 ++-- extensions/cli/src/tools/index.tsx | 4 ++-- extensions/cli/src/tools/{task.ts => subagent.ts} | 10 +++++----- extensions/cli/src/ui/ToolResultSummary.tsx | 10 +++++----- 6 files changed, 20 insertions(+), 20 deletions(-) rename extensions/cli/src/tools/{task.ts => subagent.ts} (94%) diff --git a/extensions/cli/src/subagent/builtInAgents.ts b/extensions/cli/src/subagent/builtInAgents.ts index ba6cab8e5..6947c5eb4 100644 --- a/extensions/cli/src/subagent/builtInAgents.ts +++ b/extensions/cli/src/subagent/builtInAgents.ts @@ -22,10 +22,10 @@ export const BUILT_IN_AGENTS: Record = { runTerminalCommand: true, Fetch: true, writeChecklist: true, - // Explicitly disable Task to prevent recursion - Task: false, + // Explicitly disable Subagent to prevent recursion + Subagent: false, }, - // model: "haiku-4-5-latest", // if the model is not there, skip the task tool (check api key?) + // model: "haiku-4-5-latest", // if the model is not there, skip the subagent tool (check api key?) systemPrompt: `You are a specialized task execution agent. Your role: @@ -58,13 +58,13 @@ export function listSubagents(): AgentConfig[] { /** * Generate dynamic tool description listing available agents */ -export function generateTaskToolDescription(): string { +export function generateSubagentToolDescription(): 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. + return `Launch a specialized subagent to handle complex, multi-step tasks autonomously. Available agent types: ${agentList} diff --git a/extensions/cli/src/subagent/executor.ts b/extensions/cli/src/subagent/executor.ts index 5fc095951..9c27962ac 100644 --- a/extensions/cli/src/subagent/executor.ts +++ b/extensions/cli/src/subagent/executor.ts @@ -91,7 +91,7 @@ export async function executeSubAgent( logger.debug("debug1 Filtered tools for agent", { agent: agent.name, toolCount: allowedTools.length, - tools: allowedTools.map((t) => t.name).filter((t) => t !== "Task"), + tools: allowedTools.map((t) => t.name).filter((t) => t !== "Subagent"), // explicityly remove subagent to prevent recursion }); // Build agent system message diff --git a/extensions/cli/src/tools/allBuiltIns.ts b/extensions/cli/src/tools/allBuiltIns.ts index 8f97d9922..c5e86f9f3 100644 --- a/extensions/cli/src/tools/allBuiltIns.ts +++ b/extensions/cli/src/tools/allBuiltIns.ts @@ -7,7 +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 { subagentTool } from "./subagent.js"; import { uploadArtifactTool } from "./uploadArtifact.js"; import { writeChecklistTool } from "./writeChecklist.js"; import { writeFileTool } from "./writeFile.js"; @@ -23,7 +23,7 @@ export const ALL_BUILT_IN_TOOLS = [ runTerminalCommandTool, fetchTool, writeChecklistTool, - taskTool, + subagentTool, exitTool, reportFailureTool, uploadArtifactTool, diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index d0000ccf3..87016bddc 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -28,7 +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 { subagentTool } from "./subagent.js"; import { isBetaUploadArtifactToolEnabled } from "./toolsConfig.js"; import { type Tool, @@ -120,7 +120,7 @@ export async function getAllAvailableTools( tools.push(exitTool); } - tools.push(taskTool); + tools.push(subagentTool); const mcpState = await serviceContainer.get( SERVICE_NAMES.MCP, diff --git a/extensions/cli/src/tools/task.ts b/extensions/cli/src/tools/subagent.ts similarity index 94% rename from extensions/cli/src/tools/task.ts rename to extensions/cli/src/tools/subagent.ts index ca5612dd1..b440abaef 100644 --- a/extensions/cli/src/tools/task.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -1,6 +1,6 @@ import { services } from "../services/index.js"; import { - generateTaskToolDescription, + generateSubagentToolDescription, getAgent, } from "../subagent/builtInAgents.js"; import { executeSubAgent } from "../subagent/executor.js"; @@ -8,10 +8,10 @@ import { logger } from "../util/logger.js"; import { Tool } from "./types.js"; -export const taskTool: Tool = { - name: "Task", - displayName: "Task", - description: generateTaskToolDescription(), +export const subagentTool: Tool = { + name: "Subagent", + displayName: "Subagent", + description: generateSubagentToolDescription(), readonly: false, isBuiltIn: true, diff --git a/extensions/cli/src/ui/ToolResultSummary.tsx b/extensions/cli/src/ui/ToolResultSummary.tsx index 70f2d12c6..97e179427 100644 --- a/extensions/cli/src/ui/ToolResultSummary.tsx +++ b/extensions/cli/src/ui/ToolResultSummary.tsx @@ -115,8 +115,8 @@ const ToolResultSummary: React.FC = ({ } } - // show streaming output for task tool output - if (toolName === "Task") { + // show streaming output for subagent tool output + if (toolName === "Subagent") { const metadataIndex = content.indexOf(""); const actualOutput = metadataIndex >= 0 ? content.slice(0, metadataIndex).trim() : content; @@ -125,7 +125,7 @@ const ToolResultSummary: React.FC = ({ return ( ⎿ - Task executing... + Subagent executing... ); } @@ -138,7 +138,7 @@ const ToolResultSummary: React.FC = ({ ⎿ - Task output: + Subagent output: {actualOutput.trimEnd()} @@ -151,7 +151,7 @@ const ToolResultSummary: React.FC = ({ ⎿ - Task output: + Subagent output: From c2af5a9f1f305fff9489c3bca81fe26ea8937037 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 11 Dec 2025 19:21:40 +0530 Subject: [PATCH 05/33] allow all tools inside subagents --- extensions/cli/src/subagent/builtInAgents.ts | 27 +-------- extensions/cli/src/subagent/executor.ts | 64 +++++++++++--------- extensions/cli/src/subagent/types.ts | 2 +- 3 files changed, 37 insertions(+), 56 deletions(-) diff --git a/extensions/cli/src/subagent/builtInAgents.ts b/extensions/cli/src/subagent/builtInAgents.ts index 6947c5eb4..3c8ce4359 100644 --- a/extensions/cli/src/subagent/builtInAgents.ts +++ b/extensions/cli/src/subagent/builtInAgents.ts @@ -1,7 +1,5 @@ import { AgentConfig } from "./types.js"; -// todo - move this to the subagent directory - /** * Built-in agent configurations */ @@ -11,20 +9,7 @@ export const BUILT_IN_AGENTS: Record = { 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 Subagent to prevent recursion - Subagent: false, - }, + availableTools: [], // model: "haiku-4-5-latest", // if the model is not there, skip the subagent tool (check api key?) systemPrompt: `You are a specialized task execution agent. @@ -48,19 +33,11 @@ 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 generateSubagentToolDescription(): string { - const agents = listSubagents(); - const agentList = agents + const agentList = Object.values(BUILT_IN_AGENTS) .map((agent) => ` - ${agent.name}: ${agent.description}`) .join("\n"); diff --git a/extensions/cli/src/subagent/executor.ts b/extensions/cli/src/subagent/executor.ts index 9c27962ac..2c30a7a41 100644 --- a/extensions/cli/src/subagent/executor.ts +++ b/extensions/cli/src/subagent/executor.ts @@ -1,8 +1,12 @@ import type { ChatHistoryItem } from "core"; -import { services } from "../services/index.js"; +import { + SERVICE_NAMES, + serviceContainer, + services, +} from "../services/index.js"; +import { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; import { streamChatResponse } from "../stream/streamChatResponse.js"; -import { Tool } from "../tools/types.js"; import { logger } from "../util/logger.js"; import { AgentConfig } from "./types.js"; @@ -27,17 +31,6 @@ export interface SubAgentResult { 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 */ @@ -64,11 +57,16 @@ async function buildAgentSystemMessage(agent: AgentConfig): Promise { export async function executeSubAgent( options: SubAgentExecutionOptions, ): Promise { - const { agent, prompt, abortController, onOutputUpdate } = options; + const mainAgentPermissionsState = + await serviceContainer.get( + SERVICE_NAMES.TOOL_PERMISSIONS, + ); + + const { agent: subAgent, prompt, abortController, onOutputUpdate } = options; try { logger.debug("Starting subagent execution", { - agent: agent.name, + agent: subAgent.name, }); // Get model and LLM API from model service @@ -79,23 +77,23 @@ export async function executeSubAgent( throw new Error("Model or LLM API not available"); } - logger.debug("debug1 model and llmapi", { model, llmApi }); + logger.debug("debug1 model and llmapi", { model, llmApi, subAgent }); - // Get all available tools - const { getAllAvailableTools } = await import("../tools/index.js"); - const allTools = await getAllAvailableTools(true); // headless mode + // allow all tools for now + // todo: eventually we want to show the same prompt in a dialog whether asking whether that tool call is allowed or not - // 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 !== "Subagent"), // explicityly remove subagent to prevent recursion - }); + serviceContainer.set( + SERVICE_NAMES.TOOL_PERMISSIONS, + { + ...mainAgentPermissionsState, + permissions: { + policies: [{ tool: "*", permission: "allow" }], + }, + }, + ); // Build agent system message - const systemMessage = await buildAgentSystemMessage(agent); + const systemMessage = await buildAgentSystemMessage(subAgent); // Store original system message function const originalGetSystemMessage = services.systemMessage?.getSystemMessage; @@ -167,7 +165,7 @@ export async function executeSubAgent( }); logger.debug("Subagent execution completed", { - agent: agent.name, + agent: subAgent.name, responseLength: response.length, }); @@ -185,10 +183,16 @@ export async function executeSubAgent( if (chatHistorySvc && originalIsReady) { chatHistorySvc.isReady = originalIsReady; } + + // Restore original main agent tool permissions + serviceContainer.set( + SERVICE_NAMES.TOOL_PERMISSIONS, + mainAgentPermissionsState, + ); } } catch (error: any) { logger.error("Subagent execution failed", { - agent: agent.name, + agent: subAgent.name, error: error.message, }); diff --git a/extensions/cli/src/subagent/types.ts b/extensions/cli/src/subagent/types.ts index e3575cef4..df5cb4d10 100644 --- a/extensions/cli/src/subagent/types.ts +++ b/extensions/cli/src/subagent/types.ts @@ -9,7 +9,7 @@ export interface AgentConfig { /** Description of when to use this agent */ description: string; /** Tool configuration - which tools are available to this agent */ - tools: Record; + availableTools: string[]; /** Optional custom system prompt for the agent */ systemPrompt?: string; } From 1c448c479d1e2f4c50c586d494288d6b8889c178 Mon Sep 17 00:00:00 2001 From: "continue[bot]" Date: Mon, 15 Dec 2025 03:50:39 +0000 Subject: [PATCH 06/33] fix: resolve circular dependency in subagent tool Move services import to lazy evaluation inside the run function to avoid circular dependency between ToolPermissionService -> allBuiltIns -> subagent -> services -> ToolPermissionService. This fixes the 'ToolPermissionService is not a constructor' error in tests. Co-authored-by: nate --- extensions/cli/src/tools/subagent.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index b440abaef..a8878fd79 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -1,4 +1,3 @@ -import { services } from "../services/index.js"; import { generateSubagentToolDescription, getAgent, @@ -67,6 +66,9 @@ export const subagentTool: Tool = { throw new Error(`Unknown agent type: ${subagent_name}`); } + // Lazy import services to avoid circular dependency + const { services } = await import("../services/index.js"); + // Get parent session ID from chat history service const chatHistoryService = services.chatHistory; const parentSessionId = chatHistoryService.getSessionId(); From 87fd9b67df4661a261881a2cb028ab651c695128 Mon Sep 17 00:00:00 2001 From: "continue[bot]" Date: Mon, 15 Dec 2025 04:01:04 +0000 Subject: [PATCH 07/33] fix: resolve circular dependency in subagent executor Move services import to lazy evaluation inside executeSubAgent function to avoid circular dependency. Pass services as parameter to buildAgentSystemMessage helper function. Co-authored-by: nate --- extensions/cli/src/subagent/executor.ts | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/extensions/cli/src/subagent/executor.ts b/extensions/cli/src/subagent/executor.ts index 2c30a7a41..e2ba75c52 100644 --- a/extensions/cli/src/subagent/executor.ts +++ b/extensions/cli/src/subagent/executor.ts @@ -1,10 +1,6 @@ import type { ChatHistoryItem } from "core"; -import { - SERVICE_NAMES, - serviceContainer, - services, -} from "../services/index.js"; +import { SERVICE_NAMES, serviceContainer } from "../services/index.js"; import { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; import { streamChatResponse } from "../stream/streamChatResponse.js"; import { logger } from "../util/logger.js"; @@ -34,7 +30,10 @@ export interface SubAgentResult { /** * Build system message for the agent */ -async function buildAgentSystemMessage(agent: AgentConfig): Promise { +async function buildAgentSystemMessage( + agent: AgentConfig, + services: any, +): Promise { const baseMessage = services.systemMessage ? await services.systemMessage.getSystemMessage( services.toolPermissions.getState().currentMode, @@ -69,6 +68,9 @@ export async function executeSubAgent( agent: subAgent.name, }); + // Lazy import services to avoid circular dependency + const { services } = await import("../services/index.js"); + // Get model and LLM API from model service const modelState = services.model.getState(); const { model, llmApi } = modelState; @@ -93,7 +95,7 @@ export async function executeSubAgent( ); // Build agent system message - const systemMessage = await buildAgentSystemMessage(subAgent); + const systemMessage = await buildAgentSystemMessage(subAgent, services); // Store original system message function const originalGetSystemMessage = services.systemMessage?.getSystemMessage; From 6a5f80b0fc739ed36448b62bd036c01476b91d49 Mon Sep 17 00:00:00 2001 From: "continue[bot]" Date: Mon, 15 Dec 2025 04:08:38 +0000 Subject: [PATCH 08/33] fix: break circular dependency by extracting tool names Create builtInToolNames.ts with just the tool name constants to avoid importing the actual tool implementations. This breaks the circular dependency chain: ToolPermissionService -> allBuiltIns -> subagent -> executor -> services -> ToolPermissionService. Co-authored-by: nate --- .../cli/src/services/ToolPermissionService.ts | 4 +-- extensions/cli/src/tools/builtInToolNames.ts | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 extensions/cli/src/tools/builtInToolNames.ts diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index 4e0802272..10d979f0b 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -1,4 +1,4 @@ -import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js"; +import { BUILT_IN_TOOL_NAMES } from "../tools/builtInToolNames.js"; import { ensurePermissionsYamlExists } from "../permissions/permissionsYamlLoader.js"; import { resolvePermissionPrecedence } from "../permissions/precedenceResolver.js"; @@ -143,7 +143,7 @@ export class ToolPermissionService })); policies.push(...allowed); const specificBuiltInSet = new Set(specificBuiltIns); - const notMentioned = ALL_BUILT_IN_TOOLS.map((t) => t.name).filter( + const notMentioned = BUILT_IN_TOOL_NAMES.filter( (name) => !specificBuiltInSet.has(name), ); const disallowed: ToolPermissionPolicy[] = notMentioned.map((tool) => ({ diff --git a/extensions/cli/src/tools/builtInToolNames.ts b/extensions/cli/src/tools/builtInToolNames.ts new file mode 100644 index 000000000..617f151c5 --- /dev/null +++ b/extensions/cli/src/tools/builtInToolNames.ts @@ -0,0 +1,28 @@ +/** + * List of built-in tool names + * Kept separate from allBuiltIns.ts to avoid circular dependencies + */ +export const BUILT_IN_TOOL_NAMES = [ + "Read", + "Write", + "Edit", + "MultiEdit", + "List", + "Search", + "Bash", + "Fetch", + "Checklist", + "ReportFailure", + "Exit", + "Diff", + "LS", + "Glob", + "Grep", + "NotebookRead", + "NotebookEdit", + "WebFetch", + "WebSearch", + "Subagent", +] as const; + +export type BuiltInToolName = (typeof BUILT_IN_TOOL_NAMES)[number]; From 26bef77a8859788b870e42036e0958bdbaa9d93a Mon Sep 17 00:00:00 2001 From: "continue[bot]" Date: Mon, 15 Dec 2025 04:16:11 +0000 Subject: [PATCH 09/33] fix: correct built-in tool names list Update BUILT_IN_TOOL_NAMES to match the actual tools in allBuiltIns.ts, including UploadArtifact which was missing. Remove incorrect tool names that don't exist. Co-authored-by: nate --- extensions/cli/src/tools/builtInToolNames.ts | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/extensions/cli/src/tools/builtInToolNames.ts b/extensions/cli/src/tools/builtInToolNames.ts index 617f151c5..900984dc1 100644 --- a/extensions/cli/src/tools/builtInToolNames.ts +++ b/extensions/cli/src/tools/builtInToolNames.ts @@ -4,25 +4,18 @@ */ export const BUILT_IN_TOOL_NAMES = [ "Read", - "Write", "Edit", "MultiEdit", + "Write", "List", "Search", "Bash", "Fetch", "Checklist", - "ReportFailure", - "Exit", - "Diff", - "LS", - "Glob", - "Grep", - "NotebookRead", - "NotebookEdit", - "WebFetch", - "WebSearch", "Subagent", + "Exit", + "ReportFailure", + "UploadArtifact", ] as const; export type BuiltInToolName = (typeof BUILT_IN_TOOL_NAMES)[number]; From 2003128f084517bdf5343d6e2205edc85db8ff64 Mon Sep 17 00:00:00 2001 From: "continue[bot]" Date: Mon, 15 Dec 2025 04:20:14 +0000 Subject: [PATCH 10/33] fix: correct import order in ToolPermissionService Move BUILT_IN_TOOL_NAMES import to proper position according to eslint import/order rules. Co-authored-by: nate --- extensions/cli/src/services/ToolPermissionService.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index 10d979f0b..236f72fb7 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -1,5 +1,3 @@ -import { BUILT_IN_TOOL_NAMES } from "../tools/builtInToolNames.js"; - import { ensurePermissionsYamlExists } from "../permissions/permissionsYamlLoader.js"; import { resolvePermissionPrecedence } from "../permissions/precedenceResolver.js"; import { @@ -7,6 +5,7 @@ import { ToolPermissionPolicy, ToolPermissions, } from "../permissions/types.js"; +import { BUILT_IN_TOOL_NAMES } from "../tools/builtInToolNames.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; From 85eb24913c49b2935fd8e416a4677da7042decc4 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 18 Dec 2025 20:31:10 +0530 Subject: [PATCH 11/33] wip: use the first found apply model for subagent --- extensions/cli/src/services/ModelService.ts | 24 +++++++++++++++++++++ extensions/cli/src/subagent/executor.ts | 4 ++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index 2e43062e4..cec1fc1d1 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -305,4 +305,28 @@ export class ModelService return nameMatches; }); } + + /** + * Get a subagent model + */ + getSubagentModel(): ModelServiceState | null { + const state = this.getState(); + if (!state.assistant) { + return null; + } + + const subagentModel = state.assistant.models?.find((model) => + model?.roles?.includes("apply"), + ); + if (!subagentModel) { + return null; + } + + return { + llmApi: createLlmApi(subagentModel, state.authConfig), + model: subagentModel, + assistant: state.assistant, + authConfig: state.authConfig, + }; + } } diff --git a/extensions/cli/src/subagent/executor.ts b/extensions/cli/src/subagent/executor.ts index e2ba75c52..bc7e0d077 100644 --- a/extensions/cli/src/subagent/executor.ts +++ b/extensions/cli/src/subagent/executor.ts @@ -72,8 +72,8 @@ export async function executeSubAgent( const { services } = await import("../services/index.js"); // Get model and LLM API from model service - const modelState = services.model.getState(); - const { model, llmApi } = modelState; + const modelState = services.model.getSubagentModel(); + const { model, llmApi } = modelState ?? {}; if (!model || !llmApi) { throw new Error("Model or LLM API not available"); From 0cc7a16f24d1de210ac66418cbf5e4560326f067 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 19 Dec 2025 13:39:34 +0530 Subject: [PATCH 12/33] get subagents from config --- extensions/cli/src/services/ModelService.ts | 34 +++++++------ extensions/cli/src/subagent/builtInAgents.ts | 53 +++++++------------- extensions/cli/src/subagent/executor.ts | 33 ++++++------ extensions/cli/src/subagent/types.ts | 15 ------ extensions/cli/src/tools/subagent.ts | 2 +- 5 files changed, 55 insertions(+), 82 deletions(-) delete mode 100644 extensions/cli/src/subagent/types.ts diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index cec1fc1d1..d7a8864a0 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -306,27 +306,31 @@ export class ModelService }); } - /** - * Get a subagent model - */ - getSubagentModel(): ModelServiceState | null { + getSubagentModels() { const state = this.getState(); + logger.debug("debug1 getSubagentModels", { + assistant: state.assistant, + }); if (!state.assistant) { - return null; + return []; } + logger.debug("debug1 getSubagentModels", { + assistantModels: state.assistant.models, + }); + const subagentModels = state.assistant.models + ?.filter((model) => !!model) + .filter((model) => !!model.name) // filter out models without a name + .filter((model) => model.roles?.includes("apply")) // filter with role subagent + .filter((model) => !!model.chatOptions?.baseSystemMessage); // filter those with a system message - const subagentModel = state.assistant.models?.find((model) => - model?.roles?.includes("apply"), - ); - if (!subagentModel) { - return null; + if (!subagentModels) { + return []; } - - return { - llmApi: createLlmApi(subagentModel, state.authConfig), - model: subagentModel, + return subagentModels?.map((model) => ({ + llmApi: createLlmApi(model, state.authConfig), + model, assistant: state.assistant, authConfig: state.authConfig, - }; + })); } } diff --git a/extensions/cli/src/subagent/builtInAgents.ts b/extensions/cli/src/subagent/builtInAgents.ts index 3c8ce4359..2fe2be8d1 100644 --- a/extensions/cli/src/subagent/builtInAgents.ts +++ b/extensions/cli/src/subagent/builtInAgents.ts @@ -1,47 +1,30 @@ -import { AgentConfig } from "./types.js"; - -/** - * 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", - availableTools: [], - // model: "haiku-4-5-latest", // if the model is not there, skip the subagent 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`, - }, -}; +import { services } from "../services/index.js"; +import { logger } from "../util/logger.js"; /** * Get an agent by name */ -export function getAgent(name: string): AgentConfig | null { - return BUILT_IN_AGENTS[name] || null; +export function getAgent(name: string) { + return ( + services.model + .getSubagentModels() + .find((model) => model.model.name === name) ?? null + ); } /** * Generate dynamic tool description listing available agents */ export function generateSubagentToolDescription(): string { - const agentList = Object.values(BUILT_IN_AGENTS) - .map((agent) => ` - ${agent.name}: ${agent.description}`) + const agentList = services.model + .getSubagentModels() + .map( + (subagentModel) => + ` - ${subagentModel.model.name}: ${subagentModel.model.chatOptions?.baseSystemMessage}`, + ) .join("\n"); - return `Launch a specialized subagent to handle complex, multi-step tasks autonomously. + const temp = `Launch a specialized subagent to handle complex, multi-step tasks autonomously. Available agent types: ${agentList} @@ -53,8 +36,10 @@ When to use this tool: - 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`; + + logger.debug("debug1 temp->", { temp }); + + return temp; } diff --git a/extensions/cli/src/subagent/executor.ts b/extensions/cli/src/subagent/executor.ts index bc7e0d077..409e9876f 100644 --- a/extensions/cli/src/subagent/executor.ts +++ b/extensions/cli/src/subagent/executor.ts @@ -1,17 +1,20 @@ import type { ChatHistoryItem } from "core"; -import { SERVICE_NAMES, serviceContainer } from "../services/index.js"; +import { + ModelServiceState, + SERVICE_NAMES, + serviceContainer, + services, +} from "../services/index.js"; import { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; import { streamChatResponse } from "../stream/streamChatResponse.js"; import { logger } from "../util/logger.js"; -import { AgentConfig } from "./types.js"; - /** * Options for executing a subagent */ export interface SubAgentExecutionOptions { - agent: AgentConfig; + agent: ModelServiceState; prompt: string; parentSessionId: string; abortController: AbortController; @@ -31,7 +34,7 @@ export interface SubAgentResult { * Build system message for the agent */ async function buildAgentSystemMessage( - agent: AgentConfig, + agent: ModelServiceState, services: any, ): Promise { const baseMessage = services.systemMessage @@ -40,7 +43,9 @@ async function buildAgentSystemMessage( ) : ""; - const agentPrompt = agent.systemPrompt || ""; + const agentPrompt = agent.model?.chatOptions?.baseSystemMessage || ""; + + logger.debug("debug1 agentPrompt", { agentPrompt }); // Combine base system message with agent-specific prompt if (agentPrompt) { @@ -65,21 +70,15 @@ export async function executeSubAgent( try { logger.debug("Starting subagent execution", { - agent: subAgent.name, + agent: subAgent.model?.name, }); - // Lazy import services to avoid circular dependency - const { services } = await import("../services/index.js"); - - // Get model and LLM API from model service - const modelState = services.model.getSubagentModel(); - const { model, llmApi } = modelState ?? {}; - + const { model, llmApi } = subAgent; if (!model || !llmApi) { throw new Error("Model or LLM API not available"); } - logger.debug("debug1 model and llmapi", { model, llmApi, subAgent }); + logger.debug("debug1 model and llmapi", { subAgent }); // allow all tools for now // todo: eventually we want to show the same prompt in a dialog whether asking whether that tool call is allowed or not @@ -167,7 +166,7 @@ export async function executeSubAgent( }); logger.debug("Subagent execution completed", { - agent: subAgent.name, + agent: model?.name, responseLength: response.length, }); @@ -194,7 +193,7 @@ export async function executeSubAgent( } } catch (error: any) { logger.error("Subagent execution failed", { - agent: subAgent.name, + agent: subAgent.model?.name, error: error.message, }); diff --git a/extensions/cli/src/subagent/types.ts b/extensions/cli/src/subagent/types.ts deleted file mode 100644 index df5cb4d10..000000000 --- a/extensions/cli/src/subagent/types.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * 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 */ - availableTools: string[]; - /** Optional custom system prompt for the agent */ - systemPrompt?: string; -} diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index a8878fd79..a3f229175 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -49,7 +49,7 @@ export const subagentTool: Tool = { preview: [ { type: "text", - content: `Spawning ${agent.displayName} to: ${description}`, + content: `Spawning ${agent.model.name} to: ${description}`, }, ], }; From 53becf10ad5ee010a1658244b95291bf2b3616a5 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 19 Dec 2025 20:20:43 +0530 Subject: [PATCH 13/33] remove debug statements --- extensions/cli/src/services/ModelService.ts | 6 ------ extensions/cli/src/stream/streamChatResponse.ts | 2 -- extensions/cli/src/subagent/builtInAgents.ts | 7 +------ extensions/cli/src/subagent/executor.ts | 9 --------- extensions/cli/src/tools/subagent.ts | 4 ++-- 5 files changed, 3 insertions(+), 25 deletions(-) diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index d7a8864a0..3fc4a4126 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -308,15 +308,9 @@ export class ModelService getSubagentModels() { const state = this.getState(); - logger.debug("debug1 getSubagentModels", { - assistant: state.assistant, - }); if (!state.assistant) { return []; } - logger.debug("debug1 getSubagentModels", { - assistantModels: state.assistant.models, - }); const subagentModels = state.assistant.models ?.filter((model) => !!model) .filter((model) => !!model.name) // filter out models without a name diff --git a/extensions/cli/src/stream/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts index b63541db1..7a67054ea 100644 --- a/extensions/cli/src/stream/streamChatResponse.ts +++ b/extensions/cli/src/stream/streamChatResponse.ts @@ -457,8 +457,6 @@ export async function streamChatResponse( chatHistory = refreshChatHistoryFromService(chatHistory, isCompacting); logger.debug("Starting conversation iteration"); - logger.debug("debug1 streamChatResponse history", { chatHistory }); - // Get system message once per iteration (can change based on tool permissions mode) const systemMessage = await services.systemMessage.getSystemMessage( services.toolPermissions.getState().currentMode, diff --git a/extensions/cli/src/subagent/builtInAgents.ts b/extensions/cli/src/subagent/builtInAgents.ts index 2fe2be8d1..3f64acc04 100644 --- a/extensions/cli/src/subagent/builtInAgents.ts +++ b/extensions/cli/src/subagent/builtInAgents.ts @@ -1,5 +1,4 @@ import { services } from "../services/index.js"; -import { logger } from "../util/logger.js"; /** * Get an agent by name @@ -24,7 +23,7 @@ export function generateSubagentToolDescription(): string { ) .join("\n"); - const temp = `Launch a specialized subagent to handle complex, multi-step tasks autonomously. + return `Launch a specialized subagent to handle complex, multi-step tasks autonomously. Available agent types: ${agentList} @@ -38,8 +37,4 @@ When to use this tool: When NOT to use this tool: - Tasks you can complete directly with available tools - Trivial operations that don't require multiple steps`; - - logger.debug("debug1 temp->", { temp }); - - return temp; } diff --git a/extensions/cli/src/subagent/executor.ts b/extensions/cli/src/subagent/executor.ts index 409e9876f..c75abf8d1 100644 --- a/extensions/cli/src/subagent/executor.ts +++ b/extensions/cli/src/subagent/executor.ts @@ -45,8 +45,6 @@ async function buildAgentSystemMessage( const agentPrompt = agent.model?.chatOptions?.baseSystemMessage || ""; - logger.debug("debug1 agentPrompt", { agentPrompt }); - // Combine base system message with agent-specific prompt if (agentPrompt) { return `${baseMessage}\n\n${agentPrompt}`; @@ -78,8 +76,6 @@ export async function executeSubAgent( throw new Error("Model or LLM API not available"); } - logger.debug("debug1 model and llmapi", { subAgent }); - // allow all tools for now // todo: eventually we want to show the same prompt in a dialog whether asking whether that tool call is allowed or not @@ -160,11 +156,6 @@ export async function executeSubAgent( ? lastMessage.message.content : ""; - logger.debug("debug1 response was", { - response, - history: chatHistory, - }); - logger.debug("Subagent execution completed", { agent: model?.name, responseLength: response.length, diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index a3f229175..830c20b62 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -58,7 +58,7 @@ export const subagentTool: Tool = { run: async (args, context?: { toolCallId: string }) => { const { prompt, subagent_name } = args; - logger.debug("debug1 subagent args", { args, context }); + logger.debug("subagent args", { args, context }); // Get agent configuration const agent = getAgent(subagent_name); @@ -101,7 +101,7 @@ export const subagentTool: Tool = { : undefined, }); - logger.debug("debug1 subagent result->", { result }); + logger.debug("subagent result", { result }); const output = [ result.response, From 70d5be809551a726b5108420e7254126c6ed486c Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 19 Dec 2025 20:22:56 +0530 Subject: [PATCH 14/33] rename builtInAgents to get-agents --- .../cli/src/subagent/{builtInAgents.ts => get-agents.ts} | 0 extensions/cli/src/tools/subagent.ts | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) rename extensions/cli/src/subagent/{builtInAgents.ts => get-agents.ts} (100%) diff --git a/extensions/cli/src/subagent/builtInAgents.ts b/extensions/cli/src/subagent/get-agents.ts similarity index 100% rename from extensions/cli/src/subagent/builtInAgents.ts rename to extensions/cli/src/subagent/get-agents.ts diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index 830c20b62..5b0a7f641 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -1,8 +1,8 @@ +import { executeSubAgent } from "../subagent/executor.js"; import { generateSubagentToolDescription, getAgent, -} from "../subagent/builtInAgents.js"; -import { executeSubAgent } from "../subagent/executor.js"; +} from "../subagent/get-agents.js"; import { logger } from "../util/logger.js"; import { Tool } from "./types.js"; From 08465a64005e4b01975a944d73d447dc0f2bdfb2 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 19 Dec 2025 21:27:36 +0530 Subject: [PATCH 15/33] add `subagent` in model roles --- core/config/yaml/loadYaml.ts | 2 ++ extensions/cli/src/services/ModelService.ts | 2 +- extensions/cli/src/subagent/get-agents.ts | 22 +++++++++------------ extensions/cli/src/tools/subagent.ts | 12 ++++++----- packages/config-yaml/src/schemas/models.ts | 1 + 5 files changed, 20 insertions(+), 19 deletions(-) diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 40821bb04..535dd8d35 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -187,6 +187,7 @@ export async function configYamlToContinueConfig(options: { autocomplete: [], rerank: [], summarize: [], + subagent: [], }, selectedModelByRole: { chat: null, @@ -196,6 +197,7 @@ export async function configYamlToContinueConfig(options: { autocomplete: null, rerank: null, summarize: null, + subagent: null, }, rules: [], requestOptions: { ...config.requestOptions }, diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index 3fc4a4126..82e5d21e9 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -314,7 +314,7 @@ export class ModelService const subagentModels = state.assistant.models ?.filter((model) => !!model) .filter((model) => !!model.name) // filter out models without a name - .filter((model) => model.roles?.includes("apply")) // filter with role subagent + .filter((model) => model.roles?.includes("subagent")) // filter with role subagent .filter((model) => !!model.chatOptions?.baseSystemMessage); // filter those with a system message if (!subagentModels) { diff --git a/extensions/cli/src/subagent/get-agents.ts b/extensions/cli/src/subagent/get-agents.ts index 3f64acc04..80a84bd69 100644 --- a/extensions/cli/src/subagent/get-agents.ts +++ b/extensions/cli/src/subagent/get-agents.ts @@ -3,7 +3,7 @@ import { services } from "../services/index.js"; /** * Get an agent by name */ -export function getAgent(name: string) { +export function getSubagent(name: string) { return ( services.model .getSubagentModels() @@ -23,18 +23,14 @@ export function generateSubagentToolDescription(): string { ) .join("\n"); - return `Launch a specialized subagent to handle complex, multi-step tasks autonomously. + // todo: refine this prompt later + return `Launch a specialized subagent to handle a specific task. -Available agent types: +Here are the available subagents: ${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: -- Tasks you can complete directly with available tools -- Trivial operations that don't require multiple steps`; +`; +} + +export function getAgentNames(): string[] { + return services.model.getSubagentModels().map((model) => model.model.name); } diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index 5b0a7f641..29a44c549 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -1,7 +1,8 @@ import { executeSubAgent } from "../subagent/executor.js"; import { generateSubagentToolDescription, - getAgent, + getSubagent, + getAgentNames as getSubagentNames, } from "../subagent/get-agents.js"; import { logger } from "../util/logger.js"; @@ -28,8 +29,9 @@ export const subagentTool: Tool = { }, subagent_name: { type: "string", - description: - "The type of specialized agent to use for this task (e.g., 'general')", + description: `The type of specialized agent to use for this task. Available agents: ${getSubagentNames().join( + ", ", + )}`, }, }, }, @@ -37,7 +39,7 @@ export const subagentTool: Tool = { preprocess: async (args) => { const { description, subagent_name } = args; - const agent = getAgent(subagent_name); + const agent = getSubagent(subagent_name); if (!agent) { throw new Error( `Unknown agent type: ${subagent_name}. Available agents: general`, @@ -61,7 +63,7 @@ export const subagentTool: Tool = { logger.debug("subagent args", { args, context }); // Get agent configuration - const agent = getAgent(subagent_name); + const agent = getSubagent(subagent_name); if (!agent) { throw new Error(`Unknown agent type: ${subagent_name}`); } diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 9f5a9e96e..cefbd93fa 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -28,6 +28,7 @@ export const modelRolesSchema = z.enum([ "edit", "apply", "summarize", + "subagent", ]); export type ModelRole = z.infer; From 5abe556ddc5f72b3fc1ede7c03fcd7f8cff0300f Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 7 Jan 2026 11:02:13 +0530 Subject: [PATCH 16/33] pass modelstate to read subagents --- extensions/cli/src/services/ModelService.ts | 13 ++++++----- extensions/cli/src/subagent/get-agents.ts | 24 ++++++++++++--------- extensions/cli/src/tools/index.tsx | 5 ++++- extensions/cli/src/tools/subagent.ts | 22 +++++++++---------- extensions/cli/src/tools/types.ts | 6 ++++++ 5 files changed, 41 insertions(+), 29 deletions(-) diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index 82e5d21e9..9e5422057 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -306,12 +306,11 @@ export class ModelService }); } - getSubagentModels() { - const state = this.getState(); - if (!state.assistant) { + static getSubagentModels(modelState: ModelServiceState) { + if (!modelState.assistant) { return []; } - const subagentModels = state.assistant.models + const subagentModels = modelState.assistant.models ?.filter((model) => !!model) .filter((model) => !!model.name) // filter out models without a name .filter((model) => model.roles?.includes("subagent")) // filter with role subagent @@ -321,10 +320,10 @@ export class ModelService return []; } return subagentModels?.map((model) => ({ - llmApi: createLlmApi(model, state.authConfig), + llmApi: createLlmApi(model, modelState.authConfig), model, - assistant: state.assistant, - authConfig: state.authConfig, + assistant: modelState.assistant, + authConfig: modelState.authConfig, })); } } diff --git a/extensions/cli/src/subagent/get-agents.ts b/extensions/cli/src/subagent/get-agents.ts index 80a84bd69..3b5282e4a 100644 --- a/extensions/cli/src/subagent/get-agents.ts +++ b/extensions/cli/src/subagent/get-agents.ts @@ -1,22 +1,24 @@ -import { services } from "../services/index.js"; +import { ModelServiceState } from "../services/index.js"; +import { ModelService } from "../services/ModelService.js"; /** * Get an agent by name */ -export function getSubagent(name: string) { +export function getSubagent(modelState: ModelServiceState, name: string) { return ( - services.model - .getSubagentModels() - .find((model) => model.model.name === name) ?? null + ModelService.getSubagentModels(modelState).find( + (model) => model.model.name === name, + ) ?? null ); } /** * Generate dynamic tool description listing available agents */ -export function generateSubagentToolDescription(): string { - const agentList = services.model - .getSubagentModels() +export function generateSubagentToolDescription( + modelState: ModelServiceState, +): string { + const agentList = ModelService.getSubagentModels(modelState) .map( (subagentModel) => ` - ${subagentModel.model.name}: ${subagentModel.model.chatOptions?.baseSystemMessage}`, @@ -31,6 +33,8 @@ ${agentList} `; } -export function getAgentNames(): string[] { - return services.model.getSubagentModels().map((model) => model.model.name); +export function getAgentNames(modelState: ModelServiceState): string[] { + return ModelService.getSubagentModels(modelState).map( + (model) => model.model.name, + ); } diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index f90b0c577..3e7bb9401 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -120,7 +120,7 @@ export async function getAllAvailableTools( tools.push(exitTool); } - tools.push(subagentTool); + tools.push(subagentTool({ modelServiceState: modelState })); const mcpState = await serviceContainer.get( SERVICE_NAMES.MCP, @@ -132,6 +132,9 @@ export async function getAllAvailableTools( export function getToolDisplayName(toolName: string): string { const tool = ALL_BUILT_IN_TOOLS.find((t) => t.name === toolName); + if (typeof tool === "function") { + return toolName; + } return tool?.displayName || toolName; } diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index 29a44c549..fe39addcc 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -6,12 +6,12 @@ import { } from "../subagent/get-agents.js"; import { logger } from "../util/logger.js"; -import { Tool } from "./types.js"; +import { GetTool } from "./types.js"; -export const subagentTool: Tool = { +export const subagentTool: GetTool = (params) => ({ name: "Subagent", displayName: "Subagent", - description: generateSubagentToolDescription(), + description: generateSubagentToolDescription(params.modelServiceState), readonly: false, isBuiltIn: true, @@ -29,17 +29,17 @@ export const subagentTool: Tool = { }, subagent_name: { type: "string", - description: `The type of specialized agent to use for this task. Available agents: ${getSubagentNames().join( - ", ", - )}`, + description: `The type of specialized agent to use for this task. Available agents: ${getSubagentNames( + params.modelServiceState, + ).join(", ")}`, }, }, }, - preprocess: async (args) => { + preprocess: async (args: any) => { const { description, subagent_name } = args; - const agent = getSubagent(subagent_name); + const agent = getSubagent(params.modelServiceState, subagent_name); if (!agent) { throw new Error( `Unknown agent type: ${subagent_name}. Available agents: general`, @@ -57,13 +57,13 @@ export const subagentTool: Tool = { }; }, - run: async (args, context?: { toolCallId: string }) => { + run: async (args: any, context?: { toolCallId: string }) => { const { prompt, subagent_name } = args; logger.debug("subagent args", { args, context }); // Get agent configuration - const agent = getSubagent(subagent_name); + const agent = getSubagent(params.modelServiceState, subagent_name); if (!agent) { throw new Error(`Unknown agent type: ${subagent_name}`); } @@ -116,4 +116,4 @@ export const subagentTool: Tool = { return output; }, -}; +}); diff --git a/extensions/cli/src/tools/types.ts b/extensions/cli/src/tools/types.ts index f7b1ad3f1..3d2a4b579 100644 --- a/extensions/cli/src/tools/types.ts +++ b/extensions/cli/src/tools/types.ts @@ -1,5 +1,7 @@ import type { ToolPolicy } from "@continuedev/terminal-security"; +import { ModelServiceState } from "src/services/types.js"; + // JSON Schema compatible parameter definition export interface ParameterSchema { type: string; @@ -46,6 +48,10 @@ export interface Tool { ) => ToolPolicy; } +export type GetTool = (params: { + modelServiceState: ModelServiceState; +}) => Tool; + export interface ToolCall { id: string; name: string; From 27ac8cc23bf814d128c50fc515a680bef4358bfe Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 7 Jan 2026 18:24:28 +0530 Subject: [PATCH 17/33] include model roles subagent --- core/config/yaml/loadYaml.ts | 4 ++++ extensions/cli/src/tools/subagent.ts | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 535dd8d35..3c0f2d220 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -335,6 +335,10 @@ export async function configYamlToContinueConfig(options: { if (model.roles?.includes("rerank")) { continueConfig.modelsByRole.rerank.push(...llms); } + + if (model.roles?.includes("subagent")) { + continueConfig.modelsByRole.subagent.push(...llms); + } } catch (e) { localErrors.push({ fatal: false, diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index fe39addcc..145d18a91 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -42,7 +42,9 @@ export const subagentTool: GetTool = (params) => ({ const agent = getSubagent(params.modelServiceState, subagent_name); if (!agent) { throw new Error( - `Unknown agent type: ${subagent_name}. Available agents: general`, + `Unknown agent type: ${subagent_name}. Available agents: ${getSubagentNames( + params.modelServiceState, + ).join(", ")}`, ); } From 8381812d9246b834d44df0b23f894c1ea6842928 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 7 Jan 2026 19:50:09 +0530 Subject: [PATCH 18/33] allow escaping of subagent tool using event emit --- extensions/cli/src/subagent/executor.ts | 12 ++++++++++++ extensions/cli/src/ui/UserInput.tsx | 4 ++++ extensions/cli/src/util/cli.ts | 4 ++++ 3 files changed, 20 insertions(+) diff --git a/extensions/cli/src/subagent/executor.ts b/extensions/cli/src/subagent/executor.ts index c75abf8d1..b0ecc2c5a 100644 --- a/extensions/cli/src/subagent/executor.ts +++ b/extensions/cli/src/subagent/executor.ts @@ -8,6 +8,7 @@ import { } from "../services/index.js"; import { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; import { streamChatResponse } from "../stream/streamChatResponse.js"; +import { escapeEvents } from "../util/cli.js"; import { logger } from "../util/logger.js"; /** @@ -125,6 +126,17 @@ export async function executeSubAgent( try { let accumulatedOutput = ""; + escapeEvents.on("user-escape", () => { + abortController.abort(); + chatHistory.push({ + message: { + role: "user", + content: "Subagent execution was cancelled by the user.", + }, + contextItems: [], + }); + }); + // Execute the chat stream with child session await streamChatResponse( chatHistory, diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index 470688120..205d48b2e 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -1,4 +1,5 @@ /* eslint-disable max-lines */ + import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text, useApp, useInput } from "ink"; import React, { useCallback, useRef, useState } from "react"; @@ -13,6 +14,7 @@ import { services, } from "../services/index.js"; import { messageQueue } from "../stream/messageQueue.js"; +import { escapeEvents } from "../util/cli.js"; import { InputHistory } from "../util/inputHistory.js"; import { FileSearchUI } from "./FileSearchUI.js"; @@ -616,6 +618,8 @@ const UserInput: React.FC = ({ const handleEscapeKey = (key: any): boolean => { if (!key.escape) return false; + escapeEvents.emit("user-escape"); + // If only "!" is present, clear shell mode if (inputMode && showBashMode && inputText.trim() === "!") { textBuffer.clear(); diff --git a/extensions/cli/src/util/cli.ts b/extensions/cli/src/util/cli.ts index 5132fd4c1..b8e359a1d 100644 --- a/extensions/cli/src/util/cli.ts +++ b/extensions/cli/src/util/cli.ts @@ -2,6 +2,8 @@ * Utility functions for CLI operations */ +import EventEmitter from "events"; + /** * Check if running in headless mode (-p/--print flags) */ @@ -90,3 +92,5 @@ export function hasSuppliedPrompt(): boolean { return false; } + +export const escapeEvents = new EventEmitter(); From d510de946bb4ec1a53ced8b37bd0b4318a8ee701 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 7 Jan 2026 20:11:18 +0530 Subject: [PATCH 19/33] remove builtintoolnames --- .../cli/src/services/ToolPermissionService.ts | 4 +-- extensions/cli/src/tools/allBuiltIns.ts | 2 +- extensions/cli/src/tools/builtInToolNames.ts | 21 ----------- extensions/cli/src/tools/index.tsx | 3 -- extensions/cli/src/tools/subagent.ts | 35 ++++++++++++------- extensions/cli/src/tools/types.ts | 2 +- 6 files changed, 27 insertions(+), 40 deletions(-) delete mode 100644 extensions/cli/src/tools/builtInToolNames.ts diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index 236f72fb7..f1566900a 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -5,7 +5,7 @@ import { ToolPermissionPolicy, ToolPermissions, } from "../permissions/types.js"; -import { BUILT_IN_TOOL_NAMES } from "../tools/builtInToolNames.js"; +import { ALL_BUILT_IN_TOOLS } from "../tools/allBuiltIns.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; @@ -142,7 +142,7 @@ export class ToolPermissionService })); policies.push(...allowed); const specificBuiltInSet = new Set(specificBuiltIns); - const notMentioned = BUILT_IN_TOOL_NAMES.filter( + const notMentioned = ALL_BUILT_IN_TOOLS.map((t) => t.name).filter( (name) => !specificBuiltInSet.has(name), ); const disallowed: ToolPermissionPolicy[] = notMentioned.map((tool) => ({ diff --git a/extensions/cli/src/tools/allBuiltIns.ts b/extensions/cli/src/tools/allBuiltIns.ts index c5e86f9f3..be5e68b36 100644 --- a/extensions/cli/src/tools/allBuiltIns.ts +++ b/extensions/cli/src/tools/allBuiltIns.ts @@ -23,7 +23,7 @@ export const ALL_BUILT_IN_TOOLS = [ runTerminalCommandTool, fetchTool, writeChecklistTool, - subagentTool, + subagentTool(), exitTool, reportFailureTool, uploadArtifactTool, diff --git a/extensions/cli/src/tools/builtInToolNames.ts b/extensions/cli/src/tools/builtInToolNames.ts deleted file mode 100644 index 900984dc1..000000000 --- a/extensions/cli/src/tools/builtInToolNames.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * List of built-in tool names - * Kept separate from allBuiltIns.ts to avoid circular dependencies - */ -export const BUILT_IN_TOOL_NAMES = [ - "Read", - "Edit", - "MultiEdit", - "Write", - "List", - "Search", - "Bash", - "Fetch", - "Checklist", - "Subagent", - "Exit", - "ReportFailure", - "UploadArtifact", -] as const; - -export type BuiltInToolName = (typeof BUILT_IN_TOOL_NAMES)[number]; diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index 3e7bb9401..cfc508579 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -132,9 +132,6 @@ export async function getAllAvailableTools( export function getToolDisplayName(toolName: string): string { const tool = ALL_BUILT_IN_TOOLS.find((t) => t.name === toolName); - if (typeof tool === "function") { - return toolName; - } return tool?.displayName || toolName; } diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index 145d18a91..ce8044e13 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -1,3 +1,4 @@ +import { services } from "../services/index.js"; import { executeSubAgent } from "../subagent/executor.js"; import { generateSubagentToolDescription, @@ -11,7 +12,9 @@ import { GetTool } from "./types.js"; export const subagentTool: GetTool = (params) => ({ name: "Subagent", displayName: "Subagent", - description: generateSubagentToolDescription(params.modelServiceState), + description: params + ? generateSubagentToolDescription(params.modelServiceState) + : "Use a subagent to handle a specialized task.", readonly: false, isBuiltIn: true, @@ -29,14 +32,26 @@ export const subagentTool: GetTool = (params) => ({ }, subagent_name: { type: "string", - description: `The type of specialized agent to use for this task. Available agents: ${getSubagentNames( - params.modelServiceState, - ).join(", ")}`, + description: `The type of specialized agent to use for this task. Available agents: ${ + params ? getSubagentNames(params.modelServiceState).join(", ") : "" + }`, }, }, }, preprocess: async (args: any) => { + if (!params) { + return { + args, + preview: [ + { + type: "text", + content: "Subagent not found", + }, + ], + }; + } + const { description, subagent_name } = args; const agent = getSubagent(params.modelServiceState, subagent_name); @@ -60,23 +75,19 @@ export const subagentTool: GetTool = (params) => ({ }, run: async (args: any, context?: { toolCallId: string }) => { + if (!params) return ""; + const { prompt, subagent_name } = args; logger.debug("subagent args", { args, context }); - // Get agent configuration + // get agent configuration const agent = getSubagent(params.modelServiceState, subagent_name); if (!agent) { throw new Error(`Unknown agent type: ${subagent_name}`); } - // Lazy import services to avoid circular dependency - const { services } = await import("../services/index.js"); - - // Get parent session ID from chat history service - const chatHistoryService = services.chatHistory; - const parentSessionId = chatHistoryService.getSessionId(); - + const parentSessionId = services.chatHistory.getSessionId(); if (!parentSessionId) { throw new Error("No active session found"); } diff --git a/extensions/cli/src/tools/types.ts b/extensions/cli/src/tools/types.ts index 3d2a4b579..235b7e140 100644 --- a/extensions/cli/src/tools/types.ts +++ b/extensions/cli/src/tools/types.ts @@ -48,7 +48,7 @@ export interface Tool { ) => ToolPolicy; } -export type GetTool = (params: { +export type GetTool = (params?: { modelServiceState: ModelServiceState; }) => Tool; From 8e0212268db31734c22c704b31da2b58994fe691 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 7 Jan 2026 20:18:54 +0530 Subject: [PATCH 20/33] cleanup listener after execution --- extensions/cli/src/subagent/executor.ts | 29 +++++++++++++++---------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/extensions/cli/src/subagent/executor.ts b/extensions/cli/src/subagent/executor.ts index b0ecc2c5a..b42b86baf 100644 --- a/extensions/cli/src/subagent/executor.ts +++ b/extensions/cli/src/subagent/executor.ts @@ -57,6 +57,7 @@ async function buildAgentSystemMessage( /** * Execute a subagent in a child session */ +// eslint-disable-next-line complexity export async function executeSubAgent( options: SubAgentExecutionOptions, ): Promise { @@ -123,20 +124,22 @@ export async function executeSubAgent( }, ] as ChatHistoryItem[]; + const escapeHandler = () => { + abortController.abort(); + chatHistory.push({ + message: { + role: "user", + content: "Subagent execution was cancelled by the user.", + }, + contextItems: [], + }); + }; + + escapeEvents.on("user-escape", escapeHandler); + try { let accumulatedOutput = ""; - escapeEvents.on("user-escape", () => { - abortController.abort(); - chatHistory.push({ - message: { - role: "user", - content: "Subagent execution was cancelled by the user.", - }, - contextItems: [], - }); - }); - // Execute the chat stream with child session await streamChatResponse( chatHistory, @@ -178,6 +181,10 @@ export async function executeSubAgent( response, }; } finally { + if (escapeHandler) { + escapeEvents.removeListener("user-escape", escapeHandler); + } + // Restore original system message function if (services.systemMessage && originalGetSystemMessage) { services.systemMessage.getSystemMessage = originalGetSystemMessage; From c366fa89ab279b2b6ae06d4481f59efc2f5c178d Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 7 Jan 2026 20:24:42 +0530 Subject: [PATCH 21/33] fix lint --- core/config/load.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/config/load.ts b/core/config/load.ts index 35d12d421..4a88fbcce 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -514,6 +514,7 @@ async function intermediateToFinalConfig({ autocomplete: [...tabAutocompleteModels], embed: newEmbedder ? [newEmbedder] : [], rerank: newReranker ? [newReranker] : [], + subagent: [], }, selectedModelByRole: { chat: null, // Not implemented (uses GUI defaultModel) @@ -523,6 +524,7 @@ async function intermediateToFinalConfig({ autocomplete: null, rerank: newReranker ?? null, summarize: null, // Not implemented + subagent: null, }, rules: [], }; From 3bdac8d1ceb0277cbe6a4a8fce9508ab95673a74 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 7 Jan 2026 20:37:43 +0530 Subject: [PATCH 22/33] move subagent behind beta --- extensions/cli/src/commands/BaseCommandOptions.ts | 2 ++ extensions/cli/src/index.ts | 4 ++++ extensions/cli/src/services/index.ts | 8 +++++++- extensions/cli/src/tools/index.tsx | 9 +++++++-- extensions/cli/src/tools/toolsConfig.ts | 9 +++++++++ 5 files changed, 29 insertions(+), 3 deletions(-) diff --git a/extensions/cli/src/commands/BaseCommandOptions.ts b/extensions/cli/src/commands/BaseCommandOptions.ts index 40db1aa7a..d9987403e 100644 --- a/extensions/cli/src/commands/BaseCommandOptions.ts +++ b/extensions/cli/src/commands/BaseCommandOptions.ts @@ -25,6 +25,8 @@ export interface BaseCommandOptions { agent?: string; /** Enable beta UploadArtifact tool */ betaUploadArtifactTool?: boolean; + /** Enable beta Subagent tool */ + betaSubagentTool?: boolean; } /** diff --git a/extensions/cli/src/index.ts b/extensions/cli/src/index.ts index 68a6b58cd..37dfd2cba 100644 --- a/extensions/cli/src/index.ts +++ b/extensions/cli/src/index.ts @@ -198,6 +198,10 @@ addCommonOptions(program) ) .option("--resume", "Resume from last session") .option("--fork ", "Fork from an existing session ID") + .option( + "--beta-subagent-tool", + "Enable beta Subagent tool for invoking subagents", + ) .action(async (prompt, options) => { // Telemetry: record command invocation await posthogService.capture("cliCommand", { command: "cn" }); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index f53a53c84..1ddc73da7 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -1,6 +1,9 @@ import { loadAuthConfig } from "../auth/workos.js"; import { initializeWithOnboarding } from "../onboarding.js"; -import { setBetaUploadArtifactToolEnabled } from "../tools/toolsConfig.js"; +import { + setBetaSubagentToolEnabled, + setBetaUploadArtifactToolEnabled, +} from "../tools/toolsConfig.js"; import { logger } from "../util/logger.js"; import { AgentFileService } from "./AgentFileService.js"; @@ -62,6 +65,9 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { if (commandOptions.betaUploadArtifactTool) { setBetaUploadArtifactToolEnabled(true); } + if (commandOptions.betaSubagentTool) { + setBetaSubagentToolEnabled(true); + } // Handle onboarding for TUI mode (headless: false) unless explicitly skipped if (!initOptions.headless && !initOptions.skipOnboarding) { const authConfig = loadAuthConfig(); diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index cfc508579..797ec1bae 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -29,7 +29,10 @@ import { reportFailureTool } from "./reportFailure.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; import { checkIfRipgrepIsInstalled, searchCodeTool } from "./searchCode.js"; import { subagentTool } from "./subagent.js"; -import { isBetaUploadArtifactToolEnabled } from "./toolsConfig.js"; +import { + isBetaSubagentToolEnabled, + isBetaUploadArtifactToolEnabled, +} from "./toolsConfig.js"; import { type Tool, type ToolCall, @@ -120,7 +123,9 @@ export async function getAllAvailableTools( tools.push(exitTool); } - tools.push(subagentTool({ modelServiceState: modelState })); + if (isBetaSubagentToolEnabled()) { + tools.push(subagentTool({ modelServiceState: modelState })); + } const mcpState = await serviceContainer.get( SERVICE_NAMES.MCP, diff --git a/extensions/cli/src/tools/toolsConfig.ts b/extensions/cli/src/tools/toolsConfig.ts index b1703a545..e9a2e0233 100644 --- a/extensions/cli/src/tools/toolsConfig.ts +++ b/extensions/cli/src/tools/toolsConfig.ts @@ -4,6 +4,7 @@ */ let betaUploadArtifactToolEnabled = false; +let betaSubagentToolEnabled = false; export function setBetaUploadArtifactToolEnabled(enabled: boolean): void { betaUploadArtifactToolEnabled = enabled; @@ -12,3 +13,11 @@ export function setBetaUploadArtifactToolEnabled(enabled: boolean): void { export function isBetaUploadArtifactToolEnabled(): boolean { return betaUploadArtifactToolEnabled; } + +export function setBetaSubagentToolEnabled(enabled: boolean): void { + betaSubagentToolEnabled = enabled; +} + +export function isBetaSubagentToolEnabled(): boolean { + return betaSubagentToolEnabled; +} From a48bb94c09a13dfcce36f24258d91b51572b83b7 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 7 Jan 2026 20:40:03 +0530 Subject: [PATCH 23/33] fix more lints --- core/config/usesFreeTrialApiKey.vitest.ts | 12 ++++++++++++ core/config/yaml/models.vitest.ts | 2 ++ gui/src/redux/slices/configSlice.ts | 2 ++ 3 files changed, 16 insertions(+) diff --git a/core/config/usesFreeTrialApiKey.vitest.ts b/core/config/usesFreeTrialApiKey.vitest.ts index 6d8318830..79dfca35a 100644 --- a/core/config/usesFreeTrialApiKey.vitest.ts +++ b/core/config/usesFreeTrialApiKey.vitest.ts @@ -58,6 +58,7 @@ describe("usesFreeTrialApiKey", () => { autocomplete: [], rerank: [], embed: [], + subagent: [], }, selectedModelByRole: { chat: null, @@ -67,6 +68,7 @@ describe("usesFreeTrialApiKey", () => { autocomplete: null, rerank: null, embed: null, + subagent: null, }, contextProviders: [], slashCommands: [], @@ -106,6 +108,7 @@ describe("usesFreeTrialApiKey", () => { autocomplete: [], rerank: [], embed: [], + subagent: [], }, selectedModelByRole: { chat: null, @@ -115,6 +118,7 @@ describe("usesFreeTrialApiKey", () => { autocomplete: null, rerank: null, embed: null, + subagent: null, }, contextProviders: [], slashCommands: [], @@ -166,6 +170,7 @@ describe("usesFreeTrialApiKey", () => { autocomplete: [], rerank: [], embed: [], + subagent: [], }, selectedModelByRole: { chat: null, @@ -175,6 +180,7 @@ describe("usesFreeTrialApiKey", () => { autocomplete: null, rerank: null, embed: null, + subagent: null, }, contextProviders: [], slashCommands: [], @@ -227,6 +233,7 @@ describe("usesFreeTrialApiKey", () => { autocomplete: [], rerank: [], embed: [], + subagent: [], }, selectedModelByRole: { chat: null, @@ -236,6 +243,7 @@ describe("usesFreeTrialApiKey", () => { autocomplete: null, rerank: null, embed: null, + subagent: null, }, contextProviders: [], slashCommands: [], @@ -281,6 +289,7 @@ describe("usesFreeTrialApiKey", () => { autocomplete: [], rerank: [], embed: [], + subagent: [], }, selectedModelByRole: { chat: null, @@ -290,6 +299,7 @@ describe("usesFreeTrialApiKey", () => { autocomplete: null, rerank: null, embed: null, + subagent: null, }, contextProviders: [], slashCommands: [], @@ -323,6 +333,7 @@ describe("usesFreeTrialApiKey", () => { autocomplete: [], rerank: [], embed: [], + subagent: [], }, selectedModelByRole: { chat: null, @@ -332,6 +343,7 @@ describe("usesFreeTrialApiKey", () => { autocomplete: null, rerank: null, embed: null, + subagent: null, }, contextProviders: [], slashCommands: [], diff --git a/core/config/yaml/models.vitest.ts b/core/config/yaml/models.vitest.ts index aa2bc4691..0e99448d5 100644 --- a/core/config/yaml/models.vitest.ts +++ b/core/config/yaml/models.vitest.ts @@ -67,6 +67,7 @@ describe("llmsFromModelConfig requestOptions merging", () => { embed: null, rerank: null, summarize: null, + subagent: null, }, modelsByRole: { apply: [], @@ -76,6 +77,7 @@ describe("llmsFromModelConfig requestOptions merging", () => { embed: [], rerank: [], summarize: [], + subagent: [], }, slashCommands: [], tools: [], diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index 678354655..202abbfbb 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -23,6 +23,7 @@ export const EMPTY_CONFIG: BrowserSerializedContinueConfig = { autocomplete: [], rerank: [], embed: [], + subagent: [], }, selectedModelByRole: { chat: null, @@ -32,6 +33,7 @@ export const EMPTY_CONFIG: BrowserSerializedContinueConfig = { autocomplete: null, rerank: null, embed: null, + subagent: null, }, rules: [], }; From 6182a3ffa0f446f054646c6a8140f8d5b21928d3 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 8 Jan 2026 18:12:19 +0530 Subject: [PATCH 24/33] restore toolpermissionservice changes --- extensions/cli/src/services/ToolPermissionService.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index f1566900a..4e0802272 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -1,3 +1,5 @@ +import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js"; + import { ensurePermissionsYamlExists } from "../permissions/permissionsYamlLoader.js"; import { resolvePermissionPrecedence } from "../permissions/precedenceResolver.js"; import { @@ -5,7 +7,6 @@ import { ToolPermissionPolicy, ToolPermissions, } from "../permissions/types.js"; -import { ALL_BUILT_IN_TOOLS } from "../tools/allBuiltIns.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; From fc5e22f5adbb12ddc3bb7c5b24aa1541181d8d1a Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 8 Jan 2026 18:16:23 +0530 Subject: [PATCH 25/33] fix cyclical import --- extensions/cli/src/tools/subagent.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index ce8044e13..bc15bdf1f 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -1,5 +1,4 @@ import { services } from "../services/index.js"; -import { executeSubAgent } from "../subagent/executor.js"; import { generateSubagentToolDescription, getSubagent, @@ -95,6 +94,8 @@ export const subagentTool: GetTool = (params) => ({ // Create abort controller for child execution const abortController = new AbortController(); + const { executeSubAgent } = await import("../subagent/executor.js"); // prevent cyclical import + // Execute subagent with output streaming const result = await executeSubAgent({ agent, From 25b08e08707851d64761030c74184039f3ad895b Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 8 Jan 2026 18:28:46 +0530 Subject: [PATCH 26/33] fix gitaiintegration test --- .../cli/src/tools/gitAiIntegration.test.ts | 18 ++++++++++++------ extensions/cli/src/tools/subagent.ts | 5 +---- extensions/cli/src/tools/types.ts | 1 + 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/extensions/cli/src/tools/gitAiIntegration.test.ts b/extensions/cli/src/tools/gitAiIntegration.test.ts index cc5c5f52a..d9d2c85e2 100644 --- a/extensions/cli/src/tools/gitAiIntegration.test.ts +++ b/extensions/cli/src/tools/gitAiIntegration.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { PreprocessedToolCall } from "./types.js"; @@ -69,6 +69,7 @@ describe("Git AI Integration - executeToolCall", () => { oldContent: "old", newContent: "new", }, + context: { toolCallId: "test-edit-id" }, }, }; @@ -94,11 +95,16 @@ describe("Git AI Integration - executeToolCall", () => { ); // Verify tool.run was called - expect(mockTool.run).toHaveBeenCalledWith({ - resolvedPath: "/test/file.ts", - oldContent: "old", - newContent: "new", - }); + expect(mockTool.run).toHaveBeenCalledWith( + { + resolvedPath: "/test/file.ts", + oldContent: "old", + newContent: "new", + }, + { + toolCallId: "test-edit-id", + }, + ); }); it("should call git-ai before and after MultiEdit tool execution", async () => { diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index bc15bdf1f..1b49d970f 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -91,9 +91,6 @@ export const subagentTool: GetTool = (params) => ({ throw new Error("No active session found"); } - // Create abort controller for child execution - const abortController = new AbortController(); - const { executeSubAgent } = await import("../subagent/executor.js"); // prevent cyclical import // Execute subagent with output streaming @@ -101,7 +98,7 @@ export const subagentTool: GetTool = (params) => ({ agent, prompt, parentSessionId, - abortController, + abortController: new AbortController(), onOutputUpdate: context?.toolCallId ? (output: string) => { try { diff --git a/extensions/cli/src/tools/types.ts b/extensions/cli/src/tools/types.ts index 235b7e140..a7d8bcde3 100644 --- a/extensions/cli/src/tools/types.ts +++ b/extensions/cli/src/tools/types.ts @@ -31,6 +31,7 @@ export interface ToolCallPreview { export interface PreprocessToolCallResult { preview?: ToolCallPreview[]; args: Record; + context?: { toolCallId: string }; } export interface Tool { From 66fe98fe7d78a15d442e5383897c079b16e84364 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 8 Jan 2026 19:22:03 +0530 Subject: [PATCH 27/33] try to fix import issues for tests --- extensions/cli/src/tools/index.tsx | 6 +++++- extensions/cli/src/tools/subagent.ts | 8 ++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index 797ec1bae..f95cf02ef 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -124,7 +124,11 @@ export async function getAllAvailableTools( } if (isBetaSubagentToolEnabled()) { - tools.push(subagentTool({ modelServiceState: modelState })); + tools.push( + subagentTool({ + modelServiceState: modelState, + }), + ); } const mcpState = await serviceContainer.get( diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index 1b49d970f..a41cc86c7 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -1,4 +1,3 @@ -import { services } from "../services/index.js"; import { generateSubagentToolDescription, getSubagent, @@ -23,7 +22,7 @@ export const subagentTool: GetTool = (params) => ({ properties: { description: { type: "string", - description: "A short (3-5 words) description of the task", + description: "A short description of the task", }, prompt: { type: "string", @@ -86,13 +85,14 @@ export const subagentTool: GetTool = (params) => ({ throw new Error(`Unknown agent type: ${subagent_name}`); } + const { executeSubAgent } = await import("../subagent/executor.js"); + const { services } = await import("../services/index.js"); + const parentSessionId = services.chatHistory.getSessionId(); if (!parentSessionId) { throw new Error("No active session found"); } - const { executeSubAgent } = await import("../subagent/executor.js"); // prevent cyclical import - // Execute subagent with output streaming const result = await executeSubAgent({ agent, From eb77a589b44dc005f1f9a9be7d560e1509626488 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 8 Jan 2026 20:17:47 +0530 Subject: [PATCH 28/33] use subagent tool meta instead of calling the func --- extensions/cli/src/services/index.ts | 2 + extensions/cli/src/subagent/executor.ts | 24 +++++++---- extensions/cli/src/subagent/get-agents.ts | 2 +- extensions/cli/src/tools/allBuiltIns.ts | 7 +-- extensions/cli/src/tools/index.tsx | 2 + extensions/cli/src/tools/subagent.ts | 52 ++++++++++++----------- extensions/cli/src/tools/types.ts | 8 +++- 7 files changed, 57 insertions(+), 40 deletions(-) diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index 1ddc73da7..56a5d4e93 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -389,6 +389,8 @@ export const services = { gitAiIntegration: gitAiIntegrationService, } as const; +export type ServicesType = typeof services; + // Export the service container for advanced usage export { serviceContainer }; diff --git a/extensions/cli/src/subagent/executor.ts b/extensions/cli/src/subagent/executor.ts index b42b86baf..405e70705 100644 --- a/extensions/cli/src/subagent/executor.ts +++ b/extensions/cli/src/subagent/executor.ts @@ -1,12 +1,9 @@ import type { ChatHistoryItem } from "core"; -import { - ModelServiceState, - SERVICE_NAMES, - serviceContainer, - services, -} from "../services/index.js"; -import { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; +import type { ServicesType } from "../services/index.js"; +import type { ServiceContainer } from "../services/ServiceContainer.js"; +import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; +import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; import { streamChatResponse } from "../stream/streamChatResponse.js"; import { escapeEvents } from "../util/cli.js"; import { logger } from "../util/logger.js"; @@ -20,6 +17,8 @@ export interface SubAgentExecutionOptions { parentSessionId: string; abortController: AbortController; onOutputUpdate?: (output: string) => void; + services: ServicesType; + serviceContainer: ServiceContainer; } /** @@ -61,13 +60,20 @@ async function buildAgentSystemMessage( export async function executeSubAgent( options: SubAgentExecutionOptions, ): Promise { + const { + agent: subAgent, + prompt, + abortController, + onOutputUpdate, + services, + serviceContainer, + } = options; + const mainAgentPermissionsState = await serviceContainer.get( SERVICE_NAMES.TOOL_PERMISSIONS, ); - const { agent: subAgent, prompt, abortController, onOutputUpdate } = options; - try { logger.debug("Starting subagent execution", { agent: subAgent.model?.name, diff --git a/extensions/cli/src/subagent/get-agents.ts b/extensions/cli/src/subagent/get-agents.ts index 3b5282e4a..9abdc2d3a 100644 --- a/extensions/cli/src/subagent/get-agents.ts +++ b/extensions/cli/src/subagent/get-agents.ts @@ -1,5 +1,5 @@ -import { ModelServiceState } from "../services/index.js"; import { ModelService } from "../services/ModelService.js"; +import type { ModelServiceState } from "../services/types.js"; /** * Get an agent by name diff --git a/extensions/cli/src/tools/allBuiltIns.ts b/extensions/cli/src/tools/allBuiltIns.ts index be5e68b36..0d46de4b9 100644 --- a/extensions/cli/src/tools/allBuiltIns.ts +++ b/extensions/cli/src/tools/allBuiltIns.ts @@ -7,13 +7,14 @@ import { readFileTool } from "./readFile.js"; import { reportFailureTool } from "./reportFailure.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; import { searchCodeTool } from "./searchCode.js"; -import { subagentTool } from "./subagent.js"; +import { SUBAGENT_TOOL_META } from "./subagent.js"; +import type { Tool } from "./types.js"; import { uploadArtifactTool } from "./uploadArtifact.js"; import { writeChecklistTool } from "./writeChecklist.js"; import { writeFileTool } from "./writeFile.js"; // putting in here for circular import issue -export const ALL_BUILT_IN_TOOLS = [ +export const ALL_BUILT_IN_TOOLS: Tool[] = [ readFileTool, editTool, multiEditTool, @@ -23,7 +24,7 @@ export const ALL_BUILT_IN_TOOLS = [ runTerminalCommandTool, fetchTool, writeChecklistTool, - subagentTool(), + SUBAGENT_TOOL_META, exitTool, reportFailureTool, uploadArtifactTool, diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index f95cf02ef..67c4f4482 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -127,6 +127,8 @@ export async function getAllAvailableTools( tools.push( subagentTool({ modelServiceState: modelState, + services, + serviceContainer, }), ); } diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index a41cc86c7..5e38e3719 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -1,3 +1,4 @@ +import { executeSubAgent } from "../subagent/executor.js"; import { generateSubagentToolDescription, getSubagent, @@ -5,17 +6,14 @@ import { } from "../subagent/get-agents.js"; import { logger } from "../util/logger.js"; -import { GetTool } from "./types.js"; +import { GetTool, Tool } from "./types.js"; -export const subagentTool: GetTool = (params) => ({ +export const SUBAGENT_TOOL_META: Tool = { name: "Subagent", displayName: "Subagent", - description: params - ? generateSubagentToolDescription(params.modelServiceState) - : "Use a subagent to handle a specialized task.", + description: "Use a subagent to handle a specialized task.", readonly: false, isBuiltIn: true, - parameters: { type: "object", required: ["description", "prompt", "subagent_name"], @@ -28,6 +26,24 @@ export const subagentTool: GetTool = (params) => ({ type: "string", description: "The task for the agent to perform", }, + subagent_name: { + type: "string", + description: "The type of specialized agent to use for this task.", + }, + }, + }, + run: async () => "", +}; + +export const subagentTool: GetTool = (params) => ({ + ...SUBAGENT_TOOL_META, + + description: generateSubagentToolDescription(params.modelServiceState), + + parameters: { + ...SUBAGENT_TOOL_META.parameters, + properties: { + ...SUBAGENT_TOOL_META.parameters.properties, subagent_name: { type: "string", description: `The type of specialized agent to use for this task. Available agents: ${ @@ -38,18 +54,6 @@ export const subagentTool: GetTool = (params) => ({ }, preprocess: async (args: any) => { - if (!params) { - return { - args, - preview: [ - { - type: "text", - content: "Subagent not found", - }, - ], - }; - } - const { description, subagent_name } = args; const agent = getSubagent(params.modelServiceState, subagent_name); @@ -73,8 +77,6 @@ export const subagentTool: GetTool = (params) => ({ }, run: async (args: any, context?: { toolCallId: string }) => { - if (!params) return ""; - const { prompt, subagent_name } = args; logger.debug("subagent args", { args, context }); @@ -85,10 +87,8 @@ export const subagentTool: GetTool = (params) => ({ throw new Error(`Unknown agent type: ${subagent_name}`); } - const { executeSubAgent } = await import("../subagent/executor.js"); - const { services } = await import("../services/index.js"); - - const parentSessionId = services.chatHistory.getSessionId(); + const chatHistoryService = params.services.chatHistory; + const parentSessionId = chatHistoryService.getSessionId(); if (!parentSessionId) { throw new Error("No active session found"); } @@ -99,10 +99,12 @@ export const subagentTool: GetTool = (params) => ({ prompt, parentSessionId, abortController: new AbortController(), + services: params.services, + serviceContainer: params.serviceContainer, onOutputUpdate: context?.toolCallId ? (output: string) => { try { - services.chatHistory.addToolResult( + chatHistoryService.addToolResult( context.toolCallId, output, "calling", diff --git a/extensions/cli/src/tools/types.ts b/extensions/cli/src/tools/types.ts index a7d8bcde3..aea513fcf 100644 --- a/extensions/cli/src/tools/types.ts +++ b/extensions/cli/src/tools/types.ts @@ -1,6 +1,8 @@ import type { ToolPolicy } from "@continuedev/terminal-security"; -import { ModelServiceState } from "src/services/types.js"; +import type { ServicesType } from "src/services/index.js"; +import type { ServiceContainer } from "src/services/ServiceContainer.js"; +import type { ModelServiceState } from "src/services/types.js"; // JSON Schema compatible parameter definition export interface ParameterSchema { @@ -49,8 +51,10 @@ export interface Tool { ) => ToolPolicy; } -export type GetTool = (params?: { +export type GetTool = (params: { modelServiceState: ModelServiceState; + services: ServicesType; + serviceContainer: ServiceContainer; }) => Tool; export interface ToolCall { From 3fbb428f3f0a7dad6bbee10d1e5e6eed2a8656df Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 8 Jan 2026 20:25:18 +0530 Subject: [PATCH 29/33] add subagent tests --- extensions/cli/src/tools/subagent.test.ts | 118 ++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 extensions/cli/src/tools/subagent.test.ts diff --git a/extensions/cli/src/tools/subagent.test.ts b/extensions/cli/src/tools/subagent.test.ts new file mode 100644 index 000000000..0d7668cea --- /dev/null +++ b/extensions/cli/src/tools/subagent.test.ts @@ -0,0 +1,118 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { executeSubAgent } from "../subagent/executor.js"; +import { getAgentNames, getSubagent } from "../subagent/get-agents.js"; + +import { subagentTool } from "./subagent.js"; + +vi.mock("../subagent/get-agents.js"); +vi.mock("../subagent/executor.js"); + +describe("subagentTool", () => { + const modelServiceState = {} as any; + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("preprocess throws when agent is not found", async () => { + vi.mocked(getAgentNames).mockReturnValue(["code-agent"]); + + const tool = subagentTool({ modelServiceState } as any); + + const args = { + description: "Test task", + prompt: "Do something", + subagent_name: "unknown-agent", + }; + + await expect(tool.preprocess!(args)).rejects.toThrow( + "Unknown agent type: unknown-agent", + ); + expect(vi.mocked(getSubagent)).toHaveBeenCalledWith( + modelServiceState, + "unknown-agent", + ); + }); + + it("preprocess includes agent model name when agent exists", async () => { + vi.mocked(getAgentNames).mockReturnValue(["code-agent"]); + + const tool = subagentTool({ modelServiceState } as any); + + vi.mocked(getSubagent).mockReturnValue({ + model: { name: "test-model" }, + } as any); + + const args = { + description: "Handle specialized task", + prompt: "Do it", + subagent_name: "code-agent", + }; + + const result = await tool.preprocess!(args); + + expect(result.preview).toEqual([ + { + type: "text", + content: "Spawning test-model to: Handle specialized task", + }, + ]); + expect(vi.mocked(getSubagent)).toHaveBeenCalledWith( + modelServiceState, + "code-agent", + ); + }); + + it("run executes subagent and returns formatted output", async () => { + vi.mocked(getAgentNames).mockReturnValue(["code-agent"]); + vi.mocked(getSubagent).mockReturnValue({ + model: { name: "test-model" }, + } as any); + vi.mocked(executeSubAgent).mockResolvedValue({ + success: true, + response: "subagent-output", + } as any); + + const services = { + chatHistory: { + getSessionId: vi.fn().mockReturnValue("parent-session-id"), + addToolResult: vi.fn(), + }, + } as any; + + const serviceContainer = {} as any; + + const tool = subagentTool({ + modelServiceState, + services, + serviceContainer, + } as any); + + const result = await tool.run( + { + prompt: "Subagent prompt", + subagent_name: "code-agent", + }, + { toolCallId: "tool-call-id" }, + ); + + expect(vi.mocked(executeSubAgent)).toHaveBeenCalledTimes(1); + const [options] = vi.mocked(executeSubAgent).mock.calls[0]; + + expect(options.prompt).toBe("Subagent prompt"); + expect(options.parentSessionId).toBe("parent-session-id"); + expect(typeof options.onOutputUpdate).toBe("function"); + + options.onOutputUpdate?.("partial-output"); + expect(services.chatHistory.addToolResult).toHaveBeenCalledWith( + "tool-call-id", + "partial-output", + "calling", + ); + + expect(result).toBe( + "subagent-output\n\nstatus: completed\n", + ); + }); +}); From 2b347b6760b23b2554f89d8899fea3e4d7436825 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 8 Jan 2026 21:39:12 +0530 Subject: [PATCH 30/33] use dynamic to prevent cyclical dependency --- extensions/cli/src/subagent/executor.ts | 15 +++------------ extensions/cli/src/tools/index.tsx | 2 -- extensions/cli/src/tools/subagent.ts | 9 +++++---- extensions/cli/src/tools/types.ts | 4 ---- 4 files changed, 8 insertions(+), 22 deletions(-) diff --git a/extensions/cli/src/subagent/executor.ts b/extensions/cli/src/subagent/executor.ts index 405e70705..1580e7f7f 100644 --- a/extensions/cli/src/subagent/executor.ts +++ b/extensions/cli/src/subagent/executor.ts @@ -1,7 +1,7 @@ import type { ChatHistoryItem } from "core"; -import type { ServicesType } from "../services/index.js"; -import type { ServiceContainer } from "../services/ServiceContainer.js"; +import { services } from "../services/index.js"; +import { serviceContainer } from "../services/ServiceContainer.js"; import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; import { streamChatResponse } from "../stream/streamChatResponse.js"; @@ -17,8 +17,6 @@ export interface SubAgentExecutionOptions { parentSessionId: string; abortController: AbortController; onOutputUpdate?: (output: string) => void; - services: ServicesType; - serviceContainer: ServiceContainer; } /** @@ -60,14 +58,7 @@ async function buildAgentSystemMessage( export async function executeSubAgent( options: SubAgentExecutionOptions, ): Promise { - const { - agent: subAgent, - prompt, - abortController, - onOutputUpdate, - services, - serviceContainer, - } = options; + const { agent: subAgent, prompt, abortController, onOutputUpdate } = options; const mainAgentPermissionsState = await serviceContainer.get( diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index 67c4f4482..f95cf02ef 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -127,8 +127,6 @@ export async function getAllAvailableTools( tools.push( subagentTool({ modelServiceState: modelState, - services, - serviceContainer, }), ); } diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index 5e38e3719..aad198b8b 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -1,4 +1,3 @@ -import { executeSubAgent } from "../subagent/executor.js"; import { generateSubagentToolDescription, getSubagent, @@ -87,7 +86,11 @@ export const subagentTool: GetTool = (params) => ({ throw new Error(`Unknown agent type: ${subagent_name}`); } - const chatHistoryService = params.services.chatHistory; + // Dynamically import to avoid circular dependency and passing repeated params + const { executeSubAgent } = await import("../subagent/executor.js"); + const { services } = await import("../services/index.js"); + + const chatHistoryService = services.chatHistory; const parentSessionId = chatHistoryService.getSessionId(); if (!parentSessionId) { throw new Error("No active session found"); @@ -99,8 +102,6 @@ export const subagentTool: GetTool = (params) => ({ prompt, parentSessionId, abortController: new AbortController(), - services: params.services, - serviceContainer: params.serviceContainer, onOutputUpdate: context?.toolCallId ? (output: string) => { try { diff --git a/extensions/cli/src/tools/types.ts b/extensions/cli/src/tools/types.ts index aea513fcf..faf68cd4e 100644 --- a/extensions/cli/src/tools/types.ts +++ b/extensions/cli/src/tools/types.ts @@ -1,7 +1,5 @@ import type { ToolPolicy } from "@continuedev/terminal-security"; -import type { ServicesType } from "src/services/index.js"; -import type { ServiceContainer } from "src/services/ServiceContainer.js"; import type { ModelServiceState } from "src/services/types.js"; // JSON Schema compatible parameter definition @@ -53,8 +51,6 @@ export interface Tool { export type GetTool = (params: { modelServiceState: ModelServiceState; - services: ServicesType; - serviceContainer: ServiceContainer; }) => Tool; export interface ToolCall { From c2d928d48346125a3b681bb1a8548e06add57b34 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 8 Jan 2026 21:44:08 +0530 Subject: [PATCH 31/33] fix subagent tests --- extensions/cli/src/tools/subagent.test.ts | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/extensions/cli/src/tools/subagent.test.ts b/extensions/cli/src/tools/subagent.test.ts index 0d7668cea..90a53ac8e 100644 --- a/extensions/cli/src/tools/subagent.test.ts +++ b/extensions/cli/src/tools/subagent.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; +import { services } from "../services/index.js"; import { executeSubAgent } from "../subagent/executor.js"; import { getAgentNames, getSubagent } from "../subagent/get-agents.js"; @@ -7,6 +8,14 @@ import { subagentTool } from "./subagent.js"; vi.mock("../subagent/get-agents.js"); vi.mock("../subagent/executor.js"); +vi.mock("../services/index.js", () => ({ + services: { + chatHistory: { + getSessionId: vi.fn().mockReturnValue("parent-session-id"), + addToolResult: vi.fn(), + }, + }, +})); describe("subagentTool", () => { const modelServiceState = {} as any; @@ -74,18 +83,10 @@ describe("subagentTool", () => { response: "subagent-output", } as any); - const services = { - chatHistory: { - getSessionId: vi.fn().mockReturnValue("parent-session-id"), - addToolResult: vi.fn(), - }, - } as any; - const serviceContainer = {} as any; const tool = subagentTool({ modelServiceState, - services, serviceContainer, } as any); @@ -105,7 +106,7 @@ describe("subagentTool", () => { expect(typeof options.onOutputUpdate).toBe("function"); options.onOutputUpdate?.("partial-output"); - expect(services.chatHistory.addToolResult).toHaveBeenCalledWith( + expect(vi.mocked(services.chatHistory.addToolResult)).toHaveBeenCalledWith( "tool-call-id", "partial-output", "calling", From d55a13894f842464d71bb2f0e5c4ada17ba8fbeb Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 9 Jan 2026 16:16:01 +0530 Subject: [PATCH 32/33] decouple allbuiltins and subagent tool meta --- extensions/cli/src/subagent/index.ts | 28 ++++ extensions/cli/src/tools/allBuiltIns.ts | 3 +- extensions/cli/src/tools/index.tsx | 6 +- extensions/cli/src/tools/subagent.ts | 206 +++++++++++------------- extensions/cli/src/tools/types.ts | 6 - 5 files changed, 126 insertions(+), 123 deletions(-) create mode 100644 extensions/cli/src/subagent/index.ts diff --git a/extensions/cli/src/subagent/index.ts b/extensions/cli/src/subagent/index.ts new file mode 100644 index 000000000..29f89fadc --- /dev/null +++ b/extensions/cli/src/subagent/index.ts @@ -0,0 +1,28 @@ +import { Tool } from "../tools/types.js"; + +export const SUBAGENT_TOOL_META: Tool = { + name: "Subagent", + displayName: "Subagent", + description: "Use a subagent to handle a specialized task.", + readonly: false, + isBuiltIn: true, + parameters: { + type: "object", + required: ["description", "prompt", "subagent_name"], + properties: { + description: { + type: "string", + description: "A short description of the task", + }, + prompt: { + type: "string", + description: "The task for the agent to perform", + }, + subagent_name: { + type: "string", + description: "The type of specialized agent to use for this task.", + }, + }, + }, + run: async () => "", +}; diff --git a/extensions/cli/src/tools/allBuiltIns.ts b/extensions/cli/src/tools/allBuiltIns.ts index 0d46de4b9..4e2f4a6d9 100644 --- a/extensions/cli/src/tools/allBuiltIns.ts +++ b/extensions/cli/src/tools/allBuiltIns.ts @@ -1,3 +1,5 @@ +import { SUBAGENT_TOOL_META } from "../subagent/index.js"; + import { editTool } from "./edit.js"; import { exitTool } from "./exit.js"; import { fetchTool } from "./fetch.js"; @@ -7,7 +9,6 @@ import { readFileTool } from "./readFile.js"; import { reportFailureTool } from "./reportFailure.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; import { searchCodeTool } from "./searchCode.js"; -import { SUBAGENT_TOOL_META } from "./subagent.js"; import type { Tool } from "./types.js"; import { uploadArtifactTool } from "./uploadArtifact.js"; import { writeChecklistTool } from "./writeChecklist.js"; diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index f95cf02ef..8ec0aca35 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -124,11 +124,7 @@ export async function getAllAvailableTools( } if (isBetaSubagentToolEnabled()) { - tools.push( - subagentTool({ - modelServiceState: modelState, - }), - ); + tools.push(await subagentTool()); } const mcpState = await serviceContainer.get( diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index aad198b8b..c457440c3 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -1,133 +1,117 @@ +import { serviceContainer } from "../services/ServiceContainer.js"; +import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; import { generateSubagentToolDescription, getSubagent, getAgentNames as getSubagentNames, } from "../subagent/get-agents.js"; +import { SUBAGENT_TOOL_META } from "../subagent/index.js"; import { logger } from "../util/logger.js"; -import { GetTool, Tool } from "./types.js"; +import { Tool } from "./types.js"; -export const SUBAGENT_TOOL_META: Tool = { - name: "Subagent", - displayName: "Subagent", - description: "Use a subagent to handle a specialized task.", - readonly: false, - isBuiltIn: true, - parameters: { - type: "object", - required: ["description", "prompt", "subagent_name"], - properties: { - description: { - type: "string", - description: "A short description of the task", - }, - prompt: { - type: "string", - description: "The task for the agent to perform", - }, - subagent_name: { - type: "string", - description: "The type of specialized agent to use for this task.", - }, - }, - }, - run: async () => "", -}; +export const subagentTool = async (): Promise => { + const modelServiceState = await serviceContainer.get( + SERVICE_NAMES.MODEL, + ); -export const subagentTool: GetTool = (params) => ({ - ...SUBAGENT_TOOL_META, + return { + ...SUBAGENT_TOOL_META, - description: generateSubagentToolDescription(params.modelServiceState), + description: generateSubagentToolDescription(modelServiceState), - parameters: { - ...SUBAGENT_TOOL_META.parameters, - properties: { - ...SUBAGENT_TOOL_META.parameters.properties, - subagent_name: { - type: "string", - description: `The type of specialized agent to use for this task. Available agents: ${ - params ? getSubagentNames(params.modelServiceState).join(", ") : "" - }`, - }, - }, - }, - - preprocess: async (args: any) => { - const { description, subagent_name } = args; - - const agent = getSubagent(params.modelServiceState, subagent_name); - if (!agent) { - throw new Error( - `Unknown agent type: ${subagent_name}. Available agents: ${getSubagentNames( - params.modelServiceState, - ).join(", ")}`, - ); - } - - return { - args, - preview: [ - { - type: "text", - content: `Spawning ${agent.model.name} to: ${description}`, + parameters: { + ...SUBAGENT_TOOL_META.parameters, + properties: { + ...SUBAGENT_TOOL_META.parameters.properties, + subagent_name: { + type: "string", + description: `The type of specialized agent to use for this task. Available agents: ${ + modelServiceState + ? getSubagentNames(modelServiceState).join(", ") + : "" + }`, }, - ], - }; - }, + }, + }, - run: async (args: any, context?: { toolCallId: string }) => { - const { prompt, subagent_name } = args; + preprocess: async (args: any) => { + const { description, subagent_name } = args; - logger.debug("subagent args", { args, context }); + const agent = getSubagent(modelServiceState, subagent_name); + if (!agent) { + throw new Error( + `Unknown agent type: ${subagent_name}. Available agents: ${getSubagentNames( + modelServiceState, + ).join(", ")}`, + ); + } - // get agent configuration - const agent = getSubagent(params.modelServiceState, subagent_name); - if (!agent) { - throw new Error(`Unknown agent type: ${subagent_name}`); - } + return { + args, + preview: [ + { + type: "text", + content: `Spawning ${agent.model.name} to: ${description}`, + }, + ], + }; + }, - // Dynamically import to avoid circular dependency and passing repeated params - const { executeSubAgent } = await import("../subagent/executor.js"); - const { services } = await import("../services/index.js"); + run: async (args: any, context?: { toolCallId: string }) => { + const { prompt, subagent_name } = args; - const chatHistoryService = services.chatHistory; - const parentSessionId = chatHistoryService.getSessionId(); - if (!parentSessionId) { - throw new Error("No active session found"); - } + logger.debug("subagent args", { args, context }); - // Execute subagent with output streaming - const result = await executeSubAgent({ - agent, - prompt, - parentSessionId, - abortController: new AbortController(), - onOutputUpdate: context?.toolCallId - ? (output: string) => { - try { - chatHistoryService.addToolResult( - context.toolCallId, - output, - "calling", - ); - } catch { - // Ignore errors during streaming updates + // get agent configuration + const agent = getSubagent(modelServiceState, subagent_name); + if (!agent) { + throw new Error(`Unknown agent type: ${subagent_name}`); + } + + // Dynamically import to avoid circular dependency and passing repeated params + const { executeSubAgent } = await import("../subagent/executor.js"); + const { services } = await import("../services/index.js"); + + const chatHistoryService = services.chatHistory; + const parentSessionId = chatHistoryService.getSessionId(); + if (!parentSessionId) { + throw new Error("No active session found"); + } + + // Execute subagent with output streaming + const result = await executeSubAgent({ + agent, + prompt, + parentSessionId, + abortController: new AbortController(), + onOutputUpdate: context?.toolCallId + ? (output: string) => { + try { + chatHistoryService.addToolResult( + context.toolCallId, + output, + "calling", + ); + } catch { + // Ignore errors during streaming updates + } } - } - : undefined, - }); + : undefined, + }); - logger.debug("subagent result", { result }); + logger.debug("subagent result", { result }); - const output = [ - result.response, - "", - `status: ${result.success ? "completed" : "failed"}`, - "", - ] - .filter(Boolean) - .join("\n"); + const output = [ + result.response, + "", + `status: ${result.success ? "completed" : "failed"}`, + "", + ] + .filter(Boolean) + .join("\n"); - return output; - }, -}); + return output; + }, + }; +}; diff --git a/extensions/cli/src/tools/types.ts b/extensions/cli/src/tools/types.ts index faf68cd4e..544c6d970 100644 --- a/extensions/cli/src/tools/types.ts +++ b/extensions/cli/src/tools/types.ts @@ -1,7 +1,5 @@ import type { ToolPolicy } from "@continuedev/terminal-security"; -import type { ModelServiceState } from "src/services/types.js"; - // JSON Schema compatible parameter definition export interface ParameterSchema { type: string; @@ -49,10 +47,6 @@ export interface Tool { ) => ToolPolicy; } -export type GetTool = (params: { - modelServiceState: ModelServiceState; -}) => Tool; - export interface ToolCall { id: string; name: string; From 72da79366486f358adac59aa8ec96d67ec2c9af3 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 9 Jan 2026 16:20:58 +0530 Subject: [PATCH 33/33] skip dynamic imports --- extensions/cli/src/tools/subagent.test.ts | 18 ++++++++++-------- extensions/cli/src/tools/subagent.ts | 6 ++---- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/extensions/cli/src/tools/subagent.test.ts b/extensions/cli/src/tools/subagent.test.ts index 90a53ac8e..e4f2d61ea 100644 --- a/extensions/cli/src/tools/subagent.test.ts +++ b/extensions/cli/src/tools/subagent.test.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { services } from "../services/index.js"; +import { serviceContainer } from "../services/ServiceContainer.js"; import { executeSubAgent } from "../subagent/executor.js"; import { getAgentNames, getSubagent } from "../subagent/get-agents.js"; @@ -8,6 +9,11 @@ import { subagentTool } from "./subagent.js"; vi.mock("../subagent/get-agents.js"); vi.mock("../subagent/executor.js"); +vi.mock("../services/ServiceContainer.js", () => ({ + serviceContainer: { + get: vi.fn(), + }, +})); vi.mock("../services/index.js", () => ({ services: { chatHistory: { @@ -22,12 +28,13 @@ describe("subagentTool", () => { beforeEach(() => { vi.clearAllMocks(); + vi.mocked(serviceContainer.get).mockResolvedValue(modelServiceState); }); it("preprocess throws when agent is not found", async () => { vi.mocked(getAgentNames).mockReturnValue(["code-agent"]); - const tool = subagentTool({ modelServiceState } as any); + const tool = await subagentTool(); const args = { description: "Test task", @@ -47,7 +54,7 @@ describe("subagentTool", () => { it("preprocess includes agent model name when agent exists", async () => { vi.mocked(getAgentNames).mockReturnValue(["code-agent"]); - const tool = subagentTool({ modelServiceState } as any); + const tool = await subagentTool(); vi.mocked(getSubagent).mockReturnValue({ model: { name: "test-model" }, @@ -83,12 +90,7 @@ describe("subagentTool", () => { response: "subagent-output", } as any); - const serviceContainer = {} as any; - - const tool = subagentTool({ - modelServiceState, - serviceContainer, - } as any); + const tool = await subagentTool(); const result = await tool.run( { diff --git a/extensions/cli/src/tools/subagent.ts b/extensions/cli/src/tools/subagent.ts index c457440c3..43d2d29eb 100644 --- a/extensions/cli/src/tools/subagent.ts +++ b/extensions/cli/src/tools/subagent.ts @@ -1,5 +1,7 @@ +import { services } from "../services/index.js"; import { serviceContainer } from "../services/ServiceContainer.js"; import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; +import { executeSubAgent } from "../subagent/executor.js"; import { generateSubagentToolDescription, getSubagent, @@ -69,10 +71,6 @@ export const subagentTool = async (): Promise => { throw new Error(`Unknown agent type: ${subagent_name}`); } - // Dynamically import to avoid circular dependency and passing repeated params - const { executeSubAgent } = await import("../subagent/executor.js"); - const { services } = await import("../services/index.js"); - const chatHistoryService = services.chatHistory; const parentSessionId = chatHistoryService.getSessionId(); if (!parentSessionId) {