feat: subagents

This commit is contained in:
uinstinct 2025-12-11 13:17:29 +05:30
parent 16b12305cf
commit 32af25fc99
7 changed files with 502 additions and 0 deletions

View file

@ -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<string, AgentConfig> = {
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`;
}

View file

@ -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<string> {
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<SubAgentResult> {
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,
};
}
}

View file

@ -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<string, boolean>;
/** Optional custom system prompt for the agent */
systemPrompt?: string;
}

View file

@ -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,

View file

@ -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<ChatHistoryState>(
// 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<MCPServiceState>(
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;

View file

@ -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,
"<task_metadata>",
`status: ${result.success ? "completed" : "failed"}`,
"</task_metadata>",
]
.filter(Boolean)
.join("\n");
return output;
},
};

View file

@ -115,6 +115,57 @@ const ToolResultSummary: React.FC<ToolResultSummaryProps> = ({
}
}
// show streaming output for task tool output
if (toolName === "Task") {
const metadataIndex = content.indexOf("<task_metadata>");
const actualOutput =
metadataIndex >= 0 ? content.slice(0, metadataIndex).trim() : content;
if (!actualOutput) {
return (
<Box>
<Text color="dim">⎿ </Text>
<Text color="dim"> Task executing...</Text>
</Box>
);
}
const outputLines = actualOutput.split("\n");
const MAX_TASK_OUTPUT_LINES = 20;
if (outputLines.length <= MAX_TASK_OUTPUT_LINES) {
return (
<Box flexDirection="column">
<Box>
<Text color="dim">⎿ </Text>
<Text color="dim"> Task output:</Text>
</Box>
<Box paddingLeft={2}>
<Text>{actualOutput.trimEnd()}</Text>
</Box>
</Box>
);
} else {
const lastLines = outputLines.slice(-MAX_TASK_OUTPUT_LINES).join("\n");
return (
<Box flexDirection="column">
<Box>
<Text color="dim">⎿ </Text>
<Text color="dim"> Task output:</Text>
</Box>
<Box paddingLeft={2}>
<Text color="dim">
... +{outputLines.length - MAX_TASK_OUTPUT_LINES} lines
</Text>
</Box>
<Box paddingLeft={2}>
<Text>{lastLines.trimEnd()}</Text>
</Box>
</Box>
);
}
}
// Handle all other cases with text summary
const getSummary = () => {
// Check if this is a user cancellation first