RPC Mode
RPC mode enables headless operation of the coding agent via a JSON protocol over stdin/stdout. This is useful for embedding the agent in other applications, IDEs, or custom UIs. Note for Node.js/TypeScript users: If you’re building a Node.js application, consider usingAgentSession directly from @bastani/atomic instead of spawning a subprocess. See src/core/agent-session.ts for the API. For a subprocess-based TypeScript client, see src/modes/rpc/rpc-client.ts.
Starting RPC Mode
--provider <name>: Set the LLM provider (anthropic, openai, google, etc.)--model <pattern>: Model pattern or ID (supportsprovider/idand optional:<thinking>)--no-session: Disable session persistence--session-dir <path>: Custom session storage directory
Protocol Overview
- Commands: JSON objects sent to stdin, one per line
- Responses: JSON objects with
type: "response"indicating command success/failure - Events: Agent events streamed to stdout as JSON lines
id field for request/response correlation. If provided, the corresponding response will include the same id.
Framing
RPC mode uses strict JSONL semantics with LF (\n) as the only record delimiter.
This matters for clients:
- Split records on
\nonly - Accept optional
\r\ninput by stripping a trailing\r - Do not use generic line readers that treat Unicode separators as newlines
readline is not protocol-compliant for RPC mode because it also splits on U+2028 and U+2029, which are valid inside JSON strings.
Commands
Prompting
prompt
Send a user prompt to the agent. The command response is emitted after the prompt is accepted, queued, or handled. Events continue streaming asynchronously after acceptance.streamingBehavior to queue the message:
"steer": Queue the message while the agent is running. It is delivered after the current assistant turn finishes executing its tool calls, before the next LLM call."followUp": Wait until the agent finishes. Message is delivered only when agent stops.
streamingBehavior is specified, the command returns an error.
Extension commands: If the message is an extension command (e.g., /mycommand), it executes immediately even during streaming. Extension commands manage their own LLM interaction via pi.sendMessage().
Input expansion: Skill commands (/skill:name) and prompt templates (/template) are expanded before sending/queueing.
Response:
success: true means the prompt was accepted, queued, or handled immediately. success: false means the prompt was rejected before acceptance. Failures after acceptance are reported through the normal event and message stream, not as a second response for the same request id.
The images field is optional. Each image uses ImageContent format: {"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}.
steer
Queue a steering message while the agent is running. It is delivered after the current assistant turn finishes executing its tool calls, before the next LLM call. Skill commands and prompt templates are expanded. Extension commands are not allowed (useprompt instead).
images field is optional. Each image uses ImageContent format (same as prompt).
Response:
follow_up
Queue a follow-up message to be processed after the agent finishes. Delivered only when agent has no more tool calls or steering messages. Skill commands and prompt templates are expanded. Extension commands are not allowed (useprompt instead).
images field is optional. Each image uses ImageContent format (same as prompt).
Response:
abort
Abort the current agent operation.new_session
Start a fresh session. Can be cancelled by asession_before_switch extension event handler.
State
get_state
Get current session state.model field is a full Model object or null. The sessionName field is the display name set via set_session_name, or omitted if not set.
get_messages
Get all messages in the conversation.AgentMessage objects (see Types).
Model
set_model
Switch to a specific model.cycle_model
Cycle to the next available model. Returnsnull data if only one model available.
model field is a full Model object.
get_available_models
List all configured models.Thinking
set_thinking_level
Set the reasoning/thinking level for models that support it."off", "minimal", "low", "medium", "high", "xhigh"
Note: "xhigh" is only supported by OpenAI codex-max models.
Response:
cycle_thinking_level
Cycle through available thinking levels. Returnsnull data if model doesn’t support thinking.
Queue Modes
set_steering_mode
Control how steering messages (fromsteer) are delivered.
"all": Deliver all steering messages after the current assistant turn finishes executing its tool calls"one-at-a-time": Deliver one steering message per completed assistant turn (default)
set_follow_up_mode
Control how follow-up messages (fromfollow_up) are delivered.
"all": Deliver all follow-up messages when agent finishes"one-at-a-time": Deliver one follow-up message per agent completion (default)
Compaction
compact
Manually compact conversation context to reduce token usage.set_auto_compaction
Enable or disable automatic compaction when context is nearly full.Retry
set_auto_retry
Enable or disable automatic retry on transient errors (overloaded, rate limit, 5xx).abort_retry
Abort an in-progress retry (cancel the delay and stop retrying).Bash
bash
Execute a shell command and add output to conversation context.fullOutputPath:
bash command executes immediately and returns a BashResult. Internally, a BashExecutionMessage is created and stored in the agent’s message state. This message does NOT emit an event.
When the next prompt command is sent, all messages (including BashExecutionMessage) are transformed before being sent to the LLM. The BashExecutionMessage is converted to a UserMessage with this format:
- Bash output is included in the LLM context on the next prompt, not immediately
- Multiple bash commands can be executed before a prompt; all outputs will be included
- No event is emitted for the
BashExecutionMessageitself
abort_bash
Abort a running bash command.Session
get_session_stats
Get token usage, cost statistics, and current context window usage.tokens contains assistant usage totals for the current session state. contextUsage contains the actual current context-window estimate used for compaction and footer display.
contextUsage is omitted when no model or context window is available. contextUsage.tokens and contextUsage.percent are null immediately after compaction until a fresh post-compaction assistant response provides valid usage data.
export_html
Export session to an HTML file.switch_session
Load a different session file. Can be cancelled by asession_before_switch extension event handler.
fork
Create a new fork from a previous user message on the active branch. Can be cancelled by asession_before_fork extension event handler. Returns the text of the message being forked from.
clone
Duplicate the current active branch into a new session at the current position. Can be cancelled by asession_before_fork extension event handler.
get_fork_messages
Get user messages available for forking.get_last_assistant_text
Get the text content of the last assistant message.{"text": null} if no assistant messages exist.
set_session_name
Set a display name for the current session. The name appears in session listings and helps identify sessions.get_state in the sessionName field.
Commands
get_commands
Get available commands (extension commands, prompt templates, and skills). These can be invoked via theprompt command by prefixing with /.
name: Command name (invoke with/name)description: Human-readable description (optional for extension commands)source: What kind of command:"extension": Registered viapi.registerCommand()in an extension"prompt": Loaded from a prompt template.mdfile"skill": Loaded from a skill directory (name is prefixed withskill:)
location: Where it was loaded from (optional, not present for extensions):"user": User-level (~/.atomic/agent/)"project": Project-level (./.atomic/)"path": Explicit path via CLI or settings
path: Absolute file path to the command source (optional)
/settings, /hotkeys, etc.) are not included. They are handled only in interactive mode and would not execute if sent via prompt.
Events
Events are streamed to stdout as JSON lines during agent operation. Events do NOT include anid field (only responses do).
Event Types
| Event | Description |
|---|---|
agent_start | Agent begins processing |
agent_end | Agent completes (includes all generated messages) |
turn_start | New turn begins |
turn_end | Turn completes (includes assistant message and tool results) |
message_start | Message begins |
message_update | Streaming update (text/thinking/toolcall deltas) |
message_end | Message completes |
tool_execution_start | Tool begins execution |
tool_execution_update | Tool execution progress (streaming output) |
tool_execution_end | Tool completes |
queue_update | Pending steering/follow-up queue changed |
compaction_start | Compaction begins |
compaction_end | Compaction completes |
auto_retry_start | Auto-retry begins (after transient error) |
auto_retry_end | Auto-retry completes (success or final failure) |
extension_error | Extension threw an error |
agent_start
Emitted when the agent begins processing a prompt.agent_end
Emitted when the agent completes. Contains all messages generated during this run.turn_start / turn_end
A turn consists of one assistant response plus any resulting tool calls and results.message_start / message_end
Emitted when a message begins and completes. Themessage field contains an AgentMessage.
message_update (Streaming)
Emitted during streaming of assistant messages. Contains both the partial message and a streaming delta event.assistantMessageEvent field contains one of these delta types:
| Type | Description |
|---|---|
start | Message generation started |
text_start | Text content block started |
text_delta | Text content chunk |
text_end | Text content block ended |
thinking_start | Thinking block started |
thinking_delta | Thinking content chunk |
thinking_end | Thinking block ended |
toolcall_start | Tool call started |
toolcall_delta | Tool call arguments chunk |
toolcall_end | Tool call ended (includes full toolCall object) |
done | Message complete (reason: "stop", "length", "toolUse") |
error | Error occurred (reason: "aborted", "error") |
tool_execution_start / tool_execution_update / tool_execution_end
Emitted when a tool begins, streams progress, and completes execution.tool_execution_update events stream partial results (e.g., bash output as it arrives):
toolCallId to correlate events. The partialResult in tool_execution_update contains the accumulated output so far (not just the delta), allowing clients to simply replace their display on each update.
queue_update
Emitted whenever the pending steering or follow-up queue changes.compaction_start / compaction_end
Emitted when compaction runs, whether manual or automatic.reason field is "manual", "threshold", or "overflow".
reason was "overflow" and compaction succeeds, willRetry is true and the agent will automatically retry the prompt.
If compaction was aborted, result is null and aborted is true.
If compaction failed (e.g., API quota exceeded), result is null, aborted is false, and errorMessage contains the error description.
auto_retry_start / auto_retry_end
Emitted when automatic retry is triggered after a transient error (overloaded, rate limit, 5xx).extension_error
Emitted when an extension throws an error.Extension UI Protocol
Extensions can request user interaction viactx.ui.select(), ctx.ui.confirm(), etc. In RPC mode, these are translated into a request/response sub-protocol on top of the base command/event flow.
There are two categories of extension UI methods:
- Dialog methods (
select,confirm,input,editor): emit anextension_ui_requeston stdout and block until the client sends back anextension_ui_responseon stdin with the matchingid. - Fire-and-forget methods (
notify,setStatus,setWidget,setTitle,set_editor_text): emit anextension_ui_requeston stdout but do not expect a response. The client can display the information or ignore it.
timeout field, the agent-side will auto-resolve with a default value when the timeout expires. The client does not need to track timeouts.
Some ExtensionUIContext methods are not supported or degraded in RPC mode because they require direct TUI access:
custom()returnsundefinedsetWorkingMessage(),setWorkingIndicator(),setFooter(),setHeader(),setEditorComponent(),setToolsExpanded()are no-opsgetEditorText()returns""getToolsExpanded()returnsfalsepasteToEditor()delegates tosetEditorText()(no paste/collapse handling)getAllThemes()returns[]getTheme()returnsundefinedsetTheme()returns{ success: false, error: "..." }
ctx.hasUI is true in RPC mode because the dialog and fire-and-forget methods are functional via the extension UI sub-protocol.
Extension UI Requests (stdout)
All requests havetype: "extension_ui_request", a unique id, and a method field.
select
Prompt the user to choose from a list. Dialog methods with atimeout field include the timeout in milliseconds; the agent auto-resolves with undefined if the client doesn’t respond in time.
extension_ui_response with value (the selected option string) or cancelled: true.
confirm
Prompt the user for yes/no confirmation.extension_ui_response with confirmed: true/false or cancelled: true.
input
Prompt the user for free-form text.extension_ui_response with value (the entered text) or cancelled: true.
editor
Open a multi-line text editor with optional prefilled content.extension_ui_response with value (the edited text) or cancelled: true.
notify
Display a notification. Fire-and-forget, no response expected.notifyType field is "info", "warning", or "error". Defaults to "info" if omitted.
setStatus
Set or clear a status entry in the footer/status bar. Fire-and-forget.statusText: undefined (or omit it) to clear the status entry for that key.
setWidget
Set or clear a widget (block of text lines) displayed above or below the editor. Fire-and-forget.widgetLines: undefined (or omit it) to clear the widget. The widgetPlacement field is "aboveEditor" (default) or "belowEditor". Only string arrays are supported in RPC mode; component factories are ignored.
setTitle
Set the terminal window/tab title. Fire-and-forget.set_editor_text
Set the text in the input editor. Fire-and-forget.Extension UI Responses (stdin)
Responses are sent for dialog methods only (select, confirm, input, editor). The id must match the request.
Value response (select, input, editor)
Confirmation response (confirm)
Cancellation response (any dialog)
Dismiss any dialog method. The extension receivesundefined (for select/input/editor) or false (for confirm).
Error Handling
Failed commands return a response withsuccess: false:
Types
Source files and installed definitions:node_modules/@earendil-works/pi-ai/dist/types.d.ts-Model,UserMessage,AssistantMessage,ToolResultMessagenode_modules/@earendil-works/pi-agent-core/dist/types.d.ts-AgentMessage,AgentEventsrc/core/messages.ts-BashExecutionMessagesrc/modes/rpc/rpc-types.ts- RPC command/response types, extension UI request/response types
Model
UserMessage
content field can be a string or an array of TextContent/ImageContent blocks.
AssistantMessage
"stop", "length", "toolUse", "error", "aborted"
ToolResultMessage
BashExecutionMessage
Created by thebash RPC command (not by LLM tool calls):
Attachment
Example: Basic Client (Python)
Example: Interactive Client (Node.js)
Seetest/rpc-example.ts for a complete interactive example, or src/modes/rpc/rpc-client.ts for a typed client implementation.
For a complete example of handling the extension UI protocol, see examples/rpc-extension-ui.ts which pairs with the examples/extensions/rpc-demo.ts extension.