You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Jun 3, 2026. It is now read-only.
Create an async iterator agent loop that coordinates execution between model providers and tools. The event loop manages the conversation flow by streaming model responses, executing tools when needed, and continuing until completion.
Implementation Requirements
Based on repository analysis and clarification discussions, this task involves implementing a core agent loop function without the full Agent class (which will come later).
Architecture Overview
The agent loop follows a simple top-level loop pattern that calls out to different steps:
Model invocation - Send messages to model provider and stream responses
Tool execution - Execute tools when model requests them
Loop continuation - Return to model invocation with tool results
Use the base Model interface, not provider-specific implementations
No provider-specific handling needed
Testing Requirements
Unit Tests (src/agent/__tests__/agent_loop.test.ts)
Create comprehensive unit tests using:
Mock model provider - Create if one doesn't exist in src/models/__tests__/test-utils.ts
Mock tools - Create helper for generating mock Tool implementations if needed
Test scenarios:
Simple completion without tools (endTurn stop reason)
Single tool use cycle (toolUse → execute → continue → endTurn)
Multiple tool uses in sequence
Multiple agentic loop iterations
Transactional message handling (message not added on early error)
Error propagation from model provider
Error propagation from tool execution
MaxTokens stop reason (should throw)
Event streaming (verify all events yielded)
ContentBlock construction from streaming events
Integration Tests
NOT required for this task - Will be added later when Agent class is implemented
File Structure
src/
├── agent_loop.ts # Main agent loop function (NEW)
├── agent/
│ ├── streaming.ts # AgentStreamEvent types (NEW)
│ └── __tests__/
│ └── agent_loop.test.ts # Comprehensive unit tests (NEW)
├── models/
│ └── __tests__/
│ └── test-utils.ts # Add mock model provider if needed
└── tools/
└── __tests__/
└── test-utils.ts # Add mock tool helper if needed (NEW)
Acceptance Criteria
agent_loop function implemented with correct signature
AgentStreamEvent type defined with all required event types
Transactional message handling: messages not added before first model event
Model provider streaming events yielded to caller
ContentBlocks correctly constructed from streaming events
Tool execution triggered on toolUse stop reason
Tools executed sequentially with real-time event streaming
Tool results added to messages and loop continues
Loop terminates correctly on non-toolUse stop reasons
MaxTokens stop reason throws error
Error handling for model provider errors
Error handling for tool execution errors
Unit tests cover all major scenarios
80%+ test coverage maintained
All tests pass
Code follows TypeScript coding patterns from AGENTS.md
TSDoc documentation for all exported functions
No linting errors
Types exported from src/index.ts
Notes & Future Considerations
Extensibility considerations (do NOT implement now):
Allow entry point to jump directly into tool-execution (based on if last message was a toolUse)
This will be implemented later but keep in mind during design
Agent class (do NOT implement now):
Full Agent class will be implemented in a separate task
This task focuses only on the core loop mechanism
Integration tests (do NOT implement now):
Integration tests with real model providers will be added after Agent class exists
Repository Documentation Updates
After implementation, update:
AGENTS.md - Add agent loop to directory structure if new directories created
README.md - Update development status to mark agent loop as complete
Original Context
Create an async iterator agent loop that coordinates execution between model providers and tools. The event loop manages the conversation flow by streaming model responses, executing tools when needed, and continuing until completion.
Exit Criteria
A working agent loop async iterator that coordinates model provider streaming and tool execution, properly constructs ContentBlocks from responses, handles tool_use cycles, streams all events back to the caller, and passes comprehensive unit tests.
Agentic Loop Implementation
Create an async iterator agent loop that coordinates execution between model providers and tools. The event loop manages the conversation flow by streaming model responses, executing tools when needed, and continuing until completion.
Implementation Requirements
Based on repository analysis and clarification discussions, this task involves implementing a core agent loop function without the full Agent class (which will come later).
Architecture Overview
The agent loop follows a simple top-level loop pattern that calls out to different steps:
Reference: Strands Agent Loop Documentation
Technical Specifications
1. Agent Loop Function (
src/agent_loop.ts)Create a new file
src/agent_loop.tswith:Key behaviors:
AgentStreamEventobjectsToolRegistryclass fromsrc/tools/registry.ts2. Event Types (
src/agent/streaming.tsor inagent_loop.ts)Create
AgentStreamEventtype that includes:ModelStreamEventtypes (passthrough from model provider)BeforeModelEvent- Before invoking modelAfterModelEvent- After model completesBeforeToolsEvent- Before executing toolsAfterToolsEvent- After tools completeBeforeInvocationEvent- Start of agent loop iterationAfterInvocationEvent- End of agent loop iteration3. Message Handling (Transactional)
Critical requirement: Do NOT add user messages to the messages array until the model provider returns its first event.
Reference: PR #57 contains guidance on this pattern (ContentBlock construction)
4. Model Provider Invocation
modelProvider.stream(messages, options)with:toolSpecsextracted from ToolRegistry usingtoolRegistry.list().map(t => t.toolSpec)systemPromptif providedModelStreamEventobjects to the caller (yield each one)5. ContentBlock Construction
textDelta→TextBlocktoolUseStart+toolUseInputDelta→ToolUseBlockreasoningDelta→ReasoningBlock6. Stop Reason Detection & Tool Execution
When
stopReason === 'toolUse':ToolUseBlockobjects from the assistant messagetoolRegistry.get(toolName)tool.stream({ toolUse, invocationState: {} })ToolStreamEventobjects in real-timeToolResultfrom the generatorToolResultBlockand add to messages arrayWhen
stopReason !== 'toolUse':AfterInvocationEvent7. Error Handling
Model provider errors (before first event):
Model provider errors (after first event):
Tool execution errors:
ToolResultwithstatus: 'error'MaxTokens stop reason:
MaxTokensReachedExceptionor similar8. Loop Termination
The loop terminates when:
stopReason !== 'toolUse'(normal completion)stopReason === 'maxTokens'(error - throw exception)Dependencies & Integration
Existing code to use:
src/tools/registry.ts-ToolRegistryclass for managing toolssrc/models/model.ts-Modelinterface for model providerssrc/models/streaming.ts-ModelStreamEventtypessrc/types/messages.ts-Message,ContentBlock,SystemPrompttypessrc/tools/tool.ts-Toolinterface andToolStreamEventsrc/tools/types.ts-ToolSpec,ToolUse,ToolResulttypesModel provider compatibility:
BedrockModelandOpenAIModelModelinterface, not provider-specific implementationsTesting Requirements
Unit Tests (
src/agent/__tests__/agent_loop.test.ts)Create comprehensive unit tests using:
src/models/__tests__/test-utils.tsIntegration Tests
NOT required for this task - Will be added later when Agent class is implemented
File Structure
Acceptance Criteria
agent_loopfunction implemented with correct signatureAgentStreamEventtype defined with all required event typestoolUsestop reasonsrc/index.tsNotes & Future Considerations
Extensibility considerations (do NOT implement now):
Agent class (do NOT implement now):
Integration tests (do NOT implement now):
Repository Documentation Updates
After implementation, update:
AGENTS.md- Add agent loop to directory structure if new directories createdREADME.md- Update development status to mark agent loop as completeOriginal Context
Create an async iterator agent loop that coordinates execution between model providers and tools. The event loop manages the conversation flow by streaming model responses, executing tools when needed, and continuing until completion.
Exit Criteria
A working agent loop async iterator that coordinates model provider streaming and tool execution, properly constructs ContentBlocks from responses, handles tool_use cycles, streams all events back to the caller, and passes comprehensive unit tests.