# Surplus Intelligence > An LLM inference marketplace. You call one OpenAI-compatible base URL, a router picks the cheapest > healthy seller for the model you asked for, and settlement happens underneath. Buyers pay less than > list price; sellers earn on spare capacity. > > THIS FILE IS WRITTEN FOR AGENTS. Everything a coding agent needs to operate an account on its user's > behalf — authenticate, get funded, cap its own spend, run inference, read back what it spent, manage > keys, and sell capacity — is here, with the exact request shapes. Point your agent at this URL and it > should need nothing else. ## Base URL ``` https://api.surplusintelligence.ai ``` API calls go to the `api.` host. `https://www.surplusintelligence.ai` is the website, and the dashboard is at `https://www.surplusintelligence.ai/app`. **Two things live on only one host.** `/.well-known/*` (the x402 discovery manifest) is served by the **API** host only — `www.surplusintelligence.ai/.well-known/x402` is a 404. `/llms.txt` and `/docs/*` are served by the **website** only. `/x402/info` answers on both. Where this file gives a count, a price or a limit, it names the endpoint to read instead wherever one exists — those numbers are environment configuration and they move. ## How you pay — pick one of three rails | rail | account needed | best for | how money arrives | |---|---|---|---| | **x402** | no | one-off or autonomous agents with a wallet | signed USDC per request, on Base | | **Prepaid credit** | yes (API key) | anything long-running | you top up a balance in advance | | **MPP (Tempo)** | no | agents on a Tempo credential | per request, `Authorization: Payment ` | **Prepaid credit comes in two kinds. They spend identically and only ONE can be withdrawn:** - **Fiat credit** — bought with a card through Stripe. Spendable on inference. **Not withdrawable.** - **Deposited USDC** — sent on-chain to your deposit address. Spendable on inference, **and withdrawable**. `GET /v1/payments/balance` gives you all three numbers, and which one to use depends on the question: - **"How much can I spend?"** → `credit_balance_usdc`. This is the combined spendable figure, fiat plus deposited USDC, and it is the number to show a user as their balance. - **"How much can I withdraw?"** → `usdc_available_usdc` alone. Never add fiat credit into a withdrawable figure; fiat credit cannot leave the account. So the two are one number when spending and two numbers when moving money out. The breakdown fields (`fiat_available_usdc`, `usdc_available_usdc`) exist so you can show both. > **DEPRECATED: the on-chain allowance rail.** There was a third way to fund an API key — granting the > settlement contract a USDC allowance and letting it pull per request. **Do not build on it.** It is > being retired, `POST /v1/buyer/approve-permit` is deprecated with it, and `balance_usdc` / > `allowance_usdc` on the balance response are legacy fields that describe it. An API key funds itself > with **fiat credit or deposited USDC**. x402 and MPP are per-request and unaffected. ## Before you write anything: three rules **1 · `Idempotency-Key` is REQUIRED on money and resource-creating writes, and ignored elsewhere.** This is per-route, not global: a route that requires one rejects the request without it, and a route that is not marked for idempotency ignores the header entirely. Use a UUID per intent, and **reuse the same key when you retry** — that is what makes a retry safe. A new key on a retry is a second payment. Keys are claimed for 24 hours. **REQUIRED — all 41, generated from the route decorators rather than transcribed by hand:** ``` DELETE /v1/budgets/{scope_type}/{scope_id} DELETE /v1/keys/{id} DELETE /v1/orgs/{orgId}/invites/{inviteId} DELETE /v1/orgs/{orgId}/members/{memberId} DELETE /v1/orgs/{orgId}/wallets/{address} DELETE /v1/orgs/{orgId}/workspaces/{wsId} DELETE /v1/webhooks/{id} PATCH /v1/account/activation PATCH /v1/keys/{id} PATCH /v1/orgs/{orgId} PATCH /v1/orgs/{orgId}/members/{memberId}/role PATCH /v1/orgs/{orgId}/workspaces/{wsId} PATCH /v1/seller/configs/{id} POST /v1/buyer/keys POST /v1/keys POST /v1/keys/{id}/rotate POST /v1/orgs POST /v1/orgs/{orgId}/invites POST /v1/orgs/{orgId}/invites/{token}/accept POST /v1/orgs/{orgId}/treasury/approve POST /v1/orgs/{orgId}/treasury/setup POST /v1/orgs/{orgId}/treasury/sync-signers POST /v1/orgs/{orgId}/treasury/withdraw POST /v1/orgs/{orgId}/wallets POST /v1/orgs/{orgId}/workspaces POST /v1/payments/card-setup POST /v1/payments/topup POST /v1/payments/withdraw POST /v1/resource/seller/offers POST /v1/seller/keys POST /v1/seller/offers POST /v1/seller/opportunities/{model}/dismiss POST /v1/seller/opportunities/{model}/quick-create POST /v1/seller/opportunities/{model}/request-mapping POST /v1/support/tickets POST /v1/wallet/withdraw POST /v1/webhooks PUT /v1/budgets PUT /v1/payments/auto-topup PUT /v1/seller/configs/{id}/credit-basis PUT /v1/seller/payout-destination ``` **ACCEPTED but optional** — a key is honoured for replay protection if you send one, and nothing fails if you do not. Telegram link/confirm are in this set deliberately: a duplicate link mint consumes one of the limited daily link allowances, so sending a key is worth it even though it is not demanded. ``` DELETE /v1/payments/auto-topup POST /v1/auth/active-org POST /v1/buyer/auth/keys POST /v1/buyer/providers POST /v1/notifications/telegram/confirm POST /v1/notifications/telegram/link POST /v1/seller/auth/keys POST /v1/seller/offers/bulk-cancel POST /v1/seller/offers/bulk-update POST /v1/seller/offers/{id}/rotate-credential POST /v1/seller/payouts/withdraw PUT /v1/notifications/settings ``` **Every other write ignores the header entirely** — `PATCH`/`DELETE /v1/seller/offers/{id}`, `POST /v1/notifications/test`, `POST /v1/payments/billing-portal`, `PUT /v1/buyer/keys/{id}/preferences` and the rest. A `/min{N}` mirror route inherits whatever its base route requires. **2 · `1 USD = 1_000_000` microdollars — and THE FIELD NAME DOES NOT TELL YOU THE UNIT OR THE JSON TYPE.** Read the schema in `GET /api/ops/openapi.json`, per endpoint. This document gives the exact shape wherever it shows a request or a response, and those shapes are the contract; the suffix is not. That warning is not caution for its own sake. Every pattern an agent would reasonably infer has counterexamples in the live API: - **`_micro` is usually a JSON number, occasionally a string.** Numbers: `limit_day_micro` on a budget, `limit_micro`/`spent_micro` on budget spend, `threshold_micro`/`refill_to_micro` on auto-top-up, `flat_fee_micro` on `/x402/info`. Strings: `amount_micro` on withdraw (request *and* response), `remaining_available_micro`, `stripe_fee_fixed_micro`, `stripe_invoice_fee_max_micro`. - **`_usdc` is microdollars, not decimal USDC**, and is a string on every balance and earnings field — `$142.18` is `"142180000"`. Four analytics fields are µ$ JSON *numbers* instead (`total_direct_usdc`, `total_actual_usdc`, `total_saved_usdc` inside `buckets[]`, `cache_saved_usdc`). - **`_usd` / `Usd` is dollars — except where it is not.** Dollars: `amountUsd` on top-up, `cap_daily_usd` / `cap_weekly_usd` / `cap_monthly_usd` on offers, `threshold_usd`/`refill_to_usd` on auto-top-up, `fee_usd`/`credit_usd` on a top-up response, the seller `earned_usd` analytics. But `cost_usd` and `direct_cost_usd` on market feeds and recent fills are **microdollar strings**. - **Some endpoints give you both units for one value.** `GET /v1/payments/auto-topup` returns `threshold_micro` *and* `threshold_usd`. Pick one; do not convert one into the other and compare. So: divide by 1_000_000 only for display, never before arithmetic, and only once you have confirmed the field is microdollars. If you have to guess, you have the wrong field. **3 · Field casing is not uniform.** Most bodies are `snake_case`, but a few payment bodies are `camelCase`. The exact shapes are given below for every write; use them rather than guessing: `topup` → `amountUsd`, `auto-topup` → `thresholdMicro`/`refillToMicro`, everything else → `snake_case`. ## Errors Inference endpoints return the OpenAI envelope, so an OpenAI SDK parses them unchanged: ```json {"error": {"type": "...", "code": "...", "message": "...", "detail": {}, "param": "..."}, "request_id": "req_..."} ``` - `code` is the stable string to branch on. `type` is the OpenAI-shaped family — and the two are easy to confuse here, because **`authentication_error` is the `type` for every 401 and 403** on the OpenAI surface while the `code` carries the specific reason (`invalid_api_key`, `unauthorized`, `forbidden`, `restricted_key`). Branch on `code`; match `type` only if you are deliberately treating all auth failures alike. - `detail` carries structured context. For `budget_exceeded` it is `{window, limit_micro, spent_micro, resets_at}`. - `param` appears only on validation errors (400), never on a 402. - `request_id` is on every error body, and **it only resolves at `GET /v1/requests/{requestId}` once routing has minted a settlement id.** An error raised before routing (auth, validation, no seller) carries the TRACE id instead — there is no money row for it to point at — so a 404 there means "nothing was charged", not "lost". Quote it in support either way. It also needs an authenticated principal with `usage.read`. - **Do not match on `message`.** Support text is appended to it at the edge, so the string is not stable. ### A long-running request returns 200 even when it fails A **non-streaming** request that runs long commits its status and headers before the outcome exists, so the connection can cross an intermediary that would otherwise time it out. Three consequences, and the first one breaks any client that trusts the status line: - **the status is always 200, including on failure.** The table below still tells you what a `code` means; it no longer tells you which status you will see; - the body is preceded by insignificant JSON whitespace. Hand it to your JSON parser as-is — do not trim it; - the `x-si-*` routing headers are not sent. They arrive in the body under one additive `surplus` key instead. So branch on the BODY. This is correct for fast and long requests alike, and it is the only form that is correct for both: ```js const data = await res.json(); if (data.error || !data.choices) { // failed — read data.error.code, which is the same code a fast request would have carried } ``` Checking `res.ok`, or `res.status === 200`, treats a failed generation as a success. The failure body is the envelope you already parse: ```json {"error": {"type": "service_unavailable", "code": "no_healthy_sellers", "message": "..."}} ``` `code` carries the real cause and remains the thing to branch on. The `type` field reads "service_unavailable" for anything discovered after the commit, so do not use it to tell causes apart. `upstream_error` is the code when the provider returned none of its own. What you were charged stays in `usage.buyer_cost_micro` either way. On `/anthropic/*` the same thing happens with that surface's envelope — `{"type":"error","error":{...}}`, still no `code` field — so there, branch on the presence of an error object rather than on the status. Field-by-field reference for `surplus`: https://www.surplusintelligence.ai/docs/reference/long-running-responses ### What to branch on | status | code | what it means | what to do | |---|---|---|---| | 402 | `insufficient_credit` / `insufficient_balance` | not enough money | top up, or deposit USDC | | 402 | `budget_exceeded` | a budget's hard stop fired — **you have money** | raise or clear the budget; do not top up | | 402 | `account_frozen` / `org_frozen` / `org_closed` | account or org under review | contact support; funding will not help | | 402 | `insufficient_allowance` / `onchain_wallet_required` | legacy on-chain rail, or no org treasury | use credit or deposited USDC instead | | 402 | `x402_*` | an x402 handshake or settlement problem — see the x402 section | re-sign, or fall back to a credit key | | 400 | `account_restricted` | risk enforcement. **Deliberately 400, not 403** | contact support | | 401 | `invalid_api_key` | **the ordinary bad-key failure** on `/v1/*`: unknown, revoked, expired or mistyped | re-mint | | 401 | `unauthorized` | no credential at all on a route that needs one | authenticate | | 401 | `authentication_required` | async media / transcription reached anonymously — **this is what you get today while the accountless prepay rails are off**, instead of a 402 | use a buyer key with prepaid credit | | 403 | `buyer_not_in_allowlist` | `/v1/decisions` is limited to pilot accounts | not self-serve; ask support | | 401 | `authentication_error` | the same situation on **`/anthropic/*`**, where this is the code | set `ANTHROPIC_AUTH_TOKEN` to an `inf_…` key | | 403 | `restricted_key` | this key is scoped and may not do that | use an unrestricted key | | 403 | `forbidden` | authenticated, but the credential lacks the capability — e.g. a buyer key on `/v1/budgets` or `/v1/keys` | use a management key or a session | | 403 | `model_not_in_key_scope` / `endpoint_not_in_key_scope` / `provider_not_in_key_scope` | the key's scope excludes this call | widen the scope, or use another key | | 403 | `management_key_cannot_infer` | a management key cannot run inference | use a buyer key | | 404 | `no_sellers_for_model` | nobody is serving that model right now (text routes) | pick another from `GET /api/markets` | | 404 | `model_not_found` | the model is not in the catalog at all — media submission and `GET /v1/models/{id}` | check the spelling against `GET /v1/models` | | 404 | `minimum_discount_not_met` | your `/min{N}` or `X-Min-Discount` floor excluded every seller | lower the floor | | 404 | `max_price_exceeded` | your `max_price_per_1m` excluded every seller | raise it | | 409 | `duplicate_offer_for_credential` | that (key, base URL, model) triple is already listed | reprice the existing offer | | 429 | `rate_limit_exceeded` | rate limited | back off; **`Retry-After` is set** | | 429 | `idempotency_in_progress` / `too_many_keys` | a retry arrived while the first is in flight / key ceiling | retry shortly / revoke an old key | | 503 | `no_healthy_sellers` / `route_deadline_exceeded` | transient routing failure | retry with backoff — on a media route a `no_healthy_sellers` may carry `Retry-After` (seconds until the earliest seller can recover): honour it | | 400 | `unsupported_provider` | a pinned `provider` (or one in the allow-list) is not supported for this model — `detail` names which | drop the pin, or pick a provider from `GET /v1/providers` | | 400 | `invalid_secret_masking_header` | `X-SI-Mask-Secrets` is not exactly `on` | send `on`, or leave the header out | | 400 | `secret_masking_too_large` | more text, or more distinct secrets (500), than masking scans | send less | | 400 | `secret_in_schema` | a detected secret in a schema `enum`, `const`, `pattern`, `default` or `examples` | take it out of the schema | | 400 | `secret_in_unmaskable_field` | a detected secret in a field masking cannot change: an id, a name, `model`, `user`, a signature or an object key | move it out of that field | | 409 | `secret_in_signed_reasoning` | signed reasoning in the current tool-use turn holds a secret, so it can be neither dropped nor masked | start a new conversation, or drop that turn | | 500 | `secret_masking_failed` | masking could not be applied | retry; if it persists quote `request_id` | | 500 | `secret_egress_blocked` | a detected secret was found in a body about to go upstream; it was not sent and the reserve was released | retry; report it with `request_id` | | 503 | `secret_masking_unavailable` | masking is running and the stored setting the request depends on could not be read, or the service cannot confirm right now whether masking is running | retry | | 500 | `server_error` | ours, not yours | retry; if it persists quote `request_id` to support | Two traps worth stating outright: - The two "bad model" codes are **not interchangeable, and which one you get depends on the route.** A text route (`/v1/chat/completions` and friends) answers **`no_sellers_for_model`** — the model is known, nobody is serving it, so retrying another seller or waiting can work. Media submission answers **`model_not_found`** when the model is not in the media catalog, which retrying never fixes. - `402 budget_exceeded` and `402 insufficient_credit` are different situations and must never be collapsed: the first means a cap you set, the second an empty balance. **On the Anthropic skin the error shape is different.** `/anthropic/*` emits `{"type":"error","error":{"type","message","detail"}}` with **no `code` field at all**, and it maps a payment failure to **400 `invalid_request_error`** rather than 402. So the table above does not apply under `/anthropic/*`: branch on `error.type` and the HTTP status there, or use the `/v1/*` surface if you need machine-readable payment codes. ## Rate limits Per minute, **per credential** — the bucket is keyed on the API key (or the session, or, unauthenticated, the client IP), not on the account. All routes in a tier share one counter; the tier is not per-path. | tier | per minute | covers | |---|---|---| | `completions` | 1200 | `/v1/chat/completions`, `/v1/completions` | | `generation` | 1200 | image / video / music submission | | `media_poll` | 1800 | polling a media job | | `read` (fallback) | 1200 | everything not listed, incl. `/v1/responses`, `/anthropic/*`, `/v1/decisions` | | `sellers` | 1200 | seller routes | | `buyers` | 600 | buyer reads | | `analytics` | 300 | `/v1/analytics/*`, and unfiltered `/v1/requests` and `/v1/audit` | | `markets` | 180 | `/api/markets*` (per IP) | | `auth` | 120 | the SIWE challenge/mint pair | | `seller_history` | 120 | `/v1/seller/earnings-history` | | `filtered_logs` | 60 | FILTERED `/v1/requests`, `/v1/audit`, `/v1/seller/earnings-history` | | `webhooks` | 6000 | inbound provider webhooks | These are compile-time constants, not per-account quotas, and there is no override. Every response carries `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset`; a `rate_limit_exceeded` 429 also carries `Retry-After`. The other 429 codes do not. ## Path A — x402, no account No account and no API key. A wallet with USDC on Base is enough. x402 is content-negotiated on the standard OpenAI-compatible endpoints — there is no separate x402 path. Send a normal request to `/v1/chat/completions`; with no payment header you get a 402 challenge, then you sign and retry the **same** endpoint. Two schemes are advertised: - `upto` (preferred): authorize a maximum, pay only actual usage after the response completes. - `exact` (fallback): sign and settle the fixed estimate. For `upto` the buyer needs a one-time USDC approval to canonical Permit2 (`0x000000000022D473030F116dDEE9F6B43aC78BA3`) — **that is the approval target.** Note that `/x402/info` also reports a `permit2` address, which is the `upto` witness proxy and is a different contract; read the challenge and `/x402/info` rather than hard-coding either. After the approval, requests are gasless for the buyer; CDP sponsors the x402 settlement gas when available. **This Permit2 approval is part of x402 and is not the deprecated settlement-contract allowance described above.** **Cost, and what `amount` actually is — ON THE SYNCHRONOUS ROUTES.** Everything in this section describes the routes that answer in one request: `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/embeddings`, `/v1/images/*` and `/v1/audio/*`. Two exclusions, both load-bearing: - **`/anthropic/*` does NOT support x402 at all.** The Anthropic skin requires a Surplus buyer key and answers `401 authentication_error` without one — it never issues a 402 challenge, because the challenge dance writes straight to the response and an Anthropic client cannot satisfy it. Use Path B for the skin. - **Async media (`/v1/video/generations`, `/v1/music/generations`) charges differently** and is described below. One exception inside the synchronous set, and note it is **currently off in production** for the same reason as async media (`MEDIA_STT_PREPAY_RAILS_MODE=off` → anonymous callers get 401, not a challenge): when enabled, **`/v1/audio/transcriptions` advertises `upto` ONLY.** The server must challenge before it reads the multipart body, so with no model hint on the request it quotes the MAXIMUM across the served speech-to-text models (with a hint, that model's own price). A figure that can differ from what the funding gate later rebuilds cannot be paid with `exact`, whose EIP-3009 signature must EQUAL the rebuilt amount — so the `exact` arm is dropped rather than offered and refused. An `exact`-only client cannot pay for transcription; use `upto` or a prepaid-credit key. The challenge's `amount` is an **authorization ceiling that already includes everything**, computed as `ceil((estimated usage + platform fee + x402 flat fee) × 1.1)` — the ×1.1 is an estimation buffer. So: - **Do not add the flat fee to `amount`.** It is in there. Read its value from `/x402/info` (`flat_fee_micro`) if you want to show it separately, not to compute what to sign. - **`upto`: you authorize `amount` and pay actual usage.** Settlement is `min(actual, authorized)`, so the buffer and the ceiling are not what you are charged. - **`exact`: the whole `amount` is settled**, buffer included. That is the price of the fallback scheme; prefer `upto` where your client supports it. ### Async media over x402 — OFF IN PRODUCTION TODAY, and different when it is on **Check before you build against this.** The accountless prepay rails for async media and for transcription are behind `MEDIA_ASYNC_PREPAY_RAILS_MODE` and `MEDIA_STT_PREPAY_RAILS_MODE`, and **both are `off` in production right now** (read from live config, 2026-10-06). While they are off an anonymous request to these routes gets `401 authentication_required`, **not** a 402 challenge — so an x402-only agent cannot use async media or `/v1/audio/transcriptions` at all today. Use a buyer key with prepaid credit for those. Detect it the plain way: submit and see whether you get a 402 challenge or a 401. When they ARE enabled, `POST /v1/video/generations` and `POST /v1/music/generations` do **not** behave like the synchronous routes, and the difference costs money rather than clarity: - **The full authorization is SETTLED IMMEDIATELY**, before the job is created. `upto` and `exact` are equivalent here — there is no deferred settle and no `min(actual, authorized)`. - **`amount` is a FAILOVER MAXIMUM, not an estimate of your render.** It is the priciest of the first several candidate sellers, so that a refusal by the cheapest does not strand the job — plus a media buffer of **1.1× or 2.0×** (the larger for an image-input render, whose real cost is only known from the provider's live quote), plus the flat fee. - **So expect to pay the quoted maximum up front, not your actual usage.** If the render costs less, the difference is refunded — but **as fiat credit, not as USDC**. Fiat credit is spendable on inference and is **never withdrawable**, so an anonymous x402 wallet with no account cannot reach a refund at all. - If pre-funding is refused, nothing moves: no job, no hold, no usage row, no flat fee. If you are an autonomous payer on a wallet, price async media as "the quoted amount is what I am spending" and use an account with prepaid credit if you want usage-based charging with a reachable refund. **KEEP THE `job_token`.** A submission answers with `job_token`, `poll_url` and `cancel_url`. With no account, that token is the ONLY thing that proves the job is yours: send it as **`X-Job-Token`** on the poll, the cancel and the artifact fetch. Without it those calls deliberately answer **404** rather than 403 — they give no existence oracle — so an anonymous payer who discards the token cannot retrieve what it just paid for, and there is no recovery. ### Step 1: Send request → get 402 challenge ``` POST /v1/chat/completions Content-Type: application/json {"model": "llama-3.3-70b", "messages": [{"role": "user", "content": "Hello"}], "max_tokens": 100} ``` Returns HTTP 402. **Its body is not the ordinary error envelope** — an unauthenticated challenge carries `error.type: "payment_required"` with `error.code: "x402_payment_required"` alongside the `accepts` array, and no `request_id`. Treat it as the challenge, not as a failure to branch on. Payment requirements are in: - **Header:** `PAYMENT-REQUIRED` (base64-encoded JSON, x402 v2 standard) - **Compatibility header:** `x-payment-required` carries the same payload for legacy clients - **Body:** `accepts[]` with scheme, network, asset, amount, payTo Do not rely on the order of `accepts[]`. Select by `scheme`: prefer `upto`, fall back to `exact`. ### Step 2: Sign payment and retry For `upto`, sign a Permit2 witness authorization for the maximum `amount` in the 402 response; only actual usage is settled after inference succeeds. For `exact`, sign an EIP-3009 `TransferWithAuthorization`. ``` POST /v1/chat/completions Content-Type: application/json PAYMENT-SIGNATURE: {"model": "llama-3.3-70b", "messages": [{"role": "user", "content": "Hello"}], "max_tokens": 100} ``` Returns 200 with an OpenAI-compatible completion. ### Step 3: Read the receipt — and note that a STREAMED response has none **Non-streaming.** The successful response carries a **`PAYMENT-RESPONSE`** header with the settlement receipt — transaction hash, network, payer and the amount actually settled. Settlement happens BEFORE the body is sent, so the receipt is authoritative and a settlement failure becomes a 402 instead of served content. **Streaming (`stream: true`) is different, and this is a protocol limit rather than an omission.** HTTP headers freeze at the first byte, so a streamed response settles only AFTER the bytes have gone. Two consequences: - **There is no `PAYMENT-RESPONSE` on a streamed response.** Do not wait for one. - **A post-stream settlement failure cannot become a 402.** The content has already been delivered, so the fail-closed signal that turns a failed settle into a 402 applies to non-streaming callers only. What a streaming client uses instead **depends on whether it has an account**, and the honest answer for Path A is that it has nothing: - **With a buyer key** (Path B): the **`x-request-id`** header is published before any byte and carries the settlement id, so read the actual charge afterwards with `GET /v1/requests/{id}`. That endpoint needs `usage.read` on the key. - **Anonymous x402, no account: there is no way to confirm settlement today.** The header is there, but `GET /v1/requests/{id}` requires an authenticated principal, so an accountless payer can neither read a receipt nor look the charge up. This is a real gap, not an omission from this document. So on x402 without an account: **do not stream if you need the charge confirmed.** A non-streamed request gives you `PAYMENT-RESPONSE` and fails closed. If settlement fails or cannot be confirmed you get a 402 with one of `x402_verification_failed`, `x402_payment_in_progress`, `x402_payment_already_used`, `x402_settlement_failed`, `x402_settlement_unknown`, `x402_settlement_unconfirmed` or `x402_settlement_submitted_receipt_timeout`. Treat the `unknown` / `unconfirmed` / `timeout` trio as indeterminate: do not re-sign the same authorization blindly. ### Using @x402 SDKs (simplest) ```typescript import { wrapFetchWithPayment } from '@x402/fetch'; import { x402Client } from '@x402/core/client'; import { ExactEvmScheme } from '@x402/evm/exact/client'; import { privateKeyToAccount } from 'viem/accounts'; const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY); const client = new x402Client(); client.register('eip155:*', new ExactEvmScheme(signer)); const fetchWithPayment = wrapFetchWithPayment(fetch, client); const response = await fetchWithPayment( 'https://api.surplusintelligence.ai/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'llama-3.3-70b', messages: [{ role: 'user', content: 'Hello' }], max_tokens: 100, }), } ); const data = await response.json(); console.log(data.choices[0].message.content); ``` ### Direct `upto` signing with @x402/evm + viem If you sign `upto` manually, use a signer object with an explicit `address`. Do **not** pass a raw viem `walletClient` to a helper if `walletClient.address` is undefined — the resulting Permit2 payload will be rejected by the facilitator. ```typescript import { createPublicClient, createWalletClient, http, publicActions } from 'viem'; import { base } from 'viem/chains'; import { privateKeyToAccount } from 'viem/accounts'; import { UptoEvmScheme } from '@x402/evm'; const endpoint = 'https://api.surplusintelligence.ai/v1/chat/completions'; const account = privateKeyToAccount(process.env.PRIVATE_KEY); const publicClient = createPublicClient({ chain: base, transport: http() }); createWalletClient({ account, chain: base, transport: http() }).extend(publicActions); const signer = { address: account.address, signTypedData: (msg) => account.signTypedData(msg), readContract: publicClient.readContract.bind(publicClient), getTransactionCount: publicClient.getTransactionCount.bind(publicClient), estimateFeesPerGas: publicClient.estimateFeesPerGas.bind(publicClient), }; const body = { model: 'llama-3.3-70b', messages: [{ role: 'user', content: 'Hello' }], max_tokens: 100 }; const challenge = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); const paymentRequired = JSON.parse(Buffer.from(challenge.headers.get('PAYMENT-REQUIRED'), 'base64').toString()); const upto = paymentRequired.accepts.find((a) => a.scheme === 'upto'); const paymentPayload = await new UptoEvmScheme(signer).createPaymentPayload(2, upto); const paymentHeader = Buffer.from(JSON.stringify(paymentPayload)).toString('base64'); const paid = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', 'PAYMENT-SIGNATURE': paymentHeader }, body: JSON.stringify(body) }); console.log(await paid.json()); ``` ### Using Python ```python from x402 import x402_fetch response = x402_fetch( 'https://api.surplusintelligence.ai/v1/chat/completions', wallet=wallet, method='POST', json={ 'model': 'llama-3.3-70b', 'messages': [{'role': 'user', 'content': 'Hello'}], 'max_tokens': 100, } ) ``` ### 402 Response Format The response includes both `exact` and `upto` payment requirements. Current production responses emit `exact` first and `upto` second, but clients should select by `scheme` rather than array position. ```json { "x402Version": 2, "accepts": [ { "scheme": "exact", "network": "eip155:8453", "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "amount": "1000", "payTo": "0x...", "maxTimeoutSeconds": 120, "extra": { "name": "USD Coin", "version": "2" } }, { "scheme": "upto", "network": "eip155:8453", "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "amount": "1000", "payTo": "0x...", "maxTimeoutSeconds": 120, "extra": { "name": "USD Coin", "version": "2", "facilitatorAddress": "0x..." } } ], "resource": { "url": "/v1/chat/completions", "description": "LLM inference request for model llama-3.3-70b", "mimeType": "application/json" } } ``` - `amount` is in USDC micro-units (6 decimals). "1000" = $0.001 USDC. - `payTo` is the settlement address on Base. **Read it from the challenge every time — never hard-code it.** It is derived from the operator wallet, which rotates. - `asset` is the USDC contract on Base. - The same data is in the `PAYMENT-REQUIRED` response header (base64-encoded). ### Pricing Pricing is model-specific and market-based. SI routes to the cheapest available seller for the requested model. Prices are often below direct provider rates, but the final amount is always returned in the 402 challenge. On the synchronous routes, `upto`'s `amount` is the authorized maximum and settlement is `min(actual, authorized)` — the flat fee and the 10% estimation buffer are already inside that maximum, so an `upto` client is charged its real usage plus the fee and no more. `exact` settles the whole advertised amount, buffer included. **Async media does not work this way**: the full authorization is settled at submission, and any excess comes back as fiat credit — see "Async media over x402 pays differently" above. To require a minimum discount versus direct provider rates, prefix a `/v1/...` path with `/min{N}` (use an integer 0–100). Example: `POST /min50/v1/chat/completions` only routes to sellers ≥50% cheaper than the reference price; a floor nothing satisfies is `404 minimum_discount_not_met`, not a silent fall back to full price. **`/v1/embeddings` has no `/min{N}` mirror** and is excluded from every discount floor. See "Requiring a discount" below for the other two ways to set one. --- ## Path B — an API key, for anything long-running Four steps: authenticate, fund, cap, call. **Read this before planning the sequence: TWO DIFFERENT CREDENTIALS ARE INVOLVED, and the one you mint by SIWE cannot do all four.** A buyer key spends and reads. It cannot manage budgets or mint keys — those are a separate control plane: | capability | buyer key (`inf_…`) | management key / dashboard session | |---|---|---| | run inference, spend credit or USDC | ✅ | ❌ (a management key is refused on inference) | | read balance, spend, requests, audit, payouts | ✅ | ✅ | | `PUT`/`DELETE /v1/budgets` (B3) | ❌ `403 forbidden` | ✅ | | `POST`/`PATCH`/`DELETE /v1/keys` (B6) | ❌ `403 forbidden` | ✅ | So B3 and B6 need a **management key** (`key_type: "admin"`) or a signed-in session; B2 and B4 work with the buyer key from B1. The first management key cannot be minted over the API by a buyer key — it comes from the dashboard, because minting one requires the `keys.manage` capability a buyer key does not have. An agent that needs to cap its own spend unattended must therefore be ISSUED a management key up front; it cannot bootstrap one from a wallet signature alone. ### B1 · Authenticate (SIWE — no browser) ``` GET /v1/buyer/auth/challenge?address=0xYourWallet → a SIWE message to sign POST /v1/buyer/auth/keys → your buyer key { "message": "", "signature": "0x...", "label": "my-agent" } ``` The response carries an `inf_…` buyer key. **It is shown once.** Send it on every call as: ``` Authorization: Bearer inf_0f8c2a1b4d6e47f9a3c5b7d9e1f24680 ``` (the prefix is `inf_` followed by 32 hex characters; a management key is `inf_admin_…` and a seller key `si_seller_…`). This key spends and reads; it does NOT manage budgets or keys — see the table above. Sellers use the identical flow at `/v1/seller/auth/challenge` and `/v1/seller/auth/keys`, which returns an `si_seller_…` key. `GET /v1/auth/session` describes the current session and what the principal may do. **Activation.** `GET /v1/account/activation` reports whether anything is outstanding for a new account and `PATCH /v1/account/activation` (requires `Idempotency-Key`) updates it. Check it once after minting your first key rather than discovering a block mid-flow. ### B2 · Fund it — fiat credit or deposited USDC **Check first:** ``` GET /v1/payments/balance ``` Every money value below is an integer-microdollar STRING. This example is a buyer holding **$142.18**: ```jsonc { "credit_balance_usdc": "142180000", // COMBINED spendable: fiat + deposited USDC = $142.18. Show this as "Credits". "fiat_available_usdc": "120000000", // $120.00 card credit — spendable, NOT withdrawable "usdc_available_usdc": "22180000", // $22.18 deposited USDC — spendable AND withdrawable "fiat_held_usdc": "0", // reserved against in-flight requests "usdc_held_usdc": "0", "pending_deposit_usdc": "0", // seen on chain, not yet credited "pending_withdrawal_usdc": "0", // prepared but not submitted "pending_deposits": [], // each with amount_usdc (µ$ string), observed time, confirmations "pending_deposit_count": 0, // a NUMBER "deposit_address": "0x...", // your address — see below "deposit_chain_id": 8453, "deposit_min_confirmations": 20, // READ IT — per-environment configuration, not a constant "account_status": "active", // active | frozen | closed "withdrawals_paused": false, "prefunded_usdc_enabled": true, "stripe_fee_mode": "actual", // "actual" | "flat" — BRANCH ON THIS before previewing a fee "stripe_fee_bps": 290, // a NUMBER — 2.9%; only exact in "flat" mode, see the fee note below "stripe_fee_fixed_micro": "300000", // a STRING — $0.30 "stripe_invoice_fee_bps": 40, // a NUMBER — 0.4% "stripe_invoice_fee_max_micro": "2000000" // a STRING — $2.00 cap } ``` `balance_usdc` and `allowance_usdc` are also present and also µ$ strings; both describe the deprecated on-chain allowance rail and are not what you spend. **Fiat credit (card, via Stripe).** Returns a hosted Checkout URL to send the user to: ``` POST /v1/payments/topup Idempotency-Key: { "amountUsd": 50, "return_to": "dashboard" } ``` `amountUsd` is **dollars**, and camelCase — the one place this API takes either. It is bounded **$10 minimum, $2000 maximum**; outside that is a 400. **Crediting is NET of fees, and the fee is usually NOT KNOWABLE in advance.** You are charged `amountUsd` and credited `amountUsd − fee`. Which fee depends on `stripe_fee_mode`, which the balance response exposes — branch on it rather than computing blind: - **`actual`** (the default, and what production runs): the fee is the REAL one Stripe deducted, read from the charge's `balance_transaction` when it lands, including international and Amex surcharges. **It cannot be computed up front**, and `POST /v1/payments/topup` therefore omits `fee_usd`/`credit_usd` from its response. The `stripe_fee_*` fields on the balance response are a reasonable ESTIMATE for a preview; they are not the figure that will be credited. - **`flat`**: the fee is known at session-create, so the top-up response DOES carry `fee_usd` and `credit_usd` — **read those rather than recomputing**, since the same function stamps them, the session metadata and the webhook credit, and cannot drift. The formula behind them is `round(amount × stripe_fee_bps / 10_000) + stripe_fee_fixed_micro`, plus an invoicing surcharge of `stripe_invoice_fee_bps` capped at `stripe_invoice_fee_max_micro` *when that surcharge is enabled* — it is a separate switch, so whether a $50 top-up credits $48.25 or $48.05 depends on it. Hence: read the echoed fields. Either way: **never tell a user they will receive the amount they paid**, and in `actual` mode do not promise an exact figure before the charge lands. Poll `GET /v1/payments/balance` for what was really credited. `return_to` accepts `"dashboard"` (lands on `/app/buy/funding`), any path under `/app`, or `"legacy"`. **Omitting it means `legacy`**, which lands on `/payments/success` and forwards into the dashboard — so pass `"dashboard"` explicitly if you want a direct landing. An unrecognised value is a 400 `invalid_return_to` rather than a silent fallback. The balance updates on Stripe's webhook, not on redirect, so poll `GET /v1/payments/balance` rather than trusting the return. `POST /v1/payments/billing-portal` returns a Stripe portal URL for managing the saved card. It takes the same `return_to` and throws `404 no_billing_history` for an account that has never topped up. `GET /v1/payments/history` lists past top-ups (50 per page). **Deposited USDC (on-chain).** Get the address, send USDC on Base to it, wait for confirmations: ``` GET /v1/payments/deposit-address ``` The address is **per account** and stable — reuse it. Send only USDC (`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`) on Base (chain id `8453`). Credit appears after `deposit_min_confirmations`; before that it shows in `pending_deposits[]`. Deposited USDC is the only balance you can take back out: ``` POST /v1/payments/withdraw Idempotency-Key: { "amount_micro": "10000000", "destination": "0xYourWallet" } ``` `amount_micro` is a **string** of microdollars. Omit it to withdraw everything available. Withdrawals refuse while `withdrawals_paused` is true, and the route answers **404 when the prefunded-USDC rail is disabled for the environment** — so treat a 404 here as "not available", not "wrong path". **Keep it funded automatically** — the agent-friendly option: ``` PUT /v1/payments/auto-topup Idempotency-Key: { "thresholdMicro": 5000000, "refillToMicro": 50000000 } ``` When spendable credit falls below `thresholdMicro`, the card on file is charged back up to `refillToMicro`. Both are microdollars and camelCase. Both sit in a **$5–$2000** band and `refillToMicro` must exceed `thresholdMicro` by at least $5. `GET` reads the current setting and the card on file; `DELETE` turns it off (and also requires an `Idempotency-Key`). ### B3 · Cap what it can spend — do this before letting an agent run **Needs a management key or a session, not the buyer key from B1** — a buyer key gets `403 forbidden` here (`requires budgets.manage`). Budgets are the control a user actually wants when delegating spend. A hard-stopped budget refuses the request with `402 budget_exceeded` **while the account still has money**, which is the point. ``` PUT /v1/budgets Idempotency-Key: { "scope_type": "key", // key | member | workspace | org "scope_id": "", "limit_day_micro": 5000000, // $5.00/day "limit_month_micro": 100000000, // $100.00/month "hard_stop": true, // false = alert only, never block "alert_threshold_pct": 80 } ``` `GET /v1/budgets` lists them; `GET /v1/budgets/spend` returns current spend per budget in one call; `DELETE /v1/budgets/{scope_type}/{scope_id}` removes one (`Idempotency-Key` required). Windows are UTC. A paused budget keeps counting but never blocks. Set `hard_stop: true` for an autonomous agent — without it, a budget only warns. The 402's `detail` carries `{window, limit_micro, spent_micro, resets_at}`, so you can tell the user when it clears. ### B4 · Call inference Point any OpenAI client at the base URL: ```python from openai import OpenAI client = OpenAI(api_key="inf_...", base_url="https://api.surplusintelligence.ai/v1") client.chat.completions.create(model="llama-3.3-70b", messages=[{"role": "user", "content": "Hello"}]) ``` Streaming, tools and the usual parameters work. Provider extras pass through. **Reading the cost of a call.** A non-streamed response carries `usage.buyer_cost_micro` in the body and `x-si-buyer-cost-micro` as a header. **A streamed response cannot carry the header** — HTTP headers freeze at the first byte — so for `stream: true` you must send `stream_options: {"include_usage": true}` and read the figure off the final usage chunk. Without it, a streamed call tells you nothing about its cost and you have to look it up in `GET /v1/requests`. | Method | Path | Description | |--------|------|-------------| | GET | /v1/models | Live catalog with pricing | | GET | /v1/models/{id} | One model | | GET | /v1/prices | Direct provider price comparison matrix | | GET | /v1/providers | Known providers | | POST | /v1/chat/completions | Chat completions (OpenAI-compatible) | | POST | /v1/completions | Legacy completions | | POST | /v1/responses | OpenAI Responses API | | POST | /v1/decisions | Structured decisions: OpenAI's Decisions API (`input` + an ordered `questions` array, `client.decisions.create`) or the JEV format (`state` + a `questions` map). Input-token billing only | | POST | /v1/embeddings | Embeddings (no `/min{N}` mirror) | | POST | /v1/audio/* | Speech and transcription | | POST | /v1/images/generations | Image generation | | POST | /v1/images/edits | Image editing | | POST | /v1/video/generations | Video generation (async; poll the job) | | POST | /v1/music/generations | Music generation (async; poll the job) | | POST | /anthropic/v1/messages | Anthropic Messages API — see the skin section | | GET | /api/markets | Market summary per model | | GET | /api/markets/{model} | Order book and recent fills for one model | | GET | /v1/markets/usage-leaderboard | Most-used models | **Routing controls**, as request fields or headers: pin a `provider`, pass a `provider_base_url`, set `max_price_per_1m`, or require a minimum discount (next section). A floor that excludes every seller is a 404 (`minimum_discount_not_met` / `max_price_exceeded`), not a silent fall back to full price. #### Requiring a discount — three ways, strictest wins 1. **The URL mirror:** `POST /min50/v1/chat/completions`. Use an integer 0–100. The URL form parses any run of digits rather than range-checking it, so `/min500` is NOT an error — it simply matches no seller and comes back `404 minimum_discount_not_met`. No mirror for `/v1/embeddings`. 2. **A request header:** `X-Min-Discount: 50` (sent as `x-min-discount`; headers are case-insensitive). THIS one is range-checked — a non-integer or anything outside 0–100 is `400 invalid_min_discount_header`. 3. **Per key, persistently:** the key's `scope.min_discount_pct` (0–100), set at mint or via `PUT /v1/buyer/keys/{id}/preferences`. `GET`/`PUT /v1/buyer/preferences` holds the account default. When more than one applies, the resolved floor is `max(url, header, key)` — **the strictest wins**, so a key-level floor cannot be lowered by a request. Note that `0` on a key is a real value meaning "no floor", which is not the same as leaving it unset. #### Masking secrets in a prompt (beta) — off unless something turns it on An optional extra layer of protection. On a masked request, API keys, private keys, seed phrases, passwords and tokens are replaced with placeholders (`SI_SECRET__<8 chars>`) before it is routed, and EVERY value is put back in the response — prose, code, tool-call arguments, structured output, links and markup, passwords and seed phrases alike. Only the model's reasoning is left as written (signed reasoning must be replayed byte for byte), so a reply never carries a placeholder your agent has to work around. Three switches. Any one turns masking ON, and none can turn it off for a request another one turned on: 1. **Per request:** `X-SI-Mask-Secrets: on`. Exactly `on`; anything else, an empty value or a repeated header is `400 invalid_secret_masking_header`. It applies at once. 2. **Per key:** `mask_secrets: true` via `PUT /v1/buyer/keys/{id}/preferences`, or on `POST /v1/keys` / `PATCH /v1/keys/{id}`. 3. **Account-wide:** `mask_secrets: true` via `PUT /v1/buyer/preferences`. It covers every key; a key's `false` does not opt out of it. To turn it off: drop the header, and set the key's or the account's `mask_secrets` to `false` or `null` (the switch that turned it on). A key cannot opt out of an account that masks — turn the account off and switch keys on one by one instead. Turning off also takes up to ~31 s to reach every server. A stored switch applies from `secret_masking_effective_at`, which the write returns (about 31 s later; about 70 s right after masking is turned on for the service); send the header until then. The preference responses carry `secret_masking_available`: when it is `false`, masking is paused on the service and a request that asks for it is sent WITHOUT masking (no `x-si-secret-masking` header on its response) — check that header if you need to know. **The preference PUTs merge:** a field you leave out is unchanged and `null` clears that field, so you can set `mask_secrets` alone. Text endpoints only: `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/anthropic/v1/messages` and `/v1/decisions`, with their `/min{N}` mirrors. **Embeddings, images, audio, video, music and x402 resources are never masked:** a masked key or account works there like any other key, the request is sent as it is, and while masking is running its response carries `x-si-secret-masking: not_applied`. A masked response carries `x-si-secret-masking: applied` and `x-si-secrets-masked: `. Placeholders left in place are counted in `x-si-secrets-withheld` on a JSON response, or in one SSE comment line, `: si-secrets-withheld `, just before a stream's final event — each only when the count is more than 0. **What it trusts.** Values are restored wherever the model writes them: a command that sends a placeholder to the seller's own server gets the real value if you run it; a link or image carrying one sends it to that host when a client renders or previews it; and a password repeated on a later turn without its context goes upstream unmasked. Check commands before running them, as you would without masking. If masking was asked for, is running, and cannot be applied, the request is refused before funding and nothing is sent; the codes are in the Errors table above. Full guide: /docs/guides/secret-masking #### Media generation is asynchronous Submit, then poll. **Paying for one over x402 charges the full quoted maximum up front** rather than actual usage — see "Async media over x402 pays differently" in Path A. On a prepaid-credit key it is an ordinary hold-then-capture, so the refund of any unused estimate is simply credit you can spend. ``` POST /v1/video/generations → a job GET /v1/video/generations/{id} → status; same shape for /v1/music/generations/{id} DELETE /v1/video/generations/{id} → cancel GET /v1/media/artifacts/{jobId}/{index} → the output itself — see below, it is NOT a JSON URL ``` **The artifact endpoint does not return a URL in a body.** It answers in one of three shapes depending on how the job was delivered, so **follow redirects and do not parse JSON**: - **`302` to a short-TTL presigned S3 URL** — an SI-hosted artifact. The presigned URL is short-lived (~15 min), so follow it promptly rather than storing it. - **`302` to the provider's own URL** — a provider-hosted artifact (the poll response already carries this URL too, so you may not need this call at all). - **The bytes, streamed directly** — relay mode, where nothing is stored on our side. Any HTTP client that follows redirects by default (curl `-L`, `fetch`, `requests`) handles all three. Errors, all four of them: - **`404 not_found`** covers a missing job, a job that has not succeeded, and a missing artifact index — one code for all three. A job you are not authorised for also 404s rather than 403s, so a 404 is not proof the job is absent. - **`404 artifact_expired`** is distinct, but appears only where expiry enforcement is switched on. - **`503 artifact_unavailable`** when a relay-mode artifact is requested somewhere the relay is not configured. Retryable. Artifacts are retained about 3 hours in production; a presigned URL lives 15 minutes. ### B5 · Read back what it spent | | | |---|---| | `GET /v1/payments/balance` | live balances, all three figures | | `GET /v1/payments/history` | past top-ups | | `GET /v1/buyer/overview?range=7d\|30d\|90d` | spend, savings, pace, daily series, top models | | `GET /v1/buyer/savings?period=daily\|weekly\|all_time` | saved versus reference prices | | `GET /v1/requests` | the request log — per-call cost, model, provider, latency, settlement | | `GET /v1/requests/{requestId}` | one request; `/facets` for the filter vocabulary | | `GET /v1/budgets/spend` | spend against every budget | | `GET /v1/analytics/spend/{summary,trend,breakdown}` | precomputed spend analytics | | `GET /v1/analytics/savings/summary` | precomputed savings | | `POST /v1/analytics/explorer` | a bounded ad-hoc query; poll `/{queryId}`, then `/export` | | `GET /v1/audit` | the account's audit trail; `/export` for a file | | `GET /v1/buyer/usage/export` | usage as a file | | `GET /v1/attention` | what needs the user's attention right now, ranked | **Pagination.** `GET /v1/requests` takes `limit` (default 50, max 200) and `cursor`; pass the returned cursor back to continue. Page sizes differ per endpoint — `/v1/audit` is a fixed 50 and ignores `limit`, `/v1/payments/history` is 50, `/v1/seller/earnings-history` is 25 (max 50). Filters on `/v1/requests`: `from`/`to`, comma lists for `model`/`provider`/`key_id`, `statuses`, `funding`, `cache`, `latency_*`, `search`, `endpoint`, `member_id`. **A filtered read is rate-limited far more tightly** (60/min, not 300/min), so paginate rather than re-querying. These are precomputed reads and are cheap to poll at human intervals; they are not a streaming feed. **`coverage: false` is not zero.** `GET /v1/buyer/overview` can answer with `coverage: false` and every figure null, which means the aggregate has not been computed for that window — not that the account spent nothing. Omit the number; never render it as `0`. **Prompt and response bodies are not stored by default.** Metadata, token counts, cost and settlement fields are. Body capture is an explicit opt-in: `PUT /v1/requests/settings {"body_capture_enabled": true}`, after which `GET /v1/requests/{requestId}/bodies` returns them. Leave it off unless the user asked for it. ### B6 · Manage keys **This whole surface needs a management key or a session** (`requires keys.manage`); the buyer key from B1 gets `403 forbidden` on every route below, including rotating itself. The section heading used to say "its own keys", which was wrong in both directions. ``` POST /v1/keys mint (Idempotency-Key REQUIRED) { "name": "ci-runner", "key_type": "buyer", "budget": { "limit_day_micro": 1000000, "hard_stop": true }, "expires_in_seconds": 86400, "ephemeral": true } GET /v1/keys list (never returns the secret) PATCH /v1/keys/{id} rename, re-scope, change the budget (required) POST /v1/keys/{id}/rotate new secret, same id and settings (required) DELETE /v1/keys/{id} revoke immediately (required) ``` The field is `name` here. (`POST /v1/buyer/auth/keys`, the SIWE mint, calls it `label` — the one inconsistency worth remembering.) A key may carry its own budget, an expiry, and a scope. Two separate refusals apply and they are often confused: a **scoped** key gets `403 restricted_key` if it tries to mint, and **any buyer key — scoped or not — gets `403 forbidden`** on this surface because minting needs `keys.manage`. Either way a key you hand to a subagent cannot mint a sibling, which is what makes it safe to hand over. `ephemeral: true` plus `expires_in_seconds` is the right shape for a short-lived task. **There is a ceiling of 200 keys per workspace**, past which minting answers `429 too_many_keys`. An agent that mints a key per task must revoke them, or reuse one scoped key. ## Anthropic API ("Anthropic Skin") — Claude Code & the Anthropic SDK Surplus speaks Anthropic's Messages API, so Claude Code and the Anthropic Agent SDK can route through the marketplace with only environment variables — no local proxy. Same idea as OpenRouter's Anthropic skin. It is model-agnostic: route Claude Code to Claude OR to GPT/GLM/Llama/Gemini/DeepSeek/etc. via the `model` string. The OpenAI-compatible `/v1/...` surface is unchanged; the skin lives under `/anthropic`. Base URL (set as `ANTHROPIC_BASE_URL`): `https://api.surplusintelligence.ai/anthropic` (The Anthropic client appends `/v1/messages`. Auth: a Surplus buyer key `inf_…` via `ANTHROPIC_AUTH_TOKEN` (→ `Authorization: Bearer`) or `x-api-key`; set `ANTHROPIC_API_KEY=""`.) Claude Code config (these 3 vars are the whole required setup): ```bash export ANTHROPIC_BASE_URL="https://api.surplusintelligence.ai/anthropic" export ANTHROPIC_AUTH_TOKEN="inf_your_key" export ANTHROPIC_API_KEY="" ``` Model env vars are OPTIONAL — with none set, Claude Code uses its built-in default models and the marketplace serves them. Set them only to pin a specific model, control cost, or run on a non-Claude model (if you pin one slot, pin both): ```bash export ANTHROPIC_MODEL="claude-opus-4.8" # main loop export ANTHROPIC_SMALL_FAST_MODEL="gpt-4o-mini" # background tasks ``` Endpoints (under `/anthropic`): `POST /v1/messages` (non-stream + Anthropic SSE; `+ /min{N}/v1/messages` minimum-discount mirror), `POST /v1/messages/count_tokens`, `GET /v1/models` (+ `/{id}`). Model names accept `-latest` aliases (incl. cross-family `gpt-latest`/`glm-latest`/…), dated Anthropic IDs, and the `~anthropic/…` prefix. Routing controls (`provider` pin/allow-list, `provider_base_url`, `max_price_per_1m`, `/min{N}`) work here too. Extended thinking is best-effort (Claude only). **Error handling differs here, and it matters.** The skin uses the Anthropic envelope `{"type":"error","error":{"type","message"}}` with **no `code` field**, issues **no 402 challenges**, and maps a payment failure to **400 `invalid_request_error`**. A missing or invalid buyer key is `401 authentication_error`. If your agent needs to distinguish "out of credit" from "bad request" programmatically, use the `/v1/*` surface. Full guide: /docs/guides/claude-code-setup · Reference: /docs/api-reference/messages ## Selling capacity You have spare provider capacity; list it and the router sells it. SIWE auth, no browser. ``` GET /v1/seller/auth/challenge?address=0xYourWallet → SIWE message POST /v1/seller/auth/keys → si_seller_… key POST /v1/seller/offers Idempotency-Key: { "model": "claude-sonnet-4-5", "api_key": "", "seller_base_url": "https://api.anthropic.com/v1", "cost_multiplier": 0.70, // charge 70% of the reference price "cap_daily_usd": 25, // optional daily ceiling "payout_address": "0x..." // optional; defaults to your account's } ``` **Price by multiplier, not per token.** `cost_multiplier` (0–2 on create) or `discount` (0–100) is how a text offer is priced. Absolute per-token pricing (`price_input_per_1m` / `price_output_per_1m`) is **retired for text models** and quoting it will be refused. Note an asymmetry worth knowing: `PATCH` does not bound `cost_multiplier`, so a reprice can set a value a create would reject. Your upstream key is KMS-encrypted at rest, is **never returned by any read**, and is decrypted only by the workers that have to use it: the request proxy that serves a buyer, the scheduled health and capability probers that check your offer still works, and the media workers that verify and render an async job. It is never logged. | | | |---|---| | `GET /v1/seller/offers` | your offers with health and live rank | | `PATCH /v1/seller/offers/{id}` | reprice, cap, relist, change payout address | | `DELETE /v1/seller/offers/{id}` | **soft** delete — revoke the upstream key for immediate invalidation | | `POST /v1/seller/offers/{id}/rotate-credential` | swap the upstream key; probed before it is accepted | | `POST /v1/seller/offers/{id}/reset-health` | clear backoff after you have fixed the upstream | | `POST /v1/seller/offers/bulk` · `bulk-update` · `bulk-cancel` | many at once; async — poll `GET /v1/seller/operations/{id}` | | `GET` · `POST` · `DELETE /v1/seller/keys` | your provider credentials (create requires `Idempotency-Key`) | | `POST /v1/seller/test-connection` · `test-health` | probe an upstream before listing it | | `POST /v1/seller/discover` | enumerate what an upstream key can serve | | `GET` · `PATCH` · `DELETE /v1/seller/configs` | reusable offer templates | | `GET /v1/seller/earnings` · `earnings-history` | what you earned, by range, model, offer and provider | | `GET /v1/seller/payouts` | owed, held and paid | | `POST /v1/seller/payouts/withdraw` | claim what you are owed (`{self_submit, destination}`) | | `POST /v1/seller/payouts/submitted` | report a self-submitted payout transaction | | `GET /v1/seller/usage/export` | your usage as a file | | `GET /v1/seller/health-log` | why an offer was skipped or backed off | **Payouts** batch above a threshold (currently $5). What you are owed and what has been paid are separate figures on `GET /v1/seller/payouts` (`available_usdc`, `in_flight_usdc`, `paid_usdc`), and the paid figure advances only when a payout CONFIRMS on chain — never when you claim it. A claim moves money from available to in-flight. **One active offer per (upstream key, base URL, model).** A second one is refused with **`409 duplicate_offer_for_credential`** — the same key may serve many different models, and the same model through a different base URL, but not the same triple twice. Unhealthy offers are backed off exponentially and skipped by the router until they recover or you reset them. ### Selling API resources (not inference) Sellers can also list upstream API keys for non-inference resources, priced the same way: ``` GET /v1/resource/markets what resources have liquidity GET /v1/resource/seller/offers your resource offers POST /v1/resource/seller/offers list one (Idempotency-Key REQUIRED) PATCH /v1/resource/seller/offers/{id} reprice (required) DELETE /v1/resource/seller/offers/{id} delist ``` Create requires `resource_type` and `api_key`; `resource_type` is one of exactly **`twitter_api`** or **`venice_rpc`**: ``` POST /v1/resource/seller/offers Idempotency-Key: { "resource_type": "twitter_api", // or "venice_rpc" "api_key": "", "pricing_multiplier": 0.70, // or "discount_percent" "cap_daily_usd": 25, // optional; cap_weekly_usd / cap_monthly_usd also accepted "payout_address": "0x..." // optional } ``` ## Teams An account can be a personal org or a team org. A team adds workspaces, members with roles, and scoped budgets. `POST /v1/orgs` creates one and requires a `name` (`slug` is optional); `/v1/orgs/{orgId}/workspaces`, `/members`, `/invites` and `/wallets` manage it; `POST /v1/auth/active-org` switches which org a session acts as. Every org write requires an `Idempotency-Key`. Budget `scope_type` accepts `member`, `workspace` and `org`, so a team can cap a person or a project rather than a key. Members hold capabilities, and a request that exceeds them gets `403` — read `GET /v1/auth/session` for what the current principal may do. ## Webhooks **Needs a management key or a session** — `webhooks.manage`, which a buyer key does not carry, so every mutating route below answers `403 forbidden` to an `inf_…` key. Listing deliveries and reading one is `audit.read`, which a buyer key DOES have. ``` POST /v1/webhooks register (Idempotency-Key REQUIRED) GET /v1/webhooks list PATCH /v1/webhooks/{id} update DELETE /v1/webhooks/{id} remove (required) POST /v1/webhooks/{id}/test send a test event POST /v1/webhooks/{id}/deliveries/{deliveryId}/resend replay one ``` **Create takes exactly two required fields — `url` AND `event_types`:** ``` POST /v1/webhooks Idempotency-Key: { "url": "https://your.host/hooks/surplus", "event_types": ["usage.recorded", "request.failed"] } ``` The event vocabulary is a closed set of eight — anything else is `400 invalid_event_types`: ``` usage.recorded request.failed audit.event key.created key.revoked member.added member.role_changed resource.job.completed ``` `resource.job.completed` is a Provider Market job reaching its outcome (see Jobs below). It is being enabled; until it is, keep polling. A workspace can hold at most 50 webhooks; the 51st create is `400 webhook_limit_reached` (delete one first). There is **no balance, budget or payout event**, so a webhook cannot be used for funding alerts — use the notification channels below for those. **Verifying a delivery — the signed material is NOT the body alone.** The header is ``` X-Surplus-Signature: t={unixSeconds},v1={hexHmac} ``` and the HMAC-SHA256 is computed over the string **`{t}.{rawBody}`** — the timestamp, a literal dot, then the raw body bytes — keyed with the `whsec_…` secret returned **once** at registration. A verifier that MACs the body alone computes a different digest and rejects every genuine delivery. To verify: parse `t` and `v1` out of the header, recompute `HMAC_SHA256(secret, t + "." + rawBody)` over the **raw bytes as received** (never a re-serialised object — JSON encoders disagree on key order and whitespace), compare in constant time, and **reject when `|now − t| > 300` seconds**. The timestamp is inside the signed material precisely so a captured delivery cannot be replayed for ever; skipping the window check throws that property away. ```python import hmac, hashlib, time def verify(header: str, raw_body: bytes, secret: str) -> bool: parts = dict(p.split("=", 1) for p in header.split(",")) t, sig = parts.get("t", ""), parts.get("v1", "") if not t.isdigit() or abs(time.time() - int(t)) > 300: return False expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, sig) ``` ## Alerts for a human in the loop **The credential rule here is the INVERSE of webhooks and budgets:** notification settings accept a buyer key, a seller key or a session, and **reject a management key** (`401 unauthorized`). A management credential is not an account that receives alerts. ``` PUT /v1/notifications/settings { "channel": "email", // email | telegram; `email` field required when email "email": "ops@example.com", "rules": [ { "rule_type": "buyer.balance_low", "enabled": true, "config": { "threshold_micro": 10000000 }, "rearm_after_ms": 86400000 } ], "reminders": [] } POST /v1/notifications/test prove the channel works ``` **There are exactly four rule types.** Anything else is `400 unknown_rule_type`: | `rule_type` | fires when | |---|---| | `buyer.balance_low` | spendable credit drops below `config.threshold_micro` | | `buyer.out_of_balance` | spendable credit reaches zero | | `seller.offer_unhealthy` | an active offer has failed `config.n` times | | `seller.key_out_of_balance` | a provider rejected your upstream key (401/402/403) | `channel` is optional and defaults to `email`. The limits are enforced at the handler, each with its own code: at most **20** rules (`400 too_many_rules`); `rearm_after_ms` an integer in **900_000 … 604_800_000** (15 minutes to 7 days — `400 invalid_rearm`), which stops an alert re-firing continuously; a valid `email` is required when the channel is email (`400 invalid_email`); and at most 5 active destinations (`400 too_many_destinations`). **Telegram needs three more calls**, not just the `PUT`: `POST /v1/notifications/telegram/link` → `POST /v1/notifications/telegram/confirm` → `POST /v1/notifications/telegram/disconnect` to undo. ## Discovery - `GET /v1/models` — the live catalog. Read this rather than trusting any list in this file. - `GET /api/markets` — models with active seller liquidity, and the current best discount. - `GET /v1/prices` — reference provider prices, for comparison. - `/.well-known/x402` — x402 resource discovery manifest (**api host only**) - `/x402/info` — x402 payment info: operator, flat fee, schemes (both hosts) - `/llms.txt` — this file (**website only**) - `/docs/*` — the human documentation (**website only**), including `/docs/payments/x402` and `/docs/api-reference/seller-endpoints` ## Contracts (Base, chain id 8453) - Settlement proxy: `0x0770d2124C0a581C28Cfc47a659817145e6Cc137` - USDC: `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` - Permit2 (the x402 `upto` approval target): `0x000000000022D473030F116dDEE9F6B43aC78BA3` `/x402/info` additionally reports an `upto` witness-proxy address, which is a different contract from canonical Permit2 above. Approve canonical Permit2; read anything else from discovery. ## Retired - **The on-chain allowance funding rail** for API keys, and `POST /v1/buyer/approve-permit` with it. Fund with fiat credit or deposited USDC instead. `balance_usdc` and `allowance_usdc` on the balance response are legacy fields describing this rail. - **Absolute per-token pricing for text offers** (`price_input_per_1m` / `price_output_per_1m`). Quote `cost_multiplier` or `discount`. - **`POST /api/purchase`**, which sold Venice credit packages — returns `404` with `ROUTE_RETIRED`. Use per-request x402. (`/api/x402/purchase` answers `410 Gone` on the website host and 404 on the API host.) - The signed-in product moved from `/buy`, `/sell`, `/settings`, `/finops`, `/keys`, `/invite`, `/imagegen`, `/payments` and `/miniapp` to `/app/*`. Old URLs redirect (307, so do not cache them); `/miniapp` goes to the home page and `/imagegen` to the dashboard home, as neither has an `/app` equivalent. The **API surface did not move** — `/v1/*`, `/anthropic/*`, `/api/*` and `/x402/*` are unchanged. ## Notes and limits - Media generation is asynchronous: submit, then poll, then fetch the artifact before it expires. - Buyer and seller identities are not exposed to each other anywhere in the public API. - `expires_in_seconds` and `alert_threshold_pct` have no validated range; do not rely on one. ## Provider Market — Fal, Wavespeed, ElevenLabs Call a media provider on **someone else's** API key, at a discount off that provider's own list price, with your Surplus API key. Three providers are live. Full guide: /docs/marketplace/provider-market-calling · Reference: /docs/api-reference/resources Base path: `https://api.surplusintelligence.ai/v1/resources/{provider}/{the provider's own path}` This rail is **prepaid credit only** — it never falls through to the on-chain rail. No credit ⇒ `402 insufficient_credit`, and nothing is reserved. ```bash # ElevenLabs and Wavespeed are PATH style: the provider's own path goes straight on. curl -X POST https://api.surplusintelligence.ai/v1/resources/elevenlabs/v1/sound-generation \ -H "Authorization: Bearer $SURPLUS_API_KEY" -H 'Content-Type: application/json' \ -d '{"text":"a short soft chime","duration_seconds":1}' --output chime.mp3 curl -X POST https://api.surplusintelligence.ai/v1/resources/wavespeed/api/v3/wavespeed-ai/flux-schnell \ -H "Authorization: Bearer $SURPLUS_API_KEY" -H 'Content-Type: application/json' \ -d '{"prompt":"a tiny blue paper boat","size":"1024*1024"}' # Fal is HEADER style: the path must be EMPTY and the target rides in x-fal-target-url. # A path here is refused `unexpected_path`. This is the most common first mistake. curl -X POST https://api.surplusintelligence.ai/v1/resources/fal \ -H "Authorization: Bearer $SURPLUS_API_KEY" -H 'Content-Type: application/json' \ -H 'x-fal-target-url: https://fal.run/fal-ai/flux/schnell' \ -d '{"prompt":"a tiny red origami crane","image_size":"square"}' ``` What is reachable, per provider: Fal — only `fal-ai` public models on `fal.run` / `queue.fal.run`, and LLMs (`fal-ai/any-llm`) are refused provider-wide (use `/v1/chat/completions`). Wavespeed — 44 allowed publishers' models plus one result read. ElevenLabs — exactly three routes: `POST /v1/sound-generation`, `POST /v1/music`, `GET /v1/models`. Streaming is refused on every provider. Account, billing and key-minting routes are never reachable, for any seller. Every response carries `x-si-buyer-cost-micro` (what you paid) and `x-si-list-cost-micro` (what it would have cost direct). A failed call is charged **zero**; a successful one is charged the provider's reported usage or the quote, whichever is lower. Jobs (Wavespeed tasks, Fal queue submits) answer with an id, not a result. **The charge settles when you fetch the result**, not at submit; polling is free. A job is bound to the one offer that took it for 27 hours, so follow the URLs the submit returns — on path-style providers we rewrite them to come back through us on your key. A relay carries no idempotency: replaying a succeeded call is a second real generation and is billed as one. Retry only failures. To be told when a job finishes instead of polling, either pass your URL in the provider's own webhook parameter on the submit (WaveSpeed's `?webhook=`; the response then carries that job's signing secret, once, in `x-surplus-webhook-secret`, or `x-surplus-webhook-status: unavailable` if the job started without one), or subscribe a workspace webhook to `resource.job.completed` (that same header on the submit says the event will not come for that job: poll it). The event has the same fields for every provider: `job_id`, `request_id`, `resource`, `model` (the submit path), `status` (succeeded, failed, canceled or expired), `submitted_at`, `completed_at`, `outputs` (the output URLs, where the provider names them), `error` (null, or a Surplus code and message) and `charged_micro`. It is at least once: dedupe on `request_id`. Verify Surplus's signature, not the provider's. Fetch the full result through your usual follow-up URL, which costs nothing once the job is settled. Keep a slow poll as a fallback. Discovery, no auth: `GET /v1/resource/markets` (live providers, best and median discount), `GET /v1/resource/capabilities`, `GET /v1/resource/traits`, `GET /v1/resource/book/{provider}`. Require properties of the serving account with `X-SI-Require: data.zdr,residency.eu` — no offer claiming all of them ⇒ `trait_unavailable`. Prefix with `/min{N}` to route only to offers at least N% off. To sell: `POST /v1/resource/seller/keys/probe` then `POST /v1/resource/seller/offers` (`discount_percent` 5–80, both `ack_persists_state` and `ack_provider_terms` must be true). One active offer per credential per model. Guide: /docs/marketplace/provider-market-listing ## x402 API Resource Endpoints Surplus Intelligence also exposes seller-backed API resources via x402. Sellers list upstream API keys and configure a discount/multiplier versus official upstream prices; agents pay per request in USDC on Base. The seller-side endpoints are under `/v1/resource/*` (see "Selling API resources" above). These are a **separate, older resource family** from the Provider Market above (Fal, Wavespeed, ElevenLabs), which is served on `/v1/resources/*` against prepaid credit. ### Twitter/X API v2 — read-only Base path: `https://api.surplusintelligence.ai/x402/resources/twitter/...` Examples: ```bash curl -i "https://api.surplusintelligence.ai/x402/resources/twitter/tweets/search/recent?query=x402&max_results=10" curl -i "https://api.surplusintelligence.ai/x402/resources/twitter/users/by/username/mac_eth" ``` The first request returns an x402 402 challenge. Sign an `accepts[]` requirement and retry with `PAYMENT-SIGNATURE`. This resource is **read-only**: write and action endpoints are intentionally not supported, and there is no user-context path, so engagement reads that require a user's own authorization are not available. Seller credentials are never used for account-control access. ### Venice Crypto RPC Base path: `https://api.surplusintelligence.ai/x402/resources/venice-rpc/{network}` Example: ```bash curl -i https://api.surplusintelligence.ai/x402/resources/venice-rpc/base-mainnet \ -H 'Content-Type: application/json' \ -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' ``` Supported networks mirror Venice's crypto RPC network slugs, including `ethereum-mainnet`, `base-mainnet`, `arbitrum-mainnet`, `optimism-mainnet`, `polygon-mainnet`, `linea-mainnet`, `avalanche-mainnet`, `bsc-mainnet`, `blast-mainnet`, `zksync-mainnet`, and `starknet-mainnet` plus their documented testnets. Discovery: see `/.well-known/x402` and `/x402/info`.