What are Generators?
ThehandleSteps function is a TypeScript generator that gives you programmatic control over your agent’s execution. It allows you to:
- Call tools directly from code
- Mix AI decision-making with programmatic logic
- Control when the AI model runs
- Process tool results before continuing
- Implement complex workflows
Basic Syntax
Context Parameters
agentState: Current agent state including message history and outputprompt: Input prompt passed when spawning the agentparams: Additional parameters from inputSchemalogger: Logger instance for debugging (logger.info(),logger.debug())
Yield Patterns
The generator can yield three types of values:1. Tool Calls
Yield an object to call a tool directly:2. STEP
Yield'STEP' to run the AI model once and generate a single assistant message:
3. STEP_ALL
Yield'STEP_ALL' to run the AI model until it stops or uses the end_turn tool:
4. STEP_TEXT
Yield text to add a message without calling tools:Return Value
Every yield returns an object:Real Examples from Codebuff Source
Example 1: Pre-read Files, Then AI
Fromgeneral-agent.ts - Read files programmatically, then let AI take over:
Example 2: Call Tool, Process Results
Fromresearcher-web.ts - Call web search, extract results, add text:
Example 3: Spawn Subagents, Read Files, Step AI
Fromfile-picker.ts - Complex workflow with subagents:
Example 4: Capture AI Output
Fromeditor.ts - Capture AI-generated messages:
Example 5: Continuous Loop with Context Management
Frombase2.ts - Run pruning before each step:
Example 6: Extract and Process Structured Output
Fromthinker.ts - Process AI output and clean it:
Common Patterns
Pre-process, AI, Post-process
Conditional Tool Execution
Error Handling
Parallel Agent Spawning
Type Safety
Use TypeScript for full type safety:Best Practices
- Use generators for complex workflows - Simple agents don’t need handleSteps
- Mix AI and code strategically - Use code for deterministic steps, AI for complex decisions
- Hide internal tool calls - Use
includeToolCall: falsefor implementation details - Log important steps - Help with debugging and monitoring
- Handle errors gracefully - Check tool results for errors
- Type your parameters - Cast
paramsto expected types - Return early on errors - Don’t continue if something fails
When to Use Generators
UsehandleSteps when you need:
- Pre-processing: Read files, prepare data before AI runs
- Post-processing: Format output, extract specific data
- Multi-step workflows: Spawn agents, process results, continue
- Conditional logic: Different behavior based on input
- Error handling: Graceful fallbacks and retries
- Context management: Clean up or optimize context between steps
- Simple single-step agents
- Agents that just call one tool
- When AI should have full control
Next Steps
Spawning Subagents
Learn how to compose multiple agents
Agent Definition
Full reference for all agent properties

