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

  1. Add incoming prompts to context.
  2. Convert AgentMessage[] to LLM Message[] via convertToLlm.
  3. Call streamSimple or a custom streamFn.
  4. Emit streaming events as the assistant responds.
  5. Execute tool calls and emit tool execution events.
  6. Insert tool results into the context and continue if tool calls exist.
  7. Apply steering messages or follow-up messages if configured.
  8. Emit agent_end and return new messages.

Tool Execution

executeToolCalls does the following:

  • Finds matching AgentTool by name.
  • Validates tool arguments via validateToolArguments from the AI module.
  • Executes tools sequentially.
  • Emits tool_execution_start, tool_execution_update, and tool_execution_end.
  • Creates ToolResultMessage objects 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 error or aborted, the loop ends.
  • If a tool fails, the error is converted to a ToolResultMessage with isError: true.
  • Aborted assistant messages are not replayed by transformMessages.

Customization Points

You can customize behavior with these hooks in AgentLoopConfig:

  • convertToLlm for message transformation.
  • transformContext for pruning or augmentation.
  • getApiKey for short-lived tokens.
  • getSteeringMessages for mid-run interrupts.
  • getFollowUpMessages for post-run continuation.