Skip to content

Reference

Connect & Grants

Connect sessions, grant lifecycle, delegation revoke, managed-secret grants, HITL approvals.

This page covers every surface for getting a credential into the system and managing its lifecycle: the OAuth provider catalog, Connect sessions (user-consent flows), grant CRUD, agent-delegation revoke, managed-secret grant creation, and human-in-the-loop approvals.

// Provider catalog
const catalog = await app.oauthProviders.list();
// Connect flows
const results = await app.connect({ providers: ["<provider-id>"] });
const session = await app.createConnectSession({ allowedProviders: ["<provider-id>"] });
const grants = await app.pollConnectSession(session.sessionToken);
const recover = await app.createConnectSessionForError(caughtError);
const msSess = await app.createManagedSecretConnectSession({ /* ... */ });
const own = await agent.createManagedSecretConnectSession({ /* ... */ }); // for this agent
// End-user sign-in (IDP login)
const auth = await app.authenticate(); // CLI convenience
const authSession = await app.createAuthSession(); // headless / remote user
const result = await app.pollAuthSession(authSession.sessionToken);
// Grants
const page = await app.listGrants({ limit: 50 });
await app.revokeGrant(grantId, { reason: "rotation" });
const grant = await app.createManagedSecretGrant("ms_…", { principal });
const sibling = await app.mintGrant(grantId, { label: "read-only" });
// Delegations
await app.revokeDelegation(grantId, agentId); // operator
await agent.revokeDelegation(grantId); // agent self-revoke
// Approvals
const final = await app.awaitApproval(approvalId, { timeoutMs: 600_000 });
const status = await app.getApprovalStatus(approvalId);

Fetch the OAuth provider catalog: the connectable providers configured for the platform and, per provider, the scopes you can request. Use it to drive provider pickers and scope selection instead of hardcoding scope strings.

async list(options?: { forceRefresh?: boolean }): Promise<OAuthProviderCatalog>
OptionTypeDefaultDescription
forceRefreshbooleanfalseBypass the in-process cache and re-fetch.

Results are cached in-process for 5 minutes. The catalog lists only active (connectable) providers. Available on both App and Agent as app.oauthProviders / agent.oauthProviders.

Returns OAuthProviderCatalog — a providers record keyed by id, plus getDefaultScopes(provider) / getRequiredScopes(provider) helpers. Throws BackendError on a malformed catalog response. Requires the providers:read scope.

const catalog = await app.oauthProviders.list();
const provider = catalog.providers["<providerId>"];
console.log(provider.displayName, provider.defaultScopes);
// Pre-fill a Connect flow with the provider's default scopes.
const scopes = catalog.getDefaultScopes("<providerId>");

Mint a Connect session URL. The application then surfaces the URL to the user — popup, redirect, chat message, etc. In a native app, open it in the system browser rather than an embedded WebView: identity providers refuse or cannot share their sign-in session with embedded WebViews, and approving a delegation on an account the user already connected asks the user to sign in first.

async createConnectSession(
options?: CreateConnectSessionOptions,
): Promise<ConnectSession>
OptionTypeDescription
allowedProvidersstring[]Restrict to specific provider IDs (for example, ["<provider-id>"]). When omitted the user can pick any configured provider. Exactly one entry skips the provider picker — there is nothing to choose — and sends the user straight to that provider’s sign-in, with no Alter-branded page before or after it. The response’s singleProvider flag is true; passed to the browser widget as open({ container, singleProvider }) from the user’s click, the inline widget opens the provider window immediately too (a single tile only if the browser blocks the window). The end user still confirms the connection on the way back; to skip that as well, see direct. An empty array or a blank entry throws AlterValueError before any request is sent (omit the option to offer every configured provider). Entries are matched case-insensitively after trimming, so ["GitHub", "github"] counts as one provider.
directbooleanOpt the session out of the end-user consent screens: no confirmation screen, no duration choice and no in-flow policy-authoring step, and the page delivers the outcome and closes instead of showing the user what happened. Requires exactly one provider in allowedProviders and throws AlterValueError locally otherwise — with a picker on screen the flag contradicts itself. Never implied by the provider count: how many providers an application offers says nothing about whether the person granting access should still see and shape what they are granting. On a direct session allowUserPolicyRules and session grant-expiry bounds add no end-user step, so the grant is issued with the requested scopes and the default duration; the application’s own grantPolicy bounds still apply. A session that delegates to an agent and sets delegable: true is never direct: the user decides onward sharing on the confirmation screen, so the screen is shown and the session reports direct as false.
returnUrlstringURL the browser redirects to after consent (mobile / single-page flows).
allowedOriginstringOrigin allowed for the postMessage completion event (popup flow).
metadata{ ipAddress?: string; userAgent?: string }Forwarded to the audit row.
grantPolicyGrantPolicyInputOptional absolute expiry and TTL bounds the user picks from on the consent screen. TTL fields are seconds.
requiredScopesRecord<string, string[]>Per-provider scope ceiling. The OAuth URL is built with these scopes (must be a subset of the application’s Dev Portal configuration).
agentstringAgent UUID or managed-agent name. When set, on approval the SDK returns a delegation grant that the agent uses as grantId on request(), and the approval must come from the end user. Connecting an account at the provider proves that on its own; approving on an account the user already connected (the one-click shortcut) first shows a Sign in to approve step, a sign-in through the application’s identity provider in the browser that approves. When the identity provider cannot sign users in (no wallet client ID and secret), the session skips the shortcut and sends the user through the provider’s own authorization instead. A failed sign-in never ends the session: the page lets the user sign in again or cancel, and no sign-in failure code reaches the application — pollConnectSession and the Connect widget see only the session’s outcome. While Alter is being upgraded, a session created by the previous version also skips the shortcut and sends the user through the provider’s own sign-in; if the page’s own sign-in start refuses such a session, it shows session_outdated to the user only — the code never reaches the application or an SDK. Who may be named depends on the key: an app key (including an Agent from App.getAgent()) names any active agent of the app. An agent’s own key requests a delegation only for itself: omit agent (with a userToken) or pass the calling agent’s own id or name. Naming another active agent of the app throws BackendError with HTTP 400 agent_cannot_delegate_to_other_agent, and an id or name that matches no active agent throws AgentNotFoundError (HTTP 404 agent_not_found, details.error === "agent_not_found"). Every such refusal is recorded in the audit trail under the calling agent, never under the agent it named.
requestedGrantRequestedGrantSibling-grant request (multi-grant model). The grant created by this session carries the required label (the sibling address — resolution key is provider + label) and, when set, the method/endpoint restrictions, which make it proxy-only. Unknown keys throw AlterValueError at the SDK boundary.
repairGrantIdstringReauthorize this active grant in place. Requires exactly one allowedProviders entry; cannot be combined with agent, requestedGrant, or switchAccount. Normally supplied automatically by createConnectSessionForError() after CredentialRevokedError.
delegablebooleanOnly meaningful with agent. true asks that the agent may share this access with other agents through agent.delegate(); the user decides on the consent screen, which shows a May share this access with other agents checkbox (on by default when the application’s key asks, off when the agent asks with its own key) and only the user’s choice is stored. The checkbox appears only when the provider’s agent sharing setting allows onward sharing, except that an existing delegation that can already be shared onward keeps it, turned on, when the setting no longer allows that, and the user can then only turn it off. The user signs in through the application’s identity provider before choosing: the confirmation screen that follows a provider login shows Sign in to choose first. Embedded Connect shows that confirmation screen in the window where the user signed in to the provider, so the sign-in and the checkbox are offered there too. Where a screen cannot run that sign-in (one shown inside the embedded Connect frame, such as the approval step for an account the user already connected, or an identity provider that cannot sign users in), no checkbox is offered, a new delegation is created as a leaf, and an existing one keeps its setting. true also shows the consent screen for a direct session. false stores false, with no checkbox, and on a re-consent turns an existing delegation’s onward capability off. Omit delegable to keep the existing delegation’s setting: re-consenting for an agent that already holds a delegation on this account keeps its current value unless the user changes it, and a new delegation is created as a leaf the recipient cannot pass on (onward delegation is opt-in at every hop). The stored outcome is on the result’s delegation. The SDK sends the field only when it is set, including an explicit false.
scopeConstraintstring[]Requires agent (a constraint with no delegation to narrow is rejected). Narrow the delegated agent’s first-hop grant to a subset of the credential’s provider scopes (least privilege). Omit for full credential scope. Provide a non-empty array of at most 100 concrete scope strings, each ≤ 512 characters and a valid RFC 6749 scope-token (printable ASCII — no spaces, " or \; one atom per scope); "*", empty strings, and an empty array are rejected. Every atom must be within at least one allowed provider’s effective scopes for the session (a broader scope that subsumes the atom qualifies): a constraint invalid for every allowed provider fails session creation with BackendError (HTTP 422, invalid_scope_constraint); a constraint invalid for only some providers succeeds and ConnectSession.scopeConstraintWarnings carries one diagnostic per affected provider — completing consent for such a provider fails with the same typed error. A scope-narrowed grant is proxy-only — call it with proxyRequest().
userTokenstringPer-call user JWT. Overrides userTokenGetter. Omit both for an unbound (app-scoped) session: the hosted flow still completes, but the resulting grant belongs to the application rather than to any end user — JWT resolution will not find it, so call it with provider or its grantId from a call that carries no user token (with one in scope, the backend rejects an app-scoped grant: system_grant_user_token_mismatch). Required when agent is set and no userTokenGetter is configured: a session with neither is rejected with BackendError HTTP 400 agent_requires_user_token, because a delegation needs a consenting user.
switchAccountbooleanForce the full provider authorization flow, skipping the already-connected fast path — the programmatic equivalent of the consent screen’s “Use a different account” link. Set it when the flow’s purpose is connecting a different account for a provider the application already holds a connection to. Default false (routine reconnects keep the one-click fast path). Must be a boolean — a non-boolean throws AlterValueError at the SDK boundary.
allowUserPolicyRulesbooleanWhether the end user may set their own usage limits, that is policy rules (deny, require-approval, time window, request quota, or operation-parameter content rules), in the Connect popup while authorizing. The limits are applied as part of authorizing it; if they cannot be applied, the connection is revoked rather than left in place without them. Default true; set false to hide the policy step. Has no effect on a session minted with direct, which has no confirmation screen; naming one provider alone does not remove it. Must be a boolean; a non-boolean throws AlterValueError at the SDK boundary.

RequestedGrant and RequestedGrantRestrictions are exported from the package root:

interface RequestedGrant {
label: string;
restrictions?: RequestedGrantRestrictions | null;
}
interface RequestedGrantRestrictions {
allowedMethods?: string[];
allowedEndpoints?: string[];
}

Returns ConnectSession — connectUrl is what the user opens; sessionToken is what you pass to pollConnectSession().

Throws:

  • AlterValueError — a boundary guard named in the option table: an empty or malformed allowedProviders or a blank entry in it, a non-boolean switchAccount / allowUserPolicyRules / direct, direct without exactly one provider, a malformed grantPolicy / requestedGrant keyset, or an invalid scopeConstraint atom. Thrown before any request is sent.
  • ConnectConfigError — the typed managed_oauth_scope_approval_required terminal (HTTP 409): the requested scopes exceed what the Alter-managed OAuth client is approved for. It is not a BackendError, so a handler that branches only on BackendError leaves it uncaught. Contact Alter to approve the scopes, or narrow the app’s configured scopes to the approved set, and only then create a new session — the response is retryable: false and every fresh session fails identically until the approval changes.
  • BackendError — a backend rejection, including scope_not_allowed when a requested scope is outside the app’s configured allowlist, HTTP 422 invalid_scope_constraint when the scopeConstraint is invalid for every allowed provider, HTTP 400 invalid_origin when allowedOrigin is not a single origin, and the delegation-target refusals in the agent and userToken rows (agent_cannot_delegate_to_other_agent, agent_requires_user_token); the code is in details.error.
  • AgentNotFoundError — agent matches no active agent of the app. For an Agent from App.getAgent() whose agent is no longer active, the caller check refuses first, with details.error === "caller_agent_unresolved".
  • AlterSDKError — the SDK client is closed.
  • NetworkError / TimeoutError — transport failure.

On this call the error’s details is the full 409 body, which is the only way to tell an operator which scopes need approving:

import { ConnectConfigError } from "@alter-ai/alter-sdk";
try {
const session = await app.createConnectSession({ allowedProviders: ["<provider-id>"] });
} catch (error) {
if (
error instanceof ConnectConfigError &&
error.details.error === "managed_oauth_scope_approval_required"
) {
// `details` is `Record<string, unknown>` — narrow before reading.
const blocked = error.details.details as {
provider_id: string;
unapproved_scopes: string[];
};
const remediation = error.details.remediation as {
action: string;
description: string;
};
console.log(blocked.provider_id, blocked.unapproved_scopes);
console.log(remediation.action, remediation.description);
// error.details.retryable === false — do not retry.
}
throw error;
}
const session = await app.createConnectSession({
allowedProviders: ["<provider-id>"],
allowedOrigin: "https://app.example.com",
grantPolicy: { maxTtlSeconds: 30 * 24 * 3600, defaultTtlSeconds: 7 * 24 * 3600 },
});
window.open(session.connectUrl, "alter-connect", "popup");
const grants = await app.pollConnectSession(session.sessionToken);

Mint a Connect session for the user → agent delegation flow on a managed secret. The user consents to the named agent using the user’s existing managed-secret access. An agent asks for its own delegation with agent.createManagedSecretConnectSession(), which takes the same options without delegatedAgentId.

async createManagedSecretConnectSession(
options: CreateManagedSecretConnectSessionOptions,
): Promise<ManagedSecretConnectSession>
OptionTypeDescription
templateSlugstringCanonical managed-secret template slug in kebab-case. Required.
delegatedAgentIdstringUUID of the agent being authorized. Required on App, because an app key has no agent of its own; a missing value throws AlterValueError before any request. An id that is not an active agent of the app throws AgentNotFoundError (HTTP 404 agent_not_found), never a GrantNotFoundError.
userTokenstringIDP JWT identifying the consenting user. Required.
requestedTtlSecondsnumberOptional positive integer caller-suggested TTL in seconds. Capped by the per-secret policy, source credential expiry, and 90 days; omit it to use the selected secret’s policy and default cap.
allowedOriginstringOrigin allowed for the postMessage event. It must be a single origin — a scheme, a host and an optional port, with no path, query, fragment, credentials or wildcard — and in production it must use https:// unless the host is localhost or a loopback IP address. A lone trailing / is removed. Anything else, including * and a value without a scheme, throws BackendError with HTTP 400 invalid_origin. A value longer than 300 characters throws BackendError with HTTP 400 invalid_origin too, as on createConnectSession. There is no fallback to the app’s website URL: omit the option when there is no popup opener.
returnUrlstringURL for the mobile redirect flow.
allowUserPolicyRulesbooleanWhether the consenting user may add self-scoped, narrowing-only usage limits in the hosted approval flow. Defaults to true; set false to hide the policy step. The rules are attached atomically to the delegated managed-secret grant, and approval fails if they cannot be applied. A non-boolean throws AlterValueError before any request.
delegablebooleanAsk the user to let the agent share this access with other agents through agent.delegate(). Default false. With true, the Connect page shows the user a May share this access with other agents (up to N more hops) checkbox and says next to it who asked for onward sharing: the application, or the agent itself when its own key asked. The delegation stores the user’s choice. N is how many more delegation steps the secret’s policy allows below this one. The checkbox appears only when the selected credential’s policy allows onward delegation with at least one more hop, except that an existing delegation that can already be shared onward keeps the checkbox, which the user can then only turn off (below); so the user can never turn onward sharing on past the operator’s ceiling. It starts from the user’s existing delegation to this agent when there is one, so a re-consent never turns onward sharing on unless the user does; for a new delegation it starts on, except when the agent asked with its own key (agent.createManagedSecretConnectSession()), where it starts off so the user opts the agent in. With false the page shows the checkbox only when the user’s existing delegation to this agent can already be shared onward, turned on to keep it; a new delegation is created as a leaf. When that existing delegation can be shared onward but the policy no longer allows it (the ceiling was lowered, or no hops are left), the checkbox is still shown, turned on, and the user can only turn it off. The approval reports the stored setting as delegable (see the return value below). Echoed on the result as delegableRequested. Requires a backend that supports it: an older one ignores the option, so the SDK throws ServerFeatureUnsupportedError rather than return a session that would create a leaf.

The consent page names the agent from its stored record (its display name, else its name); the requesting application cannot supply a name. Passing the removed delegatedAgentName option (or delegated_agent_name) throws AlterValueError before any request.

The user must hold something to delegate. Before creating the session, Alter checks that the user holds a credential the delegation could use: an active grant for a secret created from templateSlug, held directly or through a group, that the secret’s delegation policy lets this user delegate and that the agent’s capability allowlist names. If none qualifies, no session is created and the call throws ConnectConfigError with code no_eligible_grants (HTTP 409). details.details.reason names the cause:

reasonCauseWho fixes it
no_grantThe user holds no active grant for a secret created from this template.The application’s administrator issues the user a grant. The user cannot issue one.
grant_expiredEvery grant the user holds for it has passed its own expiry.The application’s administrator renews the grant or issues a new one. The user cannot renew it.
delegation_depth_exceededThe secret’s max_delegation_depth leaves no room for a delegation below the user’s grant.An administrator raises the depth ceiling.
group_source_not_allowedThe user holds the credential only through a group, and the secret does not allow delegation from group grants.An administrator allows group-source delegation on the secret, or gives the user a direct grant.
agent_not_allowlistedThe agent’s capability allowlist does not contain the secret’s slug.An administrator adds the secret’s exact slug to the agent’s managed_secret_slugs allowlist.

A grant the agent’s allowlist does not name carries agent_not_allowlisted whatever its delegation policy says, because no policy change would let the agent use it; a policy reason is reported only for a grant the agent could use once that reason is fixed. When the user’s grants are blocked for different reasons, reason is the first of grant_expired, delegation_depth_exceeded, group_source_not_allowed and agent_not_allowlisted that any of them carries. This check applies only to a key bound to no managed agent: an app key, including an Agent built with App.getAgent(), or an agent-typed alter_ak_… key minted under API Keys. A managed agent’s own key never receives no_eligible_grants (see the Agent method).

The user signs in to approve. The session token does not approve anything on its own, because the application that requested the delegation holds it too. The hosted page first asks the user to sign in through the application’s identity provider — usually a silent redirect when the user already has a session there — and only the browser that completed that sign-in, as the user userToken names, can list the user’s credentials and approve. Cancelling needs no sign-in, so the user can always decline. A failed sign-in never ends the request: if the user signs in with a different account, cancels at the identity provider, or the sign-in cannot be verified, nothing is granted, the page says why, and the user can sign in again (after a wrong account, Use a different account forces a fresh sign-in) or cancel. The identity provider therefore needs its sign-in client configured: the wallet client ID and secret, with the SDK callback URL registered (see Approving Connect delegations). Without it, this call throws ConnectConfigError with code idp_signin_not_configured (HTTP 409, details.retryable is false), and details.details.reason says what to change: missing_client_id or missing_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 issuer https://<slug>.authkit.app). A wrong delegatedAgentId is reported first: agent_not_found is thrown even when the identity provider is not ready.

The page lists only the credentials the user may delegate to this agent. Approval checks the chosen credential again, including the agent’s allowlist, so an allowlist narrowed after the page loaded refuses the approval on the page (agent_allowlist_exceeded) and creates nothing. A credential that expired, was revoked or is being deleted after the page loaded, or that the user held through a group they have since left, is refused on the page as grant_not_found, and onward sharing the credential’s policy no longer allows as grant_not_delegable (the user can approve again without it). Neither creates anything.

Open connectUrl in the system browser (a popup or a redirect on the web; the system browser, not an embedded WebView, in a native app): identity providers refuse or cannot share their sign-in session with embedded WebViews, and an app that controls the WebView could drive the approval itself.

What the application learns. The request’s outcome — approved or cancelled — or an error code: session_expired (the request expired while the page was open), idp_signin_not_configured (the identity provider lost its sign-in client after the session was created, so nobody can approve until an administrator fixes it; in the popup flow the user can still cancel), or the code of an approval the final write refused, which ends the request: grant_not_found (the selected access was revoked or expired meanwhile), agent_not_found, agent_allowlist_exceeded, group_delegation_not_allowed, delegation_depth_exceeded, grant_not_delegable, policy_violation, delegation_ttl_out_of_bounds, delegation_conflict, invalid_scope_constraint, delegation_refused, invalid_policy_draft or approver_not_found (a usage limit the user added could not be applied), or internal_server_error. They arrive as {"type": "alter:managed-secret-connect:error", "error_code": "<code>"} in the popup postMessage, or error=<code> on returnUrl in the redirect flow. Nothing was delegated; start a new session. A refusal the user can still answer — the selected access stopped being one this agent may use before the approval started, or the user must sign in again — sends nothing: the page asks the user to pick again or sign in, and the request stays open. A sign-in is never an outcome — no approver_* or binding_cookie_mismatch code is ever sent to the application — and a request that was already answered (for example in another tab) sends nothing more. session_expired is delivered only while the page still holds the live request: once the session is gone the page no longer knows the opener’s origin or the returnUrl, so a link opened after expiry shows the user an ended page and sends nothing. Treat a flow that ends with no message and no return as not approved, and start a new session.

Returns ManagedSecretConnectSession with the session URL and polling metadata; it does not contain a delegation ID. The user opens connectUrl. After approval, the hosted flow delivers delegation_id in the postMessage payload or returnUrl query, and the agent passes that value as grantId on proxyRequest(). A delegation is proxy-only: request() throws RestrictedGrantRequiresProxyError for it. The approval carries updated: true when the user already had a live delegation to this agent from the chosen credential and the approval renewed it in place (same delegation_id), false when it created a new one. It also carries delegable: the delegation’s onward-sharing setting as stored after the approval, which is the user’s choice or the existing delegation’s kept setting (a new delegation the user was not asked about is false). false means the agent cannot share this access onward. true is the setting, not a promise: the secret’s delegation policy still decides every onward delegation, so an existing delegation can keep true after the policy stopped allowing onward sharing (the ceiling was lowered, or no hops are left), and agent.delegate() from it is then refused until an administrator allows onward sharing again. The approved postMessage is {"type": "alter:managed-secret-connect:approved", "delegation_id": …, "agent_id": …, "template_slug": …, "expires_at": …, "updated": …, "delegable": …} (snake_case, as the page sends it). On the returnUrl flow the query carries delegation_id, expires_at, updated and delegable (updated and delegable as true or false) on approval, denied=true on denial, or error=<code> (one of the two codes above) when no answer came — after consuming them, remove whichever landed (delegation_id, expires_at, updated, delegable, denied or error) from the address bar (history.replaceState) so a refresh or a shared link cannot re-trigger the return handling against a spent session.

Throws:

  • AlterValueError — a missing or malformed templateSlug, delegatedAgentId or userToken, a non-boolean allowUserPolicyRules / delegable, or the removed delegatedAgentName, before any request.
  • ConnectConfigError — no_eligible_grants or idp_signin_not_configured (above).
  • ServerFeatureUnsupportedError — delegable: true against a backend that predates it, so the session does not echo it as true.
  • AgentNotFoundError — delegatedAgentId names no active agent of the app; for an Agent from App.getAgent() whose agent is no longer active, details.error === "caller_agent_unresolved".
  • BackendError — invalid_origin, an unknown template, a user token that fails validation, identity synchronization that could not complete, or a malformed response, including a delegable_requested of true when delegable was not sent. When userToken verifies but its user cannot be synchronized, the error is split by statusCode, as on connect(): 503 (details.error === "service_unavailable") is transient — retry after details.retry_after_seconds — while 409 (identity_provider_inactive: the identity provider is disabled; identity_group_name_ambiguous: two of its groups share the display name the token claims) is a condition an administrator must repair, carries no retry hint, and does not clear on retry.

The supplied user JWT is validated and the normal grant/policy checks apply.

import { App, ConnectConfigError } from "@alter-ai/alter-sdk";
const app = new App({ apiKey: process.env.ALTER_API_KEY! });
try {
const session = await app.createManagedSecretConnectSession({
templateSlug: "provider-api-key",
delegatedAgentId: process.env.AGENT_ID!,
userToken: process.env.USER_JWT!,
delegable: true, // ask the user to let the agent share it onward
});
console.log(session.connectUrl, session.delegableRequested);
} catch (error) {
if (error instanceof ConnectConfigError && error.details.error === "no_eligible_grants") {
// Nothing the user holds can be delegated to this agent yet.
const { reason } = error.details.details as { reason: string };
console.log("cannot request a delegation:", reason);
} else {
throw error;
}
} finally {
await app.close();
}

Block until a session reaches a terminal state. Use this when application code minted the session itself and needs to wait for completion.

async pollConnectSession(
sessionToken: string,
options?: {
timeoutMs?: number;
pollIntervalMs?: number;
onEvent?: (event: {
type: "provider_declined";
provider_id: string;
error_code: string;
declined_at: string | null;
}) => void;
},
): Promise<ConnectResult[]>
OptionTypeDefaultDescription
timeoutMsnumber300_000 (5 min)Positive, finite maximum time to wait. Milliseconds. An explicit value is honored; it does not shorten the server session. Elapsed time uses a monotonic clock.
pollIntervalMsnumber2_000Positive, finite time between polls. Milliseconds.
onEventfunction—Synchronous callback fired once per provider the user declines while the session remains recoverable (a multi-provider picker where another provider can still be chosen). declined_at is an ISO-8601 timestamp string, or null when the service omits it. Exceptions it throws are logged and never interrupt the poll; a returned Promise is not awaited, but its rejection is caught and logged.

Returns one ConnectResult per provider the user completed. On partial completion, every result carries the same typed failedGrants array (providerId, reason, message) for providers the session connected but did not keep: reason is "not_selected" when the user did not select the provider on the Confirm screen, "activation_failed" when the connection could not be completed as the user confirmed it, and another value when the selected usage limits could not be applied. The array is empty for full success; unknown reason strings are preserved. When the Alter deployment holds new connections until Confirm, a connection becomes usable only when the user confirms it: a session the user leaves after the provider sign-in without confirming ends as expired, and none of its connections is usable. On a deployment that does not, such a connection is usable as soon as the provider sign-in completes, without the usage limits or expiry the user had not yet confirmed. A grant whose session delegated to an agent also carries delegation (agentId, delegable, policyRefused): the delegation’s stored onward-sharing setting after the user’s approval, and whether the provider’s agent sharing setting refused the user’s choice to share when the connection was confirmed (the setting changed while the consent screen was open; delegable is then the setting that was kept).

Throws:

  • AlterValueError — blank/non-string token or non-finite/non-positive polling control; rejected before any request.
  • ConnectTimeoutError — the local deadline elapsed (details.reason === "poll_deadline_elapsed"), a session observed pending expired before Alter received a callback ("session_expired"), or the whole budget was spent backing off a throttled poll ("rate_limited", with details.retryAfter carrying the last hint the service gave).
  • PolicyViolationError — policyError === "ip_not_allowed", when the API key is restricted to an IP range that the polling host is outside of.
  • ConnectDeniedError — the user clicked Deny.
  • ConnectConfigError — provider configuration issue (invalid redirect URI, unknown client, etc.), including typed provider_configuration_unavailable, shared_dev_credential_unavailable, and managed_oauth_scope_approval_required terminals when the app cannot start a fresh provider authorization. For managed OAuth approval, an operator must approve the requested permissions before the application creates a new Connect session.
  • ConnectFlowError — other failure, including an unavailable/expired token on the first poll (the API deliberately does not reveal whether a session existed) or a completed flow that kept no grant. In the latter case, error.details.failed_grants contains the typed failures in snake_case wire form and error.details.error_code names the cause: grant_policy_application_failed (selected usage limits could not be applied) or grant_activation_failed (every selected connection could not be completed at Confirm).
  • BackendError — an identity-synchronization refusal, split by statusCode: 503 is transient identity-provider sync unavailability (retry later; details.retry_after_seconds carries a backoff hint when present), while 409 means the identity provider is inactive or a group name is ambiguous — conditions an app operator must repair, so retrying does not help. details.error_code names the terminal. Also thrown for malformed terminal error fields or another malformed backend response.

Denials while the session stays open. On a picker offering several providers, declining one is not terminal — the user can still choose another. Those denials are observable three ways: onEvent fires as each one is seen, a timeout after denials lists them in ConnectTimeoutError.details.declined_providers (on every timeout reason, session_expired and rate_limited included), and once the user has declined every offered provider — leaving nothing else to try (an already-connected account still awaiting approval counts as something to try) — the session ends with ConnectDeniedError instead of leaving the poll waiting.

Recover from a typed credential failure. Pass the caught exception and the method extracts the provider, the delegated agent (when present), and builds a re-authorization session. For CredentialRevokedError, it also targets the error’s grantId, so success preserves that grant and returns operation: "reauth" instead of creating a duplicate.

async createConnectSessionForError(
error: NoDelegatedGrantError | GrantNotFoundError | CredentialRevokedError,
options?: {
allowedOrigin?: string;
returnUrl?: string;
metadata?: { ipAddress?: string; userAgent?: string };
grantPolicy?: GrantPolicyInput;
requiredScopes?: Record<string, string[]>;
userToken?: string;
},
): Promise<ConnectSession>
try {
await app.request("GET", url, { provider: "<provider-id>" });
} catch (error) {
if (error instanceof NoDelegatedGrantError) {
const session = await app.createConnectSessionForError(error, {
allowedOrigin: "https://app.example.com",
});
redirectUser(session.connectUrl);
const results = await app.pollConnectSession(session.sessionToken);
// Retry the original call.
} else {
// Re-throw anything you don't explicitly recover from — never silently
// swallow an unexpected error (e.g. a network failure or provider error).
throw error;
}
}

Throws:

  • AlterValueError — the typed error has no providerId context (rare — only happens when the original failure was direct-mode against a stale grantId), or a NoDelegatedGrantError carries no agentId.
  • ConnectConfigError — the recovery session could not be minted because the Alter-managed OAuth client is not approved for the scopes this app requests (managed_oauth_scope_approval_required). Not recoverable by retrying: contact Alter to approve the scopes, or narrow the app’s configured scopes to the approved set, and only then mint a recovery session. See createConnectSession for the details payload naming the unapproved scopes.
  • Everything else createConnectSession throws — this method forwards to it. The else { throw error; } branch in the example above re-throws these, so a handler that only catches NoDelegatedGrantError will surface a ConnectConfigError to its own caller.

The all-in-one headless flow. Mints a session, opens the user’s default browser, polls until done, and returns the resulting grants.

async connect(options: ConnectOptions): Promise<ConnectResult[]>
OptionTypeDefaultDescription
providersstring[]—Restrict to specific providers. An empty array or a blank entry throws AlterValueError before any request is sent.
timeoutnumber300_000Positive, finite maximum wait. Milliseconds. An explicit value is honored; it does not shorten the server session. Elapsed time uses a monotonic clock.
pollIntervalnumber2_000Positive, finite time between polls. Milliseconds.
openBrowserbooleantrueWhen false, prints the URL instead of launching the browser.
directbooleanfalseSkip the end user’s confirmation screen, duration choice and in-flow policy step, closing the page on delivery. Requires exactly one entry in providers; throws AlterValueError locally otherwise. Never implied by the provider count.
grantPolicyGrantPolicyInput—Optional absolute expiry and TTL bounds passed to the Connect UI. TTL fields are seconds.
allowUserPolicyRulesbooleantrueWhether the end user may set their own usage limits, that is policy rules (deny, require-approval, time window, request quota, or operation-parameter content rules), in the Connect popup while authorizing. Forwarded to the Connect session. The limits are applied as part of authorizing the connection; if they cannot be applied, the connection is revoked rather than left in place without them. Set false to hide the policy step. Has no effect on a session minted with direct, which has no confirmation screen; naming one provider alone does not remove it. Must be a boolean; a non-boolean throws AlterValueError at the SDK boundary.
const results = await app.connect({
providers: ["<provider-id>"],
timeout: 10 * 60_000,
});
console.log(`Connected ${results.length} provider(s)`);
for (const failed of results[0]?.failedGrants ?? []) {
console.warn(`Not connected: ${failed.providerId}: ${failed.message}`);
}

Use this for CLI tools and scripts. For embedded UI flows, prefer createConnectSession() + pollConnectSession() so application code controls the rendering.

The browser launch uses the optional open package when the host application installs it. It is not a declared SDK peer dependency. When it is unavailable, connect() falls back to printing the URL.

Throws:

  • AlterValueError — grantPolicy is malformed, allowUserPolicyRules or direct is not a boolean, direct is set without exactly one provider, or providers is empty, not an array of strings, or has a blank entry.
  • ConnectTimeoutError — Alter received no completion callback before the local deadline or observed session expiry; inspect details.reason.
  • ConnectDeniedError — the user clicked Deny and the session had nothing left to try.
  • ConnectConfigError — a provider configuration failure, including the typed provider_configuration_unavailable, shared_dev_credential_unavailable, and managed_oauth_scope_approval_required terminals returned when an app cannot start a fresh provider authorization. For managed OAuth approval, contact Alter to approve the requested scopes — or narrow the app’s configured scopes to the approved set — before connect() is called again; it is retryable: false and every fresh session fails identically until the approval changes.
  • ConnectFlowError — another terminal failure, including a completed flow that kept no grant. That total-failure error carries details.failed_grants and details.error_code: grant_policy_application_failed when any grant was revoked because selected usage limits could not be applied, grant_activation_failed when every selected connection instead could not be completed at Confirm. Partial failures are returned as ConnectResult.failedGrants.
  • BackendError — an identity-synchronization refusal from polling, split by statusCode: 503 is transient identity-provider sync unavailability (retry later; details.retry_after_seconds carries a backoff hint when present), while 409 means the identity provider is inactive or a group name is ambiguous — conditions an app operator must repair, so retrying does not help. details.error_code names the terminal. Also thrown for malformed backend responses.

Open the application’s configured IDP login page in the user’s default browser, poll until the user authenticates, and return their IDP JWT.

async authenticate(options?: { timeoutMs?: number }): Promise<AuthResult>
OptionTypeDefaultDescription
timeoutMsnumber300_000Maximum wait. Milliseconds.

Returns AuthResult with userToken and userInfo. Throws BackendError with details.error no_idp_configured (HTTP 400 — the application has no identity provider) or no_wallet_client (HTTP 400 — the identity provider verifies JWTs but has no sign-in client, so sign users in with the identity provider’s own SDK and pass the token to verifyUserToken() instead; see Sign-in modes). Throws BackendError with details.error === "idp_signin_client_approvals_only" (HTTP 409) when the identity provider’s sign-in client is registered for approvals only, so it cannot sign users in here.

App-only method.

The split, headless counterpart to authenticate(). Mints a sign-in session and returns the IDP authUrl without opening a browser or mutating the instance. Hand authUrl to a user on any channel (a chat message, an MCP client, a printed link), then poll with pollAuthSession(). Because it installs no userTokenGetter, it is safe on a shared App that resolves a JWT per request.

async createAuthSession(): Promise<AuthSession>

Returns AuthSession with sessionToken, authUrl, expiresIn, and expiresAt. sessionToken is persistable: a worker can store it, poll in the background, and resume after a restart. Throws BackendError with details.error no_idp_configured (HTTP 400 — the application has no identity provider) or no_wallet_client (HTTP 400 — the identity provider verifies JWTs but has no sign-in client, so sign users in with the identity provider’s own SDK and pass the token to verifyUserToken() instead; see Sign-in modes), or BackendError (malformed response, or HTTP 409 idp_signin_client_approvals_only when the identity provider’s sign-in client is registered for approvals only). Requires the idp_users:write scope. App-only — agents do not start user logins.

const session = await app.createAuthSession();
// Send `session.authUrl` to the user; never log it (it carries the session token).
return { signInUrl: session.authUrl, session: session.sessionToken };

The polling half of the link-based flow. Resolves when the user finishes IDP login, returning their JWT. Like createAuthSession(), it installs no userTokenGetter — the caller decides what to do with the token.

async pollAuthSession(
sessionToken: string,
options?: { timeoutMs?: number; pollIntervalMs?: number },
): Promise<AuthResult>
OptionTypeDefaultDescription
timeoutMsnumber300_000Maximum wait. Milliseconds. The Python SDK’s equivalent takes seconds.
pollIntervalMsnumber2_000Milliseconds between polls.

Transient network blips and non-200 responses are retried until the deadline; only a terminal IDP error, an expired session, or the timeout ends the loop.

Returns AuthResult with userToken and userInfo. Throws AlterValueError (blank sessionToken), ConnectTimeoutError (deadline; details.reason is "poll_deadline_elapsed"), or the matching typed subclass on a permanent backend failure. An identity-synchronization refusal is surfaced as BackendError rather than a generic sign-in failure, split by statusCode: 503 is transient identity-provider sync unavailability (retry later; details.retry_after_seconds carries a backoff hint when present), while 409 means the identity provider is inactive or a group name is ambiguous — conditions an app operator must repair, so retrying does not help. details.error_code names the terminal. Requires the idp_users:read scope.

const session = await app.createAuthSession();
const result = await app.pollAuthSession(session.sessionToken, { timeoutMs: 600_000 });

Return the calling principal’s accessible grants, paginated.

async listGrants(
options?: AppListGrantsOptions | AgentListGrantsOptions,
): Promise<UnifiedGrantListResult>

Available on both App and Agent. The backend dispatches by principal kind:

  • App — every grant the application owns: OAuth and managed-secret, across all principal kinds (user, group, system, agent). With userTokenGetter configured (or endUserToken passed), the list narrows to that end user — their own grants plus group grants they are a live member of.
  • Agent — only what the agent can reach: OAuth grants delegated to it, plus managed-secret grants it owns or that are delegated to it (accessVia marks ownership vs delegation). Other agents’ grants, non-delegating users’ grants, and generic system grants are invisible. Mixed result type.

Both AppListGrantsOptions and AgentListGrantsOptions accept the same filters — all AND-ed, each only narrowing the result:

OptionTypeDefaultDescription
providerIdstring—Filter to one provider. OAuth: the provider ID. Managed secret: the per-secret slug, unique per app.
statusstring—Filter by grant status (e.g. "active", "expired", "revoked").
accountstring—Filter by accountIdentifier (multi-account disambiguation).
labelstring—Filter to one sibling-grant label (multi-grant model; applies to both OAuth and managed-secret labels).
endUserTokenstring—Scope to one end user by their JWT — their direct grants plus live group-member grants. On App, takes precedence over userTokenGetter; on Agent, narrows the delegated OAuth grants (agent-owned managed-secret grants are unaffected). An invalid token is a hard 401, never a silent fall-through to app scope.
limitnumber100Page size (1..1000).
offsetnumber0Page offset.

Returns UnifiedGrantListResult. Each entry is either an OAuthGrantItem or a ManagedSecretGrantItem; branch on grantKind.

const page = await agent.listGrants({ limit: 50 });
for (const grant of page.grants) {
if (grant.grantKind === "oauth") {
console.log(grant.providerId, grant.scopes);
} else {
console.log(grant.managedSecretSlug, grant.label);
}
}
if (page.hasMore) {
// Fetch next page with offset = page.offset + page.limit.
}

Throws AlterValueError for out-of-range limit / offset / providerId.

Revoke a grant. App-only.

async revokeGrant(
grantId: string,
options?: RevokeGrantOptions,
): Promise<RevokeGrantResult>
OptionTypeDescription
reasonstringFree-form reason stored on the audit row.

Returns RevokeGrantResult carrying the grant ID, success flag, and revocation timestamp.

await app.revokeGrant(grantId, { reason: "User requested account deletion" });

Revoking an OAuth grant also cascades the revocation to every agent delegation on it. With an agent key, the revoke is bound to the grants the agent is the principal of (its own delegations and agent-owned grants); any other grant rejects with GrantNotFoundError, regardless of the agent’s capability allowlist.

Mint a sibling grant on an existing grant’s credential without starting a new authorization flow. App-only.

async mintGrant(
sourceGrantId: string,
options: {
label: string;
grantPolicy?: Record<string, unknown>;
grantTags?: string[];
},
): Promise<GrantInfo>
ParameterTypeDescription
sourceGrantIdstringActive grant owned by the application. Its credential and principal binding are reused.
labelstringRequired sibling address. It must be unique among active grants on the credential.
grantPolicyRecord<string, unknown>Optional per-grant policy. expiresAt and maxTtlSeconds use this SDK’s camelCase (the same GrantPolicyInput keys createConnectSession takes) and are validated locally; the wider policy grammar (restrictions, requires_approval, …) uses the backend’s snake_case keys and is validated server-side. A default TTL is not part of the mint grammar — defaultTtlSeconds (either spelling) throws AlterValueError; it is accepted only by the Connect-session methods and createManagedSecretGrant. Supplying both spellings of one camelCase field also throws.
grantTagsstring[]Optional non-empty tag strings.

The new grant copies the source principal binding but not its delegations. It can only tighten access through its own policy.

const sibling = await app.mintGrant(sourceGrantId, {
label: "read-only",
grantPolicy: {
expiresAt: "2026-08-01T00:00:00Z",
restrictions: { allowed_methods: ["GET"] },
},
grantTags: ["reporting"],
});
console.log(sibling.grantId, sibling.credentialId, sibling.label);

Returns GrantInfo. Throws AlterValueError for malformed local input, GrantNotFoundError when the source grant is unavailable, SiblingLabelConflictError when the label is already active, PolicyViolationError for an agent caller (error agents_cannot_mint) or a source grant that carries grant-level policy rules (error mint_source_has_grant_rules: a sibling does not inherit them, so mint from a grant without grant-level rules, or author the rules on the new grant), and BackendError for invalid policy or grant-limit responses.

Revoke an agent’s delegation on a grant. The grant itself stays active; only the named agent loses access.

// App: operator revokes a named agent's delegation.
async revokeDelegation(grantId: string, agentId: string): Promise<void>
// Agent: agent revokes its own delegation on a grant.
async revokeDelegation(grantId: string): Promise<void>

Both paths are idempotent.

// Operator path.
await app.revokeDelegation(grantId, agentId);
// Self-revoke path — the agent removes its own access.
await agent.revokeDelegation(grantId);

Throws AlterValueError when agentId is missing on the App path.

Agent only. Onward (agent → agent) delegation — the second hop. An agent that already holds a grant mints a child of it for another agent, without the credential owner consenting again.

async delegate(
grantId: string,
toAgentId: string,
options?: {
delegable?: boolean;
scopeConstraint?: string[] | null;
ttlSeconds?: number | null;
},
): Promise<DelegationResult>
ParameterTypeDescription
grantIdstringA grant the calling agent already holds.
toAgentIdstringThe agent that should receive the child grant.
delegablebooleanWhether the recipient may re-delegate the child onward. true or false is stored as given. Whatever delegable says, the held grant must be delegable and the credential’s operator ceiling (a managed secret’s delegation policy, or the OAuth provider’s agent sharing setting) must allow onward delegation; otherwise the call throws GrantNotDelegableError, renewals included. true also needs room under the ceiling’s depth for the child to delegate once more, and throws GrantNotDelegableError when there is none; false never triggers that depth check. Omit delegable to keep the existing delegation’s setting: re-delegating to an agent that already holds a child of this grant keeps its current value, and a new child is created as a leaf (onward delegation is opt-in per hop). The SDK sends the field only when it is set, so an explicit false reaches the backend.
scopeConstraintstring[] | nullNarrow the child to a subset of the parent’s provider scopes. Provide a non-empty array of at most 100 concrete scope strings, each ≤ 512 characters and a valid RFC 6749 scope-token (printable ASCII — no spaces, " or \; one atom per scope); "*", empty strings, and an empty array are rejected (a wildcard never narrows). Omit or pass null for full scope. Every atom must be within the parent grant’s effective scopes (its credential scopes, narrowed by any constraint already on its chain; a broader scope that subsumes the atom qualifies) — an atom outside that set is rejected with HTTP 422 invalid_scope_constraint, and an existing child delegation is left unchanged. Managed-secret grants carry no provider scopes, so a constraint on a managed-secret delegation is always rejected — narrowing applies to OAuth delegations. A scope-narrowed grant is proxy-only — call it with proxyRequest().
ttlSecondsnumber | nullPositive-integer lifetime cap in seconds. Omit or pass null for no child-specific cap. A value never extends past the parent; the backend clamps the child’s expiry to the parent’s.

The held grant must have been created as delegable: the user chose that on the consent screen (or in the wallet), within the credential’s operator ceiling, which is a managed secret’s delegation policy or the OAuth provider’s agent sharing setting. The ceiling is checked again on every onward call, so a ceiling turned off after the grant was created refuses further delegation. A child can only narrow — fewer scopes, a shorter lifetime — never widen.

Returns DelegationResult — the freshly minted child grant (grantId, parentGrantId, depth, delegable, status, expiresAt).

Throws:

  • GrantNotDelegableError — the held grant has no consenting user, is not delegable, or the credential’s operator ceiling is off (a managed secret’s delegation policy or the OAuth provider’s agent sharing setting), or delegable: true for a child the depth ceiling leaves no further hop (HTTP 403 grant_not_delegable). Its detailReason names which: no_consenting_user, holder_not_delegable, ceiling_off or no_onward_hop.
  • GrantNotFoundError — the caller does not hold grantId.
  • AgentNotFoundError — toAgentId names no active agent of the app (HTTP 404 agent_not_found).
  • AlterValueError — empty inputs, a malformed scope constraint, or a non-positive/non-integer ttlSeconds.
  • BackendError — HTTP 422 delegation_depth_exceeded: the child would sit deeper than the ceiling allows.
  • BackendError — HTTP 422 invalid_scope_constraint: a scopeConstraint atom outside the parent’s effective scopes (the existing child, if any, is unchanged).
import { Agent, GrantNotDelegableError } from "@alter-ai/alter-sdk";
// The agent's own key, from agents.create.
const agent = new Agent({ apiKey: "alter_key_…" });
try {
const child = await agent.delegate("…", "…", {
scopeConstraint: ["resource:write"],
ttlSeconds: 3600,
});
console.log(child.grantId, child.parentGrantId, child.depth);
} catch (e) {
if (e instanceof GrantNotDelegableError) {
// e.detailReason says why: "ceiling_off" — the operator turns sharing on;
// "holder_not_delegable" — ask the user again with delegable: true.
console.warn("cannot share onward:", e.detailReason);
} else {
throw e;
}
} finally {
await agent.close();
}

listGrants() returns each grant with parentGrantId (the grant it was minted under, null for a root) and depth (its distance from the root), so the full delegation chain reconstructs from the flat list.

Provision a managed-secret grant. App-only.

async createManagedSecretGrant(
managedSecretId: string,
options: {
principal: Principal;
grantPolicy?: GrantPolicyInput;
},
): Promise<CreateGrantResult>

The principal field is a discriminated union — TypeScript narrows it based on the type discriminator. Each principal kind binds the grant to a different identity surface; the label lives on the principal itself (required for user/group bindings, optional otherwise):

Principal kindtypeRequired fieldsWhen to use
UserPrincipal"user"userToken, labelOne end user (resolved from JWT).
GroupPrincipal"group"externalGroupId, idpId, labelAll members of an IDP group inherit access. Requires an identity provider that supports group grants, with its webhook integration enabled — otherwise the backend rejects the call with a 422 group_principal_unsupported_idp error.
SystemPrincipal"system"label (optional)Server-to-server. No caller identity.
AgentPrincipal"agent"—Not accepted by this SDK method. Create agent-bound managed-secret grants via the Developer Portal flow instead.

The optional grantPolicy overrides the TTL bounds inherited from the parent managed secret:

FieldTypeDescription
expiresAtstring | nullAbsolute ISO 8601 expiry.
maxTtlSecondsnumber | nullCap on requested credential TTL.
defaultTtlSecondsnumber | nullDefault TTL when callers don’t request one.
import type { Principal } from "@alter-ai/alter-sdk";
const principal: Principal = {
type: "user",
userToken: callingUserJwt,
label: "production-read-only",
};
const grant = await app.createManagedSecretGrant("ms_…", {
principal,
grantPolicy: { maxTtlSeconds: 3600 },
});
console.log(grant.grantId, grant.principalType);

Returns CreateGrantResult with the new grantId, the resolved principal type, and the label.


Poll an approval row. By default returns immediately; pass wait to have the server hold the request open until the status changes.

async getApprovalStatus(
approvalId: string,
options?: { wait?: number },
): Promise<ApprovalStatus>

options.wait is an optional number of seconds to wait for a status change before returning. 0 (the default) returns immediately; a positive value asks the server to hold the request open until the status changes or wait elapses, then return the current status — a latency optimization that avoids tight re-polling, with an identical response shape either way. The maximum is 25; larger values are rejected with a validation error, thrown as a BackendError. Most callers should prefer awaitApproval, which manages the wait loop and returns the result.

Returns ApprovalStatus. The status field is one of:

  • "pending" — no approver decision yet.
  • "approved" — approver said yes; backend is about to execute.
  • "executing" — backend is calling the provider.
  • "executed" — finished; the result blob is available.
  • "denied" — approver said no.
  • "expired" — approval window elapsed without a decision.
  • "failed" — backend errored while executing the proxied call.

The returned ApprovalStatus exposes a derived isTerminal boolean — true when status is "denied", "expired", "executed", or "failed". Use result.isTerminal to check whether further polling is pointless.

Throws BackendError, NetworkError, TimeoutError.

Poll until the approval reaches a terminal state, then return the result. Transient 502 / 503 / 504 responses and transport blips are retried within the deadline; permanent failures propagate immediately.

async awaitApproval(
approvalId: string,
options?: { timeoutMs?: number; pollIntervalMs?: number },
): Promise<ApprovalResult>
OptionTypeDefaultDescription
timeoutMsnumber300_000 (5 min)Maximum local wait. Milliseconds.
pollIntervalMsnumber2_000Fallback cadence between polls. Each poll asks the server to hold the request open until the status changes, so this rarely paces the loop; it spaces retries after a transient failure, and it paces polling against an older backend that answers every poll immediately. Milliseconds.

Returns ApprovalResult when the row reaches executed.

Throws:

try {
const final = await app.awaitApproval(approvalId, { timeoutMs: 10 * 60_000 });
return final.bodyJson();
} catch (error) {
if (error instanceof ApprovalDeniedError) {
// Surface "request was rejected" to the user.
}
throw error;
}

ApprovalResult carries the provider response as base64.

final.bodyBytes(); // Uint8Array
final.bodyText(); // string (utf-8 default)
final.bodyText("latin1");
final.bodyJson(); // parsed JSON

final.bodyTruncated is true if the backend truncated the body (very large responses).

PendingApproval .approvalUrl is the deep link to the approver’s wallet UI. Surface it through whatever channel the application uses — modal, redirect, chat message, or push notification. Email is sent automatically when the backend has an email provider configured.

if (result instanceof PendingApproval) {
await notifyApprover({
title: "Approval requested",
expiresAt: result.expiresAt,
url: result.approvalUrl,
});
await app.awaitApproval(result.approvalId, { timeoutMs: 60 * 60_000 });
}

Report an issue with this page

Necessary

Required for sign-in, security, authorization, and remembering your choices.

Always active

Analytics

Helps us understand which product and documentation features are useful.

Performance diagnostics

Uses performance tracing and privacy-masked session replay to diagnose problems.

You can change these choices at any time from Cookie settings.