-
Notifications
You must be signed in to change notification settings - Fork 4.2k
feat(cli): parallel subagents #10893
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
uinstinct
wants to merge
16
commits into
continuedev:main
Choose a base branch
from
uinstinct:cli-parallel-subagents
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+817
−376
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
e6c04e9
remove unnecessary lint
uinstinct ce5cf78
add tool result in chat history for subagent
uinstinct 4125fb2
prevent nested subagent execution
uinstinct bbcf04e
add builtin subagents
uinstinct d5676db
refine subagent tool description
uinstinct e19a8b1
put subagent tool out of beta
uinstinct 40394bc
Merge branch 'main' into cli-default-subagents
uinstinct c116640
rename to getAgents
uinstinct af13df6
change code review to generalist subagent
uinstinct 9a6f308
refactor subagent executor to subagent service
uinstinct 60ade99
separate out subagent output from tool results
uinstinct 064f45b
emit a single line instead of accumulated output
uinstinct c6961b4
separate out execution contexts of subagents
uinstinct 59057b5
refactor subagent execution into subagent service file
uinstinct c65c213
add subagent parallel tool
uinstinct 698e237
show outputs for parallel subagents
uinstinct File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,277 @@ | ||
| import { AsyncLocalStorage } from "node:async_hooks"; | ||
|
|
||
| import type { ChatHistoryItem } from "core"; | ||
|
|
||
| import { streamChatResponse } from "../stream/streamChatResponse.js"; | ||
| import { escapeEvents } from "../util/cli.js"; | ||
| import { logger } from "../util/logger.js"; | ||
|
|
||
| import { BaseService } from "./BaseService.js"; | ||
| import { serviceContainer } from "./ServiceContainer.js"; | ||
| import type { ToolPermissionServiceState } from "./ToolPermissionService.js"; | ||
| import { type ModelServiceState, SERVICE_NAMES } from "./types.js"; | ||
|
|
||
| /** Service */ | ||
|
|
||
| export class SubAgentService extends BaseService<SubAgentServiceState> { | ||
| constructor() { | ||
| super("SubAgentService", { | ||
| activeExecutions: new Map(), | ||
| }); | ||
| } | ||
|
|
||
| async doInitialize(): Promise<SubAgentServiceState> { | ||
| return { | ||
| activeExecutions: new Map(), | ||
| }; | ||
| } | ||
|
|
||
| private generateExecutionId(): string { | ||
| return `subagent-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`; | ||
| } | ||
|
|
||
| isInsideSubagent(): boolean { | ||
| return subAgentExecutionContext.getStore() !== undefined; | ||
| } | ||
|
|
||
| private async buildAgentSystemMessage( | ||
| agent: ModelServiceState, | ||
| services: any, | ||
| ): Promise<string> { | ||
| const baseMessage = services.systemMessage | ||
| ? await services.systemMessage.getSystemMessage( | ||
| services.toolPermissions.getState().currentMode, | ||
| ) | ||
| : ""; | ||
|
|
||
| const agentPrompt = agent.model?.chatOptions?.baseSystemMessage || ""; | ||
|
|
||
| if (agentPrompt) { | ||
| return `${baseMessage}\n\n${agentPrompt}`; | ||
| } | ||
|
|
||
| return baseMessage; | ||
| } | ||
|
|
||
| async executeSubAgent( | ||
| options: SubAgentExecutionOptions, | ||
| ): Promise<SubAgentResult> { | ||
| if (this.isInsideSubagent()) { | ||
| return { | ||
| success: false, | ||
| response: "", | ||
| error: "Nested subagent invocation is not allowed", | ||
| }; | ||
| } | ||
|
|
||
| const { agent: subAgent, prompt, abortController } = options; | ||
| const executionId = this.generateExecutionId(); | ||
| const agentName = subAgent.model?.name || "unknown"; | ||
|
|
||
| const mainAgentPermissionsState = | ||
| await serviceContainer.get<ToolPermissionServiceState>( | ||
| SERVICE_NAMES.TOOL_PERMISSIONS, | ||
| ); | ||
|
|
||
| const execution: PendingExecution = { | ||
| executionId, | ||
| agentName, | ||
| startTime: Date.now(), | ||
| }; | ||
|
|
||
| const activeExecutions = new Map(this.currentState.activeExecutions); | ||
| activeExecutions.set(executionId, execution); | ||
| this.setState({ activeExecutions }); | ||
|
|
||
| this.emit("subagentStarted", { | ||
| executionId, | ||
| agentName: subAgent.model?.name, | ||
| prompt, | ||
| }); | ||
|
|
||
| try { | ||
| logger.debug("Starting subagent execution", { | ||
| executionId, | ||
| agent: subAgent.model?.name, | ||
| }); | ||
|
|
||
| const { model, llmApi } = subAgent; | ||
| if (!model || !llmApi) { | ||
| throw new Error("Model or LLM API not available"); | ||
| } | ||
|
|
||
| const { services } = await import("./index.js"); | ||
|
|
||
| // Build agent system message | ||
| const systemMessage = await this.buildAgentSystemMessage( | ||
| subAgent, | ||
| services, | ||
| ); | ||
|
|
||
| // 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 | ||
| const subAgentPermissions: ToolPermissionServiceState = { | ||
| ...mainAgentPermissionsState, | ||
| permissions: { | ||
| policies: [{ tool: "*", permission: "allow" }], | ||
| }, | ||
| }; | ||
|
|
||
| const chatHistorySvc = services.chatHistory; | ||
| const originalIsReady = | ||
| chatHistorySvc && typeof chatHistorySvc.isReady === "function" | ||
| ? chatHistorySvc.isReady | ||
| : undefined; | ||
|
|
||
| if (chatHistorySvc && originalIsReady) { | ||
| chatHistorySvc.isReady = () => false; | ||
| } | ||
|
|
||
| const chatHistory = [ | ||
| { | ||
| message: { role: "user", content: prompt }, | ||
| contextItems: [], | ||
| }, | ||
| ] 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 { | ||
| const result = await subAgentExecutionContext.run( | ||
| { | ||
| executionId, | ||
| systemMessage, | ||
| permissions: subAgentPermissions, | ||
| }, | ||
| async () => { | ||
| await streamChatResponse( | ||
| chatHistory, | ||
| model, | ||
| llmApi, | ||
| abortController, | ||
| { | ||
| onContent: (content: string) => { | ||
| this.emit("subagentContent", { | ||
| executionId, | ||
| agentName: model?.name, | ||
| content, | ||
| type: "content", | ||
| }); | ||
| }, | ||
| onToolResult: (result: string) => { | ||
| this.emit("subagentContent", { | ||
| executionId, | ||
| agentName: model?.name, | ||
| content: result, | ||
| type: "toolResult", | ||
| }); | ||
| }, | ||
| }, | ||
| false, | ||
| ); | ||
|
|
||
| const lastMessage = chatHistory.at(-1); | ||
| const response = | ||
| typeof lastMessage?.message?.content === "string" | ||
| ? lastMessage.message.content | ||
| : ""; | ||
|
|
||
| return { success: true as const, response }; | ||
| }, | ||
| ); | ||
|
|
||
| logger.debug("Subagent execution completed", { | ||
| executionId, | ||
| agent: model?.name, | ||
| responseLength: result.response.length, | ||
| }); | ||
|
|
||
| this.emit("subagentCompleted", { | ||
| executionId, | ||
| agentName: model?.name, | ||
| success: true, | ||
| }); | ||
|
|
||
| return result; | ||
| } finally { | ||
| escapeEvents.removeListener("user-escape", escapeHandler); | ||
|
|
||
| if (chatHistorySvc && originalIsReady) { | ||
| chatHistorySvc.isReady = originalIsReady; | ||
| } | ||
| } | ||
| } catch (error: any) { | ||
| logger.error("Subagent execution failed", { | ||
| executionId, | ||
| agent: subAgent.model?.name, | ||
| error: error.message, | ||
| }); | ||
|
|
||
| this.emit("subagentFailed", { | ||
| executionId, | ||
| agentName: subAgent.model?.name, | ||
| error: error.message, | ||
| }); | ||
|
|
||
| return { | ||
| success: false, | ||
| response: "", | ||
| error: error.message, | ||
| }; | ||
| } finally { | ||
| const updatedExecutions = new Map(this.currentState.activeExecutions); | ||
| updatedExecutions.delete(executionId); | ||
| this.setState({ activeExecutions: updatedExecutions }); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export const subAgentService = new SubAgentService(); | ||
|
|
||
| // Subagent execution context | ||
|
|
||
| interface ExecutionContext { | ||
| executionId: string; | ||
| systemMessage: string; | ||
| permissions: ToolPermissionServiceState; | ||
| } | ||
|
|
||
| /* Scopes system messages and tool permissions per subagent execution for enabling parallel execution*/ | ||
| export const subAgentExecutionContext = | ||
| new AsyncLocalStorage<ExecutionContext>(); | ||
|
|
||
| // Types | ||
|
|
||
| export interface SubAgentExecutionOptions { | ||
| agent: ModelServiceState; | ||
| prompt: string; | ||
| parentSessionId: string; | ||
| abortController: AbortController; | ||
| } | ||
|
|
||
| export interface SubAgentResult { | ||
| success: boolean; | ||
| response: string; | ||
| error?: string; | ||
| } | ||
|
|
||
| export interface PendingExecution { | ||
| executionId: string; | ||
| agentName: string; | ||
| startTime: number; | ||
| } | ||
|
|
||
| export interface SubAgentServiceState { | ||
| activeExecutions: Map<string, PendingExecution>; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2: Parallel subagent executions race on the global chatHistorySvc.isReady override, so completion order can restore a stale override and leave chat history disabled or re-enable it while another subagent still runs.
Prompt for AI agents