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
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.
580 lines
26 KiB
Markdown
580 lines
26 KiB
Markdown
# Vend — Resellable Metered AI SDK + Reserve-Backed Wallet (spec v0.1)
|
||
|
||
> Concrete developer/contract spec for **Vend**: the drop-in, multi-tenant,
|
||
> white-label AI SDK. A founder installs one SDK and gets an OpenAI-compatible
|
||
> gateway, per-end-user metered + marked-up billing, a reserve-backed wallet
|
||
> (top-ups, auto-recharge, dunning), and provider failover.
|
||
>
|
||
> Vend is a **control plane over three things that already ship**: the inference
|
||
> data plane (**Relay**, OpenAI-compatible routing + failover), the wallet/fee
|
||
> ledger (**ReelForge `apps/api` gateway+wallet**, integer-microdollar), and the
|
||
> settlement layer (**Mint** + **AITP-402**). Every successfully-metered call in
|
||
> Vend settles as an AITP-402 `aitp-hold` producing hash-linked Mint receipts.
|
||
>
|
||
> Companion docs: [`docs/apps-vision/vend.md`](../apps-vision/vend.md) (product),
|
||
> [`docs/mint/AITP-402-SPEC.md`](../mint/AITP-402-SPEC.md) (settlement wire spec),
|
||
> [`docs/relay/PLAN.md`](../relay/PLAN.md) (inference plane).
|
||
>
|
||
> **Inherited invariants (non-negotiable):** ADR-0001 integer-microdollar money
|
||
> (never floats; `$` is display-only), ADR-0002 success-only billing (hold on
|
||
> start, capture on success, release on any failure/failover — the end-user never
|
||
> pays for a 500).
|
||
|
||
---
|
||
|
||
## 1. Object model
|
||
|
||
```
|
||
Workspace (the AI-SaaS customer, = Mint org account + treasury)
|
||
│
|
||
├─ Management key vm_live_… → control plane (create apps/keys, set policy, read usage)
|
||
│
|
||
└─ App app_… → one product/environment, owns model allowlist + defaults
|
||
│
|
||
├─ Provisioning key vk_live_… → data plane (per-end-user metered inference calls)
|
||
│ • policy: markup_bps, min_fee_micros, daily spend cap, allowed models, ZDR
|
||
│
|
||
└─ End-user eu_… (or tenant-supplied external id)
|
||
• Wallet = Mint account (reserve-backed AIT balance)
|
||
• funded either end-user-funded (top-up page) or workspace-funded (allowance)
|
||
• per-end-user daily spend cap (midnight-UTC reset)
|
||
```
|
||
|
||
- **Workspace** — the tenant. Maps to a Mint **org** account plus a **treasury**
|
||
account (`type=1 org` / `5 treasury`) where the workspace's margin accrues.
|
||
- **App** — an environment/product under a workspace. Carries the default model
|
||
allowlist, data-logging/ZDR flag, and default markup.
|
||
- **Provisioning key** (`vk_live_…` / `vk_test_…`) — the **data-plane** credential
|
||
the SDK ships with. Scopes every metered call to `workspace → app → end-user`.
|
||
Secret returned **once** at creation, stored server-side as a hash.
|
||
- **Management key** (`vm_live_…`) — the **control-plane** credential. Never
|
||
shipped to clients; used server-side to provision apps/keys, set policy, read
|
||
usage, and register webhooks.
|
||
- **End-user** — the tenant's own user. Has a reserve-backed **wallet** (a Mint
|
||
account). Identified by a tenant-supplied external id resolved to an `eu_…`.
|
||
- **Platform treasury** — Vend's own Mint treasury; receives the platform take.
|
||
|
||
---
|
||
|
||
## 2. Identifiers & money
|
||
|
||
- **Money:** integer **microdollars** everywhere (`amount_micros`, `i64`/`u64`),
|
||
`1 AIT = 1 USD = 1_000_000 µ$`. Wire and storage are integers only. Formatting
|
||
(`$5.04`) is a UI concern (ADR-0001).
|
||
- **Ids:** opaque ULID with a typed prefix.
|
||
|
||
| Prefix | Object | Notes |
|
||
|---|---|---|
|
||
| `ws_` | workspace | = Mint org account |
|
||
| `app_` | app | environment under a workspace |
|
||
| `vk_live_` / `vk_test_` | provisioning key | data-plane secret, shown once, stored hashed |
|
||
| `vm_live_` | management key | control-plane secret, server-side only |
|
||
| `eu_` | end-user | tenant-supplied external id resolves here |
|
||
| `qt_` | quote | price for one call, short-lived |
|
||
| `chg_` | charge | one metered call's lifecycle (quote→hold→capture) |
|
||
| `hold_` | Mint hold | echoes `hold_id` from AITP-402 §4 |
|
||
| `top_` | top-up | wallet funding attempt |
|
||
| `evt_` | webhook event | delivered payload id |
|
||
| `rcpt_` | receipt | hash-linked Mint receipt id |
|
||
|
||
- **Auth (HTTP):** `Authorization: Bearer <vk_live_… | vm_live_…>`. Data-plane
|
||
calls also carry `Vend-End-User: <external id>` to attribute the charge.
|
||
- **Idempotency:** every mutating call accepts `Idempotency-Key: <req_…>`; replays
|
||
return the original result. Metered calls additionally carry an AITP `nonce`
|
||
(single-use) so SDK retries are safe no-ops returning the original receipt.
|
||
|
||
---
|
||
|
||
## 3. The drop-in SDK surface (< 10 lines)
|
||
|
||
Illustrative surface (contract shape, not runnable). Every method maps to an HTTP
|
||
call below; the metered call transparently runs quote → hold → serve → capture.
|
||
|
||
```
|
||
const vend = Vend.init({ apiKey: "vk_live_…", endUser: "user_42" }); // 1 init: key scopes ws→app; endUser attributes spend
|
||
const res = await vend.chat.completions.create({ // 2 metered call (OpenAI-compatible)
|
||
model: "openai/gpt-4o", messages: [{ role: "user", content: "hi" }],
|
||
}); // → quote→hold→failover-routed serve→capture-on-success
|
||
const link = await vend.wallet.topup({ amount_micros: 20_000_000 }); // 3 top-up: returns hosted white-label pay URL
|
||
const wal = await vend.wallet.get(); // 4a wallet read: reserve-backed balance (µ$)
|
||
const use = await vend.usage.list({ since: "2026-08-01" }); // 4b usage read: metered rollup + receipts
|
||
```
|
||
|
||
| SDK method | HTTP | Plane | Settles as |
|
||
|---|---|---|---|
|
||
| `Vend.init({apiKey,endUser})` | — (resolves on first call) | — | — |
|
||
| `vend.chat.completions.create(...)` | `POST /v1/chat/completions` | data | `hold.create`→`hold.capture` |
|
||
| `vend.wallet.topup({amount_micros})` | `POST /v1/wallets/{eu}/topups` | control | `mint` (reserve-gated) |
|
||
| `vend.wallet.get()` | `GET /v1/wallets/{eu}` | control | balance projection |
|
||
| `vend.usage.list({since,until})` | `GET /v1/usage` | control | receipt rollup |
|
||
| `vend.quote(...)` (optional) | `POST /v1/quote` | data | none (price only) |
|
||
|
||
The SDK is thin: it forwards the OpenAI-shaped body verbatim to the data plane,
|
||
attaches key + end-user + idempotency headers, and surfaces the settlement receipt
|
||
id from the response. No provider integration, no billing code on the client.
|
||
|
||
---
|
||
|
||
## 4. Multi-tenant model (workspace → keys → caps + markup)
|
||
|
||
### 4.1 Provisioning a workspace, app, and keys (control plane)
|
||
|
||
```
|
||
POST /v1/workspaces Authorization: Bearer vm_live_… (platform-admin)
|
||
```
|
||
```jsonc
|
||
// request
|
||
{ "name": "AcmeWrite", "treasury_currency": "AIT" }
|
||
// response
|
||
{
|
||
"id": "ws_01J8…",
|
||
"mint_org_account": "acct_01J8…org",
|
||
"mint_treasury_account": "acct_01J8…treas",
|
||
"created": 1723958400000
|
||
}
|
||
```
|
||
|
||
```
|
||
POST /v1/workspaces/ws_01J8…/apps
|
||
```
|
||
```jsonc
|
||
// request
|
||
{
|
||
"name": "prod",
|
||
"allowed_models": ["openai/gpt-4o", "anthropic/claude-3.5", "meta/llama-3.1-70b"],
|
||
"zdr": true, // zero-data-retention: no prompt logging
|
||
"default_markup_bps": 2000 // 20% default markup for keys under this app
|
||
}
|
||
// response
|
||
{ "id": "app_01J8…", "workspace": "ws_01J8…", "zdr": true }
|
||
```
|
||
|
||
```
|
||
POST /v1/workspaces/ws_01J8…/apps/app_01J8…/keys
|
||
```
|
||
```jsonc
|
||
// request — mint a data-plane provisioning key
|
||
{
|
||
"kind": "provisioning", // "provisioning" (vk_) | "management" (vm_)
|
||
"label": "web-client",
|
||
"markup_bps": 2000, // tenant's take-rate on base provider cost
|
||
"min_fee_micros": 100, // floor per call after markup
|
||
"daily_cap_micros": 500000000, // 500 AIT/day across all end-users on this key
|
||
"per_end_user_daily_cap_micros": 5000000, // 5 AIT/day/end-user
|
||
"allowed_models": ["openai/gpt-4o"], // ⊆ app.allowed_models (optional narrowing)
|
||
"funding_mode": "end_user_funded" // "end_user_funded" | "workspace_funded"
|
||
}
|
||
// response — SECRET RETURNED ONCE
|
||
{
|
||
"id": "key_01J8…",
|
||
"kind": "provisioning",
|
||
"secret": "vk_live_9f2c8a…", // shown once; server stores blake3(secret) only
|
||
"markup_bps": 2000,
|
||
"daily_cap_micros": 500000000,
|
||
"per_end_user_daily_cap_micros": 5000000,
|
||
"resets_at": 1724025600000 // next midnight UTC
|
||
}
|
||
```
|
||
|
||
### 4.2 Policy semantics
|
||
|
||
- **`markup_bps`** — basis points added on top of *base provider cost* (the exact
|
||
cost the data plane reports per call). `end_user_price = base_cost + max(base_cost
|
||
× markup_bps / 10_000, min_fee_micros)`. Integer µ$ throughout; rounding is
|
||
round-half-up on the markup term only, never on `base_cost`.
|
||
- **Spend caps** are **rolling daily** windows that **reset at 00:00:00 UTC**.
|
||
Two independent gates, both checked before a hold is created:
|
||
- `daily_cap_micros` — total end-user price captured under the key today.
|
||
- `per_end_user_daily_cap_micros` — per-end-user price captured today.
|
||
Cap consumption is measured on **captured** amount (success-only), so released
|
||
(failed/failover) calls do not consume cap. `resets_at` is always the next
|
||
midnight UTC; at reset the counters zero atomically.
|
||
- **`funding_mode`** —
|
||
- `end_user_funded`: each end-user tops up their own reserve-backed wallet; the
|
||
hold is against the end-user's Mint account balance.
|
||
- `workspace_funded`: the workspace treasury funds a Mint **allowance**
|
||
(`allowance.grant`) per end-user; the hold spends the allowance
|
||
(`allowance.spend`) and the workspace treasury is the payer.
|
||
- **Model allowlist** narrows per app → per key; a call for a model outside the
|
||
effective allowlist is rejected with `model_not_allowed` before any hold.
|
||
- **Revocation:** `POST /v1/keys/key_01J8…/revoke` invalidates the secret hash;
|
||
in-flight holds still resolve, new calls return `key_revoked`.
|
||
- **Isolation invariant (property-tested):** usage, balances, holds, and receipts
|
||
never cross workspaces; each workspace's reserve slice is segregated
|
||
(`Σ balances + Σ holds == reserve` holds **per workspace**, see §7 / vend.md R5).
|
||
|
||
---
|
||
|
||
## 5. Metered-billing API (quote → hold → capture-on-success)
|
||
|
||
Every metered inference call is one **charge** (`chg_…`) with three phases. Phases
|
||
1–3 are internal to the data plane; the SDK sees a single request/response, and the
|
||
settlement receipt id comes back in a header.
|
||
|
||
### 5.1 Quote (price this call)
|
||
|
||
```
|
||
POST /v1/quote Authorization: Bearer vk_live_… Vend-End-User: user_42
|
||
```
|
||
```jsonc
|
||
// request (OpenAI-shaped, plus optional max_tokens for ceiling)
|
||
{ "model": "openai/gpt-4o", "messages": [{ "role": "user", "content": "hi" }], "max_tokens": 512 }
|
||
// response
|
||
{
|
||
"quote_id": "qt_01J8…",
|
||
"resource": "POST /v1/chat/completions#openai/gpt-4o",
|
||
"base_cost_ceiling_micros": 4200, // max provider cost at max_tokens
|
||
"markup_bps": 2000,
|
||
"markup_micros": 840,
|
||
"platform_fee_bps": 50, // Vend take, applied to end-user price
|
||
"end_user_price_ceiling_micros": 5040,
|
||
"hold_ceiling_micros": 5040, // amount to reserve; actual capture ≤ this
|
||
"currency": "AIT",
|
||
"expiry": 1723958430000 // ~30s; quote must be consumed before expiry
|
||
}
|
||
```
|
||
|
||
### 5.2 The metered call (quote+hold+serve+capture in one request)
|
||
|
||
The SDK's `chat.completions.create` posts the OpenAI body directly. The data plane:
|
||
prices it (§5.1), creates the hold on Mint (§6), routes to the best provider with
|
||
failover, and captures the **exact** cost on success.
|
||
|
||
```
|
||
POST /v1/chat/completions Authorization: Bearer vk_live_… Vend-End-User: user_42
|
||
Idempotency-Key: req_7d1e…
|
||
```
|
||
```jsonc
|
||
// request (verbatim OpenAI-compatible)
|
||
{ "model": "openai/gpt-4o", "messages": [{ "role": "user", "content": "hi" }] }
|
||
```
|
||
```jsonc
|
||
// 200 OK — OpenAI-compatible body, plus Vend settlement headers
|
||
// headers:
|
||
// Vend-Charge-Id: chg_01J8…
|
||
// Vend-Receipt-Id: rcpt_01J8… (the hold.capture receipt)
|
||
// AITP-Receipt: rcpt_01J8… (mirrors AITP-402 §5.3 step 4)
|
||
// Vend-Base-Cost-Micros: 4185
|
||
// Vend-Price-Micros: 5022
|
||
// Vend-Provider: openai (route=primary)
|
||
{
|
||
"id": "chatcmpl-…",
|
||
"choices": [ { "message": { "role": "assistant", "content": "Hello!" } } ],
|
||
"usage": { "prompt_tokens": 3, "completion_tokens": 5, "total_tokens": 8 }
|
||
}
|
||
```
|
||
|
||
- **Actual < ceiling:** capture is the *exact* metered cost (`Vend-Price-Micros`);
|
||
the unused remainder of the hold is released automatically (Mint `hold.capture`
|
||
releases `held − captured`).
|
||
- **Streaming:** for SSE responses the charge uses a Mint **stream**
|
||
(`stream.open`→`stream.tick` per token bucket→`stream.close`) against the same
|
||
ceiling; the final captured total is settled on `stream.close`.
|
||
- **Failure / failover:** if all provider routes fail (after `allow_fallbacks`
|
||
reroute), the hold is **released in full** and the response is a normal error
|
||
with `Vend-Price-Micros: 0`. The end-user is charged **nothing** (ADR-0002). A
|
||
transparent failover to a healthy provider emits a `provider.failover` webhook
|
||
but does **not** change the price (still exact final-provider cost).
|
||
|
||
### 5.3 Charge lifecycle (states)
|
||
|
||
| State | Meaning | Mint op |
|
||
|---|---|---|
|
||
| `quoted` | priced, not yet held | — |
|
||
| `held` | funds reserved | `hold.create` |
|
||
| `serving` | request in flight (possibly across failover routes) | — |
|
||
| `captured` | success; exact cost + markup settled | `hold.capture` (+ split transfers) |
|
||
| `released` | failure/failover; nothing charged | `hold.release` |
|
||
| `expired` | quote/hold expired before capture | `hold.release` (auto) |
|
||
|
||
---
|
||
|
||
## 6. Settlement mapping (Mint holds / allowances / receipts / AITP-402)
|
||
|
||
Vend does **not** invent money math — it drives Mint via AITP-402 (see AITP-402
|
||
§4–6). One metered call is one AITP-402 `aitp-hold` exchange.
|
||
|
||
### 6.1 Hold creation
|
||
|
||
`end_user_funded`: Vend acts as the settlement client and creates a hold against
|
||
the end-user's Mint account for the price ceiling.
|
||
|
||
```jsonc
|
||
// Vend → Mint POST /v1/holds (AITP-402 §4: hold.create)
|
||
{
|
||
"from": "acct_01J8…user42", // end-user wallet (reserve-backed)
|
||
"amount_micros": 5040, // hold ceiling from the quote
|
||
"ref": "chg_01J8…", // Vend charge id
|
||
"idempotency_key": "req_7d1e…",
|
||
"nonce": "9f2c…", "expiry": 1723958430000,
|
||
"pubkey_id": "key_…", "op_hash": "…", "sig": "…" // signed per AITP-402 §3
|
||
}
|
||
// ← { "hold_id": "hold_01J8…", "receipt": "rcpt_01J8…hold" }
|
||
```
|
||
|
||
`workspace_funded`: instead of a raw hold, Vend spends the end-user's Mint
|
||
**allowance** granted by the workspace treasury:
|
||
|
||
```jsonc
|
||
// one-time (or on cap change): allowance.grant
|
||
POST /v1/allowances { "to_key": "eu:user_42", "limit_micros": 5000000, "window": "1d", "scope": "app_01J8…" }
|
||
// per call: allowance.spend (auto-creates the hold against treasury)
|
||
POST /v1/allowances/aln_01J8…/spend { "amount_micros": 5040, "ref": "chg_01J8…", "idempotency_key": "req_7d1e…" }
|
||
```
|
||
|
||
### 6.2 Capture + margin split (on success)
|
||
|
||
On success the exact cost is captured, then the price is fanned out double-entry so
|
||
provider cost, platform take, and tenant margin all land as receipts (vend.md §7).
|
||
|
||
```jsonc
|
||
// 1) hold.capture EXACT (releases unused remainder) AITP-402 §4
|
||
POST /v1/holds/hold_01J8…/capture
|
||
{ "amount_micros": 5022, "to": "acct_01J8…vend_settle", "ref": "chg_01J8…" }
|
||
// 2) pay provider its base cost
|
||
POST /v1/transfers { "from": "acct_01J8…vend_settle", "to": "ait1q…openai", "amount_micros": 4185, "memo": "chg_01J8…" }
|
||
// 3) Vend platform take (platform_fee_bps of end-user price = 50 bps of 5022 ≈ 25µ$)
|
||
POST /v1/transfers { "from": "acct_01J8…vend_settle", "to": "acct_01J8…platform_treasury", "amount_micros": 25 }
|
||
// 4) remainder = tenant margin → workspace treasury (5022 − 4185 − 25 = 812µ$)
|
||
POST /v1/transfers { "from": "acct_01J8…vend_settle", "to": "acct_01J8…treas", "amount_micros": 812, "memo": "margin chg_01J8…" }
|
||
```
|
||
|
||
Each op appends a hash-linked receipt (AITP-402 §6). The four receipts for a charge
|
||
share the `ref` `chg_01J8…`, so a workspace's finance can reconcile every captured
|
||
call to provider cost + margin + platform fee, and export a verifiable log via
|
||
`GET /v1/receipts/audit` (merkle root) + `GET /v1/reserve` (solvency proof).
|
||
|
||
### 6.3 Release (on failure / expiry)
|
||
|
||
```jsonc
|
||
POST /v1/holds/hold_01J8…/release { "ref": "chg_01J8…" } // AITP-402 §4: full release, no settlement
|
||
// end-user balance restored to pre-hold value; a `charge.released` receipt is logged with amount 0.
|
||
```
|
||
|
||
### 6.4 AITP-402 pass-through (agent callers)
|
||
|
||
An **agent** end-user can pay per call with no pre-funded Vend wallet by speaking
|
||
AITP-402 directly to the data plane: `POST /v1/chat/completions` with no funded
|
||
end-user returns `402` + `AITP-Challenge` (price = `end_user_price_ceiling_micros`,
|
||
`scheme:"aitp-hold"`); the agent retries with a signed `AITP-Authorization`; Vend
|
||
verifies via Mint and proceeds exactly as §6.1–6.3. This is how each Vend app seeds
|
||
AITP-402 endpoints (vend.md §8).
|
||
|
||
---
|
||
|
||
## 7. Reserve-backed wallet semantics
|
||
|
||
- **Reserve-backed:** every AIT in an end-user wallet is 1:1 reserve-backed via
|
||
Mint (`mint` op is reserve-gated). The conservation invariant
|
||
`Σ balances + Σ active holds == reserve` holds globally **and per workspace**
|
||
(segregated slices; see vend.md R5). A charge only moves value between accounts —
|
||
it never changes reserve.
|
||
- **Balance read:**
|
||
|
||
```
|
||
GET /v1/wallets/user_42 Authorization: Bearer vk_live_… | vm_live_…
|
||
```
|
||
```jsonc
|
||
{
|
||
"end_user": "eu_01J8…",
|
||
"external_id": "user_42",
|
||
"balance_micros": 14980000, // spendable (reserve-backed)
|
||
"held_micros": 5040, // reserved by in-flight charges
|
||
"funding_mode": "end_user_funded",
|
||
"low_balance_threshold_micros": 2000000,
|
||
"auto_recharge": { "enabled": true, "trigger_micros": 2000000, "amount_micros": 20000000 },
|
||
"state": "active" // active | past_due | suspended
|
||
}
|
||
```
|
||
|
||
### 7.1 Top-up (hosted, white-label)
|
||
|
||
```
|
||
POST /v1/wallets/user_42/topups Authorization: Bearer vk_live_…
|
||
```
|
||
```jsonc
|
||
// request
|
||
{ "amount_micros": 20000000, "return_url": "https://acmewrite.com/wallet" }
|
||
// response — hosted, tenant-branded page (Stripe or web3 on-ramp)
|
||
{
|
||
"topup_id": "top_01J8…",
|
||
"checkout_url": "https://pay.vend.sh/t/top_01J8…", // white-label; "powered by Vend" optional
|
||
"amount_micros": 20000000,
|
||
"fee_micros": 60000, // wallet fee schedule (ReelForge wallet/policy.py), versioned
|
||
"credited_micros": 19940000,
|
||
"state": "pending" // pending → succeeded → (mint) | failed
|
||
}
|
||
```
|
||
|
||
- Bounds (min/max top-up) and the fee schedule come straight from the existing
|
||
versioned wallet policy; violations return `top_up_bounds`.
|
||
- On confirmed deposit Vend issues Mint `mint` (reserve-gated) crediting the wallet
|
||
and emits `topup.succeeded`. A failed charge emits `topup.failed` and enters
|
||
dunning if it was an **auto-recharge** (§8).
|
||
|
||
### 7.2 Auto-recharge
|
||
|
||
When `balance_micros − held_micros` drops below `auto_recharge.trigger_micros`,
|
||
Vend attempts an off-session charge for `auto_recharge.amount_micros`. Success →
|
||
`mint` + `wallet.auto_recharge.succeeded`. Failure → `wallet.auto_recharge.failed`
|
||
and the wallet enters the **dunning** flow.
|
||
|
||
---
|
||
|
||
## 8. Dunning flow (retry → backoff → suspend)
|
||
|
||
Dunning governs failed **auto-recharges** (and, for `workspace_funded`, failed
|
||
workspace treasury top-ups). It never charges on failure and never double-charges
|
||
(idempotency-keyed attempts).
|
||
|
||
### 8.1 States & transitions
|
||
|
||
```
|
||
active ──auto-recharge fails──▶ past_due ──retries exhausted──▶ suspended
|
||
▲ │ │
|
||
└────────any successful top-up─────┴───────────reinstate──────────┘
|
||
```
|
||
|
||
- **`active`** — normal; metered calls flow.
|
||
- **`past_due`** — recharge failing; **soft-limit** applied: calls are allowed only
|
||
while spendable balance covers the hold ceiling; new holds that would exceed the
|
||
remaining balance return `wallet_insufficient`. Dunning retries run on a backoff.
|
||
- **`suspended`** — retries exhausted; **hard-limit**: all metered calls return
|
||
`end_user_suspended` (`workspace_suspended` if the workspace treasury is the
|
||
payer). In-flight holds still resolve (capture or release) normally.
|
||
|
||
### 8.2 Retry / backoff schedule (default, configurable per workspace)
|
||
|
||
| Attempt | Delay after previous | Event emitted |
|
||
|---|---|---|
|
||
| 1 | immediate (at threshold trip) | `wallet.auto_recharge.failed`, `dunning.started` |
|
||
| 2 | +24h | `dunning.retry` |
|
||
| 3 | +72h | `dunning.retry` |
|
||
| 4 | +120h | `dunning.retry` |
|
||
| — | after attempt 4 fails | `dunning.exhausted`, `end_user.suspended` |
|
||
|
||
- Any successful manual top-up or recharge at any point clears dunning, moves the
|
||
wallet back to `active`, and emits `end_user.reinstated`.
|
||
- Each attempt carries a distinct idempotency key so a duplicated webhook or retry
|
||
never double-charges. A card that succeeds on the acquirer but whose webhook is
|
||
lost is reconciled by `topup_id`, not re-attempted.
|
||
- Backoff is jittered ±10% to avoid thundering-herd on shared acquirers.
|
||
|
||
---
|
||
|
||
## 9. Webhook events
|
||
|
||
Vend POSTs signed events to the workspace's registered endpoint(s). Registration is
|
||
control-plane (`POST /v1/webhooks` with `vm_live_…`). Delivery is at-least-once with
|
||
its own retry/backoff; consumers must dedupe on `id`.
|
||
|
||
### 9.1 Envelope
|
||
|
||
```jsonc
|
||
// headers:
|
||
// Vend-Signature: t=1723958400,v1=<hmac_sha256(secret, "t.body")>
|
||
// Vend-Event-Id: evt_01J8…
|
||
{
|
||
"id": "evt_01J8…",
|
||
"type": "charge.captured",
|
||
"created": 1723958400123,
|
||
"workspace": "ws_01J8…",
|
||
"app": "app_01J8…",
|
||
"livemode": true,
|
||
"data": { /* type-specific, see below */ }
|
||
}
|
||
```
|
||
|
||
### 9.2 Event types
|
||
|
||
| Event | When | Key `data` fields |
|
||
|---|---|---|
|
||
| `charge.captured` | metered call settled on success | `charge_id`, `end_user`, `base_cost_micros`, `price_micros`, `markup_micros`, `platform_fee_micros`, `receipt_id`, `model`, `provider` |
|
||
| `charge.released` | failure/failover — nothing charged | `charge_id`, `end_user`, `reason`, `receipt_id` |
|
||
| `provider.failover` | reroute happened mid-serve | `charge_id`, `from_provider`, `to_provider`, `reason` |
|
||
| `topup.succeeded` | deposit confirmed → `mint` | `topup_id`, `end_user`, `credited_micros`, `fee_micros`, `receipt_id` |
|
||
| `topup.failed` | deposit failed | `topup_id`, `end_user`, `reason` |
|
||
| `wallet.low_balance` | spendable < threshold | `end_user`, `balance_micros`, `threshold_micros` |
|
||
| `wallet.auto_recharge.succeeded` | off-session recharge cleared | `end_user`, `topup_id`, `credited_micros` |
|
||
| `wallet.auto_recharge.failed` | off-session recharge failed | `end_user`, `topup_id`, `reason`, `next_retry_at` |
|
||
| `dunning.started` | first recharge failure | `end_user`, `attempt`, `next_retry_at` |
|
||
| `dunning.retry` | subsequent attempt | `end_user`, `attempt`, `next_retry_at` |
|
||
| `dunning.exhausted` | retries used up | `end_user`, `attempts` |
|
||
| `end_user.suspended` | hard-limit engaged | `end_user`, `reason` |
|
||
| `end_user.reinstated` | dunning cleared | `end_user` |
|
||
| `spend_cap.reached` | daily cap hit | `key_id`, `end_user?`, `scope`, `resets_at` |
|
||
| `key.created` / `key.revoked` | key lifecycle | `key_id`, `kind` |
|
||
| `receipt.created` | any Mint receipt for this workspace | `receipt_id`, `op`, `amount_micros`, `ref` |
|
||
|
||
### 9.3 Delivery guarantees
|
||
|
||
- **Signature:** HMAC-SHA256 over `"{t}.{raw_body}"`; reject if `|now − t| > 5min`.
|
||
- **Retries:** on non-2xx, redeliver at 1m, 5m, 30m, 2h, 6h (max 5), then mark the
|
||
event `undelivered` (fetchable via `GET /v1/events?status=undelivered`).
|
||
- **Ordering:** not guaranteed; consumers reconcile by `created` + object id.
|
||
|
||
---
|
||
|
||
## 10. Errors (stable codes)
|
||
|
||
Vend surfaces its own gate errors plus Mint/AITP-402 codes (AITP-402 §7) verbatim
|
||
for settlement failures.
|
||
|
||
**Vend gates:** `key_revoked` · `key_invalid` · `end_user_suspended` ·
|
||
`workspace_suspended` · `spend_cap_exceeded` · `per_end_user_cap_exceeded` ·
|
||
`model_not_allowed` · `wallet_insufficient` · `quote_expired` · `markup_invalid` ·
|
||
`top_up_bounds` · `provider_unavailable` (all routes failed after failover).
|
||
|
||
**Passed through from Mint/AITP-402:** `insufficient_funds` · `allowance_exceeded` ·
|
||
`hold_not_found` · `capture_exceeds_hold` · `nonce_replayed` ·
|
||
`authorization_expired` · `signature_invalid` · `account_frozen` ·
|
||
`reserve_insufficient` · `idempotency_conflict`.
|
||
|
||
**HTTP mapping:** `401` (bad/revoked key), `402` (AITP challenge / wallet
|
||
insufficient for an agent caller), `403` (`end_user_suspended`,
|
||
`model_not_allowed`), `409` (idempotency/replay), `422` (invalid signature/expiry),
|
||
`429` (`spend_cap_exceeded`, velocity), `503` (`provider_unavailable`). Error body:
|
||
|
||
```jsonc
|
||
{ "error": { "code": "spend_cap_exceeded", "message": "per-end-user daily cap reached",
|
||
"scope": "per_end_user", "resets_at": 1724025600000, "charge_id": "chg_01J8…" } }
|
||
```
|
||
|
||
Error responses that occur **before or at** hold time never charge; a
|
||
`provider_unavailable` after a hold **always** releases the hold (ADR-0002).
|
||
|
||
---
|
||
|
||
## 11. Idempotency, concurrency & correctness
|
||
|
||
- **Idempotency:** `Idempotency-Key` on every mutating call; the metered path also
|
||
binds an AITP `nonce` (single-use until `expiry`). A retried call returns the
|
||
original charge + receipt, never a second hold.
|
||
- **Success-only (ADR-0002):** the only path that captures is `serving → captured`;
|
||
every other terminal path releases the hold in full. Property tests inject
|
||
provider failures at each step and assert `captured == 0`.
|
||
- **Conservation (per workspace):** `Σ balances + Σ active holds == reserve` for
|
||
each workspace's segregated slice; cross-workspace value movement is impossible by
|
||
construction (settlement account fan-out only targets that workspace's provider +
|
||
treasury + the platform treasury).
|
||
- **Cap accounting:** caps consume on **capture**, are keyed to the UTC day, and
|
||
reset atomically at `resets_at`. Concurrent calls near a cap are serialized so the
|
||
cap can never be overshot (a would-be overshoot returns `spend_cap_exceeded`
|
||
before its hold is created).
|
||
- **Integer money:** all arithmetic in µ$; the only rounding is the markup term
|
||
(round-half-up), applied once, never to base cost or captured amount.
|
||
|
||
---
|
||
|
||
## 12. Versioning
|
||
|
||
- **HTTP:** `Vend-Version: 0.1` header negotiates; `v0.1` is pre-GA. Additive fields
|
||
only within a minor; breaking changes bump the major and are dual-served during
|
||
migration (mirrors AITP-402 §9).
|
||
- **Settlement:** Vend pins an `AITP-Version` per call; a workspace is never
|
||
silently upgraded across an AITP major.
|
||
- **Policy versioning:** markup and top-up fee schedules are versioned (the existing
|
||
wallet `policy.py` fee-schedule versioning); a charge records the policy version
|
||
it settled under, so historical receipts remain reproducible.
|
||
```
|