Reference
Errors
Exception hierarchy exported from @alter-ai/alter-sdk.
Every public exception thrown by the SDK extends AlterSDKError. The hierarchy mirrors the Python SDK one-for-one — same class names, same semantics, same fields.
Version compatibility: this page tracks the latest published SDK line.
CallerAgentMismatchError,CallerAgentResolutionError,KeyExpiredError,KeyRotationExpiredError,KeyInactiveError, andKeyAppNotFoundErrorrequire@alter-ai/alter-sdk>=0.23.1. Version 0.22.0 does not export them; upgrade before importing or checkinginstanceofagainst these classes.MemoryIsolationError, itscodeproperty and theMEMORY_ISOLATION_CODESvocabulary require@alter-ai/alter-sdk>=0.28.0. Version 0.27.0 and earlier do not export them.
For the canonical error code → exception class mapping and recovery guidance, see Errors.
import { NoDelegatedGrantError, QuotaExceededError, RateLimitError, ScopeReauthRequiredError,} from "@alter-ai/alter-sdk";
const makeRequest = () => app.proxyRequest({ method: "GET", url: url, provider: "<provider-id>" });
// Bounded retries on a throttle: honour `retryAfter` when the response carried// one, otherwise back off exponentially; add jitter so callers spread out.async function withRateLimitRetry<T>( call: () => Promise<T>, maxAttempts = 5,): Promise<T> { for (let attempt = 1; ; attempt++) { try { return await call(); } catch (error) { if (!(error instanceof RateLimitError) || attempt >= maxAttempts) { throw error; } // `scope` says WHICH ceiling was hit: spreading load across keys helps // an `api_key` throttle and does nothing for an `organization` one. It is // undefined for a non-JSON 429 from an intermediary. console.warn(`Throttled on ${error.scope ?? "an unidentified limiter"}`); const waitSeconds = error.retryAfter ?? Math.min(60, 2 ** attempt); const jitterSeconds = Math.random() * waitSeconds * 0.2; await new Promise((r) => setTimeout(r, (waitSeconds + jitterSeconds) * 1000), ); } }}
try { await withRateLimitRetry(makeRequest);} catch (error) { if (error instanceof NoDelegatedGrantError) { const session = await app.createConnectSessionForError(error); redirectUser(session.connectUrl); return; } if (error instanceof ScopeReauthRequiredError) { // The user must re-authorize with wider provider scopes. console.warn(`Missing scopes: ${error.missingScopes?.join(", ")}`); } if (error instanceof QuotaExceededError) { // Request-quota policy denial — the SDK never auto-retries it. await new Promise((r) => setTimeout(r, (error.retryAfter ?? 60) * 1000)); return makeRequest(); } throw error;}Every name imported above is used by the snippet, so it compiles as-is under
noUnusedLocals. The classes documented below that it does not branch on
(AlterSDKError, GrantNotFoundError, GrantNotDelegableError, …) are
deliberately not imported here — add them when you add a branch for them.
NonProxyDisabledError
Section titled “NonProxyDisabledError”No active credential-release exception covers the caller and the provider or credential, or the organization has disabled all release. The message and details identify the missing caller, grant/provider and credential type.
Use proxy execution. Only a session-authenticated organization administrator can accept the scoped risk
through the portal; see the advanced reference.
The backend code is non_proxy_disabled (HTTP 403).
Class hierarchy
Section titled “Class hierarchy”AlterSDKError— root of the hierarchy. Every other exception extends this.AlterValueError— input validation failed at the SDK boundary. Distinct fromBackendErrorso callers can branch on “I passed something bad” vs “the backend said no.”MemoryIsolationError— the private-memory identity or partition could not be verified. A direct child ofAlterSDKError, thrown locally bymemoryScope(),ScopedMemoryStoreandverifyIdentityAssertion(), never from an HTTP response. Branch oncode(aMemoryIsolationCode, one of the exportedMEMORY_ISOLATION_CODES);details.reasoncarries a coarse category formemory_assertion_invalid. See Errors for the code table.
Backend errors
Section titled “Backend errors”BackendError— generic backend failure.details.status_codeis populated when an HTTP status code is the proximate cause.ServerFeatureUnsupportedError— extendsBackendError; no extra fields. The Alter backend predates a feature the call used, so the SDK throws instead of returning a session that would not do what was asked. OncreateManagedSecretConnectSession()(App and Agent),details.featurenames what is missing:managed_secret_connect_provider— the backend still requirestemplateSlugwhen onlyproviderwas sent, refuses an option it does not know (provider,agent,requestedGrant,grantPolicy,direct,repairGrantId), answered a session without thepatha current backend always reports (it ignored those options), or still requires an agent on a session that names none for an app key;agent_managed_secret_connect_session— a session naming no agent (the Agent method on an agent’s own key, or the application’s own use of the user’s key) against a backend that still requiresdelegated_agent_id;managed_secret_connect_delegable—delegable: truewhen the backend did not echodelegable_requested, or echoed it asfalse.details.status_codecarries the HTTP status. Retrying against the same backend cannot help: upgrade the backend, or until then request the session with an app key and an agent —app.getAgent(agentId).createManagedSecretConnectSession({ templateSlug, ... })or the App method withtemplateSluganddelegatedAgentId— withoutdelegable.RestrictedGrantRequiresProxyError— the grant is proxy-only, sorequest()(raw credential release) refuses it; useproxyRequest().details.errornames why:restricted_grant_requires_proxy(the grant carries method/endpoint restrictions or an operation policy — a content rule or an operation allowlist),delegated_grant_requires_proxy(a delegated or scope-narrowed grant),hitl_grant_requires_proxy(the grant requires approval) oruser_limits_require_proxy(the grant’s user set a usage limit on it — a quota, a time window or an operation rule — on an OAuth or a managed-secret grant alike). Each of these is enforceable only when the backend makes the provider call itself. A fix-your-call error: switch the call site, do not retry.SiblingLabelConflictError— the sibling label is already in use on this connection; pick another label.CredentialIdRequiredError— the provider holds several developer credentials andcreateManagedSecretGrant()named none (HTTP 409credential_id_required); retry with one ofcredentials.EndUserCredentialNotAssignableError—credentialIdnamed an end user’s own key, which has one grant (the user’s) and is never assigned (HTTP 409end_user_credential_not_assignable).ReAuthRequiredError— the user must re-authorize via Alter Connect. Parent class of the grant-state errors below (GrantExpiredError,GrantRevokedError,GrantDeletedError,CredentialRevokedError), so oneinstanceofcatch covers every “send the user back through Connect” condition.
Grant state
Section titled “Grant state”GrantExpiredError— the grant’s TTL has elapsed. ExposesproviderId,agentId,appUserId, populated only on the delegation-path expiry (a TTL-lapsed delegation chain);undefinedon the root-path TTL expiry.GrantRevokedError— the grant was explicitly revoked (the end user revoked it in the Wallet or disconnected the connection, or an administrator revoked it). Raised on every subsequentApp-side call that addresses the revoked grant.Agentcallers — and calls addressing a delegated (child) grant — never receive this class: for them a revoked grant surfaces as the reason-neutralGrantDeletedError, so a delegated agent cannot probe whether its access was deliberately revoked.GrantDeletedError— the grant existed but is permanently gone with no more specific terminal signal (for example, a TTL-expired grant addressed again, a grant whose underlying credential was torn down, or any revoked grant addressed from theAgentpath). Re-authorization issues a new grant id.GrantNotFoundErrorAgentDelegationMissingError— extendsGrantNotFoundError(so aninstanceof GrantNotFoundErrorcatch still fires). Thrown on the agent path whenrequest(method, url, { grantId })/proxyRequest({ grantId })hits agrant_not_found— the grant is not delegated to this agent, or a user/base grant id was passed where the agent’s own delegation id (listGrants) was required. Recover by delegating the agent through Connect, or resolve by provider (omitgrantId). TheApp/operator path is unaffected.GrantNotDelegableError— extendsBackendError. Thrown byagent.delegate()when the held grant has no consenting user or is not delegable, the credential’s operator ceiling is off (a managed-secret provider’s delegation policy or the OAuth provider’s agent sharing setting), ordelegable: trueasks for a child that the depth ceiling leaves no further hop (HTTP 403grant_not_delegable).detailReasonnames which:no_consenting_user,holder_not_delegable,ceiling_off,no_onward_hopornot_requested(nullwhen the backend sent none).CredentialRevokedError: the underlying OAuth connection is permanently broken, or its provider issues no refresh token and the session ended (Encompass; the audit reason isprovider_session_ended). ExposesgrantId,providerIdandappUserId.
Identity resolution
Section titled “Identity resolution”AmbiguousGrantError— multiple grants match the identity + provider tuple. Passaccountor use directgrantIdmode.NoDelegatedGrantError— the calling agent has no delegation for the resolved user on this provider. Recoverable viacreateConnectSessionForError().
Authorization
Section titled “Authorization”PolicyViolationError— backend policy denial.StepUpRequiredError— extendsPolicyViolationError. Acontent_matchstep-up obligation requires a fresher user session.RedactDischargeFailedError— extendsPolicyViolationError. The request was denied because a redact obligation could not be applied safely.OperationUnreviewedError— extendsPolicyViolationError. The call is an unreviewed operation of the provider’s API, and a rule refused it because no rule admits it by name. An organization admin namesoperationId(the provider-qualified name a rule uses, such aszoom:deleteRole) in an operation allowlist to allow it, or in arequire_approvalrule whose every condition names it to hold it for approval, and add a scopedcredential_mintingallowance naming it (details).InsufficientScopeError— API key lacks the required scope.messagenames the missing scopes and then says how to fix it: rotate the key with the scope added, load the new key, and restart the process (the client keeps the key it was created with, so a running process keeps failing until it is restarted), or, when the key already holds the scope, send the request without the scope constraint that narrowed it away. Branch onmissing, not on the message text.TokenRefreshInProgressError— concurrent refresh in flight; retry shortly.QuotaExceededError— a request-quota policy window is exhausted. ExposesretryAfter(seconds until the window resets, capped at 2,678,400 seconds / 31 days — a quota window is a calendar period up to a month long, and the response reports the longest exhausted one; may beundefined). A policy denial, not a transient outage — the SDK never auto-retries it.RateLimitError— the platform rate limit for the API key (or the organization-wide aggregate, when configured) is exhausted. A transient throttle, not a denial: waitretryAfterseconds and retry the same request (retryAfteris capped at 3,600 seconds — one hour, above the platform’s legitimate retry guidance). Also exposesscope(which ceiling was hit — a plainstring, not a closed union, so a ceiling added later stays parseable; the known values are exported asRATE_LIMIT_SCOPE_VALUES, currently"ip","api_key"and"organization", ordered outermost-first),limit, andwindowSeconds. Each of those three may beundefined— not every response carrying this error code supplies them, so branch on a missing value rather than assuming one. Also thrown for a non-JSON 429 from an intermediary such as an edge provider: the limiting layer is unknown, soscope,limitandwindowSecondsareundefined,retryAfteris set only from aRetry-Afterheader, anddetailsis{ status_code: 429 }.
Provider
Section titled “Provider”ProviderAPIError— provider returned a 4xx/5xx that is not a scope or credential-rejection failure.ProviderResponseTooLargeError— extendsBackendError. The provider answered, but its response is too large to return whole. See below.ScopeReauthRequiredError— provider returned 403insufficient_scope, or the backend already knew the grant’s scopes are drifted. ExposesmissingScopesandproviderId.ProviderUnauthorizedError— provider returned 401: the credential was revoked, expired, or otherwise invalidated provider-side. ExposesgrantId,providerId,statusCode,responseBody. Recovery: re-authorize an OAuth grant via a new Connect session. For a managed-secret grant, the application rotates a developer credential (Developer Portal, oralter managed-secrets credentials rotate); an end user replaces their own key through a managed-secret Connect session withrepairGrantId. A 401 whoseWWW-Authenticatechallenge carrieserror="insufficient_scope"(RFC 6750 — the credential is still valid, it just lacks a scope) surfaces as a genericProviderAPIErrorinstead.
Connect flow
Section titled “Connect flow”ConnectFlowError— generic flow failure, including an unavailable/expired token on the first poll, an unknown terminal state, or a total usage-limit application failure.ConnectDeniedError— user clicked Deny.ConnectConfigError— provider configuration issue (invalid redirect URI, unknown client, etc.), includingprovider_configuration_unavailable,shared_dev_credential_unavailable, andmanaged_oauth_scope_approval_requiredwhen fresh authorization cannot start.createManagedSecretConnectSession()also throws it when the session cannot be created until an administrator or the application changes something (retrying does not help);details.errornames it:secret_not_found(HTTP 404 — no active provider of the application has theproviderslug);secret_template_mismatch(HTTP 422 —providerwas not created fromtemplateSlug);idp_signin_not_configured(HTTP 409,details.retryable === false— the application’s identity provider cannot sign users in to approve;details.details.reasonsays what to change:missing_client_idormissing_client_secret— add the sign-in client ID and secret to the identity provider;issuer_cannot_sign_in— use an issuer that supports OpenID Connect sign-in, for WorkOS the AuthKit issuerhttps://<slug>.authkit.app);binding_hosts_required(HTTP 409 — the user would enter a key, but the provider derives its hosts from the key and has no host patterns set: an administrator sets them);provider_contract_repair_required(HTTP 409 — the provider’s stored contract is out of date: an administrator rotates its existing developer credential once before a key can be entered);no_eligible_grants(HTTP 409 — no path can succeed: on a key entry with anagent, that agent could never be delegated the key,details.details.reasonagent_not_allowlistedordelegation_depth_exceeded; or atemplateSlug-only request whose template names no single provider found no grant the user holds,reasonno_grant,grant_expired,delegation_depth_exceeded,group_source_not_allowedoragent_not_allowlisted— see the reasons).binding_hosts_required,provider_contract_repair_requiredandno_eligible_grantsreach only a key bound to no managed agent: an app key, including anAgentfromApp.getAgent(), or an agent-typedalter_ak_…key minted under API Keys. A managed agent’s own key never receives them; the hosted page tells the user instead.createConnectSessionwithagent, or on an agent’s own key with a user token (agent.createConnectSession(), andconnect(), which creates the session first), throws it withdetails.error === "agent_allowlist_exceeded"(HTTP 422) when the delegated agent’s capability allowlist cannot use what the user would grant, before the user is sent to the provider:details.details.detail_reasonisprovider_not_allowlisted,scopes_not_allowlistedorgrant_scopes_malformed,details.details.provider_idnames the provider anddetails.details.uncovered_providersevery provider refused.pollConnectSession, andconnect()once the session exists, throw it withdetails.error_code === "agent_allowlist_exceeded"when the allowlist was narrowed before the user finished, with the samedetails.details(detail_reason,provider_id,uncovered_providers). An administrator widens the agent’s allowlist, or the application narrows the scopes it requests or passes a coveringscopeConstraint, before a new session.delegate()throwsBackendErrorfor the same code (details).ConnectTimeoutError— Alter received no completion callback before the local deadline or before a session observed pending expired.details.reasonis"poll_deadline_elapsed"or"session_expired"; without a callback, an exact provider-side error is unknowable. A user who signed in to the provider but closed Connect without confirming also ends here; when the Alter deployment holds new connections until Confirm, no connection from that session is usable.
Approvals
Section titled “Approvals”ApprovalError— base class.ApprovalDeniedErrorApprovalExpiredErrorApprovalTimeoutError— local wait elapsed before any decision. Original transient (when present) is preserved on.cause.ApprovalExecutionFailedErrorApprovalPayloadTooLargeError— extendsBackendError, notApprovalError(HTTP 413approval_payload_too_large). The call needs approval, and its request is too large to hold for approval on this deployment; nothing was held or sent. See below.WebhookSignatureError— extendsAlterSDKError.verifyWebhook()refused a delivery. See below.
Managed agents
Section titled “Managed agents”AgentError— base class.InvalidKeyErrorKeyExpiredErrorKeyRotationExpiredErrorKeyInactiveErrorKeyAppNotFoundErrorAgentNotFoundErrorCallerAgentMismatchErrorCallerAgentResolutionErrorAgentNameExistsErrorAgentConcurrentUpdateError— the agent changed after it was read. Fetch it again, recompute the full desired scope allowlist, and retry with the freshversion.AgentInactiveErrorAgentRevokedErrorMeRequiresAgentKeyError—agent.me()was called through an impersonatingAgentreturned byApp.getAgent(), so the request still used an application key rather than a genuine agent key.KeyRevokedErrorKeyAlreadyRevokedErrorKeyNotFoundErrorLastActiveKeyError— would revoke the agent’s only remaining active key. Passforce: trueto override.AgentKeyLimitError— the mint would take the agent past its per-agent active-key cap. Revoke a key it no longer uses, then retry.AgentCannotMintSubagentsErrorIdempotencyKeyBodyMismatchErrorIdempotencyKeyAgentRevokedErrorIdempotencyKeyAgentInactiveError
Network
Section titled “Network”NetworkError— TCP / DNS / socket failure.TimeoutError— extendsNetworkError. Local or remote timeout.
Common fields
Section titled “Common fields”Every AlterSDKError carries details: Record<string, unknown>. toString() returns only the safe message and never stringifies details. Common detail keys:
| Key | Type | Description |
|---|---|---|
status_code | number | HTTP status code from the backend or provider. |
grant_id | string | Grant the call resolved to (when applicable). |
provider_id | string | Provider slug (when applicable). |
method, url | string | HTTP method and pre-injection URL. |
reason | string | Backend-reported reason code. |
retry_after | number | Seconds to wait before retrying — a quota window reset or a rate-limit backoff. QuotaExceededError and RateLimitError also expose it as the typed retryAfter field (may be undefined). On both, the typed field prefers the Retry-After response header over this body value and caps the result — at 3,600 seconds for RateLimitError, at 2,678,400 (31 days) for QuotaExceededError, whose windows are calendar periods — so the two can differ. |
Typed fields
Section titled “Typed fields”The following public fields supplement message, name, and details:
| Class | Fields |
|---|---|
GrantExpiredError | providerId, agentId, appUserId (string | undefined) |
GrantRevokedError | grantId: string | undefined |
CredentialRevokedError | grantId, providerId, appUserId (string | undefined) |
GrantNotFoundError | providerId, agentId, appUserId (string | undefined) |
AmbiguousGrantError | providerId, accountIdentifiers, accountWasProvided, appUserIds, grantIds, candidates, candidatesTruncated — when candidatesTruncated is true every disambiguator here is a bounded sample, so an absence from any of them proves nothing |
NoDelegatedGrantError | providerId, agentId, appUserId (string | undefined) |
PolicyViolationError | policyError: string | undefined |
StepUpRequiredError | maxSessionAgeSeconds: number | undefined; inherited policyError is "step_up_required" |
RedactDischargeFailedError | no extra fields; inherited policyError is "redact_discharge_failed" |
OperationUnreviewedError | operationId (the provider-qualified name a rule uses), method, pathTemplate (string | undefined); inherited policyError is "operation_unreviewed" |
SiblingLabelConflictError | label: string | null |
CredentialIdRequiredError | credentials: CredentialChoice[] — every developer credential the provider holds |
EndUserCredentialNotAssignableError | no extra fields |
ProviderResponseTooLargeError | statusCode (the provider’s status), headers (the provider’s headers), limitBytes: number | undefined (the buffered limit when the response passed it; undefined when an approval’s result was too large to store), approvalId: string | undefined (set when thrown reading an executed approval’s result) |
ApprovalPayloadTooLargeError | limitChars: number | undefined — the largest request this deployment can hold for approval |
InsufficientScopeError | required, granted, missing, scopeVersion, currentScopeVersion, scopeVersionMismatch, documentationUrl; aliases requiredScopes, grantedScopes, docsUrl |
TokenRefreshInProgressError | grantId: string | undefined |
QuotaExceededError | retryAfter: number | undefined |
ProviderAPIError | statusCode: number | undefined, responseBody: string | undefined |
ScopeReauthRequiredError | grantId, providerId, missingScopes; inherits provider response fields |
ProviderUnauthorizedError | grantId, providerId; inherits provider response fields |
ApprovalError and subclasses | approvalId: string | null |
AgentError and subclasses | code: string, hint?: string |
CredentialIdRequiredError.credentials contains CredentialChoice entries with credentialId (what createManagedSecretGrant(id, { credentialId }) takes) and label.
AmbiguousGrantError.candidates contains GrantCandidate entries with grantId, label, accountIdentifier, and accountDisplayName. The account fields are nullable.
Recover deliberately, never by taking the first candidate:
try { response = await app.proxyRequest({ method: HttpMethod.GET, url: url, provider: "<provider-id>", userToken: userJwt });} catch (e) { if (!(e instanceof AmbiguousGrantError)) throw e; const grantId = chooseGrant(e.candidates); // the user's choice, persisted on their profile response = await app.proxyRequest({ method: HttpMethod.GET, url: url, grantId, userToken: userJwt });}For the typed exception fields and recovery flows for each code, see Errors.
Destination refusal
Section titled “Destination refusal”Version compatibility:
BlockedDestinationError, andRateLimitErrorfor a non-JSON 429, require@alter-ai/alter-sdk>=0.28.0. Version 0.27.0 and earlier throw a genericBackendErrorfor both responses.
BlockedDestinationError inherits from BackendError. The requested destination
failed the provider’s host/path allowlist or the network security check, or is
a route the provider’s reference page lists as refused on every connection. When
a call held for approval is refused as the approved call executes, the approval
wait raises ApprovalExecutionFailedError instead. Correct the URL before
retrying. Its details includes error: "blocked_destination", status_code,
and request_id when the server supplied one; use the request ID
when investigating the refusal. Private resolver addresses and credentials are
not part of the diagnostic contract.
ManagedOperationError
Section titled “ManagedOperationError”A managed integration rejected by the backend raises ManagedOperationError with
its stable code and HTTP status. Examples include unknown_contract_version,
integration_grant_mismatch and invalid operation arguments. A provider whose connections each use their own API host (a data center or a company host) refuses a connection with no such host as connection_origin_missing and one outside the hosts it allows as connection_origin_not_allowed (both 409); reconnecting, or saving the key with an allowed host, fixes them. Provider HTTP failures
and successful HTTP responses flagged provider_fault are represented by the retained
approval result and rejected by typed result decoding; they are not successful writes.
reason is an optional, machine-readable refinement of code (undefined when the backend sends none), also kept in details.reason. An attachment sent without its metadata (a bare file object for an operation whose file goes in a multipart attachment body) is code invalid_operation_input with reason attachment_metadata_required: send the file with its metadata (integrations.executeUpload({ ..., metadata })). Branch on code first; reason only narrows it.
ProviderResponseTooLargeError
Section titled “ProviderResponseTooLargeError”Extends BackendError. The provider answered, but its response is larger than the
5 MiB a buffered call returns. proxyRequest() throws it instead of returning a cut
body, and so does reading an executed approval’s result (awaitApproval() and the
other result readers) when the result was kept without its body. statusCode and
headers are the provider’s. The call was made, so a write may have happened: do not
resend a non-idempotent call to recover. Fetch a large response with
proxyStreamRequest(),
which returns any size. A managed operation (integrations.execute(), or reading its
typed result) throws it the same way. Its message names
integrations.executeStream() for a
binary response (it refuses a JSON operation) and proxyStreamRequest() for any other.
ApprovalPayloadTooLargeError
Section titled “ApprovalPayloadTooLargeError”Extends BackendError (HTTP 413, approval_payload_too_large). The call needs
approval, and its request is too large to hold for approval on this deployment.
Nothing was held or sent. limitChars is the largest request the deployment can
hold. Send a smaller request, or send a file with
proxyUploadRequest(),
whose bytes are delivered after the approval instead of held.
ProxyTransferError
Section titled “ProxyTransferError”Extends BackendError. The streaming/binary proxy refused the call. code identifies
proxy_body_uninspectable (422, a rule or an approval needs to read the body; on GraphQL, any operation, family or parameter rule does),
proxy_stream_capacity (503, dedicated stream slots full),
proxy_stream_timeout (504, deadline before response headers), or
proxy_stream_approval_required (409, approval-gated streaming is unavailable).
Uploads from proxyUploadRequest() add the proxy_upload_* and
proxy_approved_upload_too_large codes listed in the
error reference.
After response headers, transport failures interrupt iteration as NetworkError
or TimeoutError; never treat a partial stream as a complete provider response.
WebhookSignatureError
Section titled “WebhookSignatureError”Extends AlterSDKError. verifyWebhook()
refused a delivery: a missing webhook-id, webhook-timestamp or webhook-signature
header, a timestamp outside the tolerance window (a replay), a signature no active
secret produced, or a body that is not the event envelope. The request reached the
receiver; it just was not from Alter — respond 400 and do not act on it. A malformed
secret argument is the receiver’s own configuration error and throws AlterValueError
instead.