videogen/docs/mint/AITP-402-SPEC.md
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

202 lines
7.7 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# AITP-402 — AI Token Payment Protocol (spec v0.1)
> Concrete wire spec for the **AI Token (AIT)** and its payment protocol.
> Companion to `docs/mint/PLAN.md`. This is the contract `mint-core`,
> `mint-ledger`, `mint-receipts`, and `mint-protocol` implement, and the surface
> Relay / ReelForge / agents integrate against.
>
> **AITP is x402-shaped but settles in AIT (a fiat-backed internal credit), not
> crypto.** No chain, no gas. Central verifier, tamper-evident log.
---
## 1. The AI Token (AIT)
- **Unit:** `AIT`. **1 AIT = 1 USD of prepaid credit.**
- **Representation on the wire and in storage:** integer **microdollars**
(`amount_micros`, `i64`/`u64`), `1 AIT = 1_000_000 µ$`. **Never floats.**
Display formatting (`$22.99`) is a UI concern only.
- **Backing:** every AIT outstanding is 1:1 reserve-backed (Stripe fiat +
crypto on-ramp). Supply == reserve is an enforced invariant, not a claim.
- **Not a security / not a cryptocurrency:** closed-loop, redeemable 1:1,
non-tradeable on public markets.
---
## 2. Accounts & addresses
- **AccountId:** opaque ULID (`acct_01J…`). Owner = user | org | agent |
provider | model | treasury.
- **Address:** a shareable receive handle, bech32-style string:
`ait1<type><data><checksum>` (e.g. `ait1qxy…`). Derived from an account's
ed25519 public key; an account may hold several (rotation, per-purpose).
- `type` nibble: `0=user 1=org 2=agent 3=provider 4=model 5=treasury`.
- Address is **display/routing only** — authorization is by signature, not by
holding the address.
- **Keypair:** ed25519. The account's signing key authorizes debits from it.
Custodial (platform-held, HSM/KMS) by default; self-custody (client-held key)
optional for agents/enterprises.
---
## 3. Canonical serialization & signing
- **Canonical form:** deterministic JSON (sorted keys, no insignificant
whitespace, integers only for amounts) → bytes.
- **Digest:** `blake3(canonical_bytes)` → 32-byte `op_hash`.
- **Signature:** `ed25519_sign(signing_key, op_hash)` → `sig` (base64url).
- **Verify:** server recomputes `op_hash`, checks `sig` against the source
account's registered public key, checks `nonce`/`expiry`, then applies.
Every state-changing operation carries: `op_hash`, `sig`, `pubkey_id`,
`nonce` (per-account monotonic or random-with-window), `expiry` (unix ms),
and `idempotency_key`.
---
## 4. Operation types (the ledger verbs)
All are double-entry; all emit a **Receipt** (§6). Amounts in `amount_micros`.
| Op | Body (core fields) | Effect |
|---|---|---|
| `transfer` | `from`, `to`, `amount`, `memo?` | atomic debit `from` / credit `to` |
| `hold.create` | `from`, `amount`, `ref` | reserve `amount` from `from` (spendable balance drops) |
| `hold.capture` | `hold_id`, `amount≤held`, `to` | capture (settle) up to held amount to `to`; release remainder |
| `hold.release` | `hold_id` | release full hold, no settlement (**failure path**) |
| `stream.open` | `from`, `to`, `rate`, `cap`, `unit` | open a metered channel (per-token/second), reserve `cap` |
| `stream.tick` | `stream_id`, `units`, `seq` | settle `units × rate`, monotonically |
| `stream.close` | `stream_id` | settle final, release unused reservation |
| `allowance.grant` | `to_key`, `limit`, `window`, `scope?` | delegated spend budget |
| `allowance.spend` | `allowance_id`, `amount`, `ref` | spend within budget (auto-transfer/hold) |
| `mint` | `to`, `amount`, `reserve_ref` | create AIT against confirmed deposit (**reserve-gated**) |
| `redeem` | `from`, `amount`, `payout_ref` | burn AIT → fiat/crypto payout (**KYC/limits**) |
**Invariants enforced at apply time:** non-negative balances; `capture ≤ held`;
`stream.tick` seq strictly increasing; `mint`/`redeem` adjust reserve so
`Σ balances + Σ active holds == reserve` always holds.
---
## 5. AITP-402 — machine payment handshake
Lets an agent pay **per request** with no pre-funded session. HTTP-native.
### 5.1 Challenge (server → caller)
A protected endpoint (e.g. a Relay model, a paid tool) replies:
```
HTTP/1.1 402 Payment Required
AITP-Version: 0.1
AITP-Challenge: <base64url(challenge)>
```
```jsonc
// challenge (decoded)
{
"payee": "ait1q…provider", // receive address
"amount_micros": 4200, // price for this request
"currency": "AIT",
"resource": "POST /v1/chat/completions#llama-3.1-70b",
"nonce": "9f2c…", // single-use
"expiry": 1723958400000, // unix ms
"scheme": "aitp-hold" | "aitp-transfer"
}
```
- `aitp-transfer`: pay-now, exact price known.
- `aitp-hold`: reserve up to `amount_micros`, capture actual usage after
(metered inference) — this is success-only for agents.
### 5.2 Authorization (caller → server)
Caller retries with a signed intent:
```
POST /v1/chat/completions
AITP-Version: 0.1
AITP-Authorization: <base64url(authorization)>
```
```jsonc
// authorization (decoded)
{
"payer": "acct_01J…", // paying account
"payee": "ait1q…provider",
"amount_micros": 4200,
"nonce": "9f2c…", // echoes challenge nonce
"resource": "…",
"expiry": 1723958400000,
"idempotency_key": "req_…",
"pubkey_id": "key_…",
"op_hash": "…", // blake3 of canonical intent
"sig": "…" // ed25519(op_hash)
}
```
### 5.3 Verify + settle (server-side)
1. Decode; check `nonce` unused, `expiry` in future, `resource` matches.
2. `POST /v1/aitp/verify` → `mint-protocol`: verify `sig` vs `payer` key;
check balance/allowance; **create hold** (`aitp-hold`) or **transfer**
(`aitp-transfer`).
3. Serve the request. On completion:
- success → `hold.capture` actual usage (or transfer already final);
- failure → `hold.release` (agent pays nothing — **ADR-0002**).
4. Return the settlement `Receipt` id in `AITP-Receipt` response header.
### 5.4 Replay & idempotency
`nonce` is single-use (stored until `expiry`); `idempotency_key` makes retries
no-ops returning the original receipt. Expired authorizations are rejected.
---
## 6. Receipts — verifiable, hash-linked
Every applied op appends one receipt to the account's tamper-evident log:
```jsonc
{
"seq": 10432,
"op": "hold.capture",
"op_hash": "…",
"amount_micros": 4200,
"from": "acct_…", "to": "ait1q…",
"balance_after_micros": 1840000,
"ts": 1723958399123,
"prev_hash": "…", // hash of receipt seq-1
"hash": "blake3(this ⊕ prev_hash)",
"signer": "mint-verifier-key-1",
"sig": "…" // server signature over hash
}
```
- **Chain rule:** `receipt[n].prev_hash == receipt[n-1].hash`. Any edit breaks
the chain.
- **Audit:** `GET /v1/receipts/audit` returns a periodic **merkle root** over
the global log; `GET /v1/reserve` returns supply-vs-backing proof.
- Clients can independently verify their full history offline.
---
## 7. Errors (stable codes)
`insufficient_funds` · `allowance_exceeded` · `hold_not_found` ·
`capture_exceeds_hold` · `nonce_replayed` · `authorization_expired` ·
`signature_invalid` · `account_frozen` · `reserve_insufficient` (mint) ·
`kyc_required` / `payout_limit` (redeem) · `idempotency_conflict`.
HTTP: `402` (payment required), `409` (idempotency/replay), `422`
(invalid signature/expiry), `429` (velocity).
---
## 8. Concurrency & correctness
- Per-account **serialized apply** (ordered by `seq`), so balance projections are
linearizable; cross-account transfers use a 2-account lock ordering by AccountId.
- Ledger is **append-only**; balances are cached projections rebuildable from the
log.
- Property tests (in `mint-testkit`): random op storms preserve conservation +
double-entry + non-negativity + chain integrity.
---
## 9. Versioning
`AITP-Version` header negotiates; `v0.1` is pre-GA. Additive fields only within a
minor; breaking changes bump the major and are dual-served during migration.