<!-- TokenOS docs · P2P AI · Markdown mirror of https://tokenos.ai/docs/p2p-agents · HTML: https://tokenos.ai/docs/p2p-agents · index: https://tokenos.ai/llms.txt -->

# Agents: buy inference on P2P

TokenOS P2P is an OpenAI-compatible inference market: peers post a price per model, buyers pay per request with x402 (USDC on Solana) or with a `tos_` key funded by credits. This page is the machine-facing contract: how an agent discovers what is for sale, asks for a neutral ranked match, pays, stays inside a human-signed budget, and reads errors. Everything here is a public, versioned HTTP surface — nothing is hidden in prompts or tool descriptions.

> **Note — Neutral by construction**
> Matching ranks by price first, then trust and measured first-token latency; wash-flagged peers are excluded. The reference seller TokenOS runs is listed like any other peer with `firstParty: true` and ranks after independent peers. Public statistics exclude TokenOS’ own traffic and test keys. Every match response carries `neutral.neutralMatching` and `neutral.houseSellerFavored` with the rule in plain words; if either ever changes, the response says so.

## Discover and match

Two free endpoints, no key, CORS open, cacheable. Prices are per million tokens; quotes are upper bounds (input estimate + `max_tokens`).

**offers → match**

```
# 1. What is for sale right now (free, no key, cached 60 s)
curl https://tokenos.ai/api/p2p/v1/offers
# → offers[]: peerId, model, capability, routes, inputUsdPerMillion, outputUsdPerMillion, trust, verification, latencyMs,
#   signals{sessions30d, successRate, ghostRate, refundRate, medianTtftMs, disputes}; models[]: cheapest/median/peers per model

# 2. Ask for a ranked match (read-only — nothing is reserved or paid)
curl -X POST https://tokenos.ai/api/p2p/v1/match -H 'content-type: application/json' -d '{
  "capability": "chat", "models": ["gpt-oss-120b", "llama-3.3-70b"],
  "max_output_usd_per_million": 1.0, "max_quote_usd": 0.01, "min_trust": 40, "max_ttft_ms": 1500,
  "sample": {"messages": [{"role": "user", "content": "…your prompt…"}], "max_tokens": 512}, "limit": 3 }'
# → matches[]: rank, peerId, model, pricing{inputUsdPerMillion, outputUsdPerMillion}, quoteUsd, trust, signals{medianTtftMs,…}, reasons[] (factual),
#   quote{usd, atomic, resource, body, headers}: the same number the 402 challenge will carry for this body; rejected{reason: count};
#   neutral{neutralMatching: true, houseSellerFavored: false, rule}
```

- **POST /api/p2p/v1/match** — Body: `models[]` or `capability` (chat · messages · responses · embeddings · audio · images), `features` (tools, json_mode, vision, streaming, context_length), `max_output_usd_per_million` , `max_input_usd_per_million` , `max_quote_usd` (per-request budget), `min_trust` , `max_ttft_ms` , `privacy` ( `hosted_ok` | `local_only` : skip hosted/relayed supply and return peer endpoints), `sample` (the body you will send), `limit` . Returns ranked matches with factual `reasons[]` and a quote that equals the 402 challenge for the same body. Read-only: no hold, no payment.
- **GET /api/p2p/v1/offers** — Every live peer × model × price × capability, with per-peer signals from settled sessions (served, success rate, median TTFT, refund rate) and per-model price summaries. `?model=` , `?capability=` , `?route=` filter.
- **GET /api/p2p/v1/stats** — Public network statistics over the last 30 days — settled sessions, success rate, refund rate, median TTFT, per-model cheapest/median prices. Internal and test identities excluded.
- **GET /api/p2p/wanted** — Demand board: models buyers asked for that no peer served, with the price points agents asked for (counts only; never prompts or buyer identities).

## Try it: live match

The same `POST /api/p2p/v1/match` the agents call, against the live network. Move the constraints and read the `reasons[]` each peer was ranked on — price floor, trust, measured first-token latency, verification, bonding. Free, no key, nothing reserved.

Interactive in the browser: open [tokenos.ai/docs/p2p-agents#playground](https://tokenos.ai/docs/p2p-agents#playground), or call `POST /api/p2p/v1/match` directly with the body shown above.

## Pay: x402 or a scoped key

**x402 (no account) · scoped key (budgeted)**

```
# 3. Buy — x402, no account. Send the body; the 402 carries the price; pay; retry the identical body.
curl -i https://tokenos.ai/api/p2p/v1/chat/completions -H 'content-type: application/json' \
  -d '{"model":"gpt-oss-120b","messages":[{"role":"user","content":"hello"}],"max_tokens":512}'
# HTTP/1.1 402 · PAYMENT-REQUIRED: <base64 x402 v2 challenge> · body.quote.usd == match.quote.usd for the same body
# x402 v2 clients (x402-fetch, x402 python, Coinbase AgentKit) handle the pay-and-retry automatically.

# — or with a scoped key under a budget your principal signed (no wallet on the agent):
curl https://tokenos.ai/api/p2p/v1/chat/completions -H 'authorization: Bearer tos_…' -H 'content-type: application/json' -d '{…}'
curl https://tokenos.ai/api/p2p/v1/budget -H 'authorization: Bearer tos_…'      # caps, spent, remaining, resetsAt
```

The hosted gateway routes to the cheapest offer, then higher trust, with failover before anything is charged. Response headers carry `x-tokenos-peer`, `x-tokenos-session`, `x-tokenos-match-reason` and, when a failover happened, `x-tokenos-rematched-from`. Prompts travel gateway → seller only; TokenOS stores aggregate counts, never prompts or completions.

## Budgets: human-signed, server-enforced

A principal (wallet) signs a mandate once on [/p2p/budgets](https://tokenos.ai/p2p/budgets) and mints scoped `tos_` keys under it. The agent only ever holds the key. Enforcement happens in the gateway on every request — nothing in a prompt, tool description or client flag can raise a cap.

1. **Mandate** — Caps nest: `perRequestUsd ≤ hourlyUsd ≤ dailyUsd ≤ totalUsd`. Optional `allowed.models` / `allowed.capabilities`, `maxUnitPrice`, `minTrust`, `expiresAt`, `approvalThresholdUsd`, `notify.email` / `notify.webhook`. JSON Schema: [/api/p2p/budgets/schema.json](https://tokenos.ai/api/p2p/budgets/schema.json).
2. **Check before hold** — Every request is quoted at its upper bound at the chosen peer’s price. If it would cross any window, the answer is `402 budget_cap_reached` with `quoteUsd`, `remainingUsd`, `window`, `resetsAt` — before a hold is reserved.
3. **Approvals** — Requests above `approvalThresholdUsd` create an item in the principal’s Approvals Inbox (email / webhook if configured). The agent gets `402 approval_pending` with `approval.pollUrl`; once approved it retries with `x-tokenos-approval: <itemId>`. The allowance is single-use and capped at the approved quote (+10%).
4. **Holds and receipts** — Session holds are sized to the remaining headroom so the sum of holds never exceeds a cap; unspent holds return when sessions close. Receipts are seller-signed settlements (`GET /api/p2p/budgets/{id}/receipts`); their sum equals the dashboard total.
5. **Kill switch** — Revoking a budget revokes every key under it; the agent’s next request fails with `401 key_invalid`.

> **Warning — Status**
> Scoped-key budgets are enforced for credit-funded keys. Wallet-bound enforcement of x402 payers at the facilitator (`agent.payerWallet` is recorded today) ships after the P2P money-path fixes are re-tested. TokenOS keeps the no-account x402 flow available under platform guardrails regardless — budgets are optional.

## Errors an agent can act on

Every 4xx/5xx from `/api/p2p/v1/*` carries the same envelope: `error.code` (machine-readable), `error.message` (plain), `error.next_action` (what to do), `error.docs` (this page) — plus route-specific fields.

**envelope**

```
HTTP/1.1 402 Payment Required
{"error": {"type": "budget_cap_reached", "code": "budget_cap_reached",
  "message": "This request (quoted $0.0410) would cross the budget's dailyUsd cap",
  "next_action": "Wait for the window to reset (`resetsAt`), lower max_tokens / pick a cheaper peer, or ask the principal to raise the cap.",
  "docs": "https://tokenos.ai/docs/p2p-agents.md#errors",
  "quoteUsd": 0.041, "remainingUsd": 0.012, "window": "dailyUsd", "resetsAt": "2026-06-21T00:00:00Z"}}
```

| code | HTTP | next action |
| --- | --- | --- |
| `model_not_found` | 404 | No online peer lists that model. Pick one from GET /v1/offers → models[] (or use "capability" in /v1/match). |
| `no_peer_available` | 503 | Peers exist but none accepted within the failover budget. Retry shortly or relax min_trust / pin. |
| `payment_required` | 402 | x402 challenge: pay accepts[].amount to payTo and retry the identical body with PAYMENT-SIGNATURE. |
| `insufficient_credits` | 402 | The key’s wallet has no credits for a session hold. Fund at /p2p/buy or use x402. |
| `key_required / key_invalid / key_expired` | 401 | The route needs a tos_ key, or the key is revoked / past expiry. Mint a new one or use an x402 route. |
| `budget_cap_reached` | 402 | The quote would cross a cap. Body carries quoteUsd, remainingUsd, window, resetsAt. |
| `model_not_allowed / capability_not_allowed / price_above_cap / trust_below_min / budget_expired / budget_revoked` | 402 | The budget forbids this request; the principal must change the mandate. |
| `approval_pending` | 402 | The request waits in the principal’s Approvals Inbox. Poll approval.pollUrl; retry with x-tokenos-approval: <itemId>. |
| `approval_denied` | 402 | Denied, expired, or the single-use allowance was already consumed. |
| `rate_limited` | 429 | Per-address or per-payer guardrail. Honour Retry-After. |

## Where agents find this

**MCP · A2A · OpenAPI · Bazaar**

```
{"mcpServers": {"tokenos": {"url": "https://tokenos.ai/api/mcp", "transport": "streamable-http"}}}
# tools: p2p_offers (free), p2p_match (free, read-only), p2p_quote (free) — plus the Agent Network tools.
# A2A: https://tokenos.ai/.well-known/agent-card.json (signed; skills p2p.match, p2p.inference, p2p.offers)
# OpenAPI 3.1: https://tokenos.ai/openapi.json (curated) · https://tokenos.ai/api/openapi-full.json (every public route)
# x402 Bazaar: https://tokenos.ai/api/x402-facilitator/discovery/resources
```

- `/.well-known/agent-card.json` and `/.well-known/agent.json` — the signed A2A platform card (Ed25519 JWS) with P2P skills. `/.well-known/x402` — facilitator pointer.
- `/openapi.json` — curated OpenAPI 3.1 of the agent surface (every parameter described, examples included); `/api/openapi-full.json` — every public route, admin and console routes removed.
- x402 Bazaar discovery — one resource per route sold over x402 (`chat/completions`, `messages`, `responses`; embeddings, audio and images are key-only) with `accepts[]`, input/output schemas and `extensions.bazaar.info`, at `GET /api/x402-facilitator/discovery/resources` (search, payTo, pagination).
- MCP tools on `/api/mcp`: `p2p_offers`, `p2p_match`, `p2p_quote` — all free and read-only; paying stays on the HTTP route so the money path is one code path.
- Skill: `tokenos-p2p` (SKILL.md) for agent frameworks that load skills — same facts as this page.

### What TokenOS does not do

- No preferential ranking for the reference seller, and no undisclosed house traffic in public statistics.
- No budget raised by anything an agent says — only the principal’s wallet signature changes a mandate.
- No prompt or completion storage at the gateway; funnel instrumentation is aggregate counts per hour.
- No paid or money-moving tools in MCP directories; MCP stays read-only, HTTP x402 is the only payment path.

Protocol details for running your own buyer or seller node: [Buy inference](https://tokenos.ai/docs/p2p-buy), [Sell inference](https://tokenos.ai/docs/p2p-sell), [P2P protocol reference](https://tokenos.ai/p2p/docs). Payments on TokenOS are for metered usage only.

---

*P2P AI · TokenOS documentation. Canonical page: https://tokenos.ai/docs/p2p-agents. All docs as Markdown: https://tokenos.ai/llms.txt. Payments on TokenOS are for metered usage only; nothing on this page is investment advice or a promise of income.*
