# JavaScript / TypeScript SDK

The `@getstackrun/sdk` package is the STACK client for Node.js JavaScript and TypeScript applications. The package requires Node.js 18 or newer.

## Installation

```bash
npm install @getstackrun/sdk
```

## Quick Start

Sign in once on your development machine:

```bash
npx @getstackrun/cli auth login
```

```typescript
import { Stack } from '@getstackrun/sdk';

const stack = new Stack();
const agents = await stack.agents.list();

// Open a Mission for one agent and issue its Passport in one call.
const started = await stack.missions.start({
  agent_id: 'agt_support',
  mission: { intent_summary: 'Post the daily support update', intent_services: ['slack'] },
});
const token = started.passport.token;

// Completing the Mission revokes its Passports.
await stack.missions.complete(started.mission_id);
```

new Stack() creates an API client and can use the local OAuth profile written by the CLI. A fleet worker uses new Stack({ agent_id }) to sign requests with its locally stored key.

Every Passport is issued for exactly one Mission. stack.missions.start opens the Mission and issues its Passport in one call. If issuance fails, the Mission is revoked.

## Fleet setup

Connect the service first. The policy must name an enrolled provisioner and the connected service. In this example, waitForApproval opens the returned approval URL and waits for the operator to approve the policy. It runs once for policy activation. createWorker returns new Stack({ agent_id: agentId }). The worker can then start Missions within the approved policy.

```typescript
import type { Stack, FleetPolicyInput } from '@getstackrun/sdk';

export async function setupFleet(options: {
  operator: Stack;
  provisioner: Stack;
  policy: FleetPolicyInput;
  policyKey: string;
  workerName: string;
  enrollmentKey: string;
  createWorker: (agentId: string) => Stack;
  waitForApproval: (approval: { approval_id: string; approval_url: string }) => Promise<void>;
}) {
  let policy;
  try {
    policy = await options.operator.fleets.activate(options.policy, { idempotencyKey: options.policyKey });
  } catch (error) {
    const failure = error as { code?: string; details?: { error?: { details?: { approval_id?: string; approval_url?: string } } } };
    const approval = failure.details?.error?.details;
    if (failure.code !== 'GOVERNANCE_APPROVAL_REQUIRED' || !approval?.approval_id || !approval.approval_url) throw error;
    await options.waitForApproval({ approval_id: approval.approval_id, approval_url: approval.approval_url });
    policy = await options.operator.fleets.activate(options.policy, {
      idempotencyKey: options.policyKey, governanceApprovalId: approval.approval_id,
    });
  }
  const enrolled = await options.provisioner.fleets.enrollLocal(policy.id, {
    name: options.workerName, idempotency_key: options.enrollmentKey,
  });
  const worker = options.createWorker(enrolled.agent_id);
  const session = await worker.fleets.session();
  return { policy_id: policy.id, agent_id: enrolled.agent_id, worker, session };
}
```

For workload enrollment, create a client with the trusted workload bearer token and call enrollWorkloadLocal. Use the returned agent ID with a worker client for later requests. Keep the workload token in the runtime's secret store.

enrollLocal and enrollWorkloadLocal store the private key on the worker's machine. Reusing the policy ID and enrollment key reuses that key and renews the same membership. Keep those values stable for that worker.

## Fleet Mission workflow

```typescript
import assert from 'node:assert/strict';
import type { Stack, FleetMissionStartInput, ProxyRequest } from '@getstackrun/sdk';

export async function runFleetMissionExample(stack: Stack, request: FleetMissionStartInput, providerUrl = 'https://slack.com/api/chat.postMessage') {
  const started = await stack.missions.start(request);
  const repeated = await stack.missions.start(request);
  assert.equal(repeated.mission_id, started.mission_id);

  const call: ProxyRequest = { service: 'slack', method: 'POST', url: providerUrl,
    body: { channel: 'C123', text: 'Support update' } };
  const { createHash } = await import('node:crypto');
  const operationId = createHash('sha256').update(JSON.stringify([started.mission_id, 'support-update'])).digest('base64url');
  const response = await stack.proxy.request(call, { passportToken: started.passport.token, authorityRequestId: operationId });
  assert.equal(response.status, 200);

  await assert.rejects(() => stack.proxy.request({ ...call, body: { channel: 'OTHER', text: 'Support update' } },
    { passportToken: started.passport.token, authorityRequestId: `${operationId}_denied` }),
    (error: { status?: number }) => error.status === 403);

  const before = await stack.missions.get(started.mission_id);
  const renewed = await stack.missions.renew(started.mission_id);
  const after = await stack.missions.get(renewed.mission_id);
  assert.equal(renewed.mission_id, started.mission_id);
  assert.deepEqual(after.fleet?.limits, before.fleet?.limits);
  assert.deepEqual(after.fleet?.usage, before.fleet?.usage);

  const completed = await stack.missions.complete(started.mission_id, { output: { done: true } });
  assert.equal(completed.terminal_state, 'completed_successful');
  const stopped = await stack.missions.start({ ...request, idempotency_key: `${request.idempotency_key}-stop` });
  await stack.missions.revoke(stopped.mission_id, { reason: 'operator_initiated_clean' });
  await assert.rejects(() => stack.missions.renew(stopped.mission_id));
  return { mission_id: started.mission_id, operation_id: operationId, completed: true, revoked: true };
}
```

## Services

### stack.fleets and stack.missions

```typescript
stack.fleets.list()
stack.fleets.listPage(page, limit)
stack.fleets.get(policyId)
stack.fleets.membership(agentId)
stack.fleets.membersPage(policyId, page, limit)
stack.fleets.activate(policy, { idempotencyKey, governanceApprovalId })
stack.fleets.revise(policyId, policy, { expectedRevision, idempotencyKey, governanceApprovalId })
stack.fleets.members(policyId)
stack.fleets.revokeMember(policyId, agentId)
stack.fleets.revoke(policyId)
stack.fleets.enrollLocal(policyId, { name, idempotency_key })
stack.fleets.enrollWorkloadLocal(policyId, { name, idempotency_key })
stack.fleets.session(fleetPolicyId)
stack.missions.start({ agent_id, mission: { intent_summary, intent_services?, ... }, passport? })
stack.missions.start(fleetRequest) // fleet form: { fleet_policy_id, idempotency_key, ... }
stack.missions.open({ intent_summary, intent_services?, agent_id?, expires_in_seconds?, max_actions?, ... })
stack.missions.renew(missionId)
stack.missions.complete(missionId, { output })
stack.missions.revoke(missionId, { reason: 'operator_initiated_clean' })
```

The operator form of missions.start returns { mission_id, claim_id, expires_at, passport: { token, jti, expires_at } }. passport is optional and takes the issue fields such as scopes, ttl_seconds and intent. missions.open assigns the Mission to agent_id when given. Completing or revoking a Mission revokes every Passport bound to it, for any revoke reason.

### stack.accounts

```typescript
stack.accounts.open({ name, monthly_budget_cents?, phone?, wallet?, skip? }, { idempotencyKey })
stack.accounts.list({ limit? })
stack.accounts.get(accountId)
stack.accounts.close(accountId)
stack.accounts.messages.list(accountId, { limit?, cursor?, channel? }, { passportToken? })
stack.accounts.messages.get(accountId, messageId, { passportToken? })
stack.accounts.messages.delete(accountId, messageId)
stack.accounts.sendEmail(accountId, { to, cc?, bcc?, subject?, body, body_html?, thread_id?, attachments?, reply_to_message? }, { passportToken? })   // to: one address or a list (the mail provider takes one To address, so further ones are delivered as Cc); attachments: { file_id, filename? } or { filename, content_type, content_base64 }
stack.accounts.replyEmail(accountId, messageId, { body, body_html?, reply_all?, cc?, bcc?, subject?, attachments?, include_quote? }, { passportToken? })
stack.accounts.forwardEmail(accountId, messageId, { to, cc?, bcc?, body?, include_quote?, include_attachments?, attachments? }, { passportToken? })
stack.accounts.sendSms(accountId, { to, body, reply_to_message? }, { passportToken? })
stack.accounts.sendTelegram(accountId, { chat_id, text }, { passportToken? })
stack.accounts.telegram.start(accountId, { suggested_name? })   // owner or admin; returns create_url, the single-use link the owner opens in Telegram to have the bot made
stack.accounts.telegram.connect(accountId, botToken)   // owner or admin; the token goes only to this call
stack.accounts.telegram.get(accountId) | .chats(accountId) | .disconnect(accountId)
stack.chatChannels.get() | .createIdentity({ channel, phone? }) | .removeIdentity(id)
stack.chatChannels.verifyIdentity(id, code) | .confirmIdentity(id) | .installSlack({ code, redirect_uri })   // signed-in dashboard session only
stack.accounts.resumePiece(accountId, 'inbox' | 'phone')
stack.accounts.workspace.exec(accountId, { command, workspace_id?, cwd?, timeout_seconds?, env?, stack_access? }, { passportToken? })
stack.accounts.workspace.readFile(accountId, workspaceId, { path }, { passportToken? })
stack.accounts.workspace.writeFile(accountId, workspaceId, { path, content_text | content_base64 }, { passportToken? })
stack.accounts.workspace.saveFile(accountId, workspaceId, { path, name?, content_type?, visibility? }, { passportToken? })
stack.accounts.workspace.list(accountId?)   // without an account id: every workspace you may use
stack.accounts.workspace.setSharing(accountId, workspaceId, shared)   // owner or admin: may the customer's other agents use it
stack.accounts.workspace.stop(accountId, workspaceId, { delete? })
stack.accounts.browser.startSession(accountId, { passportToken? })
stack.accounts.browser.navigate(accountId, sessionId, { url }, { passportToken? })
stack.accounts.browser.act(accountId, sessionId, { action, target, ... }, { passportToken? })
stack.accounts.browser.read(accountId, sessionId, { passportToken? })
stack.accounts.browser.screenshot(accountId, sessionId, { passportToken? })
stack.accounts.browser.checkout(accountId, sessionId, { merchant_origin, amount_minor, currency }, { passportToken? })
stack.accounts.browser.endSession(accountId, sessionId)
stack.accounts.purchases.get(accountId, purchaseId)
stack.accounts.purchases.reportMerchantResult(accountId, purchaseId, { status, ... }, { passportToken? })
stack.accounts.wallet.pay(accountId, signWalletPayment(key, { appId, walletId, typedData }), { passportToken? })
stack.accounts.wallet.payUrl(accountId, url, { key, maxCents?, method?, headers?, body?, passportToken })
stack.accounts.wallet.ownerStatus()
stack.accounts.mailDomains.list()
stack.accounts.mailDomains.connect({ domain })
stack.accounts.mailDomains.verify(domainId)
stack.accounts.optOuts.list()
stack.accounts.optOuts.add('+14155550123')
stack.accounts.optOuts.remove(optOutId)
stack.accounts.blockedCallers.list()
stack.accounts.blockedCallers.add('+14155550123')
stack.accounts.blockedCallers.remove(blockedCallerId)
```

Opening an account needs no approval; a retry with the same input and the same idempotencyKey returns the same account. monthly_budget_cents is optional and needs controls (BUDGET_NEEDS_CONTROLS otherwise); without it, prepaid credit is the limit. A call to a piece that is not ready throws AccountPieceNotReadyError; a spend past the agent's monthly budget, when it has one, throws AgentBudgetExceededError. The account's agent passes its Passport as passportToken. generateAgentWalletKey() creates the agent's wallet key on its own machine and refuses inside the STACK sandbox; its publicKey is wallet.agent_public_key in the open request. wallet.payUrl buys from an x402 seller in one call: it asks the URL, pays the seller's 402 from the account's wallet (signed with your key on your machine, then checked by STACK as pay is) and asks again; result.response is what was bought, and an answer that is not a 402 comes back with paid false. Only USDC on Base with x402's exact scheme, over https; any other ask, or a price over maxCents, throws X402PaymentError before STACK is asked.

mailDomains connects your own mail domain for agent inboxes: connect returns the DNS records to publish, verify asks the mail provider to check them now, and an account opened with inbox: { domain } gets its inbox there once the domain is verified. Connecting needs the platform subscription and an owner or admin; there is no remove call, an unverified claim on a name lapses on its own.

optOuts is the customer's do-not-contact list: list (for the owner, an admin or the account's agent) returns every number on it (one that texted STOP, or that the customer or an agent added), each with its id, number, texts_blocked, calls_blocked and source, add(number) adds one (the owner, an admin or the account's agent; a number already listed returns its entry), and remove (owner or admin) takes one off by id. blockedCallers is the customer's blocked-callers list: an incoming call from a listed number is turned away before it rings. list and add(number) are for the owner, an admin or the account's agent (a number already listed returns its entry), and remove(id) is for the owner or an admin. A text or a call to a listed number throws RecipientOptedOutError (403 RECIPIENT_OPTED_OUT), which carries the accountId. Texts and calls go to any country Twilio can reach, at cost: a destination Twilio has no price for or does not allow throws DestinationNotAvailableError (422 DESTINATION_NOT_AVAILABLE, reason no_price or refused_by_twilio). A call is paid for 10 minutes at a time, and max_seconds runs from 30 to 14400 (the default).

### stack.wakes and stack.calendar

```typescript
stack.wakes.list(agentId, { status?: 'open' | 'pending' | 'delivered' | 'acknowledged' | 'refused' | 'expired', limit?, cursor? }, { passportToken? })
stack.wakes.get(agentId, wakeId, { passportToken? })
stack.wakes.acknowledge(agentId, wakeId, { passportToken? })
stack.wakes.getSettings(agentId?)
stack.wakes.setSettings({ enabled?, time_zone?, quiet_start?, quiet_end?, quiet_mode?, rate_limit_max?, rate_limit_window_seconds?, delivery?, invite_lead_minutes?, ring_incoming_calls?, webhook_url? }, agentId?)
stack.wakes.rotateWebhookSecret(agentId)
stack.wakes.testWebhook(agentId)
stack.wakes.listRules(agentId?)
stack.wakes.createRule({ name, source, filters?, task?, enabled? }, agentId?)
stack.wakes.updateRule(ruleId, { name, source, filters?, task?, enabled? })
stack.wakes.deleteRule(ruleId)
stack.wakes.listSchedules(agentId)
stack.wakes.createSchedule(agentId, { name, cron, time_zone?, task?, enabled? })
stack.wakes.updateSchedule(agentId, scheduleId, { name, cron, time_zone?, task?, enabled? })
stack.wakes.deleteSchedule(agentId, scheduleId)
stack.calendar.listEvents(accountId, { role?, response?, limit?, cursor? }, { passportToken? })
stack.calendar.getEvent(accountId, eventId, { passportToken? })
stack.calendar.agenda(accountId, { from, to, time_zone?, limit?, cursor? }, { passportToken? })
stack.calendar.createEvent(accountId, { title, start, end?, time_zone?, repeat?, location?, meeting_link?, description?, guests?, wake_minutes_before?, meeting?, attend?, max_seconds? }, { passportToken? })
stack.calendar.updateEvent(accountId, eventId, { ...fields, occurrence?, scope?, counter_id? }, { passportToken? })
stack.calendar.cancelEvent(accountId, eventId, { occurrence?, scope? }, { passportToken? })
stack.calendar.respond(accountId, eventId, { response: 'accept' | 'tentative' | 'decline', notify_organizer? }, { passportToken? })
stack.calendar.declineProposal(accountId, eventId, counterId, { comment? }, { passportToken? })
stack.calendar.feed(accountId) | stack.calendar.rotateFeed(accountId) | stack.calendar.revokeFeed(accountId)
// The agent in the room of one of its events (made with meeting: true); STACK runs no model
stack.meetings.join(accountId, { event_id, max_seconds?, wait_seconds? }, { passportToken? })
stack.meetings.say(accountId, meetingId, { text?, wait_seconds? }, { passportToken? })
stack.meetings.chat(accountId, meetingId, text, { passportToken? }) | stack.meetings.leave(accountId, meetingId, { passportToken? })
stack.meetings.list(accountId, { status?, limit?, cursor? }) | stack.meetings.get(accountId, meetingId)
stack.meetings.getVoice(accountId) | stack.meetings.setVoice(accountId, { voice?, language? })  // an event's own: meeting_voice on calendar.createEvent / updateEvent
const stream = await stack.meetings.live(accountId, meetingId); for await (const event of stream.events()) {}
// RentAHuman: the agent hires people through the customer's own account. The key stays in STACK; the agent signs the payment with its own wallet key
stack.rentahuman.join(accountId, { country, city?, agent_name?, accept_terms: true }, { passportToken? })       // what a new account costs, and the payment to sign
stack.rentahuman.completeJoin(accountId, { join_id, signed }, { passportToken })                               // the agent's signature (only the account's own agent)
stack.rentahuman.fund(accountId, amountCents, { passportToken? }) | stack.rentahuman.completeFund(accountId, { fund_id, signed }, { passportToken })
stack.rentahuman.joinWithKey(accountId, walletKey, input, { passportToken }) | stack.rentahuman.fundWithKey(accountId, walletKey, amountCents, { passportToken })
stack.rentahuman.get(accountId)                                                                                // the connection; it shows no key
// Any connected service that speaks MCP over HTTP (its connection carries its mcp_url), through the credential proxy; the answers are untrusted
await stack.proxy.serviceTools('rentahuman', { passportToken, connection? })
await stack.proxy.serviceCallTool('rentahuman', 'send_message', { conversationId, content }, { passportToken, authorityRequestId?, connection? })
```

A wake starts an agent with a task, with or without an agent account. An agent id addresses one agent; without one the settings and rules are your defaults for all of them; the calendar takes the account id (making, changing, cancelling and answering are one action each and mail the guests or the organizer). The agent's own calls take its Passport; the settings, rules, schedules and webhook calls are owner or admin only. A webhook signing secret is returned once, to an API key or a session, never to an OAuth token. On the agent's own endpoint, verifyWakeWebhook({ headers, body, secret }) checks the Standard Webhooks signature and returns { ok: true, wake } or { ok: false, reason } (stale, bad_signature, id_mismatch and so on). A wake carries facts, never what a stranger wrote; a decision wake's event names the pending item and how it ended (item_kind, item_id, result).

Every request STACK signs to your server (a wake-up, a notification, an inbound-webhook forward, a network revocation push, the control socket) is a Standard Webhooks message. verifyWebhook({ headers, body, secret, replayGuard }) checks any of them and returns { ok: true, id, payload } or { ok: false, reason }; createReplayGuard() notices a repeated message id.

### stack.billing

```typescript
stack.billing.subscriptions()
stack.billing.subscribePlatform({ governanceApprovalId? })
stack.billing.subscribeControls({ governanceApprovalId? })
```

subscriptions returns { platform: { status, active, contract }, controls: { status }, this_month: { account_actions, control_checks } }. subscribePlatform and subscribeControls return { checkout_url, session_id, trial }: open checkout_url to pay by card, with a free trial the first time. The subscription itself is written from Stripe's events, so read it back with subscriptions. Both writes are owner or admin calls and need no approval: the person pays on Stripe's own page. An account on a contract plan, or already on the subscription, gets a 409 SUBSCRIPTION_CONFLICT. subscribeControls needs the platform subscription first. When the controls subscription lapses, controls switch off and the agent accounts keep running.

### stack.agents

```typescript
stack.agents.register({ name, description?, credential_access? })
stack.agents.list()
stack.agents.get(id)
stack.agents.update(id, { name?, status?, credential_access? })
stack.agents.delete(id)
stack.agents.unblock(id)
```

### stack.passports

```typescript
stack.passports.issue({ agent_id, mission_ids: [missionId], scopes?, ttl_seconds?, authority_binding_ids?, ... })
stack.issuePassport({ agent_id, mission_ids: [missionId], ... }) // returns a PassportSession
stack.passports.verify(token, serviceId?)
stack.passports.revoke(jti, reason?)
stack.passports.delegate({ parent_token, child_agent_id, ... })
stack.passports.refresh(token, ttlSeconds?)
stack.passports.listActive({ agentId?, sessionId? })
stack.passports.revokeAgent(agentId, reason?)
stack.passports.revokeAll(reason?)
stack.passports.checkpoint(jti, input)
stack.passports.checkout(jti, input)
```

mission_ids is required and holds exactly one live Mission ID. The Mission must be assigned to the agent or unassigned. The Passport never outlives its Mission. Refresh and delegation fail once the Mission is completed, revoked or expired, and a PassportSession from issuePassport stops refreshing with a clear error.

```typescript
const mission = await stack.missions.open({
  intent_summary: 'Post the daily support update',
  intent_services: ['slack'],
  agent_id: 'agt_support',
});
const passport = await stack.passports.issue({ agent_id: 'agt_support', mission_ids: [mission.mission_id] });
```

`authority_binding_ids` attaches up to eight active bindings for the exact agent and current agent key. The returned Passport carries opaque `authority_refs`. Authority management and the native receiver protocol use the [Authority REST API](/docs/api/authority).

### stack.skills

```typescript
// Publishing
stack.skills.publish({ name, description, version, input_schema, output_schema, ... })
stack.skills.get(id)
stack.skills.browse({ query?, tags?, trust_level? })
stack.skills.listOwned()
stack.skills.update(id, updates)
stack.skills.suspend(id)
stack.skills.activate(id)

// Invocations
stack.skills.invoke(skillId, { agent_id?, input, passport_id? }, { approvalId?, authorityRequestId?, idempotencyKey? })
stack.skills.getInvocation(invocationId)
stack.skills.poll(invocationId, { intervalMs?, timeoutMs? })
stack.skills.listInvocations()

// Requests
stack.skills.postRequest({ description, max_price_cents?, tags? })
stack.skills.listRequests({ status?, limit? })
stack.skills.suggestComposition(requestId)
```

### stack.identity

```typescript
stack.identity.listProviders()
stack.identity.initiateVerification({ provider_key, return_url? })
stack.identity.completeVerification(providerKey, sessionRef)
stack.identity.listClaims()
stack.identity.revokeClaim(id)
stack.identity.replaceServiceRequirement(serviceId, requirementOrNull)
stack.identity.grantDelegation(scopes)
```

### Other Services

```typescript
stack.services.listAvailable()
stack.services.listConnected()
stack.services.connect({ service_id, credential, scopes, connection_name? })
stack.services.connectCustom({ name, credential, connection_name? })
stack.services.rename(connectionId, connectionName)
stack.services.disconnect(connectionId)
stack.services.createConnectLink({ service_id, scopes?, connection_name? })
stack.services.getConnectLink(linkId)
stack.services.listConnectLinks()
stack.governance.getApproval(approvalId)

stack.credentials.get(provider, connection?)
stack.credentials.getByConnection(connectionId)

stack.dropoffs.create({ from_agent, to_agent | to_agents, schema }, { passportToken? })  // to_agents: any number of your agents, all woken, the first to collect takes it
stack.dropoffs.deposit(id, agentId, payload, { passportToken?, passportJti?, missionId? })
stack.dropoffs.collect(id, agentId, { passportToken? })

stack.team.invite({ email, name, role?, allowed_connections? })
stack.team.list()
stack.team.update(id, { role?, allowed_connections? })
stack.team.revoke(id)

stack.deliveryMethods.add({ channel_type, destination })
stack.deliveryMethods.list()
stack.deliveryMethods.sendVerificationCode(id)
stack.deliveryMethods.verify(id, code)
stack.deliveryMethods.test(id)
stack.deliveryMethods.rotateSecret(id)
stack.deliveryMethods.delete(id)

stack.notifications.createRule({ destination_ids, events, min_severity? })
stack.notifications.listRules()
stack.notifications.updateRule(id, { destination_ids?, events?, min_severity? })
stack.notifications.deleteRule(id)

stack.securityEvents.list({ agentId?, page?, limit? })
stack.securityEvents.resolve(id)

stack.proxy.request(
  { service, method, url, headers?, body?, query?, connection? },
  { passportToken, approvalId?, authorityRequestId?, onOperationId? }
)
stack.proxy.getOperation(operationId, { passportToken, includeResponse? })

stack.scan.scan({ content, context?, source? }, { passportToken? })
stack.scan.usage()

stack.audit.list({ limit?, since?, agentId?, passportJti? })
stack.audit.chainHead()
stack.audit.verifyChain({ from?, to?, limit? })
```

createConnectLink connects a service without the credential passing through your program or a chat: it returns a one-time url (the only copy) that the person opens in their browser while signed in to STACK. The link is bound to the account and member, works once and expires after 10 minutes; any number can be open at once. getConnectLink reads pending, connected (with connection_id) or expired, and never the url. governance.getApproval reads one approval: its status, the payload_hash of the change it covers and its approval_url. It never decides: a person does that in the dashboard.

An account can hold several named connections of one service: the first needs no connection_name (it is called default), a second does. A call that may use more than one connection names the one it wants with connection (a name in any case, or its id). Without it the call throws ConnectionAmbiguousError (409 CONNECTION_AMBIGUOUS) whose connections lists the { id, name } of each it may use; nothing was sent. services.rename is owner or admin only.

Non-GET proxy calls generate an operation ID before network I/O. Durable workers should use `onOperationId` to persist it, then reuse `authorityRequestId` only for the unchanged request. Use `getOperation` after response loss. See [Proxy operation recovery](/docs/api/proxy#operation-recovery).

### stack.audit

```typescript
// Tail recent entries — newest-first. Pass `since` (epoch ms) for
// incremental polling; pass `agentId` or `passportJti` to narrow.
const { entries, max_timestamp } = await stack.audit.list({
  limit: 20,
  agentId: 'agt_support',
});

// Anchor the chain head externally to prove no row was rewritten later.
const head = await stack.audit.chainHead();
console.log(head.latest_entry_hash, head.total_entries);

// Walk the chain and verify every entry's hash + link integrity.
const verdict = await stack.audit.verifyChain({ limit: 10_000 });
if (!verdict.valid) {
  console.error('chain break at', verdict.first_break);
}
```

Each entry carries `layer`, `action`,`outcome`, `duration_ms`, plus the hash-chain fields. Cascade revokes write one`passport.revoke` entry plus one`passport.revoke_cascade` per child — filter by`passportJti` to see the chain for a single passport.

## Offline passport verification

The SDK exports `verifyPassportOffline` as a standalone function (not a method on `Stack`). It verifies the JWT signature using only the public JWKS. It does not call the STACK API. Use it when a downstream service needs signature and expiry checks without an online verification call.

```typescript
import { verifyPassportOffline } from '@getstackrun/sdk';

// Mode 1: JWKS URL - fetched + cached once per URL per process.
const claims = await verifyPassportOffline(token, {
  jwksUrl: 'https://api.getstack.run/v1/.well-known/jwks.json',
});

// Mode 2: pre-fetched JWK - no network call at verification time.
const claims2 = await verifyPassportOffline(token, {
  publicJwk: {
    kty: 'OKP', crv: 'Ed25519', x: '...',
    kid: 'stack-passport-v1', alg: 'EdDSA', use: 'sig',
  },
});

console.log(claims.jti, claims.stk.agent_id, claims.stk.services);
```

Offline mode checks the signature, issuer, audience, and token expiry when the token has an`exp` claim. Reject any result without `exp`. Offline verification does not check revocation or current account, agent, Mission, service, or identity state. Use `POST /v1/passports/verify` when current STACK state affects the decision.

Use this helper only with standard STACK-issued Passports until the SDK requires an expiry claim itself.

## Error Handling

```typescript
import { Stack, StackError, NotFoundError } from '@getstackrun/sdk';

try {
  const agent = await stack.agents.get('agt_nonexistent');
} catch (err) {
  if (err instanceof NotFoundError) {
    console.log('Agent not found');
  } else if (err instanceof StackError) {
    console.log(err.code, err.status, err.message);
  }
}
```

## Direct REST calls

Use the HTTP API directly when your integration needs an operation that this SDK does not expose. See `/docs/api/billing` for the billing shapes.

```typescript
const stack = new Stack();
const headers = { Authorization: await stack.authorizationHeader() };

// Audit export (full date-range; the SDK's `stack.audit.list` covers tailing)
const exp = await fetch('https://api.getstack.run/v1/audit/export?format=ndjson', { headers });

// Billing balance
const balance = await fetch('https://api.getstack.run/v1/billing/balance', { headers }).then(r => r.json());
```
