Agentagent/loop-and-tools
Agent Loop and Tools
The loop is implemented in indusagi/src/agent/agent-loop.ts.
It is responsible for turning messages into LLM calls, executing tools, and emitting events.
Loop Phases
- Add incoming prompts to context.
- Convert
AgentMessage[]to LLMMessage[]viaconvertToLlm. - Call
streamSimpleor a customstreamFn. - Emit streaming events as the assistant responds.
- Execute tool calls and emit tool execution events.
- Insert tool results into the context and continue if tool calls exist.
- Apply steering messages or follow-up messages if configured.
- Emit
agent_endand return new messages.
Tool Execution
executeToolCalls does the following:
- Finds matching
AgentToolby name. - Validates tool arguments via
validateToolArgumentsfrom the AI module. - Executes tools sequentially.
- Emits
tool_execution_start,tool_execution_update, andtool_execution_end. - Creates
ToolResultMessageobjects and appends them to context.
If a steering message arrives during tool execution, remaining tool calls are skipped. Skipped tool calls still produce tool results marked as errors.
Error Handling
- If the assistant response ends with
errororaborted, the loop ends. - If a tool fails, the error is converted to a
ToolResultMessagewithisError: true. - Aborted assistant messages are not replayed by
transformMessages.
Customization Points
You can customize behavior with these hooks in AgentLoopConfig:
convertToLlmfor message transformation.transformContextfor pruning or augmentation.getApiKeyfor short-lived tokens.getSteeringMessagesfor mid-run interrupts.getFollowUpMessagesfor post-run continuation.
