Skip to main content
Stateful agent with tool execution and event streaming, built on @bastani/atomic-ai. It is the agent loop Atomic’s sessions run on; use it directly to build your own agent. Atomic’s SDK wraps it with sessions, tools, extensions and compaction, so prefer the SDK when you want Atomic’s behaviour.

Installation

Quick Start

Core Concepts

AgentMessage vs LLM Message

The agent works with AgentMessage, a flexible type that can include:
  • Standard LLM messages (user, assistant, toolResult)
  • Custom app-specific message types via declaration merging
LLMs only understand user, assistant, and toolResult. The convertToLlm function bridges this gap by filtering and transforming messages before each LLM call.

Message Flow

  1. transformContext: Prune old messages, inject external context
  2. convertToLlm: Filter out UI-only messages, convert custom types to LLM format

Event Flow

The agent emits events for UI updates. Understanding the event sequence helps build responsive interfaces.

prompt() Event Sequence

When you call prompt("Hello"):

With Tool Calls

If the assistant calls tools, the loop continues:
Tool execution mode is configurable:
  • parallel (default): preflight tool calls sequentially, execute allowed tools concurrently, emit tool_execution_end as soon as each tool is finalized, then emit toolResult messages and turn_end.toolResults in assistant source order
  • sequential: execute tool calls one by one, matching the historical behavior
In parallel mode, tool completion events follow tool completion order, but persisted toolResult messages still follow assistant source order. The mode can be set globally via toolExecution in the agent config, or per-tool via executionMode on AgentTool. If any tool call in a batch targets a tool with executionMode: "sequential", the entire batch executes sequentially regardless of the global setting. The beforeToolCall hook runs after tool_execution_start and validated argument parsing. It can block execution and attach terminate: true to the blocked result. The afterToolCall hook runs after tool execution finishes and before tool_execution_end and final tool result message events are emitted. Tools, blocked beforeToolCall results, and afterToolCall overrides can return terminate: true to hint that the automatic follow-up LLM call should be skipped. The loop only stops early when every finalized tool result in that batch sets terminate: true. Mixed batches continue normally. When you use the Agent class, assistant message_end processing is treated as a barrier before tool preflight begins. That means beforeToolCall sees agent state that already includes the assistant message that requested the tool call.

Request preparation and turn finalization

prepareRequest runs immediately before every conversational provider request, including the first. Use it to install canonical persisted context after pending input has been emitted:
prepareRequest does not poll queues. Steering queued while it runs waits for the next normal steering poll. finishTurn runs after the assistant and all tool results are finalized, but before turn_end. It runs for normal, error, and aborted responses:
Returning undefined preserves normal scheduling. { action: "end" } stops immediately after turn_end, before polling steering or follow-up queues or preparing another request. On a normal response, { action: "continue" } ensures one next provider request. If tool results, steering, or a follow-up already cause that request, they satisfy the decision and no additional request is made; otherwise the loop makes one context-only request. Error and aborted responses remain hard exits, so their decisions are ignored. finishTurn runs again after the next request, so returning { action: "continue" } unconditionally creates an endless loop. To migrate from the removed shouldStopAfterTurn, return { action: "end" }. Guard error and aborted responses to preserve the old hook’s normal-response-only invocation, especially when the predicate has side effects or assumes a successful response:
Each provider turn follows this lifecycle:

continue() and queued input

continue() retains its existing queue behavior. Empty and system-only transcripts reject without consuming queues. A non-assistant tail continues from existing context: steering is polled at startup, while follow-up input waits until the response naturally stops.
An assistant tail cannot be sent directly, so continue() falls back to one queued steering batch, then one queued follow-up batch. Queue mode still controls whether that selected batch contains one message or all messages:

Event Types

Agent.subscribe() listeners are awaited in registration order. agent_end means no more loop events will be emitted, but await agent.waitForIdle() and await agent.prompt(...) only settle after awaited agent_end listeners finish.

Agent Options

Agent State

Access state via agent.state. Assigning agent.state.tools = [...] or agent.state.messages = [...] copies the top-level array before storing it. Mutating the returned array mutates the current agent state. The transcript owns the system prompt and tool declarations: the leading system message is the prompt, later system messages patch it (see SystemMessage in @bastani/atomic-ai). agent.state.systemPrompt is read-only and replays the transcript. agent.state.tools is the executable loadout; before every request the loop diffs it against the tools the transcript declares and, if they differ, announces the change in a system message (merged into a pending system message when one exists). @bastani/atomic-ai’s getCurrentSystemMessage(messages) returns the replayed head, including declared tools, for any message array, including agent transcripts with custom message roles. To change the prompt mid-conversation, append a system message with content (added instructions) or sections (named replacements):
During streaming, agent.state.streamingMessage contains the current partial assistant message. agent.state.isStreaming remains true until the run fully settles, including awaited agent_end subscribers.

Methods

Prompting

State Management

Session and Thinking Budgets

Control

Events

Steering and Follow-up

Steering messages let you interrupt the agent while tools are running. Follow-up messages let you queue work after the agent would otherwise stop.
Use clearSteeringQueue, clearFollowUpQueue, or clearAllQueues to drop queued messages. When steering messages are detected after a turn completes:
  1. All tool calls from the current assistant message have already finished
  2. Steering messages are injected
  3. The LLM responds on the next turn
Follow-up messages are checked only when there are no more tool calls and no steering messages. If any are queued, they are injected and another turn runs.

Custom Message Types

Extend AgentMessage via declaration merging:
Handle custom types in convertToLlm:

Tools

Define tools using AgentTool. parameters is any JSON Schema object; built with @bastani/atomic-schema’s builders, it also types params (other schemas give unknown, AgentTool<any> gives any):

Error Handling

Throw an error when a tool fails. Do not return error messages as content.
Thrown errors are caught by the agent and reported to the LLM as tool errors with isError: true. Return terminate: true from execute(), a blocked beforeToolCall, or afterToolCall to hint that the agent should stop after the current tool batch. This only takes effect when every finalized tool result in the batch is terminating. The hint is runtime-only; emitted toolResult transcript messages remain standard LLM tool results.

MCP and Codemode

@bastani/atomic-codemode runs model-written JavaScript that calls tools. Wrap it as an AgentTool named codemode whose scripts call the agent’s tools through runToolCall(), so beforeToolCall and afterToolCall apply to those nested calls too; see Using with agent-core. Tools that wrap an MCP server’s tools work the same way. Atomic’s own MCP support is the MCP servers extension.

Proxy Usage

For browser apps that proxy through a backend:

Low-Level API

For direct control without the Agent class:
These low-level streams are observational. They preserve event order, but they do not wait for your async event handling to settle before later producer phases continue. If you need message processing to act as a barrier before tool preflight, use the Agent class instead of raw agentLoop() or agentLoopContinue().