# @azothos/sdk and the v1 REST API

Two ways in. Send calls through the governed gateway with any OpenAI-compatible client — the path where rules apply and decisions are sealed — or report calls made elsewhere with the SDK’s wrappers.

## Installation

```
npm install @azothos/sdk
```

Node.js 18 or later, and an API key from **Settings › Access** (`az_live_…` or `az_test_…`). The SDK checks the key’s shape before any request.

## Through the gateway

Point an OpenAI client at `https://www.azothos.ai/api/v1` — or your own host, self-hosted. `azothGatewayHeaders` builds the Azoth headers and throws on a value the gateway would refuse:

```
import OpenAI from 'openai';
import { azothGatewayHeaders } from '@azothos/sdk';

const openai = new OpenAI({
  baseURL: 'https://www.azothos.ai/api/v1',
  apiKey: process.env.AZOTH_API_KEY,
  defaultHeaders: azothGatewayHeaders({ usecaseId }),
});

await openai.chat.completions.create(body, {
  headers: azothGatewayHeaders({ decisionRef: creditFileId, subjectZone: 'FR' }),
});
```

- `X-Azoth-Usecase` — `usecaseId`: the system (mandate) the call serves
- `X-Azoth-Decision-Ref` — `decisionRef`: the business decision, an opaque id
- `X-Azoth-Subject-Zone` — `subjectZone`: where the people concerned are — `FR`, `US-CA`, `EU`…
- `X-Azoth-End-User` — `endUser`: the visitor of a public system, an opaque id, never an e-mail
- `X-Azoth-Challenge-Passed` — `challengePassed`: the nonce of a challenge the visitor passed
- `X-Azoth-Locale` — the language of a refusal: `en`, `fr`, `es`, `zh` or `ar`
- `X-Azoth-On-Behalf-Of` — the person a call is made for — their SCIM id or e-mail — with a service key allowed to name people; set it yourself ([human attribution](https://www.azothos.ai/docs/admin#attribution))

## Receipts

`receiptOf(response | body | headers)` reads a receipt, `decodeReceipt(token)` its claims, and `verifyReceipt(token, jwks)` checks its signature with WebCrypto. Since SDK 1.2.0 it also refuses a receipt signed at or after its key’s declared compromise (the key’s `status` and `compromised_at`): the workspace’s keys and their status are published at `/api/proof/keys/<workspaceId>`.

## Refusals and exceptions

`parseRefusal(err)` reads the refusal block, `formatRefusal` gives a text to show, `alternativeRequest(option)` the headers and the body change of a compliant option, and `requestException(…)` asks the rule’s owner for a time-limited exception. On a 428, `exhaustionChallengeOf(err)` returns the challenge to pass.

```
import { parseRefusal, formatRefusal, alternativeRequest, requestException } from '@azothos/sdk';

try {
  await openai.chat.completions.create(body, { headers: { 'X-Azoth-Locale': 'fr' } });
} catch (err) {
  const refusal = parseRefusal(err);
  if (!refusal) throw err;
  showToUser(formatRefusal(refusal));
  const option = refusal.alternatives[0];
  if (option) {
    const { headers, body: change } = alternativeRequest(option);
    await openai.chat.completions.create({ ...body, ...change }, { headers });   // governed again in full
  } else if (refusal.exception.available) {
    await requestException({
      apiKey: process.env.AZOTH_API_KEY,
      refusal,
      justification: 'Quarter-end audit needs this model this week',
    });
  }
}
```

## Also in the SDK

- `createClientVault`: keep a vault-mode system’s content encrypted with your key, in your storage; Azoth seals only the hashes.
- `groundingSources(passages)`: the passages an answer must rest on, for the grounding check.
- `runReferenceSet`: run a reference set kept in your vault and post its receipt, for model change control.

## Reporting calls made outside the gateway

`wrapOpenAI`, `wrapAnthropic`, `wrapBedrock`, `wrapMistral` and `wrapGemini` wrap your existing client: each call is reported to Azoth — cost, latency, tokens — in the background, with optional OpenTelemetry `gen_ai.*` spans. These calls are observed, not governed: no rule can stop them.

### wrapOpenAI

```
import OpenAI from 'openai';
import { AzothClient, wrapOpenAI } from '@azothos/sdk';

const azoth = new AzothClient({ apiKey: process.env.AZOTH_API_KEY });
const openai = wrapOpenAI(new OpenAI(), azoth, {
  provider: 'openai',
  model: 'gpt-4o-mini',
  agentId: 'support-bot',        // the spend line it is attributed to
  workflowId: 'ticket-triage',
});
```

### wrapAnthropic

```
import Anthropic from '@anthropic-ai/sdk';
import { AzothClient, wrapAnthropic } from '@azothos/sdk';

const azoth = new AzothClient({ apiKey: process.env.AZOTH_API_KEY });
const anthropic = wrapAnthropic(new Anthropic(), azoth);
```

### Client options

- `apiKey` — required: the workspace API key
- `baseUrl` — default `https://www.azothos.ai`; your own host when self-hosted
- `workspaceId` — required for `client.io.*` and the simulations
- `enableTracing · tracer` — emit OpenTelemetry spans
- `timeoutMs` — per attempt, 30 000 by default
- `maxRetries` — total attempts on a 429 or a 5xx, 3 by default; a 429 honours `Retry-After`

## v1 REST API

Most `/api/v1` routes take an API key: `Authorization: Bearer <key>` or `X-Azoth-API-Key: <key>`. A scoped key reaches only the routes its scopes map to. The dashboard’s own reads — `/api/v1/me` and the GreenOps reads — take a signed-in session instead, never a key. Every route, how it authenticates, its fields and its answers are in the [API reference](https://www.azothos.ai/docs/api), also published as an OpenAPI file.

- `POST /api/v1/chat/completions` — The governed gateway, OpenAI-compatible
- `POST /api/v1/chat` — The governed gateway with an explicit `provider`, fallbacks and streaming
- `POST /api/v1/infer/resume` — Run a held call once it is approved
- `GET /api/v1/journal` — The sealed decisions
- `GET /api/v1/journal/export?format=dossier` — The audit dossier, as a ZIP
- `POST /api/v1/decisions/export` — A decision dossier, by decision reference
- `POST /api/v1/exceptions` — Ask for an exception from a refusal
- `POST /api/v1/insights/{tool}` — The assistant’s read tools, with the `insights:read` scope
- `POST /api/v1/mcp` — The governed MCP gateway, with a key bound to an agent
- `GET /api/v1/usage · /api/v1/report · /api/v1/budgets` — Usage, the spend report, the budgets
- `POST /api/ingest` — Report calls made outside the gateway
- `GET /api/proof/keys/{workspaceId}` — The workspace’s public keys (JWKS), without a key

```
POST /api/v1/chat
Authorization: Bearer <key>

{
  "provider": "anthropic",             // openai | anthropic | mistral | gemini | azure_openai
  "model": "claude-haiku-4-5",         // | openrouter | ollama | deepseek | huggingface | internal
  "messages": [{ "role": "user", "content": "Summarise this document." }],
  "maxTokens": 1024,
  "stream": false,
  "fallbackProviders": [{ "provider": "mistral", "model": "mistral-small-latest" }]
}
```

## Answers to expect

- `400 validation_failed` — The body failed validation: `field` names the field, `error` says why.
- `401` — The API key is missing, invalid or revoked.
- `402 budget_exceeded` — A budget refused the call before the model.
- `202 human_review_required` — Held for a person; resume it with its `approval_request_id`.
- `403` — A rule refused it: `policy_blocked`, `usecase_unresolved`, `usecase_not_approved`, `usecase_prohibited`, `usecase_archived`, `mandate_suspended`, `mandate_expired`, `kill_switch_active`, `jurisdiction_blocked`, `sovereignty_blocked`, `egress_blocked`…
- `428 exhaustion_challenge_required` — A public system asks the visitor to pass a challenge.
- `429` — A rate limit, `exhaustion_slow` or `exhaustion_blocked`: `retryAfterMs` in the body, `Retry-After` in the headers.
- `503 governance_error` — Governance could not run and the deployment fails closed: try again.

> A governance refusal is sealed and carries its receipt. Cost-exhaustion refusals are counted instead, and sealed per change of tier. Each `code` is explained in [Error codes](https://www.azothos.ai/docs/errors), where the `doc_url` of an answer leads.
