AnyAgent

API reference

Every AnyAgent export you call as a tool builder: detect and create, the run options and result types, the events, and the error class.

This page documents what you use when building on AnyAgent: the two entry-point functions, the types you pass and receive at runtime, and the single error class. The contract for supporting a new CLI lives in the repo’s contributing guide.

Entry points

Import detect and create from the package root, AnyAgentError from anyagent/errors, and every type from anyagent/types. Each built-in adapter has its own subpath, so importing one adapter never pulls in another and your tool ships only the adapters it uses.

import { create, detect } from "anyagent";
import { AnyAgentError } from "anyagent/errors";
import type { Agent, RunOptions, RunResult } from "anyagent/types";
import { claudeCode } from "anyagent/claude-code";
import { codex } from "anyagent/codex";

The other adapter subpaths follow the same shape: anyagent/opencode, anyagent/kilo-code, anyagent/pi, anyagent/goose, anyagent/cline, anyagent/gemini-cli, anyagent/antigravity, and anyagent/cursor. Each exports one factory (claudeCode(), codex(), …) returning an adapter you can hand to create; each factory’s flag mappings and quirks live on its adapter page.

detect

detect finds every supported coding agent installed on the machine and returns one DetectResult per installed agent. The list follows the adapter registry order, which carries no ranking, and is empty when nothing is installed.

const detect: (opts?: DetectOptions) => Promise<DetectResult[]>;

Call it with no arguments to scan the built-in adapters on the real machine, then pass the result you pick to create:

import { create, detect } from "anyagent";

const installed = await detect();
const [first] = installed;
if (!first) {
  throw new Error("No supported coding agent found.");
}
const agent = create(first);

DetectOptions overrides the defaults:

NameTypeDefaultDescription
adaptersAdapter[]the built-in adaptersadapter list to scan; pass your own to scan a subset or include a custom adapter
probeVersionProbea real PATH and exec probedetection I/O; pass a fake so tests simulate any machine without spawning processes

create

create builds a runnable Agent from either an adapter or one of detect’s results. Use an adapter directly when you know which CLI you want; use a DetectResult when you want whatever is installed.

const create: (source: Adapter | DetectResult, opts?: CreateOptions) => Agent;

The call is synchronous and spawns nothing; the process starts when you call run. It also never checks that the CLI is installed, so creating from an adapter on a machine without that CLI surfaces as an Invocation error on the first run. From an adapter factory the agent is typed to that adapter’s literal Capabilities, so an unsupported option fails to compile; from a DetectResult only the shared options are typed until supports unlocks more.

import { create } from "anyagent";
import { claudeCode } from "anyagent/claude-code";

const agent = create(claudeCode());
const result = await agent.run("Summarize this repo.");
console.log(result.text);

CreateOptions overrides the defaults:

NameTypeDefaultDescription
probeSystemProbethe real machine probewhat authStatus() and models() consult; pass a fake so tests simulate any credentials and files on disk

Agent

An Agent is a ready-to-run handle on one installed CLI: run starts one turn and returns a Run, session opens a multi-turn conversation, and supports narrows the type to the gated options it unlocks.

Prop

Type

Run

One run in flight: a Promise of the RunResult that is also an AsyncIterable of AgentEvents, so you await it, iterate it, or both. It runs to completion unless abort() or its signal fires; breaking out of an iteration loop stops watching, not the agent.

Prop

Type

Session and SessionOptions

One conversation spanning many turns, from agent.session(). The session owns continuity: each turn threads the previous turn’s resume handle automatically, one CLI process per turn, and id is a plain string you persist and pass back as agent.session({ resume: id }) to continue later. Turns queue, and a failed turn rejects the turns queued behind it; steer and respond are live-tier verbs gated by session.supports(). Gated by Capabilities.session; Sessions is the guide.

Prop

Type

SessionOptions shapes the session at creation. fork requires resume (InvalidOptions without it) and is gated by Capabilities.sessionFork:

Prop

Type

A session’s per-turn options are the agent’s minus resume and forkSession, which the session owns; passing either anyway throws InvalidOptions.

Run options

Everything you can tune about a single run; all fields are optional. BaselineRunOptions are the options every supported agent honors, ExtensionOptions exist only on some agents, and RunOptions is the union of both:

type RunOptions = BaselineRunOptions & Partial<ExtensionOptions>;

Every option is validated against the agent’s capabilities before any process spawns, so requesting something the CLI cannot do throws AnyAgentError with code: "UnsupportedCapability" up front. Every run is autonomous at the most the CLI offers: nothing waits for approval.

BaselineRunOptions

The options every supported agent honors; code that types against BaselineRunOptions runs unchanged on any agent AnyAgent can drive.

schema is a plain JSON Schema object. Pass it to run and the reply is parsed, validated against it, and set on RunResult.json; Run an agent covers the parsing, validation, and retry path.

Validation covers type (including "integer"), properties and required recursively, items as a single schema over every element, and enum. Every other keyword, such as minLength, pattern, or format, passes without a check, so enforce those in your own code after reading json.

Prop

Type

ExtensionOptions

The options that exist only on some agents, each gated by the Capabilities field of the same name (resume by session); requesting one an agent does not declare throws UnsupportedCapability before anything spawns.

Prop

Type

RunOptionsFor and supports

RunOptionsFor<C> is the options one specific agent accepts: BaselineRunOptions plus every extension its capabilities C declare available. From an adapter factory the capabilities are literal, so an unsupported option is a compile error. From detect() they are dynamic, and agent.supports(...keys) is both the runtime check and the type narrowing: a true branch makes those options typecheck. Run an agent shows the pattern.

ReasoningEffort

How hard the model should think, in the shared cross-agent vocabulary. The named levels autocomplete, but any string is accepted, because several CLIs take provider-defined names AnyAgent cannot enumerate.

type ReasoningEffort =
  | "none"
  | "minimal"
  | "low"
  | "medium"
  | "high"
  | "xhigh"
  | "max"
  | "ultra"
  | (string & Record<never, never>);

Where an agent’s vocabulary is closed, Capabilities.reasoningEfforts lists the accepted values and anything else throws UnsupportedCapability before anything spawns; otherwise the value passes through and the CLI judges it. Each adapter page names its vocabulary.

RunResult

What a finished run gives you back. Holding a RunResult means the run succeeded: the CLI exited cleanly and reported no agent-level error, since every failure path throws AnyAgentError instead.

Prop

Type

AgentEvent

One normalized event from a running agent, as yielded by iterating a Run. AgentEvent is a discriminated union on type with nine variants. Every variant except done carries a raw field holding the CLI’s untouched native payload for that event.

typePayloadMeaning
sessionsessionId: stringthe CLI assigned this run a session id; emitted once, early
text-deltatext: stringa piece of the agent’s answer text
reasoning-deltatext: stringa piece of the model’s visible thinking, on CLIs that stream it
tool-callname: ToolName, nativeName: string, callId?, inputthe agent invoked a tool with this input
tool-resultname: ToolName, nativeName: string, callId?, outputa tool returned this output
file-changekind: "create" | "modify" | "delete", path: stringthe agent changed a file, on CLIs that report it
usageusage: Usagetoken and cost accounting became available
permission-requestrequestId, name, nativeName, input, options: PermissionOption[]a live-tier agent asked permission for a tool, offering its own options
doneresult: RunResultthe run finished; carries the final result

How much text one text-delta carries depends on the agent: a token, a chunk, or a whole assistant message. Concatenating every delta’s text reproduces RunResult.text exactly; reasoning-delta text is never part of it. permission-request is emitted only by live-tier sessions, which resolve it themselves by allowing the tool.

Each permission-request carries the agent’s own choices as PermissionOptions — id, a normalized kind (allow-once, allow-always, reject-once, reject-always, or the agent’s own), and the agent’s label:

Prop

Type

ToolName

The shared cross-agent tool vocabulary on tool-call and tool-result events: the common tools normalize to these names (Claude Code’s Bash and Codex’s shell both surface as "bash"), tools outside it keep their native name, and the untranslated name is always on the event’s nativeName.

type ToolName =
  | "read"
  | "write"
  | "edit"
  | "bash"
  | "grep"
  | "glob"
  | "webSearch"
  | (string & Record<never, never>);

Usage

Token and cost accounting for a run, normalized across CLIs. Every field is optional because each CLI reports a different subset, so check for undefined rather than assuming a field is present, and read the event’s or result’s raw for exact cost.

Prop

Type

CapabilitySupport

How a capability is provided. It is the value type of the option-gating Capabilities fields:

type CapabilitySupport = "native" | "emulated" | false;
ValueMeaning
"native"the CLI implements it, and the adapter maps your request onto the CLI’s own flags
"emulated"the CLI has no such flag, so AnyAgent’s core provides the behavior itself, identically on every agent
falseunavailable; requesting it throws UnsupportedCapability before anything spawns

Both "native" and "emulated" are truthy, so a caps.systemPrompt ? … : … check still reads as “is this available”, and you ask for an emulated capability exactly as you ask for a native one.

DiscoverySupport

How a discovery question, authStatus or models, is answered. It is the value type of the authStatus and modelListing capability fields:

type DiscoverySupport = "native" | "probed" | false;
ValueMeaning
"native"the CLI answers itself, so the answer is authoritative
"probed"best-effort heuristics over the CLI’s credential files and environment variables; a hint, not a guarantee
falseno answer exists; calling the method throws UnsupportedCapability

Capabilities

What one agent CLI can do, read from agent.capabilities or a DetectResult before you ask for anything. A field guards the run option or Agent method of the same name, so requesting something declared false throws UnsupportedCapability before anything spawns; authStatus and modelListing are DiscoverySupport values, and every other field is a CapabilitySupport.

Prop

Type

AuthStatus and AuthState

The answer to agent.authStatus(): whether this CLI looks ready to run. This is “are credentials configured”, never “were they verified live”, and no paid model call is ever made on your behalf; on authStatus: false the call throws UnsupportedCapability.

Prop

Type

AuthState has three values, and "unknown" is a first-class answer, returned for example when the key lives in an OS keyring the probe cannot read:

type AuthState = "authenticated" | "unauthenticated" | "unknown";

ModelInfo

One model an agent accepts, from agent.models(). id is valid verbatim as model on the same agent, and on modelListing: false the call throws UnsupportedCapability.

Prop

Type

DetectResult

One agent CLI as found on this machine, returned by detect and accepted by create. version is whatever the CLI reported, kept for display only: AnyAgent never gates behavior on it, and a failed version probe leaves it absent (undefined) without blocking use.

Prop

Type

McpServer and McpConfig

McpConfig is the MCP (Model Context Protocol) servers for a run, keyed by the name the agent will see each server under. Each value is an McpServer. Set command, args, and optionally env for a local stdio server, or url for a remote one. The adapter translates this into whatever config format its CLI expects.

Prop

Type

McpConfig is the record type wrapping it:

type McpConfig = Record<string, McpServer>;

Pass it through RunOptions.mcp on an agent whose capabilities declare mcp:

import { create } from "anyagent";
import { claudeCode } from "anyagent/claude-code";

const agent = create(claudeCode());
await agent.run("List the tables the app touches.", {
  mcp: { db: { command: "npx", args: ["acme-db-mcp"] } },
});

AgentId and KnownAgents

AgentId is the id of a coding agent, such as "claude-code". The built-in ids autocomplete, but any string is accepted, so custom adapters fit too; an AgentId is still a string you can store or compare freely.

type AgentId = keyof KnownAgents | (string & Record<never, never>);

KnownAgents is the interface whose keys feed AgentId, with a key for every built-in adapter. A third-party adapter teaches the type about its own id through module augmentation; the repo’s CONTRIBUTING.md has the recipe.

AnyAgentError

The single error type everything in AnyAgent throws; there is no subclass tree, so you branch on the code field. Errors covers what each code means and what to do about it.

class AnyAgentError extends Error {
  readonly code: AnyAgentErrorCode;
  readonly raw?: unknown;
  readonly argv?: string[];
  readonly stderr?: string;
}

type AnyAgentErrorCode =
  | "UnsupportedCapability"
  | "InvalidOptions"
  | "Invocation"
  | "Parse"
  | "Aborted";

VersionProbe

The two I/O operations detection needs. detect uses a real implementation by default; tests pass a fake via detect({ probe }) to simulate any machine without spawning processes, shown in Test and ship.

Prop

Type

SystemProbe

Everything discovery reads from the machine: the VersionProbe operations plus the environment, home directory, and file contents, consulted by authStatus() and models(). The real one is the default; tests pass a fake via create(source, { probe }) to simulate any machine, credentials included, with zero subprocesses.

Prop

Type

RawHandle

Direct access to the native CLI, reached through agent.raw, for capabilities the unified interface does not cover. buildInvocation returns the exact command AnyAgent would run; spawn launches it and hands you the Node ChildProcess to drive yourself, with the prompt wired to stdin and no normalized events.

Prop

Type

Next steps