Skip to content

Reference

Client

App and Agent — constructors, properties, lifecycle, withConstraints, getAgent.

import { App, Agent } from "@alter-ai/alter-sdk";

The SDK exposes two top-level client classes. They share most of the request surface but model two different principal kinds on the wire. Pick the right class for the workload:

  • App — application-side. Holds the application’s API key (alter_rk_…). Provisions agents, mints Connect sessions, calls provider APIs under any stored grant.
  • Agent — workload-side. Holds the agent’s own key (from agents.create or alter agents create; issued today with the legacy alter_key_… prefix — an alter_ak_… key from API Keys is bound to no agent and cannot use delegated grants). Can only reach credentials delegated or directly bound to the agent.

Methods that do not apply to a principal kind are intentionally absent from that class — TypeScript flags the missing methods at compile time.

The application-side client.

import { App, CallerType } from "@alter-ai/alter-sdk";
const app = new App({
apiKey: process.env.ALTER_API_KEY!,
timeout: 95_000,
caller: "customer-portal",
callerType: CallerType.SERVICE,
userTokenGetter: () => getCurrentUserJwt(),
});
try {
const page = await app.listGrants();
console.log(page.total);
} finally {
await app.close();
}
new App(options: AppOptions)
OptionTypeDefaultDescription
apiKeystring—Application API key (alter_rk_…). Required.
timeoutnumber95000HTTP timeout in milliseconds. The default is sized so a slow credential refresh returns the SDK’s typed timeout error (with its timeout_reason) rather than a bare client-side timeout; lower it for latency-sensitive callers that prefer to fail fast.
callerstring—Caller identifier for audit attribution.
callerTypeCallerType | "agent" | "service"SERVICEDistinguishes backend services from AI agents. Only effective when caller is set.
userTokenGetter() => string | Promise<string>—Supplies the current end-user JWT for user-scoped identity resolution. A per-call userToken overrides it; headless system-grant resolution can omit it.
loggerAlterLoggerglobal consolePluggable logger. See AlterLogger.

Throws AlterValueError when the constructor argument is not an object. Throws AlterSDKError if apiKey is missing or malformed, if userTokenGetter is present but not callable at runtime, if logger is present but logger.warn is not a function, or if the configured backend URL is invalid.

PropertyTypeDescription
actorIdstring | nullBackend-resolved actor UUID. Populated after the first authenticated call.
lastRetryInfoRetryInfo | nullToken-refresh retry metadata from the most recent request() call.
lastRateLimitRateLimitSnapshot | nullLatest complete Alter rate-limit reading from a metered backend response. null means unknown, never unlimited.
baseUrlstringBackend the client is pinned to. Diagnostic accessor.
agentsAgentsNamespaceManaged agent CRUD.
keysKeysNamespaceScoped sub-key lifecycle.
scopesScopesNamespaceScope catalog discovery.
oauthProvidersOAuthProvidersNamespaceOAuth provider catalog discovery.
providerSpecsProviderSpecsNamespaceProvider operation discovery.
spansSpansNamespaceUser-defined trace-span submission.

The App class exposes:

The workload-side client.

import { Agent } from "@alter-ai/alter-sdk";
const agent = new Agent({
apiKey: process.env.AGENT_API_KEY!,
caller: "research-agent",
userTokenGetter: () => getCallingUserJwt(),
});
try {
const info = await agent.me();
console.log(info.status);
} finally {
await agent.close();
}
new Agent(options: AgentOptions)
OptionTypeDefaultDescription
apiKeystring—Agent API key. Required. The managed agent’s own key, from alter agents create / alter agents mint-key (currently the legacy alter_key_… prefix). An agent-typed alter_ak_… key from API Keys also constructs an Agent, but it is bound to no managed agent, so it cannot reach grants bound or delegated to a named agent.
timeoutnumber95000HTTP timeout in milliseconds. The default is sized so a slow credential refresh returns the SDK’s typed timeout error (with its timeout_reason) rather than a bare client-side timeout; lower it for latency-sensitive callers that prefer to fail fast.
callerstring—Caller identifier for audit attribution.
userTokenGetter() => string | Promise<string>—Resolves the calling end-user JWT. Used for delegation disambiguation when the agent holds delegations from multiple users on the same provider.
loggerAlterLoggerglobal consolePluggable logger.

callerType is forced to AGENT on this class. Throws AlterValueError when the constructor argument is not an object or apiKey is not a non-empty string. Throws AlterSDKError if a non-empty apiKey is malformed, if userTokenGetter is present but not callable at runtime, if logger is present but logger.warn is not a function, or if the configured backend URL is invalid.

PropertyTypeDescription
actorIdstring | nullBackend-resolved actor UUID.
lastRetryInfoRetryInfo | nullToken-refresh retry metadata.
lastRateLimitRateLimitSnapshot | nullLatest complete Alter rate-limit reading from a metered backend response. null means unknown, never unlimited.
baseUrlstringBackend the client is pinned to.
keysKeysNamespaceScoped sub-key lifecycle.
scopesScopesNamespaceScope catalog discovery.
oauthProvidersOAuthProvidersNamespaceOAuth provider catalog discovery.
providerSpecsProviderSpecsNamespaceProvider operation discovery.
spansSpansNamespaceUser-defined trace-span submission.

Agent has no agents namespace — agent CRUD is application-scoped.

The Agent class exposes:

Resolve the canonical identity set for a request.

// App
async resolveIdentity(options?: {
userToken?: string;
includeProfile?: boolean;
}): Promise<IdentityContext>
// Agent
async resolveIdentity(options?: {
userToken?: string;
appUserId?: string;
includeProfile?: boolean;
}): Promise<IdentityContext>

App falls back to its configured userTokenGetter when userToken is omitted. Agent requires an explicit userToken or appUserId to resolve an end user; its constructor getter is not forwarded by this identity method. The agent-only appUserId shortcut succeeds only when an existing consent edge authorizes that agent for the user. With no user selector, the method returns the headless app or agent identity.

includeProfile defaults to false; enable it only when email and displayName are needed. Returns IdentityContext. Invalid options throw AlterValueError; identity or backend failures use the standard typed error hierarchy.

Mint a short-lived, identity-only assertion for a downstream audience.

// App
async assertIdentity(options: {
audience: string;
userToken?: string;
ttlSeconds?: number;
includeProfile?: boolean;
}): Promise<IdentityAssertion>
// Agent
async assertIdentity(options: {
audience: string;
userToken?: string;
appUserId?: string;
ttlSeconds?: number;
includeProfile?: boolean;
}): Promise<IdentityAssertion>

audience is a required URI with a scheme and at most 512 characters. ttlSeconds defaults to 120 and must be an integer from 10 through 300. User selection follows resolveIdentity(), including the agent-only appUserId shortcut and the App getter fallback. Returns IdentityAssertion.

App only. Validate an incoming end-user bearer token and return its verified subject.

async verifyUserToken(token: string): Promise<string | null>

This method is fail-closed: it returns null for a blank or untrusted token, transport failure, malformed response, unexpected status, or a closed client. Treat every null result as an authentication rejection.

Return a constrained sibling client. Macaroon-style attenuation that can only narrow access, never broaden it. Two attenuations are available, and at least one of scopes / rule must be supplied:

  • scopes narrows the scope set. The argument must be a subset of the parent client’s effective scope set; the backend enforces the narrowing on every authenticated call.
  • rule attaches an optional request rule, evaluated server-side, that can only further restrict each request the returned client makes — it can never widen access. Supported shapes include json_match deny rules, require_approval HITL rules, content_match rules built with contentMatchRule(...), operation_allowlist rules built with operationAllowlistRule(...), and request_allowlist rules built with requestAllowlistRule(...). A raw-token retrieval carries no request method/URL, so method-keyed conditions are treated as satisfied there (a raw token can issue any method) — scope method restrictions through the proxy surface, which carries the request method. If a request is frozen for human approval (HITL 202), the per-request rule is not re-evaluated on the deferred post-approval execution — it cannot widen access (the rule did not match the frozen request, and the grant plus every stored policy rule still bound the execution), but prefer a stored rule when the constraint must hold at execute time.
withConstraints(options: { scopes?: readonly string[]; rule?: RequestRule }): App
withConstraints(options: { scopes?: readonly string[]; rule?: RequestRule }): Agent

RequestRule is shaped:

interface RequestRule {
ruleType: string;
ruleBody: Record<string, unknown>;
}

For the json_match rule type, ruleBody is { when: { <attr>: string | string[] }, effect: "deny" }, where <attr> is one of method, provider_id, app_id, agent_id, api_key_id, environment, client_ip, resource_kind, and effect is always "deny". For operation-aware policies, prefer the three typed builders. The ruleBody field names are the rule grammar’s own — they are not camelCased.

contentMatchRule(options: ContentMatchRuleOptions): RequestRule
operationAllowlistRule(options: OperationAllowlistRuleOptions): RequestRule
requestAllowlistRule(options: RequestAllowlistRuleOptions): RequestRule

contentMatchRule(...) says what the client may not do: it emits the snake_case content_match body, validates parameter-condition shape, requires redactFields iff effect: "redact", and requires maxSessionAgeSeconds iff effect: "step_up" as an integer in [1, 86400]. operationAllowlistRule(...) says what the client may do: only the listed operation ids and/or families may run; every other classified operation is denied (PolicyViolationError, reason operation_not_allowed), and so is any request the catalog cannot classify (operation_unclassified) or that is an unreviewed operation the list does not name (operation_unreviewed, raised as OperationUnreviewedError). Several allowlists on one chain — a stored app or grant rule plus this per-request rule — intersect, so the per-request rule only narrows. Both builders require at least one of operations / families, accept at most 100 combined entries with operation ids of at most 255 characters, reject unknown option keys, and throw AlterValueError locally on a malformed input. Option shapes and the condition operators are on the types page.

requestAllowlistRule(...) says what a request must look like to be allowed: a request the rule selects passes only when every condition in require (1 to 20) holds, and is otherwise denied (PolicyViolationError, reason request_condition_not_met). A request it does not select is not judged by it. The rule has two forms, chosen by the selector and never mixed. With operations / families it selects cataloged operations and each condition names a projected parameter (name). With endpoints (and optionally methods) it selects by HTTP method and path and each condition addresses the request as sent (at: body:<path>, query:<name> or header:<name>), so it needs no operation catalog and compares values exactly. strict: true also denies a selected request that carries a field no condition names (reason request_field_not_listed). The builder throws AlterValueError locally when no selector or both selectors are given, a condition does not match the form, an operator or its value is malformed, an option key is unknown, or optional is combined with exists. See Allow only requests that meet conditions for the operators and the address grammar.

Both the parent and constrained sibling share the same internal transport clients, signing state, and background-task sets. Closing the parent also makes the sibling unusable; closing the sibling alone leaves the parent untouched.

withConstraints() cannot be chained — calling it on an already-constrained client throws AlterValueError. It also throws AlterValueError if neither scopes nor rule is supplied. Calling it on a closed client throws AlterSDKError.

import {
contentMatchRule,
operationAllowlistRule,
requestAllowlistRule,
} from "@alter-ai/alter-sdk";
const narrowed = app.withConstraints({ scopes: ["grants:read"] });
const page = await narrowed.listGrants();
// Attach a json_match deny rule to every request from this constrained client:
const restricted = app.withConstraints({
rule: {
ruleType: "json_match",
ruleBody: { when: { method: "POST" }, effect: "deny" },
},
});
// Attach an operation-aware content rule. The helper validates that
// maxSessionAgeSeconds is an integer in [1, 86400].
const freshSession = app.withConstraints({
rule: contentMatchRule({
operations: ["resource.create"],
effect: "step_up",
maxSessionAgeSeconds: 300,
}),
});
// Deny a QuickBooks `query` call unless the SQL it carries — the `query`
// query-string parameter of that operation — is literally one of these
// (the `*` is a star, not a wildcard; the comparison ignores case and
// surrounding whitespace):
const literalStatements = app.withConstraints({
rule: contentMatchRule({
operations: ["query"],
params: [
{ name: "query", op: "not_all_in", value: ["select * from account"] },
],
}),
});
// Allow only these two operations; everything else — and anything the
// catalog cannot classify — is denied:
const readOnly = app.withConstraints({
rule: operationAllowlistRule({
operations: ["query", "generalledger/query_a_report"],
}),
});
// Allow a POST to /v1/orders only when it meets every condition, and
// carries no field the rule does not name:
const boundedOrders = app.withConstraints({
rule: requestAllowlistRule({
methods: ["POST"],
endpoints: ["/v1/orders"],
require: [
{ at: "body:amount", op: "lte", value: 50000 },
{ at: "body:currency", op: "in", value: ["usd", "eur"] },
{ at: "body:note", op: "exists", value: true },
],
strict: true,
}),
});

Return an Agent instance that impersonates a named managed agent for audit attribution.

getAgent(agentId: string): Agent
ParameterTypeDescription
agentIdstringUUID of the managed agent to impersonate.

Throws AlterValueError if agentId is not a valid UUID, or if the App has been closed. The agent is not looked up here: when it does not exist or is no longer active, the returned Agent’s next call throws AgentNotFoundError (HTTP 404, details.error === "caller_agent_unresolved").

const research = app.getAgent("d3f4e5a6-7b8c-9d0e-1f2a-3b4c5d6e7f80");
try {
await research.proxyRequest({ method: "GET", url: url, provider: "<provider-id>",
userToken, });
} finally {
await research.close();
}

Complete any pending work, then mark the client closed so subsequent operations fail deterministically.

async close(): Promise<void>
async [Symbol.asyncDispose](): Promise<void>

Both App and Agent expose close() and Symbol.asyncDispose. The SDK does not auto-close on process exit; call it explicitly (typically from a try/finally) or use await using in runtimes that support explicit resource management:

const app = new App({ apiKey });
try {
// ...
} finally {
await app.close();
}
await using scopedApp = new App({ apiKey });
// scopedApp.close() runs when the scope exits.

close() is idempotent. Closing a root client drains the shared background-task set; closing a constrained sibling only marks that sibling closed, so close the root before process shutdown. Subsequent calls on a closed client throw AlterSDKError.

app.integrations (also available on Agent) exposes generic discovery and execution: list() lists publications, contract(provider, version) reads an immutable contract, and execute submits its provider, version, operation and arguments with a grant or connection selector. Execution returns an immediate ApprovalResult or PendingApproval. The backend authorizes OAuth or managed-secret grants before constructing provider requests.

Typed provider methods live in separate provider packages, never in core. Browse Integrations: a provider with a typed package has an SDK guide and an API reference with installation guides, complete operation schemas, both-language examples and links to each pinned OpenAPI specification. Install @alter-ai/sdk plus @alter-ai/<provider>. Their methods return IntegrationCall<T>; await call.wait({ timeoutMs: 300000, pollIntervalMs: 2000 }) returns IntegrationResult after immediate execution or approval. Waiting polls approval state and does not resubmit the provider operation. See managed result types.

executeStream takes the same options as execute and returns a ProxyStreamResponse instead of a buffered result, so a large binary response (a file download) arrives as it is sent, with no size cap and no truncation. Policy, connection authorization and audit are the same as execute. An operation a policy holds for approval is refused with ProxyTransferError code proxy_stream_approval_required: request it with execute instead.

const response = await app.integrations.executeStream({
integration: provider, version, operation: operationId, arguments: args, grantId,
});
try {
for await (const chunk of response.iterBytes()) output.write(chunk);
} finally {
await response.close();
}

executeUpload executes an operation whose body is one file (an upload) without the inline limit. Pass the operation’s other arguments (no body) and the file as path or data, named filename (default: the name of path) with media type contentType (default application/octet-stream). metadata is the file’s metadata, a JSON object (Record<string, unknown>), for an operation whose file goes in a multipart attachment body with metadata beside it (an accounting provider’s attachment record). An operation whose body is the file itself (a file-storage upload) takes no metadata and refuses it with invalid_operation_input. The operation is declared with the file’s size and SHA-256, every policy runs on that declaration, and only then are the bytes sent, once and never retried. Policy, approval and audit are the same as execute, which takes this route by itself when an inline file object, or an attachment body holding one file ({ files: [{...}] }, its metadata included), is too large (about 3.7 MiB of file; the arguments are measured as Alter measures them, JSON with a space after each , and : and every non-ASCII character counted as its six-byte \uXXXX escape), so a provider package’s typed upload method needs no change. An operation whose body is not one file is refused with ProxyTransferError code operation_not_uploadable.

A PendingApproval means nothing was sent: once approved, deliver the same bytes with deliverApprovedUpload. Waiting on a provider package’s IntegrationCall (await call.wait()) delivers them by itself.

let result = await app.integrations.executeUpload({
integration: provider, version, operation: operationId, arguments: args,
path: "report.pdf", contentType: "application/pdf", grantId,
});
if (result instanceof PendingApproval) {
result = await app.deliverApprovedUpload(result.approvalId, { path: "report.pdf" });
}

app.integrations.resume(approval_id) (Python) or app.integrations.resume(approvalId) (TypeScript) rebuilds a call from stored server identity. Use the provider package’s resume for its response validator. See restart-safe approvals.

Report an issue with this page

Necessary

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

Always active

Analytics

Helps us understand how our website, product, and documentation are used.

Performance diagnostics

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

Advertising

Shares visits and sign-ups with Meta, Reddit, and X so we can measure which of our ads work.

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