Skip to content
Esc
↑↓navigate↵open⌘Jpreview
Start
On this page

RPC Mode

Drive Autohand Code CLI from another process with JSON-RPC 2.0 over stdin and stdout. Build custom UIs, IDE integrations, and automation tools on the same agent runtime.

What is the Autohand RPC Mode integration?

RPC mode runs Autohand Code CLI as a headless JSON-RPC 2.0 server over stdin and stdout. A parent process starts the CLI, calls autohand.* methods, and consumes streamed notifications for messages, tool calls, permission requests, and proposed file changes, without parsing the terminal interface.

Status Available
Requires A signed-in or configured Autohand Code CLI, and a host process that manages stdin, stdout, and the process lifecycle.
Configure with Start autohand --mode rpc, write one JSON-RPC message per line to stdin, and read one message per line from stdout.
Best for Custom interfaces, IDE extensions, test harnesses, and process-level automation.

Start RPC mode

autohand --mode rpc

--mode rpc is the switch that enables the protocol. The usual CLI options still apply:

autohand --mode rpc \
  --path /path/to/project \
  --model <model-id> \
  --config /path/to/config.json \
  --ephemeral
Flag Effect in RPC mode
--path <path> Workspace root. Defaults to the current directory.
--model <model> Overrides the configured model.
--config <path> Uses a specific config file instead of ~/.autohand/config.json.
--ephemeral Keeps the run out of session history, auto-memory, and session sync.
--add-dir <path...> Adds more directories to the workspace scope.
--worktree [name] Runs the session in an isolated git worktree.
--yolo [pattern] Pre-approves matching tool calls before the session starts.

Before the agent starts, the CLI validates the workspace path, applies the workspace safety gate, and checks authentication. If a check fails, it writes one JSON-RPC error with "id": null to stdout and exits with status 1. A missing login returns code -32011; run autohand --login or autohand --setup in a normal terminal first.

Framing and message shapes

RPC mode uses newline-delimited JSON over stdio:

  • stdin: one JSON-RPC request per line from your client.
  • stdout: one JSON-RPC response or notification per line from Autohand. Console output is suppressed, so nothing else is written to stdout.
  • stderr: debug diagnostics when debug logging is enabled. They are not part of the protocol.

Every message carries "jsonrpc": "2.0". Blank lines are ignored. A line that is not valid JSON returns a -32700 error. A JSON array is treated as a batch, and the replies arrive as one JSON array on a single line.

Request

{"jsonrpc": "2.0", "id": 1, "method": "autohand.prompt", "params": {"message": "Add a hello.ts file"}}

id can be a string or a number. Leave id out to send a client notification: Autohand runs the method and sends no reply. autohand.abort is commonly sent this way.

Response

{"jsonrpc": "2.0", "id": 1, "result": {"success": true}}

Failed requests return error instead of result:

{"jsonrpc": "2.0", "id": 1, "error": {"code": -32602, "message": "Missing required parameter: message"}}

Notification

Server notifications have a method and params but no id. Do not reply to them.

{"jsonrpc": "2.0", "method": "autohand.toolStart", "params": {"toolId": "tool_3_1760000000000", "toolName": "write_file", "args": {"path": "hello.ts"}, "timestamp": "2026-09-29T09:00:00.000Z"}}

Autohand sends autohand.agentStart once the agent is ready. Wait for it before sending your first request.

Session and prompt methods

Method Params Result
autohand.prompt message (required), context, images, stopWhen { success }
autohand.abort none { success }
autohand.stepDecision stepId, stop (boolean) { success }
autohand.reset none { sessionId }
autohand.getState none status, sessionId, model, workspace, contextPercent, messageCount, optional authenticatedUser
autohand.getMessages limit (optional) { messages }
autohand.getHistory page (default 1), pageSize (default 20) sessions, currentPage, totalPages, totalItems
autohand.getSession sessionId Session metadata plus messages and workspaceRoot
autohand.session.attach sessionId success, sessionId, workspaceRoot, messageCount
autohand.getContextUsage none Token counts for systemPrompt, tools, messages, mcpTools, memoryFiles, and total, plus contextWindow and usagePercent when known
autohand.setContextCompact enabled (boolean) { enabled }

autohand.getState reports status as idle, processing, or waiting_permission. Credentials are never returned over RPC.

autohand.prompt

autohand.prompt acknowledges the request immediately with { "success": true }. The work streams as notifications and finishes with autohand.turnEnd. Only one prompt runs at a time; sending another while the agent is busy returns an error with the message Agent is already processing.

Param Type Description
message string The instruction. Slash commands such as /review are accepted when the runtime supports them.
context.files string[] Files to mention alongside the instruction.
context.selection object Editor selection: file, startLine, endLine, text.
images array Image attachments: data (base64, no data: prefix), mimeType (image/png, image/jpeg, image/gif, or image/webp), optional filename. Up to 10 MB each.
stopWhen object Set to { "mode": "host" } to receive autohand.stepEnd after each completed tool step and decide whether to continue.

With stopWhen, answer each autohand.stepEnd notification with autohand.stepDecision: stop: true ends the turn with reason: "stop_condition", and stop: false continues.

autohand.abort

Cancels the running prompt and denies any pending permission or directory-access request. Returns { "success": false } when nothing is running. The turn ends with reason: "aborted".

Permission methods

When a tool needs approval, Autohand sends autohand.permissionRequest and waits.

Method Params Result
autohand.permissionAcknowledged requestId { success }
autohand.permissionResponse requestId, and either decision or allowed (boolean); alternative when decision is alternative { success }
autohand.directoryAccessAcknowledged requestId { success }
autohand.directoryAccessResponse requestId, granted (boolean) { success }
autohand.permissionModeSet mode: default, interactive, bypassPermissions, unrestricted, or restricted success, currentMode, previousMode
autohand.yoloSet pattern (string), timeoutSeconds (optional) success, expiresIn
autohand.planModeSet enabled (boolean) { success }

The permissionRequest notification lists the accepted decision values in options: allow_once, deny_once, allow_session, deny_session, allow_always_project, allow_always_user, allow_prefix_project, allow_prefix_user, deny_always_project, deny_always_user, and alternative. Sending allowed: true or allowed: false is a shorthand for a one-off decision.

autohand.permissionModeSet maps default to interactive and bypassPermissions to unrestricted. autohand.yoloSet switches the session to unrestricted mode when pattern is non-empty and back to interactive when it is an empty string; with timeoutSeconds, it reverts to interactive automatically. autohand.yolo.set is accepted as an alias.

File-change review

RPC mode batches file edits for review. During each prompt, writes are held as proposed changes instead of being applied to disk:

  1. autohand.changesBatchStart opens a batch (batchId, turnId).
  2. autohand.changesBatchUpdate streams each proposed change (batchId, change).
  3. autohand.changesBatchEnd closes the batch (batchId, changeCount).

Each change has id, filePath, changeType (create, modify, or delete), originalContent, proposedContent, description, toolId, and toolName.

Method Params Result
autohand.changesDecision batchId, action (accept_all, reject_all, or accept_selected), selectedChangeIds for accept_selected success, appliedCount, skippedCount, optional errors

Model and runtime control

Method Params Result
autohand.getSupportedModels none { models: [{ id, displayName }] }
autohand.modelSet model success, currentModel
autohand.maxThinkingTokensSet maxThinkingTokens (number or null) success, currentMaxThinkingTokens
autohand.applyFlagSettings settings (object of config keys) success, appliedSettings
autohand.getSupportedCommands none { commands } (slash command names)
autohand.getToolsRegistry none tools, diagnostics
autohand.reloadPlugins none success, reloadedPlugins

autohand.getSupportedModels returns the runnable models from the CLI’s model catalog. Autohand AI models such as fantail and moa are included only when Autohand AI inference is enabled.

Agents

Method Params Result
autohand.getSupportedAgents {} { agents }

Each agent entry has id (the agent name), name, description, and tools, plus optional model, source, extensionId, extensionVersion, and extensionScope. Agent prompts and local definition paths are never returned.

The list is the effective registry used for delegation: built-in, user, external, generated, session (--agents), and enabled extension agents. After a command that changes extensions, wait for autohand.turnEnd before calling it again. The method returns an error before the session is initialized, and older CLI versions return method-not-found; surface that error instead of showing an empty list.

Skills, learning, and goals

Method Params Result
autohand.getSkillsRegistry forceRefresh (optional) success, skills, categories
autohand.installSkill skillName, scope (user or project), force (optional) success, skillName, path
autohand.learn.recommend deep (optional) projectSummary, audit, recommendations, gapAnalysis
autohand.learn.update none updated, unchanged, results
autohand.learn.generate scope (project or user) success, skillName, skillPath
autohand.goal.get none Current goal snapshot
autohand.goal.create objective, plus optional acceptance_criteria, token_budget, time_budget_seconds Created or queued goal
autohand.goal.update Any of objective, status, completion_evidence, stop_reason, resume_when, checkpoint, and budget fields Updated goal
autohand.goal.clear none Cleared goal
autohand.goal.queue objective, plus the same options as goal.create Queued goal
autohand.goal.startQueued none Started goal
autohand.goal.listTemplates none Goal templates

The autohand.goal.* methods require the goals feature to be enabled in config. When it is off, they return { "ok": false, "message": "..." }. The autohand.learn.* methods stream progress as autohand.learn.progress notifications.

MCP servers

Method Params Result
autohand.mcp.listServers none { servers: [{ name, status, toolCount }] }
autohand.mcp.listTools serverName (optional) { tools: [{ name, description, serverName }] }
autohand.mcp.getServerConfigs none { configs }
autohand.mcp.toggleServer serverName, enabled success, serverName, status
autohand.mcp.reconnectServer serverName success, serverName, status
autohand.mcp.setServers servers (map of server configs) success, configuredServers
autohand.mcp.setVscodeTools tools (name, description, serverName, optional inputSchema) { success }
autohand.mcp.invokeResponse requestId, success, result or error { success }

autohand.mcp.setVscodeTools lets a host expose its own tools to the agent. When the agent calls one, Autohand sends autohand.mcp.invokeRequest (requestId, toolName, args), and the host replies with autohand.mcp.invokeResponse.

Auto-mode

Method Params Result
autohand.automode.start prompt (required), maxIterations (default 50), completionPromise (default DONE), useWorktree (default true), checkpointInterval (default 5), maxRuntime in minutes (default 120), maxCost in dollars (default 10) success, sessionId
autohand.automode.status none active, paused, state
autohand.automode.pause none { success }
autohand.automode.resume none { success }
autohand.automode.cancel reason (optional) { success }
autohand.automode.getLog limit (optional) success, iterations

Progress arrives as notifications with the same prefix: autohand.automode.start, .iteration, .checkpoint, .pause, .resume, .cancel, .complete, and .error. See Auto-mode for how the loop works.

Autoresearch

Method Params Result
autohand.autoresearch.start objective (required), plus optional maxIterations, timeoutMs, metricName, metricUnit, direction, measureCommand or measureScript, checksCommand or checksScript, filesInScope, subagents, secondaryObjectives, constraints, sampling, retention, environmentAllowlist success, message, instruction, active, state, statusText, runsLogged, attempts, paretoAttemptIds
autohand.autoresearch.status none success, active, state, statusText, runsLogged, attempts, paretoAttemptIds
autohand.autoresearch.stop none success, message, and the current state
autohand.autoresearch.history none success, attempts
autohand.autoresearch.replay attemptId, evaluator (original or current) metrics, samples, decision, driftWarnings
autohand.autoresearch.rescore attemptId, or all: true success, decisions
autohand.autoresearch.compare leftAttemptId, rightAttemptId success, comparison
autohand.autoresearch.pareto none success, attemptIds
autohand.autoresearch.pin attemptId, pinned success, attemptId, pinned
autohand.autoresearch.prune dryRun, yes Prune summary plus success

start resumes an existing experiment when one can be resumed. When no experiment exists and you pass metricName, metricUnit, direction, and a measure command or script, it initializes the benchmark config first. Autohand also sends autohand.autoresearch.start, .status, .pause, and .event notifications. See Autoresearch for the workflow.

Browser extension

The Autohand browser extension uses these methods.

Method Params Result
autohand.browserCapabilities.set protocolVersion, extensionVersion, tools enabled, protocolVersion, tools
autohand.browserHandoff.create extensionId, installUrl (both optional) token, sessionId, workspaceRoot, createdAt, expiresAt, url
autohand.browserHandoff.attach token success, sessionId, workspaceRoot, messageCount
autohand.browserHandoff.attachLatest none Same as attach

autohand.browserCapabilities.set negotiates the browser tool set. It returns enabled: true and protocol version 2 only when the extension reports protocolVersion: 2 and the experimentalBrowserToolsV2 feature is on in config. Otherwise it returns enabled: false, protocol version 1, and no tools. Only tools on Autohand’s supported browser tool list are enabled.

Notifications

Session, turn, and message

Notification Params
autohand.agentStart sessionId, model, workspace, timestamp
autohand.agentEnd sessionId, reason (completed, aborted, or error), timestamp
autohand.turnStart turnId, timestamp
autohand.turnEnd turnId, reason (completed, aborted, or stop_condition), durationMs, tokensUsed, tokensUsageStatus, contextPercent, timestamp
autohand.messageStart messageId, role, timestamp
autohand.messageUpdate messageId, delta, optional thought, timestamp
autohand.messageEnd messageId, content, timestamp
autohand.ping status, turnId, timestamp; sent every 15 seconds while a prompt runs
autohand.error code, message, recoverable, timestamp

Tools and requests

Notification Params
autohand.toolStart toolId, toolName, args, timestamp
autohand.toolUpdate toolId, output, stream (stdout or stderr), timestamp
autohand.toolEnd toolId, toolName, success, output, error, timestamp
autohand.stepEnd stepId, step, timestamp; only with stopWhen
autohand.permissionRequest requestId, tool, description, context (command, path, args), options, timestamp
autohand.directoryAccessRequest requestId, path, reason, timestamp
autohand.changesBatchStart, autohand.changesBatchUpdate, autohand.changesBatchEnd See File-change review
autohand.mcp.invokeRequest, autohand.mcp.toolsChanged MCP bridge events

Hook lifecycle

Hook notifications mirror the CLI’s hook events, so a host can react to them without configuring shell hooks. They are read-only.

Notification Params
autohand.hook.preTool toolId, toolName, args
autohand.hook.postTool toolId, toolName, success, duration, output
autohand.hook.fileModified filePath, changeType, toolId
autohand.hook.prePrompt instruction, mentionedFiles
autohand.hook.postResponse tokensUsed, toolCallsCount, duration
autohand.hook.stop tokensUsed, toolCallsCount, duration
autohand.hook.sessionStart sessionType (startup, resume, or clear)
autohand.hook.sessionEnd reason (quit, clear, exit, or error), duration
autohand.hook.sessionError error, code, context
autohand.hook.rateLimit error, code, retryAfterMs, httpStatus, model, provider
autohand.hook.permissionRequest tool, path, command, args
autohand.hook.notification notificationType, message
autohand.hook.subagentStart, .subagentProgress, .subagentMessage, .subagentCancelRequested subagentId, subagentName, subagentType, plus optional parentId, source, status, workspace, activity, message
autohand.hook.subagentStop subagentId, subagentName, subagentType, success, duration, error
autohand.hook.reviewStart, .reviewEnd, .reviewPaused, .reviewFailed, .reviewCompleted /review lifecycle events
autohand.hook.contextWarning, .contextCritical usagePercent, remainingTokens
autohand.hook.contextCompacted croppedCount, summary, usagePercent, reason
autohand.hook.contextOverflow tokensBefore, tokensAfter, croppedCount, usagePercent

Every hook notification also carries timestamp. autohand.hook.rateLimit arrives once, alongside autohand.hook.sessionError, when a provider rate limit ends the turn.

End-to-end example

This Python client starts RPC mode, sends one prompt, streams the reply, approves permission requests, accepts the proposed file changes, and exits after the turn ends.

import json
import subprocess

proc = subprocess.Popen(
    ["autohand", "--mode", "rpc", "--ephemeral"],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    text=True,
)
next_id = 0


def send(method, params=None, notify=False):
    global next_id
    msg = {"jsonrpc": "2.0", "method": method}
    if params is not None:
        msg["params"] = params
    if not notify:
        next_id += 1
        msg["id"] = next_id
    proc.stdin.write(json.dumps(msg) + "\n")
    proc.stdin.flush()


def messages():
    for line in proc.stdout:
        if line.strip():
            yield json.loads(line)


stream = messages()

# 1. Wait until the agent is ready.
for msg in stream:
    if "error" in msg:
        raise SystemExit(f"startup failed: {msg['error']}")
    if msg.get("method") == "autohand.agentStart":
        break

# 2. Send the prompt. The response only acknowledges it.
send("autohand.prompt", {"message": "Create hello.ts that prints Hello"})

# 3. Handle notifications until the turn ends.
for msg in stream:
    method, params = msg.get("method"), msg.get("params", {})

    if "error" in msg:
        print("error:", msg["error"])
    elif method == "autohand.messageUpdate":
        print(params["delta"], end="", flush=True)
    elif method == "autohand.permissionRequest":
        send("autohand.permissionAcknowledged", {"requestId": params["requestId"]})
        send("autohand.permissionResponse",
             {"requestId": params["requestId"], "decision": "allow_once"})
    elif method == "autohand.changesBatchEnd" and params["changeCount"] > 0:
        send("autohand.changesDecision",
             {"batchId": params["batchId"], "action": "accept_all"})
    elif method == "autohand.turnEnd":
        print(f"\nTurn ended: {params.get('reason')}")
        break

# 4. Closing stdin shuts the server down.
proc.stdin.close()
proc.wait()

The same exchange on the wire, trimmed to the key lines. Client requests and server output are interleaved for readability:

{"jsonrpc":"2.0","method":"autohand.agentStart","params":{"sessionId":"session_1_1760000000000","model":"...","workspace":"/path/to/project","timestamp":"..."}}
{"jsonrpc":"2.0","id":1,"method":"autohand.prompt","params":{"message":"Create hello.ts that prints Hello"}}
{"jsonrpc":"2.0","id":1,"result":{"success":true}}
{"jsonrpc":"2.0","method":"autohand.turnStart","params":{"turnId":"turn_2_1760000000100","timestamp":"..."}}
{"jsonrpc":"2.0","method":"autohand.changesBatchStart","params":{"batchId":"changes_4_1760000000120","turnId":"turn_2_1760000000100","timestamp":"..."}}
{"jsonrpc":"2.0","method":"autohand.messageUpdate","params":{"messageId":"msg_3_1760000000110","delta":"I'll create hello.ts","timestamp":"..."}}
{"jsonrpc":"2.0","method":"autohand.changesBatchEnd","params":{"batchId":"changes_4_1760000000120","changeCount":1,"timestamp":"..."}}
{"jsonrpc":"2.0","id":2,"method":"autohand.changesDecision","params":{"batchId":"changes_4_1760000000120","action":"accept_all"}}
{"jsonrpc":"2.0","method":"autohand.turnEnd","params":{"turnId":"turn_2_1760000000100","reason":"completed","timestamp":"..."}}
{"jsonrpc":"2.0","id":2,"result":{"success":true,"appliedCount":1,"skippedCount":0}}

Responses and notifications can arrive in any order, so match responses to requests by id.

Error codes

Code Meaning
-32700 Parse error: the line is not valid JSON.
-32600 Invalid request: missing jsonrpc or method, or an empty batch.
-32601 Method not found.
-32602 Invalid params, such as a missing required parameter.
-32603 Internal error, including Agent is already processing for overlapping prompts.
-32000 to -32004 Execution error, permission denied, timeout, agent busy, aborted.
-32010 Initialization failed.
-32011 Authentication required.

Startup errors use "id": null and include data with kind, stage: "startup", and retryable.

How do I start the Autohand RPC Mode integration?

Run autohand --mode rpc, wait for the autohand.agentStart notification, then send JSON-RPC 2.0 requests on stdin, one per line.

Why did my prompt return success before the agent finished?

autohand.prompt only acknowledges that the prompt was accepted. Follow the streamed notifications and treat autohand.turnEnd as the end of the turn.

Why were my file changes not written to disk?

RPC mode holds edits in a review batch. After autohand.changesBatchEnd, send autohand.changesDecision with accept_all or accept_selected to apply them.

Why are tool calls denied without a user decision?

Permission requests that are not acknowledged with autohand.permissionAcknowledged within 30 seconds are denied. Acknowledge each request as soon as your UI shows it.

Last updated on

Was this helpful?

Send Feedback

Help us improve this documentation page. Your feedback is valuable.

We'll only contact you if we need clarification