Skip to content

Core Exports

Defined in: types/errors.ts:4

Unified error codes for all SDK errors — single source of truth.

ABORTED: "ABORTED"

Defined in: types/errors.ts:29

AUTH_EXPIRED: "AUTH_EXPIRED"

Defined in: types/errors.ts:6

AUTH_INVALID: "AUTH_INVALID"

Defined in: types/errors.ts:7

AUTH_REQUIRED: "AUTH_REQUIRED"

Defined in: types/errors.ts:44

BACKEND_NOT_INSTALLED: "BACKEND_NOT_INSTALLED"

Defined in: types/errors.ts:32

CONTEXT_OVERFLOW: "CONTEXT_OVERFLOW"

Defined in: types/errors.ts:20

DEPENDENCY_MISSING: "DEPENDENCY_MISSING"

Defined in: types/errors.ts:31

DISPOSED: "DISPOSED"

Defined in: types/errors.ts:28

INVALID_INPUT: "INVALID_INPUT"

Defined in: types/errors.ts:23

INVALID_RESPONSE: "INVALID_RESPONSE"

Defined in: types/errors.ts:24

INVALID_TRANSITION: "INVALID_TRANSITION"

Defined in: types/errors.ts:30

MODEL_NOT_FOUND: "MODEL_NOT_FOUND"

Defined in: types/errors.ts:18

MODEL_OVERLOADED: "MODEL_OVERLOADED"

Defined in: types/errors.ts:19

NETWORK: "NETWORK"

Defined in: types/errors.ts:13

PERMISSION_DENIED: "PERMISSION_DENIED"

Defined in: types/errors.ts:36

PROVIDER_ERROR: "PROVIDER_ERROR"

Defined in: types/errors.ts:17

PROVIDER_NOT_FOUND: "PROVIDER_NOT_FOUND"

Defined in: types/errors.ts:43

RATE_LIMIT: "RATE_LIMIT"

Defined in: types/errors.ts:10

REENTRANCY: "REENTRANCY"

Defined in: types/errors.ts:27

SESSION_EXPIRED: "SESSION_EXPIRED"

Defined in: types/errors.ts:40

SESSION_NOT_FOUND: "SESSION_NOT_FOUND"

Defined in: types/errors.ts:39

STORAGE_DUPLICATE_KEY: "STORAGE_DUPLICATE_KEY"

Defined in: types/errors.ts:50

STORAGE_ERROR: "STORAGE_ERROR"

Defined in: types/errors.ts:47

STORAGE_IO_ERROR: "STORAGE_IO_ERROR"

Defined in: types/errors.ts:51

STORAGE_NOT_FOUND: "STORAGE_NOT_FOUND"

Defined in: types/errors.ts:49

STORAGE_SERIALIZATION_ERROR: "STORAGE_SERIALIZATION_ERROR"

Defined in: types/errors.ts:52

TIMEOUT: "TIMEOUT"

Defined in: types/errors.ts:14

TOOL_EXECUTION: "TOOL_EXECUTION"

Defined in: types/errors.ts:35

Defined in: errors.ts:108

Thrown when an agent run is aborted

new AbortError(): AbortError

Defined in: errors.ts:109

AbortError

AgentSDKError.constructor

readonly optional code: string

Defined in: errors.ts:21

Machine-readable error code. Prefer values from the ErrorCode enum.

AgentSDKError.code

readonly optional httpStatus: number

Defined in: errors.ts:25

HTTP status code hint for error classification

AgentSDKError.httpStatus

readonly retryable: boolean

Defined in: errors.ts:23

Whether this error is safe to retry

AgentSDKError.retryable

static is(error): error is AgentSDKError

Defined in: errors.ts:36

Check if an error is an AgentSDKError (works across bundled copies)

unknown

error is AgentSDKError

AgentSDKError.is


Defined in: errors.ts:127

Thrown when a stream has no activity within the configured timeout

new ActivityTimeoutError(timeoutMs): ActivityTimeoutError

Defined in: errors.ts:128

number

ActivityTimeoutError

AgentSDKError.constructor

readonly optional code: string

Defined in: errors.ts:21

Machine-readable error code. Prefer values from the ErrorCode enum.

AgentSDKError.code

readonly optional httpStatus: number

Defined in: errors.ts:25

HTTP status code hint for error classification

AgentSDKError.httpStatus

readonly retryable: boolean

Defined in: errors.ts:23

Whether this error is safe to retry

AgentSDKError.retryable

static is(error): error is AgentSDKError

Defined in: errors.ts:36

Check if an error is an AgentSDKError (works across bundled copies)

unknown

error is AgentSDKError

AgentSDKError.is


Defined in: errors.ts:17

Base error class for agent-sdk.

Use AgentSDKError.is(err) for reliable cross-module instanceof checks (works across separately bundled entry points where instanceof may fail).

  • Error

new AgentSDKError(message, options?): AgentSDKError

Defined in: errors.ts:27

string

AgentSDKErrorOptions

AgentSDKError

Error.constructor

readonly optional code: string

Defined in: errors.ts:21

Machine-readable error code. Prefer values from the ErrorCode enum.

readonly optional httpStatus: number

Defined in: errors.ts:25

HTTP status code hint for error classification

readonly retryable: boolean

Defined in: errors.ts:23

Whether this error is safe to retry

static is(error): error is AgentSDKError

Defined in: errors.ts:36

Check if an error is an AgentSDKError (works across bundled copies)

unknown

error is AgentSDKError


Defined in: errors.ts:79

Thrown when a backend is already registered

new BackendAlreadyRegisteredError(backend): BackendAlreadyRegisteredError

Defined in: errors.ts:80

string

BackendAlreadyRegisteredError

AgentSDKError.constructor

readonly optional code: string

Defined in: errors.ts:21

Machine-readable error code. Prefer values from the ErrorCode enum.

AgentSDKError.code

readonly optional httpStatus: number

Defined in: errors.ts:25

HTTP status code hint for error classification

AgentSDKError.httpStatus

readonly retryable: boolean

Defined in: errors.ts:23

Whether this error is safe to retry

AgentSDKError.retryable

static is(error): error is AgentSDKError

Defined in: errors.ts:36

Check if an error is an AgentSDKError (works across bundled copies)

unknown

error is AgentSDKError

AgentSDKError.is


Defined in: errors.ts:66

Thrown when a backend is not found in the registry

new BackendNotFoundError(backend): BackendNotFoundError

Defined in: errors.ts:67

string

BackendNotFoundError

AgentSDKError.constructor

readonly optional code: string

Defined in: errors.ts:21

Machine-readable error code. Prefer values from the ErrorCode enum.

AgentSDKError.code

readonly optional httpStatus: number

Defined in: errors.ts:25

HTTP status code hint for error classification

AgentSDKError.httpStatus

readonly retryable: boolean

Defined in: errors.ts:23

Whether this error is safe to retry

AgentSDKError.retryable

static is(error): error is AgentSDKError

Defined in: errors.ts:36

Check if an error is an AgentSDKError (works across bundled copies)

unknown

error is AgentSDKError

AgentSDKError.is


Defined in: base-agent.ts:23

Abstract base agent with shared lifecycle logic. Concrete backends extend this and implement the protected _run/_stream methods.

new BaseAgent(config): BaseAgent

Defined in: base-agent.ts:38

FullAgentConfig

BaseAgent

protected abortController: AbortController | null = null

Defined in: base-agent.ts:25

abstract protected readonly backendName: string

Defined in: base-agent.ts:31

Backend identifier (e.g. “copilot”, “claude”, “vercel-ai”)

protected readonly config: FullAgentConfig

Defined in: base-agent.ts:26

protected state: AgentState = "idle"

Defined in: base-agent.ts:24

get sessionId(): string | undefined

Defined in: base-agent.ts:34

CLI session ID for persistent mode. Override in backends that support it.

string | undefined

The CLI session ID when using persistent session mode. Undefined in per-call mode or before the first call. Can be stored externally for session resume.

IAgent.sessionId

abort(): void

Defined in: base-agent.ts:184

Abort the current operation. No-op if not running.

void

IAgent.abort

addStreamMiddleware(middleware): void

Defined in: base-agent.ts:152

Register a stream middleware. Applied in registration order after built-in transforms.

StreamMiddleware

void

protected checkAbort(signal): void

Defined in: base-agent.ts:500

Throw AbortError if signal is already aborted

AbortSignal

void

dispose(): void

Defined in: base-agent.ts:204

Mark agent as disposed. Override to add cleanup.

void

IAgent.dispose

abstract protected executeRun(messages, options, signal): Promise<AgentResult<void>>

Defined in: base-agent.ts:214

Execute a blocking run. Backend implements the actual LLM call.

Message[]

RunOptions

AbortSignal

Promise<AgentResult<void>>

abstract protected executeRunStructured<T>(messages, schema, options, signal): Promise<AgentResult<T>>

Defined in: base-agent.ts:221

Execute a structured output run. Backend implements parsing.

T

Message[]

StructuredOutputConfig<T>

RunOptions

AbortSignal

Promise<AgentResult<T>>

abstract protected executeStream(messages, options, signal): AsyncIterable<AgentEvent>

Defined in: base-agent.ts:229

Execute a streaming run. Backend yields events.

Message[]

RunOptions

AbortSignal

AsyncIterable<AgentEvent>

getConfig(): Readonly<FullAgentConfig>

Defined in: base-agent.ts:199

Get frozen agent configuration.

Readonly<FullAgentConfig>

IAgent.getConfig

getState(): AgentState

Defined in: base-agent.ts:195

Get current agent lifecycle state.

AgentState

IAgent.getState

protected guardDisposed(): void

Defined in: base-agent.ts:493

void

protected guardReentrancy(): void

Defined in: base-agent.ts:487

void

interrupt(): Promise<void>

Defined in: base-agent.ts:191

Default interrupt — falls back to abort(). Backends may override with graceful shutdown.

Promise<void>

IAgent.interrupt

protected resolveTools(options?): ToolDefinition<unknown>[]

Defined in: base-agent.ts:337

Resolve tools to use for this call (per-call override > config default)

RunOptions

ToolDefinition<unknown>[]

run(prompt, options): Promise<AgentResult<void>>

Defined in: base-agent.ts:44

Run a single prompt and return the result. Wraps prompt in a user message.

MessageContent

RunOptions

Promise<AgentResult<void>>

IAgent.run

runStructured<T>(prompt, schema, options): Promise<AgentResult<T>>

Defined in: base-agent.ts:87

Run with structured output validated against a Zod schema.

T

MessageContent

StructuredOutputConfig<T>

RunOptions

Promise<AgentResult<T>>

IAgent.runStructured

runWithContext(messages, options): Promise<AgentResult<void>>

Defined in: base-agent.ts:66

Run with full conversation history. Messages are passed directly to the backend.

Message[]

RunOptions

Promise<AgentResult<void>>

IAgent.runWithContext

stream(prompt, options): AsyncIterable<AgentEvent>

Defined in: base-agent.ts:110

Stream events for a single prompt. Wraps prompt in a user message.

MessageContent

RunOptions

AsyncIterable<AgentEvent>

IAgent.stream

streamWithContext(messages, options): AsyncIterable<AgentEvent>

Defined in: base-agent.ts:131

Stream events with full conversation history. Messages are passed directly to the backend.

Message[]

RunOptions

AsyncIterable<AgentEvent>

IAgent.streamWithContext


Defined in: permission-store.ts:128

Composes multiple stores — checks in order, routes writes by scope.

  • “session” → sessionStore (in-memory)
  • “project” → projectStore (file-based in project directory)
  • “always” → userStore (file-based in user home)

new CompositePermissionStore(sessionStore, projectStore, userStore?): CompositePermissionStore

Defined in: permission-store.ts:133

IPermissionStore

IPermissionStore

IPermissionStore

CompositePermissionStore

approve(toolName, scope): Promise<void>

Defined in: permission-store.ts:151

Store an approval decision

string

PermissionScope

Promise<void>

IPermissionStore.approve

clear(): Promise<void>

Defined in: permission-store.ts:169

Clear all approvals

Promise<void>

IPermissionStore.clear

dispose(): Promise<void>

Defined in: permission-store.ts:175

Dispose resources

Promise<void>

IPermissionStore.dispose

isApproved(toolName): Promise<boolean>

Defined in: permission-store.ts:143

Check if tool is already approved

string

Promise<boolean>

IPermissionStore.isApproved

revoke(toolName): Promise<void>

Defined in: permission-store.ts:163

Revoke approval for a tool

string

Promise<void>

IPermissionStore.revoke


Defined in: errors.ts:95

Thrown when a required peer dependency is not installed

new DependencyError(packageName): DependencyError

Defined in: errors.ts:98

string

DependencyError

AgentSDKError.constructor

readonly optional code: string

Defined in: errors.ts:21

Machine-readable error code. Prefer values from the ErrorCode enum.

AgentSDKError.code

readonly optional httpStatus: number

Defined in: errors.ts:25

HTTP status code hint for error classification

AgentSDKError.httpStatus

readonly packageName: string

Defined in: errors.ts:96

readonly retryable: boolean

Defined in: errors.ts:23

Whether this error is safe to retry

AgentSDKError.retryable

static is(error): error is AgentSDKError

Defined in: errors.ts:36

Check if an error is an AgentSDKError (works across bundled copies)

unknown

error is AgentSDKError

AgentSDKError.is


Defined in: errors.ts:56

Thrown when an operation is attempted on a disposed agent/service

new DisposedError(entity): DisposedError

Defined in: errors.ts:57

string

DisposedError

AgentSDKError.constructor

readonly optional code: string

Defined in: errors.ts:21

Machine-readable error code. Prefer values from the ErrorCode enum.

AgentSDKError.code

readonly optional httpStatus: number

Defined in: errors.ts:25

HTTP status code hint for error classification

AgentSDKError.httpStatus

readonly retryable: boolean

Defined in: errors.ts:23

Whether this error is safe to retry

AgentSDKError.retryable

static is(error): error is AgentSDKError

Defined in: errors.ts:36

Check if an error is an AgentSDKError (works across bundled copies)

unknown

error is AgentSDKError

AgentSDKError.is


Defined in: permission-store.ts:66

File-backed store — reads/writes a JSON file for persistent approvals.

new FilePermissionStore(filePath): FilePermissionStore

Defined in: permission-store.ts:69

string

FilePermissionStore

approve(toolName, scope): Promise<void>

Defined in: permission-store.ts:78

Store an approval decision

string

PermissionScope

Promise<void>

IPermissionStore.approve

clear(): Promise<void>

Defined in: permission-store.ts:91

Clear all approvals

Promise<void>

IPermissionStore.clear

dispose(): Promise<void>

Defined in: permission-store.ts:95

Dispose resources

Promise<void>

IPermissionStore.dispose

isApproved(toolName): Promise<boolean>

Defined in: permission-store.ts:73

Check if tool is already approved

string

Promise<boolean>

IPermissionStore.isApproved

revoke(toolName): Promise<void>

Defined in: permission-store.ts:85

Revoke approval for a tool

string

Promise<void>

IPermissionStore.revoke


Defined in: permission-store.ts:29

In-memory store — approvals live until process exits (or dispose).

new InMemoryPermissionStore(): InMemoryPermissionStore

InMemoryPermissionStore

approve(toolName, scope): Promise<void>

Defined in: permission-store.ts:36

Store an approval decision

string

PermissionScope

Promise<void>

IPermissionStore.approve

clear(): Promise<void>

Defined in: permission-store.ts:45

Clear all approvals

Promise<void>

IPermissionStore.clear

dispose(): Promise<void>

Defined in: permission-store.ts:49

Dispose resources

Promise<void>

IPermissionStore.dispose

isApproved(toolName): Promise<boolean>

Defined in: permission-store.ts:32

Check if tool is already approved

string

Promise<boolean>

IPermissionStore.isApproved

revoke(toolName): Promise<void>

Defined in: permission-store.ts:41

Revoke approval for a tool

string

Promise<void>

IPermissionStore.revoke


Defined in: errors.ts:46

Thrown when agent.run() is called while already running (M8 re-entrancy guard)

new ReentrancyError(): ReentrancyError

Defined in: errors.ts:47

ReentrancyError

AgentSDKError.constructor

readonly optional code: string

Defined in: errors.ts:21

Machine-readable error code. Prefer values from the ErrorCode enum.

AgentSDKError.code

readonly optional httpStatus: number

Defined in: errors.ts:25

HTTP status code hint for error classification

AgentSDKError.httpStatus

readonly retryable: boolean

Defined in: errors.ts:23

Whether this error is safe to retry

AgentSDKError.retryable

static is(error): error is AgentSDKError

Defined in: errors.ts:36

Check if an error is an AgentSDKError (works across bundled copies)

unknown

error is AgentSDKError

AgentSDKError.is


Defined in: errors.ts:138

Thrown when structured output parsing fails

new StructuredOutputError(message, options?): StructuredOutputError

Defined in: errors.ts:139

string

ErrorOptions

StructuredOutputError

AgentSDKError.constructor

readonly optional code: string

Defined in: errors.ts:21

Machine-readable error code. Prefer values from the ErrorCode enum.

AgentSDKError.code

readonly optional httpStatus: number

Defined in: errors.ts:25

HTTP status code hint for error classification

AgentSDKError.httpStatus

readonly retryable: boolean

Defined in: errors.ts:23

Whether this error is safe to retry

AgentSDKError.retryable

static is(error): error is AgentSDKError

Defined in: errors.ts:36

Check if an error is an AgentSDKError (works across bundled copies)

unknown

error is AgentSDKError

AgentSDKError.is


Defined in: errors.ts:87

Thrown when subprocess management fails

new SubprocessError(message, options?): SubprocessError

Defined in: errors.ts:88

string

ErrorOptions

SubprocessError

AgentSDKError.constructor

readonly optional code: string

Defined in: errors.ts:21

Machine-readable error code. Prefer values from the ErrorCode enum.

AgentSDKError.code

readonly optional httpStatus: number

Defined in: errors.ts:25

HTTP status code hint for error classification

AgentSDKError.httpStatus

readonly retryable: boolean

Defined in: errors.ts:23

Whether this error is safe to retry

AgentSDKError.retryable

static is(error): error is AgentSDKError

Defined in: errors.ts:36

Check if an error is an AgentSDKError (works across bundled copies)

unknown

error is AgentSDKError

AgentSDKError.is


Defined in: errors.ts:116

Thrown when a tool execution fails

new ToolExecutionError(toolName, message, options?): ToolExecutionError

Defined in: errors.ts:119

string

string

ErrorOptions

ToolExecutionError

AgentSDKError.constructor

readonly optional code: string

Defined in: errors.ts:21

Machine-readable error code. Prefer values from the ErrorCode enum.

AgentSDKError.code

readonly optional httpStatus: number

Defined in: errors.ts:25

HTTP status code hint for error classification

AgentSDKError.httpStatus

readonly retryable: boolean

Defined in: errors.ts:23

Whether this error is safe to retry

AgentSDKError.retryable

readonly toolName: string

Defined in: errors.ts:117

static is(error): error is AgentSDKError

Defined in: errors.ts:36

Check if an error is an AgentSDKError (works across bundled copies)

unknown

error is AgentSDKError

AgentSDKError.is

Defined in: types/agent.ts:105

Identity-only agent configuration — defines the agent’s behavior, NOT per-call defaults. For creating an agent with model/tools defaults, use FullAgentConfig.

optional availableTools: string[]

Defined in: types/agent.ts:124

Filter for backend built-in tools (e.g. ["web_search", "web_fetch"] for Copilot). When set, only listed built-in tools are available. Backend-specific.

Security note: This is a trust boundary — it controls which backend-native tools the AI agent can invoke. By default, backends expose ALL their built-in tools. Set this to restrict access (e.g. prevent file system access in a web-facing agent).

optional errorHandling: ErrorHandlingConfig

Defined in: types/agent.ts:110

optional heartbeatInterval: number

Defined in: types/agent.ts:131

Interval in milliseconds for emitting heartbeat events during streaming. When set, heartbeat events are emitted to keep the stream alive during long tool executions. Default: off (no heartbeats).

optional maxTurns: number

Defined in: types/agent.ts:108

optional onUsage: (usage) => void

Defined in: types/agent.ts:127

Callback invoked with usage data after run completion or during streaming. Fire-and-forget: errors are logged but not propagated.

UsageData

void

optional permissionStore: IPermissionStore

Defined in: types/agent.ts:112

Pluggable store for persisting permission scope decisions across runs

optional sessionMode: "per-call" | "persistent"

Defined in: types/agent.ts:136

Session reuse mode for CLI backends (Copilot, Claude). “per-call” (default): creates a fresh CLI session for each run/stream call. “persistent”: reuses the same CLI session across calls, preserving conversation history natively in the CLI backend. Session is destroyed on agent dispose().

optional supervisor: SupervisorHooks

Defined in: types/agent.ts:107

optional systemMessageMode: "replace" | "append"

Defined in: types/agent.ts:115

How to apply systemPrompt: “append” adds to backend default, “replace” overrides it. Default: “append”. Currently used by the Copilot backend.

systemPrompt: string

Defined in: types/agent.ts:106

optional timeout: TimeoutConfig

Defined in: types/agent.ts:109


Defined in: types/agent.ts:161

Result of an agent run, generic over structured output type T

T = void

messages: Message[]

Defined in: types/agent.ts:170

output: string | null

Defined in: types/agent.ts:162

structuredOutput: T extends void ? undefined : T

Defined in: types/agent.ts:163

toolCalls: object[]

Defined in: types/agent.ts:164

approved: boolean

args: JSONValue

result: JSONValue

toolName: string

optional usage: UsageData

Defined in: types/agent.ts:171


Defined in: errors.ts:4

Options for constructing an AgentSDKError

  • ErrorOptions

optional code: string

Defined in: errors.ts:6

Machine-readable error code

optional httpStatus: number

Defined in: errors.ts:10

HTTP status code hint (e.g. 401, 429, 500)

optional retryable: boolean

Defined in: errors.ts:8

Whether this error is retryable (default: false)


Defined in: registry.ts:20

Map of built-in backend names to their options types

claude: ClaudeBackendOptions

Defined in: registry.ts:22

copilot: CopilotBackendOptions

Defined in: registry.ts:21

vercel-ai: VercelAIBackendOptions

Defined in: registry.ts:23


Defined in: types/agent.ts:141

Per-call defaults that can be provided at agent creation time. Each field can also be overridden on individual calls via RunOptions.

optional model: string

Defined in: types/agent.ts:143

Default model (overridable per-call via RunOptions.model)

optional modelParams: ModelParams

Defined in: types/agent.ts:145

Default model parameters

optional providerOptions: Record<string, Record<string, unknown>>

Defined in: types/agent.ts:151

Provider-specific options passed through to the underlying SDK. For Vercel AI: passed as providerOptions to generateText/streamText. Example: { google: { thinkingConfig: { thinkingBudget: 1024 } } }

optional tools: ToolDefinition<unknown>[]

Defined in: types/agent.ts:147

Default tools (overridable per-call via RunOptions.tools)


Defined in: types/agent.ts:16

Per-call overrides passed to run(), stream(), runStructured(). Allows overriding the model, tools, signal, and other parameters on a per-request basis without modifying the agent configuration.

optional maxTokens: number

Defined in: types/agent.ts:30

Per-call token limit

optional model: string

Defined in: types/agent.ts:18

Override the default model for this call

optional providerOptions: Record<string, unknown>

Defined in: types/agent.ts:26

Provider-specific options passed through to the underlying SDK

optional retry: RetryConfig

Defined in: types/agent.ts:32

Retry configuration for this call

optional signal: AbortSignal

Defined in: types/agent.ts:22

Per-call abort signal

optional systemMessage: string

Defined in: types/agent.ts:24

Override system message for this call

optional timeout: number

Defined in: types/agent.ts:28

Per-call timeout in milliseconds

optional tools: ToolDefinition<unknown>[]

Defined in: types/agent.ts:20

Override/extend tools for this call


Defined in: types/backends.ts:21

Options for Claude CLI backend

optional cliPath: string

Defined in: types/backends.ts:22

optional env: Record<string, string | undefined>

Defined in: types/backends.ts:28

Custom environment variables merged into the subprocess env

optional maxTurns: number

Defined in: types/backends.ts:24

optional oauthToken: string

Defined in: types/backends.ts:26

OAuth token for Claude authentication (set as CLAUDE_CODE_OAUTH_TOKEN env var)

optional resumeSessionId: string

Defined in: types/backends.ts:31

Session ID to resume after server restart. On startup, the backend attempts to resume this session before creating a new one.

optional workingDirectory: string

Defined in: types/backends.ts:23


Defined in: types/backends.ts:2

Options for Copilot CLI backend

optional cliArgs: string[]

Defined in: types/backends.ts:8

Extra CLI arguments passed to the Copilot subprocess (e.g. [“—allow-all”])

optional cliPath: string

Defined in: types/backends.ts:3

optional env: Record<string, string | undefined>

Defined in: types/backends.ts:14

Custom environment variables merged into the subprocess env

optional githubToken: string

Defined in: types/backends.ts:5

optional resumeSessionId: string

Defined in: types/backends.ts:17

Session ID to resume after server restart. On startup, the backend attempts to resume this session before creating a new one.

optional startupTimeoutMs: number

Defined in: types/backends.ts:12

Timeout in milliseconds for CLI startup and auth check (default: 30000).

optional timeout: number

Defined in: types/backends.ts:10

Timeout in milliseconds for sendAndWait() calls. When undefined, uses copilot-sdk default (60s).

optional useLoggedInUser: boolean

Defined in: types/backends.ts:6

optional workingDirectory: string

Defined in: types/backends.ts:4


Defined in: types/agent.ts:89

Error handling strategy configuration

optional onError: (error, context) => void

Defined in: types/agent.ts:95

Global error callback for monitoring

Error

"tool" | "llm" | "permission" | "ask-user"

void

optional onToolError: "fail" | "continue" | "ask-llm"

Defined in: types/agent.ts:91

What to do when a tool throws

optional retryLLM: object

Defined in: types/agent.ts:93

Retry config for transient LLM failures

backoffMs: number

maxAttempts: number


Defined in: types/agent.ts:182

Core agent interface — run prompts, stream events, manage lifecycle

readonly sessionId: string | undefined

Defined in: types/agent.ts:185

The CLI session ID when using persistent session mode. Undefined in per-call mode or before the first call. Can be stored externally for session resume.

abort(): void

Defined in: types/agent.ts:210

Abort the current operation. No-op if not running.

void

dispose(): void

Defined in: types/agent.ts:218

Release resources. After dispose(), agent must not be used.

void

getConfig(): Readonly<FullAgentConfig>

Defined in: types/agent.ts:216

Get frozen agent configuration.

Readonly<FullAgentConfig>

getState(): AgentState

Defined in: types/agent.ts:214

Get current agent lifecycle state.

AgentState

interrupt(): Promise<void>

Defined in: types/agent.ts:212

Gracefully interrupt the current operation. Resolves when the backend acknowledges.

Promise<void>

run(prompt, options): Promise<AgentResult<void>>

Defined in: types/agent.ts:187

Run a single prompt and return the result. Wraps prompt in a user message.

MessageContent

RunOptions

Promise<AgentResult<void>>

runStructured<T>(prompt, schema, options): Promise<AgentResult<T>>

Defined in: types/agent.ts:194

Run with structured output validated against a Zod schema.

T

MessageContent

StructuredOutputConfig<T>

RunOptions

Promise<AgentResult<T>>

runWithContext(messages, options): Promise<AgentResult<void>>

Defined in: types/agent.ts:189

Run with full conversation history. Messages are passed directly to the backend.

Message[]

RunOptions

Promise<AgentResult<void>>

stream(prompt, options): AsyncIterable<AgentEvent>

Defined in: types/agent.ts:200

Stream events for a single prompt. Wraps prompt in a user message.

MessageContent

RunOptions

AsyncIterable<AgentEvent>

streamWithContext(messages, options): AsyncIterable<AgentEvent>

Defined in: types/agent.ts:205

Stream events with full conversation history. Messages are passed directly to the backend.

Message[]

RunOptions

AsyncIterable<AgentEvent>


Defined in: types/agent.ts:224

Backend service interface — creates agents, lists models, validates config

readonly name: string

Defined in: types/agent.ts:225

createAgent(config): IAgent

Defined in: types/agent.ts:226

FullAgentConfig

IAgent

dispose(): Promise<void>

Defined in: types/agent.ts:229

Promise<void>

listModels(): Promise<ModelInfo[]>

Defined in: types/agent.ts:227

Promise<ModelInfo[]>

validate(): Promise<ValidationResult>

Defined in: types/agent.ts:228

Promise<ValidationResult>


Defined in: permission-store.ts:9

Pluggable store for persisting permission (scope) decisions across runs.

approve(toolName, scope): Promise<void>

Defined in: permission-store.ts:14

Store an approval decision

string

PermissionScope

Promise<void>

clear(): Promise<void>

Defined in: permission-store.ts:20

Clear all approvals

Promise<void>

dispose(): Promise<void>

Defined in: permission-store.ts:23

Dispose resources

Promise<void>

isApproved(toolName): Promise<boolean>

Defined in: permission-store.ts:11

Check if tool is already approved

string

Promise<boolean>

revoke(toolName): Promise<void>

Defined in: permission-store.ts:17

Revoke approval for a tool

string

Promise<void>


Defined in: types/models.ts:2

Model metadata returned by listModels()

optional capabilities: string[]

Defined in: types/models.ts:11

Model capabilities (e.g. “vision”, “tools”, “structured”)

optional contextWindow: number

Defined in: types/models.ts:9

Context window size in tokens

id: string

Defined in: types/models.ts:3

optional name: string

Defined in: types/models.ts:4

optional provider: string

Defined in: types/models.ts:5

optional tier: "fast" | "standard" | "premium"

Defined in: types/models.ts:7

Model tier for UI categorization and cost hints


Defined in: types/models.ts:15

LLM model parameters

optional maxTokens: number

Defined in: types/models.ts:17

optional stopSequences: string[]

Defined in: types/models.ts:19

optional temperature: number

Defined in: types/models.ts:16

optional topP: number

Defined in: types/models.ts:18


Defined in: types/permissions.ts:17

What the permission callback returns

allowed: boolean

Defined in: types/permissions.ts:18

optional modifiedInput: Record<string, unknown>

Defined in: types/permissions.ts:22

Modified tool arguments (tool args may be altered by user)

optional reason: string

Defined in: types/permissions.ts:24

Denial reason (if denied)

optional scope: PermissionScope

Defined in: types/permissions.ts:20

How long to remember this decision


Defined in: types/permissions.ts:5

What the permission callback receives

optional rawSDKRequest: unknown

Defined in: types/permissions.ts:13

Original SDK permission request (for pass-through)

optional suggestedScope: PermissionScope

Defined in: types/permissions.ts:11

SDK-suggested scope (from Claude CLI’s suggestions)

toolArgs: Record<string, unknown>

Defined in: types/permissions.ts:7

optional toolCallId: string

Defined in: types/permissions.ts:9

Unique identifier for this specific tool call

toolName: string

Defined in: types/permissions.ts:6


Defined in: types/agent.ts:38

Configuration for automatic retries on transient errors

optional backoffMultiplier: number

Defined in: types/agent.ts:44

Backoff multiplier (default: 2)

optional initialDelayMs: number

Defined in: types/agent.ts:42

Initial delay in ms before first retry (default: 1000)

optional maxRetries: number

Defined in: types/agent.ts:40

Maximum number of retries (default: 0 — no retry)

optional retryableErrors: ErrorCode[]

Defined in: types/agent.ts:46

Which error codes to retry (default: all recoverable codes)


Defined in: types/agent.ts:63

Options passed to agent.run() / agent.stream(). Extends CallOptions with run-specific fields (context, activityTimeoutMs). model is REQUIRED — every agent call must specify the model explicitly.

optional activityTimeoutMs: number

Defined in: types/agent.ts:71

Inactivity timeout for streaming (ms). When set, the stream aborts if no event (including heartbeats/progress) arrives within this period. Resets on every received event. Default: no timeout. Only affects stream()/streamWithContext().

optional context: Record<string, unknown>

Defined in: types/agent.ts:67

Arbitrary context passed to the agent run

optional maxTokens: number

Defined in: types/agent.ts:30

Per-call token limit

CallOptions.maxTokens

model: string

Defined in: types/agent.ts:65

Model to use for this call (required — no implicit defaults)

CallOptions.model

optional providerOptions: Record<string, unknown>

Defined in: types/agent.ts:26

Provider-specific options passed through to the underlying SDK

CallOptions.providerOptions

optional retry: RetryConfig

Defined in: types/agent.ts:32

Retry configuration for this call

CallOptions.retry

optional signal: AbortSignal

Defined in: types/agent.ts:22

Per-call abort signal

CallOptions.signal

optional systemMessage: string

Defined in: types/agent.ts:24

Override system message for this call

CallOptions.systemMessage

optional timeout: number

Defined in: types/agent.ts:28

Per-call timeout in milliseconds

CallOptions.timeout

optional tools: ToolDefinition<unknown>[]

Defined in: types/agent.ts:20

Override/extend tools for this call

CallOptions.tools


Defined in: types/events.ts:44

Context passed to stream middleware — immutable per stream invocation

abortController: AbortController

Defined in: types/events.ts:47

backend: string

Defined in: types/events.ts:46

config: Readonly<Record<string, unknown>>

Defined in: types/events.ts:49

Agent config snapshot. Loosely typed to avoid leaking internal FullAgentConfig to external middleware consumers.

model: string

Defined in: types/events.ts:45


Defined in: types/agent.ts:52

Configuration for typed structured output from LLM

T = unknown

optional description: string

Defined in: types/agent.ts:55

optional name: string

Defined in: types/agent.ts:54

schema: ZodType<T>

Defined in: types/agent.ts:53


Defined in: types/permissions.ts:51

Hooks for supervisor/UI to intercept agent actions

optional onAskUser: (request, signal) => Promise<UserInputResponse>

Defined in: types/permissions.ts:53

UserInputRequest

AbortSignal

Promise<UserInputResponse>

optional onPermission: PermissionCallback

Defined in: types/permissions.ts:52


Defined in: types/agent.ts:77

Timeout configuration for agent operations

optional perLLMRequest: number

Defined in: types/agent.ts:83

Max time for a single LLM request (ms)

optional perTool: number

Defined in: types/agent.ts:81

Max time for a single tool execution (ms)

optional total: number

Defined in: types/agent.ts:79

Max time for entire agent run (ms)


Defined in: types/tools.ts:36

A tool call made by the LLM during execution

args: JSONValue

Defined in: types/tools.ts:39

id: string

Defined in: types/tools.ts:37

name: string

Defined in: types/tools.ts:38


Defined in: types/tools.ts:28

Request-scoped context passed to tool execute functions via ChatRuntime. Contains session identity and user-defined metadata from the current session.

optional custom: Record<string, unknown>

Defined in: types/tools.ts:32

Custom metadata from the session (e.g. user ID, tenant, permissions)

sessionId: string

Defined in: types/tools.ts:30

Active chat session ID


Defined in: types/tools.ts:5

What the LLM sees — name, description, schema. Passed to all backends.

TParams = unknown

description: string

Defined in: types/tools.ts:7

optional metadata: object

Defined in: types/tools.ts:10

optional category: string

optional icon: string

optional tags: string[]

name: string

Defined in: types/tools.ts:6

optional needsApproval: boolean

Defined in: types/tools.ts:9

parameters: ZodType<TParams>

Defined in: types/tools.ts:8


Defined in: types/tools.ts:21

Full tool with execute function. Required for API-based backends. CLI backends extract declaration; execute map held internally. The optional second parameter receives request-scoped context when invoked through ChatRuntime (session ID, user data, custom metadata).

TParams = unknown

description: string

Defined in: types/tools.ts:7

ToolDeclaration.description

execute: (params, context?) => unknown

Defined in: types/tools.ts:23

TParams

ToolContext

unknown

optional metadata: object

Defined in: types/tools.ts:10

optional category: string

optional icon: string

optional tags: string[]

ToolDeclaration.metadata

name: string

Defined in: types/tools.ts:6

ToolDeclaration.name

optional needsApproval: boolean

Defined in: types/tools.ts:9

ToolDeclaration.needsApproval

parameters: ZodType<TParams>

Defined in: types/tools.ts:8

ToolDeclaration.parameters


Defined in: types/tools.ts:43

Result of executing a tool call

optional isError: boolean

Defined in: types/tools.ts:47

name: string

Defined in: types/tools.ts:45

result: JSONValue

Defined in: types/tools.ts:46

toolCallId: string

Defined in: types/tools.ts:44


Defined in: types/events.ts:6

Usage data from LLM execution — tokens consumed plus optional metadata

optional backend: string

Defined in: types/events.ts:10

completionTokens: number

Defined in: types/events.ts:8

optional model: string

Defined in: types/events.ts:9

promptTokens: number

Defined in: types/events.ts:7


Defined in: types/permissions.ts:34

Request for user input — separate from permissions

optional allowFreeform: boolean

Defined in: types/permissions.ts:38

Whether to allow freeform text input (default: true)

optional choices: string[]

Defined in: types/permissions.ts:36

question: string

Defined in: types/permissions.ts:35


Defined in: types/permissions.ts:42

Response from user to an input request

answer: string

Defined in: types/permissions.ts:43

optional selectedChoiceIndex: number

Defined in: types/permissions.ts:47

Index of selected choice (if choice was selected)

wasFreeform: boolean

Defined in: types/permissions.ts:45

true if user typed a custom answer instead of selecting a choice


Defined in: types/models.ts:23

Result of backend validation check

errors: string[]

Defined in: types/models.ts:25

valid: boolean

Defined in: types/models.ts:24


Defined in: types/backends.ts:97

Options for Vercel AI SDK backend

apiKey: string

Defined in: types/backends.ts:98

optional baseUrl: string

Defined in: types/backends.ts:100

optional provider: string

Defined in: types/backends.ts:99

AgentEvent = { text: string; type: "text_delta"; } | { text: string; type: "thinking_delta"; } | { args: JSONValue; toolCallId: string; toolName: string; type: "tool_call_start"; } | { result: JSONValue; toolCallId: string; toolName: string; type: "tool_call_end"; } | { request: PermissionRequest; type: "permission_request"; } | { decision: PermissionDecision; toolName: string; type: "permission_response"; } | { request: UserInputRequest; type: "ask_user"; } | { answer: string; type: "ask_user_response"; } | { type: "thinking_start"; } | { type: "thinking_end"; } | { backend?: string; completionTokens: number; model?: string; promptTokens: number; type: "usage_update"; } | { backend: string; sessionId: string; transcriptPath?: string; type: "session_info"; } | { type: "heartbeat"; } | { code?: ErrorCode; error: string; recoverable: boolean; type: "error"; } | { finalOutput: string | null; finishReason?: string; streamed?: boolean; structuredOutput?: unknown; type: "done"; }

Defined in: types/events.ts:14

Events emitted during streaming agent execution


AgentState = "idle" | "running" | "streaming" | "disposed"

Defined in: types/agent.ts:177

Agent lifecycle state


BackendFactory<TOptions> = (options) => IAgentService | Promise<IAgentService>

Defined in: registry.ts:15

Factory function that creates a backend service from options

TOptions = unknown

TOptions

IAgentService | Promise<IAgentService>


BuiltinBackendName = keyof BackendOptionsMap

Defined in: registry.ts:27

All known backend names (built-in + custom)


ContentPart = { text: string; type: "text"; } | { data: string; mimeType: string; type: "image"; }

Defined in: types/messages.ts:7

Individual content part within a multi-part message


FullAgentConfig = AgentConfig & CallDefaults

Defined in: types/agent.ts:156

Full agent configuration: identity + per-call defaults. This is what createAgent() accepts. Backward-compatible with the old AgentConfig shape.


JSONValue = string | number | boolean | null | JSONValue[] | {[key: string]: JSONValue; }

Defined in: types/json.ts:2

JSON-serializable value used for tool arguments and results


Message = { content: MessageContent; role: "user"; } | { content: MessageContent; role: "assistant"; thinking?: string; toolCalls?: ToolCall[]; } | { content?: string; role: "tool"; toolResults: ToolResult[]; } | { content: string; role: "system"; }

Defined in: types/messages.ts:12

Conversation message — discriminated union on role


MessageContent = string | ContentPart[]

Defined in: types/messages.ts:4

Message content — plain string or array of text/image parts


PermissionCallback = (request, signal) => Promise<PermissionDecision>

Defined in: types/permissions.ts:28

Permission callback signature

PermissionRequest

AbortSignal

Promise<PermissionDecision>


PermissionScope = "once" | "session" | "project" | "always"

Defined in: types/permissions.ts:2

Scope for “remember this decision”


StreamMiddleware = (source, context) => AsyncIterable<AgentEvent>

Defined in: types/events.ts:54

A composable transform over the agent event stream. Receives the upstream source and context, returns a transformed stream.

AsyncIterable<AgentEvent>

StreamContext

AsyncIterable<AgentEvent>

buildSystemPrompt(base, schemaInstruction?): string

Defined in: utils/messages.ts:29

Build a system prompt with optional structured output instruction

string

string

string


classifyAgentError(error): ErrorCode

Defined in: types/errors.ts:73

Classify an error message string into an ErrorCode

string | Error

ErrorCode


contentToText(content): string

Defined in: utils/messages.ts:24

Convert MessageContent to plain text

MessageContent

string


createAgentService<K>(name, options, configId?): Promise<IAgentService>

Defined in: registry.ts:171

Create a backend service with type-safe options. When configId is provided, the service instance is cached and reused on subsequent calls with the same name+configId pair. Without configId, a new instance is created every call.

K extends keyof BackendOptionsMap

K

BackendOptionsMap[K]

string

Promise<IAgentService>

createAgentService(name, options, configId?): Promise<IAgentService>

Defined in: registry.ts:176

Create a backend service with type-safe options. When configId is provided, the service instance is cached and reused on subsequent calls with the same name+configId pair. Without configId, a new instance is created every call.

string

unknown

string

Promise<IAgentService>


createDefaultPermissionStore(projectDir?): CompositePermissionStore

Defined in: permission-store.ts:187

Create a default composite store with separate project and user-level persistence.

string

CompositePermissionStore


disposeBackend(name, configId?): Promise<number>

Defined in: registry.ts:84

Dispose all cached service instances for a backend, or a single named config. Returns the number of instances disposed.

string

string

Promise<number>


getTextContent(content): string

Defined in: types/guards.ts:24

Extract text from MessageContent regardless of format

MessageContent

string


hasBackend(name): boolean

Defined in: registry.ts:63

Check if a backend is registered (eagerly or lazily)

string

boolean


isMultiPartContent(content): content is ContentPart[]

Defined in: types/guards.ts:17

Type guard: checks if MessageContent is multi-part array

MessageContent

content is ContentPart[]


isRecoverableErrorCode(code): boolean

Defined in: types/errors.ts:68

Check if an error code is recoverable

ErrorCode

boolean


isTextContent(content): content is string

Defined in: types/guards.ts:12

Type guard: checks if MessageContent is plain string

MessageContent

content is string


isToolDefinition(tool): tool is ToolDefinition<unknown>

Defined in: types/guards.ts:5

Type guard: checks if a ToolDeclaration has an execute function (i.e., is a ToolDefinition)

ToolDeclaration

tool is ToolDefinition<unknown>


listBackends(): string[]

Defined in: registry.ts:68

List all registered backend names (eager + lazy)

string[]


listConfigs(name): string[]

Defined in: registry.ts:109

List all active config IDs for a backend

string

string[]


messagesToPrompt(messages): string

Defined in: utils/messages.ts:5

Convert our Message[] to a flat prompt string (for CLIs that accept text)

Message[]

string


registerBackend<TOptions>(name, factory): void

Defined in: registry.ts:47

Register a custom backend factory

TOptions = unknown

string

BackendFactory<TOptions>

void


registerLazyBackend(name, loader): void

Defined in: registry.ts:158

Register a lazy-loaded backend. The loader is called once on first use, then the resulting factory is cached in the main registry. Use this for backends that have heavy dependencies (peer deps, native modules).

string

() => Promise<BackendFactory<unknown>>

void


resetRegistry(): void

Defined in: registry.ts:77

Reset registry to initial state (for testing)

void


unregisterBackend(name): boolean

Defined in: registry.ts:58

Unregister a backend (primarily for testing)

string

boolean


zodToJsonSchema(schema): Record<string, unknown>

Defined in: utils/schema.ts:5

Convert a Zod schema to JSON Schema. Detection order: toJSONSchema() (Zod v4) → jsonSchema() (Zod v3.24+) → _def extraction (Zod v3 legacy).

ZodType

Record<string, unknown>