Skip to content

Reference ​

Every config key, run option, response field, stream event, telemetry code, error class and environment variable. The guides explain; this page lists.

On this page: AgentConfig · Run options · Response · Stream events · Tool definition · Telemetry codes · Errors · Environment variables

The exported type declarations in src/types/ are the source of truth.

AgentConfig ​

KeyMeaningGuide
name, descriptionIdentity. A parent sees description when this agent is a worker.Sub-agents
instructionsThe system prompt. Keep it stable.Agents
modelA model string, a ModelSpec or a ModelProvider.* value. Without it, the saved choice or the list default.Models and providers
subagentModelOlder name of dynamicSubagents.model.Migration
apiKey, baseUrl, headersConnection overrides for this agent.Models and providers
toolsA record { name: tool }, or an array of tools (ToolDefinition).Tools
subagentsFixed sub-agents: an Agent, { name, description, agent }, or data (SubAgentSpec: { name, description, instructions, model?, tools? }, which runs on the worker model when it names none).Sub-agents
dynamicSubagentsWorkers the model starts, persistent workers, scheduled actions (DynamicSubagentsConfig). Keys below.Sub-agents
thinkingThe reasoning level, or { level, budgetTokens } (ThinkingOption). thinkingLevel is the older name.Reasoning and caching
cache"implicit", "5m", "30m", "1h" or "12h" (CacheOption), where the provider supports it.Reasoning and caching
serviceTier"flex" or "priority".Reasoning and caching
googleTierHow long Google keeps a conversation: "free" (23 h, default) or "paid" (54 days).Models and providers
sessionIdThe session key. Must match /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/ when saved to a folder.Sessions
maxTurnsModel calls per run. 0 or omitted means unlimited.Limits and retries
statelessClear the conversation around every run.Agents
midSessionWhat to do with a message while busy. Keys below.Streaming and steering
persistWhere to save sessions. { dir?, file?, onPersistError?, allowStateless?, loadLimits? }. loadLimits: { maxMessages?, maxBytes? } refuses bigger saved sessions; no limit by default.Sessions
resume"automatic" (default) or "explicit": whether a run that a crash cut off continues when the agent is created.Sessions
homeThe folder for everything the SDK stores. Code only.Sessions
toolChoice"auto", "none", "required", "validated" or { tool }.Tools
maxOutputTokensA cap on the output of one model call.Models and providers
outputA schema for structured output: Zod, JSON Schema or { name, schema, ... }.Agents
retryHow one provider call is retried.Limits and retries
runRetriesHow often a whole run that failed for a transient reason is tried again. Default 3, 0 is off.Limits and retries
onFailure"auto", "rollback" or "keep".Limits and retries
fetch, envA custom fetch (for provider calls and for the media URLs the SDK downloads), and per-agent environment overrides for keys.Models and providers
fileAccess{ roots }. Where local files may be read.Security
captureRaw"redacted" (default), true or false. What res.raw keeps.Security
budget, limits, usageLimitCaps. Keys below.Limits and retries
promptsReplace single SDK prompts. An unknown name or empty text throws ConfigError. Workers inherit it.Prompts
telemetry{ persist: true } appends telemetry events to files. Off by default.Errors and telemetry
hooks{ beforeTool, afterTool, beforeRequest, onYield }. Workers inherit them. beforeRequest may return { history } to replace the saved conversation; beforeRequest and onYield get ctx.inputTokens and ctx.contextWindow.Tools

Precedence: explicit config beats the environment. A per-run option beats the agent's default, and objects are merged key by key.

dynamicSubagents ​

KeyMeaning
enabledDefault true when the object is present.
allowScheduledActionsDefault false. Turns on scheduled actions.
modelThe worker model.
maxSpawnWorkers open at once. No limit by default. A number of 1 or more is a cap.
maxDepthLevels of workers below the agent. No limit by default. A whole number of 1 or more is a cap.
workerBudget{ maxCostUsd?, maxTotalTokens? }. The cap of each chat worker's run. None by default.
scheduledActionBudgetThe same shape. The cap of each scheduled run. None by default.
thinkingLevelThe workers' reasoning level.
toolsThe pool of tools workers may be granted.
workerTimeoutMsScheduled actions only: the longest a run may take. No limit by default. 0 and Infinity mean none.

timeout and modelMaySetTimeout were removed and throw ConfigError.

midSession ​

KeyMeaning
whenBusy"steer", "queue" or "auto" (default). mode is the older name.
maxQueuedWaiting follow-ups. Default 20.
maxSteersWaiting steers. Default 20.

Limits and caps ​

KeyMeaning
budgetPer run, workers included: maxCostUsd, maxTotalTokens, maxDurationMs, maxTotalSubagents.
limits (AgentRunLimits)maxTurns, deadlineMs, maxTotalTokens, maxToolCallsPerRun, requestTimeoutMs (300 s), firstByteTimeoutMs (120 s), streamIdleTimeoutMs (300 s).
usageLimitThe whole chat for its whole life, workers included: maxCostUsd, maxTotalTokens. Throws BudgetExceededError ("Usage limit reached").

Everything is unlimited until you set it, except the three network timeouts. 0 or Infinity turns a timeout off. See Limits and retries.

Run options ​

Used by agent.run(prompt, options), agent.stream(prompt, options) and agent.ask(prompt, stream?).

OptionMeaning
thinkingThe reasoning level for this run.
streamMake run return a stream that you can also await.
signalCancels the provider call, tools and workers.
sessionIdWhich in-memory session to use.
additionalContextContext added to this user turn. It is not added to instructions.
requestIdMakes the call safe to repeat. See Streaming and steering.
enqueue"steer", "queue" or "interrupt" while the agent is busy.
headersExtra request headers.
onDelta, onThinkingDelta, onEvent, onTurnCallbacks.
toolChoice, maxOutputTokens, retry, fetch, envThe same as in the config.
thinkingAsAnswerFallbacktrue makes reasoning-only output the answer when a model sends no answer text. Default false.

Response ​

An AgentResponse has: text, parsed (structured output), thinking, thoughtSignature, toolCalls, toolResults, subagents, usage, responseId, model, provider, finishReason, rawFinishReason, durationMs, raw (according to captureRaw) and turns. A failed run attaches the same shape as err.partial.

finishReason is one of stop, tool_calls, length, content_filter, refusal, max_turns, stopped (a tool called ctx.stop) or error. A finish reason the SDK does not know becomes error, and the original stays in rawFinishReason.

The fields of usage and the report from agent.usageReport() are in Usage and cost.

Worker results ​

AgentResponse.subagents has one entry per worker call, and a dynamic worker's reply carries the same shape as metadata.

FieldMeaning
name, role, taskWho ran and what it was asked.
model, provider, durationMs, turns, usageHow it ran and what it cost.
text, thinking, toolCalls, finishReason, responseIdWhat it answered.
isError, errorSet when the worker failed.
trackingId, sessionId, parentSessionIdIdentity and lineage. The tracking id is NAME-<32 hex>.
rawThe wire exchange, according to captureRaw.
stepsThe step log, one SubAgentStep per entry.

A SubAgentStep is { turn, type, name?, text?, thinking?, thoughtSignature?, isError?, timestamp, partial? }. type is "assistant", "tool_call" or "tool_result". partial is true while the worker is still streaming that step. agent.track(id) returns the steps live.

finishReason is "stopped" when a tool ended the run with ctx.stop(reason). It is "max_turns" when a finite maxTurns stopped the run with tool calls still pending. An agent.max_turns_truncated warning then names the dropped tools.

Stream events ​

Every event (a StreamEvent) has a type. The other fields depend on it.

typeWhenFields used
startThe request begins.raw
text_deltaAnswer text.delta, partialText
thinking_deltaReasoning.thinkingDelta, partialThinking
tool_call_completeThe model finished a tool call.toolCall
tool_start, tool_result, tool_endYour tools run: the batch starts, one result, the batch ends.toolCalls, toolResult, toolResults
subagent_deltaA worker streams.subagentTrackingId, delta, thinkingDelta, partialText, partialThinking
subagent_completeA worker finished.subagent
steer_injectedA steer() was applied.injectedPrompt
queuedA follow-up was queued.queuedPrompt, queueLength
usageToken counts.usage
doneThe end.finishReason, rawFinishReason, responseId, usage
errorThe run failed.error

The StreamEventType type also lists text_start, text_end, thinking_start, thinking_end, tool_call_start and tool_call_delta, and StreamEvent has a schemaVersion field. They are reserved: the SDK does not send them today.

Tool definition ​

tool({...}) takes these keys: name, description, input, parameters, strict, timeoutMs, maxTries, maxAttempts, maxConcurrency, idempotent, repeatable, replay, maxResultChars, redactError, redact and execute. __brand is internal. Never set it.

Every option does something. The executor enforces input or parameters (parameters wins if both are set), timeoutMs, maxTries or maxAttempts, maxConcurrency, idempotent, repeatable, replay (read by crash recovery), maxResultChars and redactError or redact. strict goes to the provider.

execute(args, ctx) gets a ToolExecutionContext with:

FieldMeaning
toolCallId, agentName, sessionIdIdentity of the call.
signalAborts when the run is cancelled. Pass it to I/O.
emitSends progress events.
onSubagentEventReceives events from workers.
stop(reason)Ends the run after this batch with finishReason: "stopped". The reason is the call's result. It throws and is never retried.
log(message, data?)Writes to the call's log file tool-logs/<n>-<tool>.ndjson when the agent saves to a folder. Otherwise it does nothing.

A result carries logFile. Defaults: 1 attempt (3 when idempotent), 20,000 result characters, 8 tools at once, and the third identical call in a row is answered with repeat_blocked.

Messages and parts ​

A Message is { role, content, name?, thoughtSignature?, providerSteps? }. role is "system", "user", "assistant" or "tool". content is a string or a list of parts. providerSteps is { provider, steps }: a provider's raw output for one assistant turn, kept so a resent history is identical to what the provider produced (Google's steps, Anthropic's signed thinking blocks). Treat it as opaque.

A ProviderContext is { systemPrompt?, messages, tools? }.

An agent's conversation is agent.context.messages (for a named session, agent.session(id).context.messages), and its system prompt is agent.context.systemPrompt. Read them, but do not edit them: change a conversation with importSession, reset() or a new run. A saved session notices a message replaced by another object (messages[3] = { ... }) or a new list, and saves it at the next step, but not a field changed inside a message object.

PartFields
text (TextPart)text, thoughtSignature?
thinking (ThinkingPart)thinking, thoughtSignature?
image (ImagePart)image, mimeType?, resolution? (MediaResolution)
audio (AudioPart)audio, mimeType?
video (VideoPart)video, mimeType?, resolution?, processing? (VideoProcessing)
file (FilePart)file, mimeType?, filename?
tool_call (ToolCallPart)id, name, arguments, rawArguments?, thoughtSignature?, callId?
tool_result (ToolResultPart)id, name, result, isError?, logFile?, stopped?, parts?

image, audio, video and file take a URL, a local path, a data URL, base64, a Uint8Array or an ArrayBuffer. See Media input.

A tool call the model made is a ToolCallRecord: { id, name, arguments, rawArguments?, thoughtSignature?, callId? }. callId is the provider's pairing id when it differs from id. Its result is a ToolResultRecord: { id, name, result, isError?, durationMs?, logFile?, stopped?, parts? }. res.toolCalls and res.toolResults hold them. durationMs covers the attempts and the retry waits, not the time spent queued or checking the input.

Model shapes ​

A ModelSpec describes one model: id, provider, name, contextWindow and maxOutputTokens (the same as limit.context and limit.output), capabilities, and optionally description, family, api, limit, cost, modalities, reasoning, reasoning_options, tool_call, attachment, knowledge, release_date, last_updated, pricing, compat and raw.

ModelCapabilities has these optional flags: supportsThinking, supportsThinkingBudget, supportsThinkingLevel, supportsImplicitCaching, supportsExplicitCaching, supportsLongCacheRetention, supportsParallelToolCalls, supportsStreaming, supportsStructuredOutput, supportsReasoningToggle, supportsReasoningEffort and modalities (a list of "text", "image", "audio", "video" and "pdf").

Look a model up with getModelFromCatalog, and add your own with registerModel. getModelFromCatalog returns undefined for a model the catalog does not know. resolveModel(model).modelSpec never does: for an unknown model it is a permissive placeholder (createGenericModelSpec: a 128,000-token context, 8,192 output tokens, every thinking level allowed), not the model's real limits. See Models and providers.

Helper functions ​

FunctionDoes
createSessionId(prefix?)A random session id (<prefix>-<uuid> with a prefix), at most 64 characters.
withRetries(fn, options?)Runs fn again after a transient failure. Defaults: 2 retries, a 5 second delay cap, a 30 second retry budget. A Retry-After header is honored inside that budget. An abort is never retried. Options: maxRetries, maxRetryDelayMs, retryBudgetMs, baseDelayMs, signal, label.
isTransientError(error)true for the failures withRetries retries.
normalizeMediaInput(input, mimeType?, { signal?, fetch? }?)Resolves a media input to { mimeType, base64Data, dataUrl }. A URL is downloaded with fetch (the global one when unset) and stops when signal aborts.
inferMimeType(path, fallback?), sniffMimeType(bytes)The MIME type from a file name, or from the first bytes.
ensureCustomProvider(prefix, options?), getProvider(id), normalizeProviderPrefix(prefix)Create or fetch the provider for a prefix. See Provider notes.

Two retry layers exist. retry repeats one failed provider call (seconds). runRetries repeats a whole failed run from where it stopped (minutes, with agent.run_retry on the bus). See Limits and retries.

Telemetry codes ​

Subscribe with telemetryBus.onEvent((e) => e.code). Each event has level, code, message and data.

Configuration and providers ​

CodeMeaning
config.thinking_budget_ignoredthinking.budgetTokens is not forwarded.
config.not_editableAgent.fromConfig got keys other than model, instructions and tools. They were ignored (data.fields).
config.file_invalid, config.file_restored, config.file_ignored_key, config.saved_model_ignoredProblems with <home>/configs.json: invalid or another version (data.reason), restored from its backup, an entry that is unknown, invalid or hidden (data.key, data.reason), or a saved model that left your list.
provider_warningA provider option was dropped, for example thinking: "none" on Google.
cache_clampA provider's cached-token count was larger than its input count and was reduced to it.
interaction_chain_evicted, interaction_chain_ttl_expired, interaction_history_shrinkGoogle chaining: the server chain was dropped or expired, or the input tokens fell.
stream_buffer_overflow, stream_event_oversizeA stream buffer limit was hit.
catalog_cache_write_failedThe model catalog could not be saved.
embedding_models_refresh_failed, embedding_models_cache_write_failedOpenRouter's embedding model list could not be refreshed (the saved copy is used) or saved (it stays in memory).
decision_models_refresh_failed, decision_models_cache_write_failedThe same, for decision models.

Runs ​

CodeMeaning
agent.max_turns_truncatedA run stopped at maxTurns with tool work pending.
turn.thinkingThe full reasoning text of a turn. Bus only.
agent.run_retryA failed run is being tried again (attempt, of, delayMs).
agent.resumed, agent.resume_failedA cut-off run was resumed, or resuming it (or a waiting prompt) failed.
agent.duplicate_requestA requestId that was already submitted came again.
agent.request_id_reusedThe same requestId came with a different prompt.
agent.yield_continuedAn onYield hook continued the run.
hook.errorAn afterTool hook threw. The original result was kept.
worker.invalidA saved worker.json is damaged. That worker is skipped.
session.local_media_pathsAn imported session points at local files and fileAccess.roots is not set.
session.media_write_failedsaveSessionDir could not write a media file. The media stays inside the session file.
session.journal_corruptjournal.ndjson is damaged before its last line. Replay stopped there and kept what came before.

Tools ​

tool.call_started, tool.attempt_started, tool.progress, tool.attempt_failed, tool.retry_scheduled, tool.call_succeeded, tool.call_failed, tool.call_timed_out, tool.call_aborted, tool.call_stopped (a tool called ctx.stop), tool.call_blocked (a hook blocked it) and tool.call_interrupted (crash recovery did not run it again).

Each has toolCallId, toolName, agentName and sessionId. Failures add the full error. A call_started with no ending event was running when the process died. Attach a sink to keep them.

Concurrency and scheduled actions ​

CodeMeaning
concurrency.queuedA provider call waited for a free slot (provider, waiting, active, paused). Only with the concurrency setting.
concurrency.pausedA provider answered 429 with a Retry-After. No new calls to it for ms.
scheduled_action.created, scheduled_action.updated, scheduled_action.started, scheduled_action.ready, scheduled_action.failed, scheduled_action.delivered, scheduled_action.missed, scheduled_action.skipped, scheduled_action.deleted, scheduled_action.invalid, scheduled_action.store_corrupt, scheduled_action.errorThe life of a scheduled action. Payloads are in Scheduled action files.

Errors ​

All extend AgentAccelError, which has code, retryable and context.

ClassRaised when
ConfigErrorA missing key or address, no model or a bad model string, a removed provider, Gemini 1.x or 2.x, invalid config, or a steer, queue or enqueue call that midSession forbids (before any network call).
ProviderErrorThe API failed, or it answered HTTP 200 with something that is not a reply (an empty object, a list, no choices). That is treated like a 502 and is retryable. An error object sent with HTTP 200 is reported as the provider's own error, with its message and code. A reply over the size cap (64 MB for chat) is not retryable. code is "provider" ("incomplete_stream" for a cut stream). retryable says whether a retry can help. Also statusCode, provider, model, providerCode (the provider's own code) and retryAfterMs, which are not enumerable.
TimeoutErrorA request, first-byte or idle timeout, also inside a provider call or a generator (images, videos, embeddings, decisions). Retryable. Your own abort is an AbortError.
BudgetExceededErrorbudget, or limits.maxTotalTokens, deadlineMs or maxToolCallsPerRun, was exceeded. Partial usage is attached.
ToolErrorA tool failed in a way that reaches the caller.
ValidationErrorStructured output or scheduled-action input did not validate. An input the model cannot take, before any network call. An empty prompt. A call made the wrong way: a streaming option on steer, queue or interrupt(message), steer for a session other than the running one, resume() while busy, or a full queue. A bad session id, registerModel spec or media input.
SettingNotEditableErrorsetConfig on a hidden setting. A ConfigError, never retried. key names it.
ModelNotAllowedErrorA model outside your setModels list. A ConfigError, never retried. model and allowed say what was asked and what is available.
ThinkingLevelErrorA level the model does not support. A ConfigError. allowedLevels lists the valid ones.
SubAgentModelErrorWorkers or scheduling without a worker model.
SessionLoadErrorA valid session is over the load limits you set (persist.loadLimits, or the limits argument of loadSessionDir/loadSessionFile). It is never quarantined.
SecurityPolicyError, RemoteFetchErrorA file root or private-address policy refused a path or URL.

isAbortError(err) is true only when name === "AbortError". It never reads message text, and a signal's aborted flag alone is not checked.

Environment variables ​

The environment holds API keys and nothing else. Every other option is a setting in code: see Settings. The older variables are listed in Migration.

VariablePurpose
GEMINI_API_KEY, GOOGLE_API_KEY, GOOGLE_GENAI_API_KEYThe Google key. Checked in this order.
OPENAI_BASE_API_KEY, OPENAI_API_KEYThe OpenAI key. Checked in this order.
ANTHROPIC_API_KEYThe Anthropic key.
OPENROUTER_API_KEYThe OpenRouter key.
<PREFIX>_API_KEY, <PREFIX>_BASE_API_KEYThe key of any OpenAI-compatible service (for PREFIX/model), such as GROQ_API_KEY. Checked in this order. Local services may have none.

The library reads process.env only for keys. Pass env: { ... } in the config or a run option to override a key for one agent. It is read first, with the same names in the same order. The Google names count only for google/ and gemini/ models, never for a custom prefix such as googleproxy/.

Generators ​

FunctionReturnsGuide
generateImage(options)ImageResult. Also listImageModels, getImageModel, image.edit and imageTool.Images
generateVideo(options)VideoResult. Also listVideoModels, getVideoModel, refreshOpenRouterVideoModels, video.edit and resumeVideo.Videos
generateEmbedding(options)EmbeddingResult. Also listEmbeddingModels, getEmbeddingModel, refreshOpenRouterEmbeddingModels, cosineSimilarity and EMBEDDING_TASKS.Embeddings
generateDecision(options)DecisionResult. Also listDecisionModels, getDecisionModel, refreshOpenRouterDecisionModels and DECISION_QUESTION_TYPES.Decisions

Released under the MIT License.