zidane/ errors
The typed errors an agent run can throw, with the helpers that classify and convert provider failures.
import { … } from 'zidane/errors'src/errors-entry.ts
Use zidane/errors to branch on why a run failed without importing the whole package. agent.run() wraps provider failures in these classes, so you match on instanceof instead of parsing provider strings. The entry also holds matchesContextExceeded(), toTypedError(), errorMessage() and OperationTimeoutError. See Errors for retry and budget behavior. AgentLengthResumeExhaustedError and describeProviderLimit() come from the root zidane entry.
import { createAgent } from 'zidane'
import { AgentAbortedError, AgentBudgetExceededError, AgentContextExceededError } from 'zidane/errors'
import { basic } from 'zidane/presets'
import { anthropic } from 'zidane/providers/anthropic'
const agent = createAgent({ ...basic, provider: anthropic(), behavior: { maxCostUsd: 0.5 } })
try {
await agent.run({ prompt: 'Refactor the largest file in this repo.' })
}
catch (err) {
if (err instanceof AgentBudgetExceededError)
console.error(`Hit the ${err.limit} cap at ${err.actualValue}`)
else if (err instanceof AgentContextExceededError || err instanceof AgentAbortedError)
console.error(err.message)
else
throw err
}Functions#
errorMessageFunction#
Extract a printable message from an unknown thrown value.
Standardizes the err instanceof Error ? err.message : String(err) idiom
that every catch (err) block was reaching for.
function errorMessage(err: unknown): stringParameters
| Name | Type | Description |
|---|---|---|
| err | unknown | Thrown value of any type. |
Returns
stringmatchesContextExceededFunction#
Return true when message matches any of the known "context window exceeded"
phrasings. Safe for '' / non-strings (returns false).
function matchesContextExceeded(message: unknown): booleanParameters
| Name | Type | Description |
|---|---|---|
| message | unknown | Error message, or any value. Non-string values never match. |
Returns
booleantoTypedErrorFunction#
Convert a ClassifiedError + underlying cause into the matching typed error instance.
function toTypedError(
classification: ClassifiedError,
provider: string,
cause: unknown,
): AgentAbortedError | AgentContextExceededError | AgentProviderError | AgentToolPairingErrorParameters
| Name | Type | Description |
|---|---|---|
| classification | ClassifiedError | Classification returned by the provider. |
| provider | string | Name of the provider that raised the error. |
| cause | unknown | Original error, attached as the typed error's |
Classes#
AgentAbortedErrorClass#
Thrown when a run is aborted by the consumer via agent.abort() or an external AbortSignal.
class AgentAbortedError extends ErrorConstructor
new AgentAbortedError(message?: string, options?: { cause?: unknown })Creates the error.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| message? | string | 'Agent run aborted' | Error message. Defaults to |
| options? | { cause?: unknown } | Optional |
Returns
Properties
| Name | Type | Description |
|---|---|---|
| codereadonly | 'aborted' | Stable error code, always |
AgentAuthErrorClass#
Thrown when a credential cannot be resolved, refreshed or was refused:
carries the structured AuthFailure a surface needs to offer
"sign in again" for the exact provider and account.
class AgentAuthError extends ErrorConstructor
new AgentAuthError(message: string, auth: AuthFailure, options?: { cause?: unknown })Creates the error.
Parameters
| Name | Type | Description |
|---|---|---|
| message | string | Error message, with guidance. |
| auth | AuthFailure | Which sign-in failed and why. |
| options? | { cause?: unknown } | Optional |
Returns
Properties
| Name | Type | Description |
|---|---|---|
| authreadonly | AuthFailure | Which sign-in failed and why. |
| codereadonly | 'auth_failed' | Stable error code, always |
AgentBudgetExceededErrorClass#
Thrown by the loop when a run's cumulative cost, token consumption, or
wall-clock elapsed time crosses a ceiling configured on
AgentBehavior.maxCostUsd / AgentBehavior.maxTotalTokens /
AgentBehavior.maxWallMs. Acts as a programmable circuit
breaker for unattended runs — without this, the only built-in safety net
is AgentBehavior.maxTurns, which doesn't bound a single very
expensive turn (large context, deep reasoning).
The breach is checked after each turn completes (post-turn:after),
so the run may exceed the budget by one turn's worth of usage before
tripping. Callers wanting a tighter pre-turn estimate should layer their
own check on top of the usage hook.
The harness treats this the same way as AgentAbortedError: the
session run is finalized as 'aborted', persisted stats reflect what
was actually consumed, and the parent agent re-throws so a caller's
try/catch can branch on err instanceof AgentBudgetExceededError
without string-sniffing.
class AgentBudgetExceededError extends ErrorConstructor
new AgentBudgetExceededError(
options: { actualValue: number; cause?: unknown; limit: 'cost' | 'tokens' | 'wallClock'; limitValue: number },
)Creates the error.
Parameters
| Name | Type | Description |
|---|---|---|
| options | { actualValue: number; cause?: unknown; limit: 'cost' | 'tokens' | 'wallClock'; limitValue: number } | The tripped |
Returns
Properties
| Name | Type | Description |
|---|---|---|
| actualValuereadonly | number | Actual consumed value at the moment the cap was crossed (same units as |
| codereadonly | 'budget_exceeded' | Stable error code, always |
| limitreadonly | 'cost' | 'tokens' | 'wallClock' | Which ceiling tripped. |
| limitValuereadonly | number | The configured cap (USD for |
AgentContextExceededErrorClass#
Thrown when the model or provider signals that the context window was exceeded. Downstream consumers should catch this, prune history, and retry.
class AgentContextExceededError extends ErrorConstructor
new AgentContextExceededError(message: string, options: TypedErrorOptions)Creates the error.
Parameters
| Name | Type | Description |
|---|---|---|
| message | string | Error message. |
| options | TypedErrorOptions | Provider name (required), plus optional |
Returns
Properties
| Name | Type | Description |
|---|---|---|
| codereadonly | 'context_exceeded' | Stable error code, always |
| providerreadonly | string | Name of the provider that raised the error. |
| providerCode?readonly | string | Upstream error code, when the provider surfaced one. |
AgentProviderErrorClass#
Thrown when the provider returns a non-context error (auth, rate limit, server error, etc.). Catch-all for unclassified provider failures.
class AgentProviderError extends ErrorConstructor
new AgentProviderError(message: string, options: TypedErrorOptions)Creates the error.
Parameters
| Name | Type | Description |
|---|---|---|
| message | string | Error message. |
| options | TypedErrorOptions | Provider name (required), plus optional |
Returns
Properties
| Name | Type | Description |
|---|---|---|
| codereadonly | 'provider_error' | Stable error code, always |
| limit?readonly | ProviderLimit | The rate limit, spent quota or overload behind the error, when that is what it was. |
| providerreadonly | string | Name of the provider that raised the error. |
| providerCode?readonly | string | Upstream error code, when the provider surfaced one. |
| retryable?readonly | boolean | Whether a retry with backoff is likely to succeed. See
|
AgentToolNotAllowedErrorClass#
Describes a tool call blocked because the union of allowed-tools across the
active skills does not permit it. The gate builds it but never throws it.
Built by the allowed-tools gates registered on tool:gate and
mcp:tool:gate. The gate sets block = true and copies this error's
message into reason, so consumers that do not look at this typed error
still get a useful string.
class AgentToolNotAllowedError extends ErrorConstructor
new AgentToolNotAllowedError(
options: { activeSkills: readonly string[]; allowedUnion: readonly string[]; cause?: unknown; displayName: string; toolName: string },
)Creates the error.
Parameters
| Name | Type | Description |
|---|---|---|
| options | { activeSkills: readonly string[]; allowedUnion: readonly string[]; cause?: unknown; displayName: string; toolName: string } | Tool names, the allowed-tools union, the active skill names, and an optional |
Returns
Properties
| Name | Type | Description |
|---|---|---|
| activeSkillsreadonly | readonly string[] | Names of the skills currently active when the block fired. |
| allowedUnionreadonly | readonly string[] | Flattened union of |
| codereadonly | 'tool_not_allowed' | Stable error code, always |
| displayNamereadonly | string | Aliased / wire name the LLM saw. |
| toolNamereadonly | string | Canonical tool name the agent tried to call. |
AgentToolPairingErrorClass#
Thrown by the pre-send pairing repair when AgentBehavior.strictToolPairing
is true and ensureToolResultPairing would otherwise patch over
corruption. Strict mode opts into fail-fast for training-data collectors and
any consumer that prefers to bail out rather than ship a transcript carrying
a SYNTHETIC_TOOL_RESULT_PLACEHOLDER.
The repairs field carries every repair the loop would have made — useful
for postmortems and for surfacing exactly which transcripts were rejected.
Note: callers consuming the chat layer (TUI/SDK presets) typically leave
strictToolPairing off so user-facing sessions auto-heal instead of
crashing.
class AgentToolPairingError extends ErrorConstructor
new AgentToolPairingError(
options: { cause?: unknown; message: string; provider?: string; providerCode?: string; repairs: readonly { callId?: string; messageIndex: number; mode: string }[] },
)Creates the error.
Parameters
| Name | Type | Description |
|---|---|---|
| options | { cause?: unknown; message: string; provider?: string; providerCode?: string; repairs: readonly { callId?: string; messageIndex: number; mode: string }[] } | Message, optional |
Returns
Properties
| Name | Type | Description |
|---|---|---|
| codereadonly | 'tool_pairing_corruption' | Stable error code, always |
| provider?readonly | string | Provider whose wire format the corruption would have hit. |
| providerCode?readonly | string | Upstream error code when the corruption was detected from a 400 response. |
| repairsreadonly | readonly { callId?: string; messageIndex: number; mode: string }[] | Repairs the harness would have performed had strict mode been off.
Preserves the full diagnostic so consumers can route to telemetry,
|
OperationTimeoutErrorClass#
Error thrown when an operation exceeds its configured time limit.
class OperationTimeoutError extends ErrorConstructor
new OperationTimeoutError(operation: string, timeoutMs: number, message?: string)Creates an error for an operation that exceeded its time limit.
Parameters
| Name | Type | Description |
|---|---|---|
| operation | string | Name of the operation that timed out. |
| timeoutMs | number | Time limit that was exceeded, in milliseconds. |
| message? | string | Custom message. Defaults to |
Returns
Properties
| Name | Type | Description |
|---|---|---|
| codereadonly | 'operation_timeout' | Stable error code, always |
| operationreadonly | string | Name of the operation that timed out. |
| timeoutMsreadonly | number | Time limit that was exceeded, in milliseconds. |
Constants#
CONTEXT_EXCEEDED_MESSAGE_PATTERNSConstant#
Regex patterns matching common "context window exceeded" messages across providers.
Use matchesContextExceeded to test a free-form error message against them.
Provider authors can also compose these into their own classifyError fallbacks.
const CONTEXT_EXCEEDED_MESSAGE_PATTERNS: readonly RegExp[]Interfaces#
AuthFailureInterface#
Which sign-in failed, enough for a surface to offer fixing it. JSON-safe: it is persisted with the run.
interface AuthFailureProperties
| Name | Type | Description |
|---|---|---|
| accountId? | string | Stable id of the account that failed, when the credential has one. |
| accountLabel? | string | That account's name, when it has one. |
| holderPid? | number |
|
| kind | AuthFailureKind | Why it failed. |
| provider | string | The provider name as the provider calls itself ( |
| providerId? | string | Credentials key / OAuth flow id ( |
| source | 'provider' | 'mcp' | 'integration' | What signs in: a model provider, an MCP server, an integration. |
ClassifiedErrorInterface#
Structured classification returned by Provider.classifyError
interface ClassifiedErrorProperties
| Name | Type | Description |
|---|---|---|
| kind | ClassifiedErrorKind | Category of the error. |
| limit? | ProviderLimit | Set when the provider refused for a rate limit, a spent quota or overload; |
| message? | string | Optional human-readable message override. Falls back to the underlying error's message. |
| providerCode? | string | Upstream error code as surfaced by the provider (e.g. |
| retryable? | boolean | Hint that the error is transient and a retry with backoff is reasonable (e.g. 429, 5xx, truncated stream). Omitted when the provider can't decide; callers should default to "do not retry" when absent to avoid hammering terminal failures (auth, invalid request). |
Types#
AuthFailureKindType#
Why a sign-in stopped working:
expired: the refresh failed for a reason that signing in again fixes.revoked: the grant was revoked or rejected (invalid_grant).missing: no credential is stored (or the pinned account is gone).busy: another process holds the refresh lock and has not let go.network: the refresh could not reach the provider; retrying may do.rejected: the provider refused the credential it was sent (a 401).
type AuthFailureKind =
| 'expired'
| 'revoked'
| 'missing'
| 'busy'
| 'network'
| 'rejected'ClassifiedErrorKindType#
Kind of classified provider error
type ClassifiedErrorKind =
| 'context_exceeded'
| 'provider_error'
| 'aborted'
| 'tool_pairing_corruption'