-
Notifications
You must be signed in to change notification settings - Fork 30
feat: add sub-agent spawning via delegate_task tool #451
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
shivammittal274
wants to merge
3
commits into
main
Choose a base branch
from
feat/sub-agent-spawning
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.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
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,87 @@ | ||
| import { AGENT_LIMITS } from '@browseros/shared/constants/limits' | ||
| import type { LanguageModel } from 'ai' | ||
| import { stepCountIs, ToolLoopAgent, type ToolSet, tool } from 'ai' | ||
| import { z } from 'zod' | ||
| import { logger } from '../lib/logger' | ||
| import { createCompactionPrepareStep } from './compaction' | ||
|
|
||
| export interface DelegateTaskDeps { | ||
| model: LanguageModel | ||
| instructions: string | ||
| parentTools: ToolSet | ||
| contextWindow: number | ||
| } | ||
|
|
||
| const SUB_AGENT_SUFFIX = | ||
| '\n\nIMPORTANT: When you have finished, write a clear summary of your findings ' + | ||
| 'as your final response. This summary will be returned to the main agent, ' + | ||
| 'so include all relevant information.' | ||
|
|
||
| /** | ||
| * Creates the `delegate_task` tool following the AI SDK subagent pattern. | ||
| * The sub-agent is an exact replica of the parent agent — same model, same | ||
| * instructions, same tools, same compaction — just with a fresh context | ||
| * window and a lower step limit. | ||
| * | ||
| * @see https://ai-sdk.dev/docs/agents/subagents#basic-subagent-without-streaming | ||
| */ | ||
| export function createDelegateTaskTool(deps: DelegateTaskDeps) { | ||
| // Filter out delegate_task to prevent recursive spawning | ||
| const { delegate_task: _, ...subAgentTools } = deps.parentTools | ||
|
|
||
| // Reuse parent's full instructions + summarization suffix | ||
| const instructions = deps.instructions + SUB_AGENT_SUFFIX | ||
|
|
||
| // Sub-agent gets its own compaction for context safety | ||
| const prepareStep = createCompactionPrepareStep({ | ||
| contextWindow: deps.contextWindow, | ||
| }) | ||
|
|
||
| // Create the sub-agent once — reused across invocations | ||
| const subAgent = new ToolLoopAgent({ | ||
| model: deps.model, | ||
| instructions, | ||
| tools: subAgentTools, | ||
| stopWhen: [stepCountIs(AGENT_LIMITS.SUB_AGENT_MAX_TURNS)], | ||
| prepareStep, | ||
| }) | ||
|
|
||
| return tool({ | ||
| description: | ||
| 'Delegate a focused subtask to an independent sub-agent with its own context window. ' + | ||
| 'Use for research across many pages, data extraction, deep filesystem exploration, ' + | ||
| 'or any task that would consume significant context. ' + | ||
| 'The sub-agent has full tool access and returns a text summary when done.', | ||
| inputSchema: z.object({ | ||
| task: z | ||
| .string() | ||
| .describe( | ||
| 'Clear, self-contained description of the subtask. ' + | ||
| 'Include all necessary context — URLs, file paths, search terms, expected output format.', | ||
| ), | ||
| }), | ||
| execute: async ({ task }, { abortSignal }) => { | ||
| logger.info('Spawning sub-agent', { | ||
| taskPreview: task.slice(0, 120), | ||
| }) | ||
|
|
||
| try { | ||
| const result = await subAgent.generate({ | ||
| prompt: task, | ||
| abortSignal, | ||
| }) | ||
|
|
||
| logger.info('Sub-agent completed', { | ||
| steps: result.steps.length, | ||
| finishReason: result.finishReason, | ||
| }) | ||
|
|
||
| return result.text || 'Sub-agent completed but produced no text output.' | ||
| } catch (err) { | ||
| const message = err instanceof Error ? err.message : String(err) | ||
| logger.error('Sub-agent failed', { error: message }) | ||
| return `Sub-agent failed: ${message}` | ||
| } | ||
| }, | ||
| }) | ||
| } | ||
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.
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.
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.
Sub-agent instance reused across invocations
The
ToolLoopAgentis constructed once at factory-creation time and then reused for everydelegate_taskcall. IfToolLoopAgentmaintains any per-instance state — particularly ifstepCountIstracks steps cumulatively acrossgenerate()calls rather than resetting per call — the second delegation will inherit leftover step count and may terminate sooner than the intended 15-step limit.It would be safer to construct the
ToolLoopAgentinsideexecuteso each invocation starts from a guaranteed clean state:If the AI SDK guarantees that
generate()always resets the step counter, add a brief comment referencing the SDK docs so future readers don't have to investigate this.Prompt To Fix With AI