Skip to content

TypeScript SDK

Types

Public models, interfaces, and enums exported from @alter-ai/alter-sdk.

Every shape on this page is exported from the package root:

import type {
AlterResponse,
AlterLogger,
ApprovalResult,
ConnectSession,
IdentityContext,
IdentityAssertion,
MemoryScope,
// …
} from "@alter-ai/alter-sdk";

Wire format from the backend is snake_case. The SDK accepts the wire shape in constructors and exposes camelCase properties; toJSON() round-trips back to snake_case for serialization.

Pluggable logger hook. Defaults to the global console.

interface AlterLogger {
warn: (message: string, ...args: unknown[]) => void;
info?: (message: string, ...args: unknown[]) => void;
error?: (message: string, ...args: unknown[]) => void;
debug?: (message: string, ...args: unknown[]) => void;
}

Only warn is currently called by the SDK. The other methods are part of the contract for future use.

The return type of request().

interface AlterResponse extends Response {
readonly retryInfo: RetryInfo | null;
}

Standard Response plus retryInfo — populated when the backend retried a token refresh; null when the token was served from cache or refreshed on the first attempt.

OAuth token metadata. The plaintext access token is never exposed on this object; the SDK injects it into outgoing requests at call time.

FieldTypeDescription
tokenTypestringUsually "Bearer".
expiresInnumber | nullSeconds until expiry.
expiresAtDate | nullAbsolute expiry.
scopesstring[]Scopes granted.
grantIdstringGrant the token resolves to.
providerIdstring | nullProvider slug.
scopeMismatchbooleanThe grant’s scopes no longer cover the configured required set.
injectionHeaderstringHTTP header name used for credential injection.
injectionFormatstringFormat string with a {token} placeholder.
additionalCredentialsRecord<string, string> | nullNon-secret extras (region, service).
additionalInjectionsReadonlyArray<{ target, key, valueSource }> | nullMulti-header or query-param injection rules.

Helpers:

  • isExpired(bufferSeconds?: number): boolean
  • needsRefresh(bufferSeconds?: number): boolean

Metadata about retry attempts during token refresh.

FieldType
totalAttemptsnumber
successfulAttemptnumber
errorsReadonlyArray<RetryErrorInfo>

One failed attempt.

FieldType
attemptnumber
errorstring
errorTypestring
delaySnumber
permanentboolean

A single-grant record.

FieldType
grantIdstring
providerIdstring
scopesstring[]
accountIdentifierstring | null
accountDisplayNamestring | null
statusstring
scopeMismatchboolean
expiresAtstring | null
createdAtstring
lastUsedAtstring | null
principalType"user" | "group" | "system" | "agent"

Returned by listGrants().

FieldType
grantsGrantListItem[]
totalnumber
limitnumber
offsetnumber
hasMoreboolean

Discriminated union over grantKind.

type GrantListItem = OAuthGrantItem | ManagedSecretGrantItem;
FieldType
grantKind"oauth"
grantIdstring
providerIdstring
scopesstring[]
accountIdentifierstring | null
accountDisplayNamestring | null
statusstring
scopeMismatchboolean
expiresAtstring | null
createdAtstring
lastUsedAtstring | null
principalType"user" | "system"
accessVia"ownership" | "oauth_delegation"
delegatedAtstring | null
delegatedAgentIdsstring[]

Returned for any managed-secret grant the caller can reach — an operator (App) list surfaces every principal kind the app owns; an agent list surfaces its own and delegated grants.

FieldType
grantKind"managed_secret"
grantIdstring
managedSecretIdstring
managedSecretSlugstring
managedSecretNamestring
agentIdstring | null
labelstring | null
statusstring
accountIdentifierstring | null
grantPolicyRecord<string, unknown> | null
expiresAtstring | null
createdAtstring
lastUsedAtstring | null
principalType"user" | "group" | "system" | "agent"
accessVia"ownership" | "ms_delegation"
delegatedAtstring | null

Discriminated union passed to createManagedSecretGrant().

type Principal = UserPrincipal | GroupPrincipal | SystemPrincipal | AgentPrincipal;
FieldType
type"user"
userTokenstring
labelstring
FieldType
type"group"
externalGroupIdstring
idpIdstring
labelstring
FieldType
type"system"
labelstring | null
FieldType
type"agent"
labelstring | null

Returned by createManagedSecretGrant().

FieldType
grantIdstring
principalType"user" | "group" | "system" | "agent"
labelstring | null
createdAtstring

Returned by revokeGrant().

FieldType
successboolean
messagestring
grantIdstring
revokedAtstring

Per-grant policy.

FieldType
expiresAtstring | null
createdBystring | null
createdAtstring | null

Returned by createConnectSession().

FieldType
sessionTokenstring
connectUrlstring
expiresInnumber
expiresAtstring

Returned by createManagedSecretConnectSession(). Same shape as ConnectSession.

toString() redacts connectUrl — the URL fragment carries the session token, so logging would be a leak.

Returned per provider by connect() and pollConnectSession().

FieldType
grantIdstring
providerIdstring
accountIdentifierstring | null
scopesstring[]
grantPolicyGrantPolicy | null

Returned by authenticate() and pollAuthSession().

FieldType
userTokenstring
userInfoRecord<string, unknown>

Returned by createAuthSession(). toString() redacts authUrl (it carries the session token as the OIDC state parameter).

FieldTypeDescription
sessionTokenstringHandle to poll with pollAuthSession(). Persistable.
authUrlstringIDP sign-in URL to hand to the end user. Never log it.
expiresInnumberSeconds until the session expires.
expiresAtstringISO 8601 expiry timestamp.

Returned by oauthProviders.list().

MemberTypeDescription
providersReadonly<Record<string, OAuthProviderCatalogItem>>Connectable providers, keyed by id ("<providerId>", …).
getDefaultScopes(provider)readonly string[]Default scopes for a provider, or [] if unknown.
getRequiredScopes(provider)readonly string[]Required scopes for a provider, or [] if unknown.
FieldTypeDescription
idstringProvider id.
namestringInternal provider name.
displayNamestringHuman-readable name.
categorystring | nullProvider category.
descriptionstring | nullShort description.
logoUrlstring | nullLogo URL.
supportsRefreshbooleanProvider issues refresh tokens.
supportsPkcebooleanProvider supports PKCE.
availableScopesReadonly<Record<string, OAuthProviderScopeInfo>>All requestable scopes, keyed by scope string.
defaultScopesreadonly string[]Scopes pre-selected in a Connect flow.
requiredScopesreadonly string[]Scopes that are always requested.
statusstringAlways "active" (only connectable providers are returned).
FieldTypeDescription
descriptionstringWhat the scope grants.
requiredbooleanScope is always requested.
isDefaultbooleanScope is pre-selected by default.

Returned by proxyRequest() when an HITL grant requires approval.

FieldType
approvalIdstring
status"pending"
expiresAtDate
expiresInnumber
approvalUrlstring

Discriminate from ApprovalResult with result instanceof PendingApproval or result.status === "pending".

Snapshot returned by getApprovalStatus().

FieldType
approvalIdstring
statusApprovalStatusValue
expiresAtDate
decidedAtDate | null
decisionReasonstring | null
executedAtDate | null
hasResultboolean

Helpers:

  • isTerminal: booleantrue when status is denied, expired, executed, or failed.
type ApprovalStatusValue =
| "pending"
| "approved"
| "executing"
| "denied"
| "expired"
| "executed"
| "failed";

Returned by awaitApproval() and the synchronous branch of proxyRequest().

FieldType
approvalIdstring | null
statusCodenumber
headersRecord<string, string>
bodyB64string
bodyTruncatedboolean

approvalId is null for the synchronous (non-HITL) branch of proxyRequest() — there was no approval row.

Helpers:

  • bodyBytes(): Uint8Array
  • bodyText(encoding?: BufferEncoding | "utf-8"): string
  • bodyJson(): unknown

A managed agent record. Returned by app.agents.get, app.agents.update, agent.me, and others.

FieldType
idstring
namestring
displayNamestring | null
typeAgentType
statusAgentStatus
scopesRecord<string, unknown>
scopesPendingRecord<string, unknown> | null
scopesAppliesAtDate | null
policyRecord<string, unknown>
metadataRecord<string, unknown>
rateLimitPerMinutenumber | null
versionnumber
createdAtDate
lastUsedAtDate | null
parentAgentIdstring | null
type AgentType = "agent" | "service";
type AgentStatus = "active" | "inactive" | "revoked";

Extends AgentInfo with the freshly-minted plaintext API key.

FieldType
apiKeystring | null
keyIdstring

apiKey is null on an idempotency-replay — the plaintext is not server-side recoverable. Branch on result.apiKey === null rather than treating any returned value as a usable key.

FieldType
agentsAgentInfo[]
totalnumber
limitnumber
offsetnumber
hasMoreboolean

A single API key bound to a managed agent.

FieldType
keyIdstring
keyPrefixstring
namestring
createdAtDate
deprecatedAtDate | null
revokedAtDate | null
lastUsedAtDate | null

Computed property:

  • status: AgentKeyStatus"revoked" when revokedAt is set, "deprecated" when deprecatedAt is set, "active" otherwise.
type AgentKeyStatus = "active" | "deprecated" | "revoked";

Extends AgentKey with the plaintext apiKey (returned exactly once).

FieldType
apiKeystring | null
class AgentKeyList { readonly items: AgentKey[] }

A scoped API key (not bound to a managed agent).

FieldType
idstring
namestring
keyPrefixstring
keyType"rk" | "ak" | "dk" | "pk"
scopesreadonly string[]
scopeVersionnumber
cidrAllowlistreadonly string[] | null
rateLimitRpmnumber | null
expiresAtstring | null
deprecatedAtstring | null
revokedAtstring | null
parentKeyIdstring | null
createdAtstring
lastUsedAtstring | null
status"active" | "rotated" | "revoked"

Extends APIKeyInfo with the plaintext.

FieldType
apiKeystring

Returned by scopes.list().

FieldType
scopeVersionnumber
resourcesReadonly<Record<string, ResourceScopes>>
actionVerbsreadonly string[]
deprecatedreadonly string[]
interface ResourceScopes {
readonly verbs: readonly string[];
}

A one-off deny rule passed to withConstraints({ rule }) — cryptographically bound to every request the constrained client makes and enforced on credential-using calls.

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

Reserved — represents an audit row that the SDK schedules in the background. Application code does not construct or read this directly; the type is exported for callers that want to mock the audit submission pipeline in tests.

Returned by app.resolveIdentity() and agent.resolveIdentity(). The canonical identity set the platform resolved for the request — key external data (memory partitions, channel sessions, authorization tuples) on these IDs, never on email or a raw IDP sub.

FieldTypeDescription
appIdstringThe calling application (tenant).
appUserIdstring | nullCanonical end-user key. null for headless calls.
externalSubjectIdstring | nullStable external join key — the IDP subject identifier.
idpIdstring | nullIdentity provider the subject belongs to.
userStatusstring | null"active" | "suspended". Deprovisioned users are rejected at resolution, never returned.
groupIdsreadonly string[]Stable external group IDs of the user’s unrevoked memberships.
agentIdstring | nullCanonical agent key. null for plain app callers.
actorIdstring | nullAudit correlation label only — NOT a partition key.
traceIdentityTrace | nullEcho of the ambient run/thread trace context.
emailstring | nullOnly with includeProfile: true.
displayNamestring | nullOnly with includeProfile: true.

Method memoryScope(): MemoryScope derives the deterministic memory partition keys. See Propagate identity into memory layers.

FieldType
runIdstring | null
threadIdstring | null

Deterministic, prefixed partition keys derived from an IdentityContext.

FieldTypeDescription
userKeystring | null"alter:user:<app_user_id>"; null for headless contexts.
agentKeystring | null"alter:agent:<agent_id>"; null for app callers.
appKeystring"alter:app:<app_id>".
runKeystring | null"alter:run:<run_id>" from the trace context.
namespacereadonly string[]["alter", <app_id>, <app_user_id>]; ["alter", <app_id>] headless.

Returned by app.assertIdentity() and agent.assertIdentity().

FieldTypeDescription
tokenstringCompact ES256 JWS — verify against the published Alter identity JWKS. Redacted from toString() / inspect output.
expiresAtDateAbsolute expiry (short TTL by design — default 120s, bounds 10–300s).
identityIdentityContextThe identity the assertion encodes.

The assertion is identity-only: it carries no provider tokens, no credentials, no raw IDP claims, and grants nothing by itself — downstream systems map it to their own authorization.

enum HttpMethod {
GET = "GET",
POST = "POST",
PUT = "PUT",
PATCH = "PATCH",
DELETE = "DELETE",
HEAD = "HEAD",
OPTIONS = "OPTIONS",
}
enum CallerType {
SERVICE = "service",
AGENT = "agent",
}

Distinguishes backend services from AI agents at the audit layer. Set via the callerType constructor option.

Slug enum for the OAuth provider catalog. Use the string slug ("google", "github", etc.) directly in request() and createConnectSession() — the enum is provided for IDE autocomplete.