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.
43 KiB
apps/vend — Implementation plan (deep)
Fourth Vend artifact. The ideation/strategy doc is
docs/apps-vision/vend.md; this is the build-grade detail: the control-plane Postgres schema, per-phase task lists (Vx0→Vx5) with hard gates, exact call points into Relay (inference + provider manifests) and Mint (holds/capture/allowances/receipts), reserve & dunning reconciliation, take-rate economics in exact µ$, the multi-tenant threat model, reseller-of-record compliance, observability/SLOs, and the conformance suite.Status: planning only. No code. Vend is ~80% assembly over three shipping systems — Relay (inference plane), Mint/AITP-402 (settlement plane), and the ReelForge
gateway+walletdomains (control-plane lineage). The net-new surface is the tenant/reseller layer, dunning, per-tenant reserve segregation, and the drop-in SDK — everything else is wiring. Shared invariants inherited and never re-litigated here: ADR-0001 integer-microdollar money, ADR-0002 success-only billing.
0. Plane boundaries (what owns which schema)
Vend spans three datastores; this doc's DDL is only the Vend control plane.
It never duplicates money that Mint owns — it stores tenancy, policy, dunning,
and cached projections, and holds pointers (Mint account_id, Relay
generation_id, Stripe ids) across the seam.
| Plane | Owner | Source of truth | Vend adds |
|---|---|---|---|
| Inference | Relay (Rust) | provider cost via Cost API GET /generation?id= |
per-tenant white-label routing, tenant→app→end-user key scoping, ZDR/model allowlist |
| Settlement | Mint (Rust) | the append-only journal; Σ balances + Σ holds == reserve |
per-tenant reserve segregation view, tenant treasury accounts, platform-fee transfers |
| Control | Vend (Python, apps/api lineage) |
tenancy + policy + dunning; projections of Mint balances | this whole schema |
Money invariant across the seam: Vend never mutates a balance. Every value
move is a Mint op; Vend rows referencing money carry a journal_seq /
receipt_id back-pointer and are reconciled against Mint (§4, §8). Vend's $
is display-only; all stored amounts are BIGINT µ$ (1 AIT = 1_000_000 µ$).
1. Postgres schema (Vend control plane)
Neon/Postgres. Policy and tenancy tables are mutable + versioned; usage,
reserve-mirror, dunning-event, and webhook tables are append-only (corrections
are compensating rows, never UPDATE/DELETE). Every tenant-owned row carries
tenant_id for row-level isolation (§6).
-- ============================================================================
-- Tenancy: tenant → app → end-user, plus Mint account mapping
-- ============================================================================
create table tenants (
id text primary key, -- ten_01J… (ULID)
slug text unique not null, -- url-safe, white-label subdomain
display_name text not null,
status smallint not null default 0, -- 0 active 1 suspended 2 closed
kyc_tier smallint not null default 0, -- 0 T0 1 T1 2 T2 (see §7)
ror_mode smallint not null default 0, -- reseller-of-record: 0 vend-is-RoR 1 tenant-is-RoR
treasury_acct text not null, -- Mint acct_… kind=5 treasury (tenant margin lands here)
platform_fee_bps int not null default 500, -- Vend's take on this tenant's margin (bps); 500 = 5%
created_at timestamptz not null default now(),
suspended_at timestamptz
);
create table apps (
id text primary key, -- app_01J…
tenant_id text not null references tenants(id),
name text not null,
status smallint not null default 0, -- 0 active 1 disabled
model_allowlist jsonb not null default '[]', -- [] = all; else ["author/slug", …]
zdr boolean not null default false, -- zero-data-retention flag → Relay data_collection=deny
created_at timestamptz not null default now(),
unique (tenant_id, name)
);
create table end_users (
id text primary key, -- eu_01J…
tenant_id text not null references tenants(id),
app_id text not null references apps(id),
external_ref text not null, -- tenant's own user id (opaque to Vend)
mint_account text not null, -- Mint acct_… kind=0 user (holds the AIT balance)
status smallint not null default 0, -- 0 active 1 frozen (dunning soft-limit) 2 closed
created_at timestamptz not null default now(),
unique (tenant_id, app_id, external_ref)
);
create index end_users_tenant on end_users (tenant_id, app_id);
-- ============================================================================
-- Sub-keys: scoped tenant→app→end-user. Secret shown once, only hash stored.
-- (ReelForge gateway.provisioning.ProvisioningKey, multi-tenanted.)
-- ============================================================================
create table sub_keys (
id text primary key, -- key_01J…
tenant_id text not null references tenants(id),
app_id text not null references apps(id),
end_user_id text references end_users(id), -- null = app-level (server) key
scope smallint not null, -- 0 tenant-mgmt 1 app 2 end-user
secret_hash bytea not null, -- argon2id(secret); secret returned once at mint
prefix text not null, -- vnd_live_ab12… (lookup shard, non-secret)
daily_cap_micros bigint, -- per-key UTC-day spend cap; null = inherit app policy
rate_limit_rpm int, -- null = inherit
status smallint not null default 0, -- 0 active 1 revoked
created_at timestamptz not null default now(),
revoked_at timestamptz
);
create unique index sub_keys_prefix on sub_keys (prefix);
create index sub_keys_lookup on sub_keys (tenant_id, app_id, status);
-- ============================================================================
-- Markup policy: per (tenant, app), versioned. Never edit a live row — supersede.
-- (ReelForge gateway.provisioning.MarkupPolicy, per-tenant + versioned.)
-- ============================================================================
create table markup_policy (
id text primary key, -- mkp_01J…
tenant_id text not null references tenants(id),
app_id text not null references apps(id),
version int not null, -- monotonic per (tenant,app)
markup_bps int not null, -- tenant's markup over provider cost (bps)
min_fee_micros bigint not null default 0, -- floor charged even on tiny calls
byok_fee_bps int not null default 0, -- fee when end-user brings own upstream key
effective_at timestamptz not null default now(),
superseded_at timestamptz, -- null = current
created_at timestamptz not null default now(),
unique (tenant_id, app_id, version)
);
create unique index markup_policy_current
on markup_policy (tenant_id, app_id) where superseded_at is null;
-- Platform fee schedule (Vend's own take), versioned, mirrors wallet/policy.py.
create table platform_fee_schedule (
version int primary key,
default_fee_bps int not null, -- default platform_fee_bps for new tenants
min_fee_micros bigint not null default 0,
max_fee_micros bigint, -- cap per call; null = uncapped
topup_fee_bps int not null default 0, -- fee on end-user top-ups (hosted page)
topup_min_micros bigint not null, -- top-up bounds (TopUpError guards)
topup_max_micros bigint not null,
effective_at timestamptz not null default now(),
superseded_at timestamptz
);
-- ============================================================================
-- Metered usage: append-only, one row per settled inference call. Truth for
-- rollups & invoices; money truth is Mint's receipt (receipt_id back-pointer).
-- ============================================================================
create table metered_usage (
id text primary key, -- use_01J…
tenant_id text not null references tenants(id),
app_id text not null references apps(id),
end_user_id text references end_users(id),
sub_key_id text not null references sub_keys(id),
relay_generation_id text not null, -- Relay Cost API id (dedup anchor)
model text not null, -- author/slug:variant actually served
provider text not null, -- endpoint that served (after failover)
prompt_tokens int not null default 0,
completion_tokens int not null default 0,
provider_cost_micros bigint not null, -- exact base cost from Relay Cost API
markup_micros bigint not null, -- tenant margin component
platform_fee_micros bigint not null, -- Vend take component
charge_micros bigint not null, -- end-user paid (= provider_cost + markup)
markup_policy_id text not null references markup_policy(id),
hold_id text not null, -- Mint hold id (aitp-hold)
capture_receipt_id text, -- Mint receipt id on capture (null until settled)
outcome smallint not null, -- 0 captured(success) 1 released(failure) 2 pending
utc_day date not null, -- for daily-cap rollups & partition pruning
created_at timestamptz not null default now()
);
create unique index metered_usage_gen on metered_usage (relay_generation_id); -- idempotent
create index metered_usage_rollup on metered_usage (tenant_id, app_id, utc_day);
create index metered_usage_key_day on metered_usage (sub_key_id, utc_day); -- daily-cap sum
-- ============================================================================
-- Tenant reserve: per-tenant SEGREGATION mirror of Mint reserve. R5 requires
-- one tenant can never drain another's backing. This is a projection of Mint's
-- reserve_ledger filtered to accounts owned by the tenant — reconciled continuously.
-- ============================================================================
create table tenant_reserve (
tenant_id text primary key references tenants(id),
outstanding_ait_micros bigint not null default 0, -- Σ end-user balances + Σ open holds for this tenant
backing_micros bigint not null default 0, -- confirmed deposits attributed to this tenant
last_mint_journal_seq bigint not null default 0,
updated_at timestamptz not null default now()
-- invariant (checked continuously, §4/§8): backing_micros >= outstanding_ait_micros
);
-- Append-only mirror of reserve movements per tenant (deposit|payout|chargeback|adjust).
create table tenant_reserve_ledger (
seq bigserial primary key,
tenant_id text not null references tenants(id),
kind text not null, -- deposit|payout|chargeback|clawback|adjust
amount_micros bigint not null, -- signed
source text, -- stripe:pi_…|mint:journal_seq
mint_journal_seq bigint,
ts timestamptz not null default now()
);
create index tenant_reserve_ledger_ten on tenant_reserve_ledger (tenant_id, seq);
-- ============================================================================
-- Deposits & top-ups (hosted white-label page) — Stripe/Web3 → Mint mint op.
-- ============================================================================
create table deposits (
id text primary key, -- dep_01J…
tenant_id text not null references tenants(id),
end_user_id text not null references end_users(id),
source text not null, -- stripe|web3
external_ref text unique not null, -- stripe pi_… / tx hash — idempotency anchor
gross_micros bigint not null, -- amount charged to the card
fee_micros bigint not null, -- top-up fee (platform_fee_schedule.topup_fee_bps)
net_micros bigint not null, -- credited to end-user AIT balance
mint_op_seq bigint, -- Mint `mint` journal seq (set on confirm)
status smallint not null, -- 0 pending 1 confirmed 2 failed 3 refunded 4 charged_back
created_at timestamptz not null default now(),
confirmed_at timestamptz
);
create index deposits_user on deposits (tenant_id, end_user_id, status);
-- Auto top-up config per end-user (threshold recharge; ordered payment methods).
create table autotopup (
end_user_id text primary key references end_users(id),
threshold_micros bigint not null, -- recharge when available < threshold
amount_micros bigint not null, -- top-up size
method_order jsonb not null default '[]', -- ["pm_1…","pm_2…"] tried in order on failure
enabled boolean not null default true,
updated_at timestamptz not null default now()
);
-- ============================================================================
-- Dunning: state machine over a failed recharge / negative balance. Append-only
-- attempts; one open case per (end_user, trigger). Never double-charges (§4).
-- ============================================================================
create table dunning_cases (
id text primary key, -- dun_01J…
tenant_id text not null references tenants(id),
end_user_id text not null references end_users(id),
trigger smallint not null, -- 0 autotopup_failed 1 negative_balance 2 chargeback
state smallint not null, -- 0 open 1 retrying 2 soft_limited 3 suspended 4 recovered 5 written_off
owed_micros bigint not null default 0, -- for negative_balance/chargeback clawback
next_retry_at timestamptz,
attempt_count int not null default 0,
opened_at timestamptz not null default now(),
closed_at timestamptz,
unique (end_user_id, trigger) where closed_at is null -- one open case per trigger
);
create index dunning_due on dunning_cases (state, next_retry_at) where closed_at is null;
create table dunning_attempts ( -- append-only
id text primary key,
case_id text not null references dunning_cases(id),
attempt_no int not null,
method text, -- stripe pm_…
stripe_ref text, -- pi_… / charge id
result smallint not null, -- 0 pending 1 succeeded 2 failed_retryable 3 failed_hard
failure_code text, -- card_declined|insufficient_funds|…
ts timestamptz not null default now()
);
-- ============================================================================
-- Webhook & idempotency plumbing (Stripe events, SDK retries)
-- ============================================================================
create table webhook_events ( -- append-only, idempotent on provider event id
id text primary key, -- provider event id (evt_…)
source text not null, -- stripe|web3
kind text not null, -- payment_intent.succeeded|charge.refunded|…
payload_hash bytea not null,
processed_at timestamptz,
received_at timestamptz not null default now()
);
create table idempotency_keys (
scope text not null, -- 'sub_key_mint'|'deposit'|'usage'…
idem_key text not null,
response_hash bytea not null, -- 409 idempotency_conflict on same key + different body
created_at timestamptz not null default now(),
primary key (scope, idem_key)
);
-- ============================================================================
-- Audit (append-only, every control-plane mutation)
-- ============================================================================
create table audit_log (
seq bigserial primary key,
tenant_id text,
actor text not null, -- key_… | admin | system
action text not null,
target text,
meta jsonb,
ts timestamptz not null default now()
);
Append-only guarantee: metered_usage, tenant_reserve_ledger,
dunning_attempts, webhook_events, audit_log carry no UPDATE/DELETE
grant for the app role. balances are never stored in Vend at all — they are
read from Mint and cached only in tenant_reserve as a reconciled projection.
2. Per-phase task breakdown (Vx0 → Vx5)
Each phase is its own recon→design→build→review→fix workflow, TDD, gate is a hard go/no-go. Money paths reuse ADR-0001/0002, so gates focus on tenancy isolation and settlement wiring, not money math. (These six phases refine vend.md §11's Sx0→Sx4 into a build sequence.)
Vx0 — Multi-tenant spike (internal).
Introduce the tenants/apps/end_users/sub_keys/markup_policy schema over the
ReelForge gateway+wallet lineage. Scope every provisioning key
tenant→app→end-user; make MarkupPolicy + daily cap per (tenant, app);
add tenant_id to every query path and a row-level-isolation guard.
- Tasks: schema migration; sub-key mint (secret once, argon2id hash, prefix
shard); per-key
check_spend/remainingagainstmetered_usagedaily sum; per-tenant markup resolution (current-version row); mock-charge path (no real provider, no real Mint). - Gate: two isolated tenants mint keys, meter a mock charge with distinct
markup_bps, and their usage/balances/keys never cross. Cross-tenant isolation property test green (a query for tenant A can never read tenant B rows).
Vx1 — One real metered request through all three planes.
Wire the data plane (Relay endpoint) → AITP-402 aitp-hold → Mint hold.create
→ serve → hold.capture on success / hold.release on failure → receipt.
One real provider.
- Tasks: Relay call point (§3.1); Mint client wiring (§3.2); price-the-call →
402 challenge; capture at exact Cost-API cost + tenant markup; write
metered_usagewithhold_id/capture_receipt_id; forced-failure path. - Gate: a live
chat/completionscall is priced, held, served, captured at exact provider cost + tenant markup, and produces a valid hash-linked Mint receipt; a forced provider failure (all endpoints 500) bills the end-user nothing —outcome=released, nocharge_microsdebited (ADR-0002 verified end-to-end).
Vx2 — Hosted top-up page + Stripe + dunning.
White-label top-up page → Mint mint (reserve-gated) on confirmed Stripe
deposit; auto-top-up threshold; dunning state machine (retry failed cards,
notify, soft-limit, suspend).
- Tasks:
deposits+ Stripe webhook (idempotent onexternal_ref);mintop wiring (§4);autotopupthreshold check post-capture; dunning FSM (dunning_cases/dunning_attempts) with backoff schedule; per-tenant reserve segregation writes totenant_reserve+tenant_reserve_ledger. - Gate: an end-user tops up under a tenant's brand; balance updates µ$-exact;
Σ end-user balances + Σ open holds == tenant backingholds for that tenant; a failed recharge runs the full dunning sequence (retry→soft-limit→suspend) without double-charging and without charging-on-failure; a Stripecharge.refundedproduces a clean clawback (§4) with no negative-reserve.
Vx3 — SDK + self-serve onboarding + failover/routing.
Ship the thin multi-language SDK (drop-in OpenAI-compatible client that carries
the Vend key + AITP handshake transparently); self-serve tenant signup; provider
routing with allow_fallbacks/sort; per-tenant model allowlist + ZDR flags.
- Tasks: SDK transport (AITP challenge→authorize interceptor, idempotency-key
retries); signup → tenant + treasury acct + first app + key; provider-manifest
passthrough (§3.1) with
order/allow_fallbacks/sort;model_allowlist+zdrenforcement at the edge. - Gate: a brand-new developer goes from signup to a metered, marked-up, successfully-billed request in under one afternoon with zero manual setup; provider failover reroutes transparently (kill a provider mid-stream) with no erroneous charge and ≤1 dropped token.
Vx4 — Platform take + reserve segregation proof + solvency export.
Turn on the platform take-rate transfer on every capture; expose per-tenant
receipts export + GET /reserve solvency report scoped per tenant; harden
per-tenant reserve segregation.
- Tasks: platform-fee
transfer(margin→tenant treasury, platform slice→platform treasury, §5); receipts export proxy (MintGET /v1/receipts/auditfiltered to tenant accounts) + tenant reserve proof (GET /v1/reservesegregated view); continuous reserve-segregation reconciler. - Gate: platform take accrues to the platform treasury as auditable Mint
ledger entries (not a spreadsheet); each tenant exports a verifiable receipt
log + reserve proof that reconciles to the µ$; the cross-tenant reserve-drain
property test is green (a spend/chargeback storm in tenant A never reduces
tenant B's
backing_micros).
Vx5 — Design-partner GA + hardening. Onboard the first paying design partners; suspend/clawback path; conformance suite; OTel dashboards; SLOs; blue-green; load/chaos.
- Tasks: suspend/clawback (§4) on hard dunning failure; sanctions screening on payout/redeem addresses (§7); conformance vectors (§9); solvency status page; chaos matrix (kill mid-capture, mid-mint, mid-dunning; partition Mint).
- Gate: ≥3 paying tenants live; at least one design partner has deleted their old proxy; SLOs green (§8); chaos suite yields zero conservation / isolation / success-only violations; conformance vectors pass in all SDK langs.
3. Integration wiring — exact call points
Vend is glue between two remote services. This section names the exact call sites: what Vend sends, what it stores, and the ordering that keeps ADR-0002 true (hold before serve; capture only on success; release on any failure).
3.1 Relay (inference + provider manifests)
The Vend data plane is Relay, white-labeled and multi-tenanted. Vend does not re-implement inference — it decorates the Relay request with tenant policy and reads back the exact cost.
Call point A — resolve + route (per request):
- Vend resolves
sub_key→(tenant, app, end_user); loads currentmarkup_policyand appmodel_allowlist/zdr. - Vend forwards to Relay
POST /api/v1/chat/completions(also/completions,/embeddings), injecting the Relayproviderobject from app policy:order,allow_fallbacks=true,sort(price/latency/throughput),data_collection = zdr ? "deny" : "allow",ignore/quantizationsas configured. Model suffixes (:nitro/:floor) pass through. This is where the provider manifest does failover — Vend supplies policy; Relay executes the fan-out/hedge and never charges the end-user for a failed endpoint (Relay itself is ADR-0002). - BYOK: if the app/end-user registered an upstream key, Vend forwards it and
flags the call BYOK so §5's
byok_fee_bpsbranch applies.
Call point B — exact cost readback (post-response):
- After the response (or stream close) Vend calls Relay Cost API
GET /generation?id=<relay_generation_id>to get exactprovider_cost_micros, token counts, and the endpoint actually served (after any failover). This is the authoritative base cost fed into §5 and stored inmetered_usage. Therelay_generation_idis the dedup anchor (metered_usage_genunique index) — a Relay retry with the same id never double-bills. - Streaming: Vend maps Relay SSE to Mint
stream.tick(§3.2) when the tenant opts into per-token metering; otherwise it holdsamount_microsup-front and captures once at stream close using the final Cost-API figure.
Ordering guarantee: Vend issues the Mint hold.create (call point 3.2-①)
before dispatching to Relay. If Relay returns success → capture; if Relay
exhausts fallbacks / errors → release. Relay never sees money; Vend never serves
without a live hold.
3.2 Mint (holds / capture / allowances / receipts) — AITP-402
Every metered charge is an AITP-402 aitp-hold op. Exact call sequence per
request (maps to AITP-402-SPEC §5):
- Price + challenge. Vend prices the call (an estimate ceiling for the hold),
emits the AITP
402challenge to the SDK:{payee: tenant_provider_addr, amount_micros: <ceiling>, resource, nonce, expiry, scheme:"aitp-hold"}. - Authorize + verify. SDK retries with
AITP-Authorization(signed intent). Vend calls MintPOST /v1/aitp/verify→ verifiessigvs the end-user'spayerkey, checksnonceunused +expiryfuture, checks balance/allowance. hold.create{from: end_user.mint_account, amount: ceiling, ref: request_id}→ returnshold_id. Vend writesmetered_usagerowoutcome=pending, hold_id=…. Now dispatch to Relay (§3.1).- On success →
hold.capture{hold_id, amount: charge_micros, to: <split, §5>}.charge_micros = provider_cost + markup ≤ held ceiling; Mint releases the remainder automatically. Storecapture_receipt_id, setoutcome=captured. - On failure/failover-exhausted →
hold.release{hold_id}— end-user pays nothing; setoutcome=released. (ADR-0002.) - Receipt. Mint returns the settlement receipt id in the
AITP-Receiptheader; Vend stores it and surfaces it in the tenant's exportable log.
Allowances (per-seat budgets). A tenant granting each end-user a delegated
budget maps to Mint allowance.grant {to_key: sub_key, limit, window, scope};
each metered call that draws on a seat budget is an allowance.spend
{allowance_id, amount: charge_micros, ref} instead of a raw hold, so per-seat
metering is native. Velocity/rate limits ride the sub-key rate_limit_rpm.
Top-ups → mint. On confirmed Stripe/Web3 deposit (§4), Vend calls Mint
mint {to: end_user.mint_account, amount: net_micros, reserve_ref: deposit.id}
— reserve-gated, so AIT is only created against confirmed backing.
Take-rate → transfer. The platform fee and tenant margin are Mint
transfer ops at capture time (§5), landing in the tenant treasury and Vend
platform treasury respectively — auditable ledger entries, not spreadsheet math.
Receipts / solvency export. Vend proxies Mint GET /v1/receipts/audit
(merkle root) and GET /v1/reserve (supply-vs-backing), filtered to the
tenant's accounts, as the tenant's verifiable finance export (the switching-cost
anchor).
Idempotency across the seam. AITP nonce (single-use) + idempotency_key
(SDK) + Vend idempotency_keys table + Relay generation_id + Mint idem_key
together make any SDK retry a no-op that returns the original receipt.
4. Reserve & dunning reconciliation
Vend never creates money; it moves reserve in lockstep with Mint and drives the failed-payment lifecycle. All of this is closed-loop and success-only.
Mint only on confirmed deposit. Stripe payment_intent.succeeded (webhook,
idempotent on webhook_events.id and deposits.external_ref) or a confirmed
relay-web3 crypto deposit → deposits row status=confirmed → Mint mint op
crediting the end-user + a tenant_reserve_ledger.deposit row + bump of
tenant_reserve.backing_micros. FX snapshot for crypto stored in deposits.
Auto top-up. After each capture, if available < autotopup.threshold_micros,
Vend charges autotopup.amount_micros via the first working method_order
payment method. Success → normal deposit→mint path. Failure → opens a
dunning_cases row trigger=autotopup_failed.
Dunning FSM (per dunning_cases), append-only attempts:
open → retrying: retry the charge on a backoff schedule (e.g.next_retry_atat +1h, +24h, +72h; configurable), each attempt adunning_attemptsrow. Different payment methods tried inmethod_order. Idempotency: each retry uses a distinct Stripe idempotency key derived from(case_id, attempt_no)so a webhook re-delivery never double-charges.retrying → recovered: asucceededattempt → mint the credit, close the case.retrying → soft_limited: after K retryable failures, freeze the end-user (end_users.status=frozen) — reads still allowed, new spend blocked — and notify the tenant. No money moves.soft_limited → suspended: after the grace window, hard-suspend; new holds refused. Fornegative_balance/chargebacktriggers this is where clawback runs (below).→ recoveredat any point if payment lands;→ written_offonly after the clawback path exhausts.
Refund / chargeback / clawback (never edit history). A Stripe
charge.refunded or charge.dispute.created →
tenant_reserve_ledger.chargeback (compensating negative row) + a Mint clawback
transfer reclaiming the credited AIT from the end-user balance. If the credit is
already spent (balance insufficient), open dunning_cases trigger=chargeback,
set owed_micros, freeze the account, and run the collections/write-off path —
never force a negative reserve.
Suspend/clawback attribution. Clawbacks debit tenant_reserve.backing_micros
for the correct tenant only; a chargeback in tenant A can never reduce tenant B's
backing (the segregation invariant, §6).
Float / segregation invariant (continuously checked, §8): for every
tenant, tenant_reserve.backing_micros ≥ tenant_reserve.outstanding_ait_micros,
and globally Σ backing ≥ Σ outstanding. Alarm if any tenant's cushion drops
below a configurable buffer. Reconciled against Mint's own
Σ balances + Σ holds == reserve — Vend's per-tenant view must sum to Mint's
global truth.
5. Take-rate economics (exact µ$ math)
Three stacked, reserve-backed revenue lines, all Mint ops (no floats; all integer
µ; splits are `transfer`s). Let `provider_cost` = exact Cost-API µ for the call.
① Metered inference (platform-credit call — Vend pays upstream via Relay):
markup_micros = max( ceil(provider_cost × markup_bps / 10_000), min_fee_micros )
charge_micros = provider_cost + markup_micros # end-user pays this
platform_fee_micros = ceil(markup_micros × platform_fee_bps / 10_000) # Vend's slice OF the margin
tenant_net_micros = markup_micros − platform_fee_micros # tenant keeps this
At hold.capture, the single captured charge_micros fans out as double-entry
transfers:
provider_cost→ cost-of-goods (Relay/provider settlement),platform_fee_micros→ Vend platform treasury,tenant_net_micros→ tenant treasury (tenants.treasury_acct, Mint kind=5).
Worked example (matches vend.md §7): provider_cost = 4_200 µ$,
markup_bps = 2000 (20%), platform_fee_bps = 500 (5% of margin):
markup_micros = ceil(4_200 × 2000 / 10_000) = ceil(840) = 840charge_micros = 4_200 + 840 = 5_040(end-user pays $0.005040)platform_fee_micros = ceil(840 × 500 / 10_000) = ceil(42) = 42tenant_net_micros = 840 − 42 = 798- Provider paid
4_200; Vend platform treasury+42; tenant treasury+798. Sum out =4_200 + 42 + 798 = 5_040 = charge_micros. Double-entry balances.
vend.md §7 sketches "~252 µ$" using platform-fee-on-margin at a higher rate (15% × 840 ≈ 126, or 6% × 4_200 ≈ 252 if taken on gross). This doc pins the convention: platform fee is a percentage of the tenant's markup (the margin), not of gross charge.
platform_fee_bps=500on the 840 margin → 42 µ$. The alternative (fee on gross) is an Open Decision (§10-4).
② BYOK call (end-user's own upstream key): upstream is billed to the user directly; Vend charges only a platform fee on list price:
byok_fee_micros = ceil(list_price_micros × byok_fee_bps / 10_000)
→ single transfer to the platform treasury (and optional tenant share). No
provider_cost leg through Vend.
③ Top-up fee (hosted page): on deposit, fee_micros = ceil(gross × topup_fee_bps / 10_000) clamped to [topup_min, topup_max];
net_micros = gross − fee_micros is minted to the end-user; fee_micros →
platform treasury. Top-up amount validated against topup_min_micros /
topup_max_micros (the TopUpError bounds carried over from wallet/policy.py).
Rounding rule (documented, matches Mint §5): always integer µ$; round the
platform's take toward the platform by ≤1 µ$ via ceil; never overcharge
the end-user beyond charge_micros = provider_cost + markup_micros. The tenant
absorbs the ≤1 µ$ rounding on the platform-fee split, never the end-user.
6. Threat model & tenant isolation
| Threat | Control |
|---|---|
| Cross-tenant data read | tenant_id on every row + Postgres row-level security / mandatory tenant predicate in the repository layer; property test: any query for tenant A returns zero tenant B rows. No shared-mutable state across tenants. |
| Cross-tenant reserve drain (R5) | Per-tenant reserve segregation (tenant_reserve): one tenant's spend/chargeback can only touch its own backing_micros. Mint accounts are tenant-scoped; conservation checked per tenant and globally. Ship-blocker, not a kill (vend.md R5). |
| Sub-key theft | Secret shown once, only argon2id(secret) stored; prefix shard is non-secret; revoke sets status=revoked (hold refused immediately); per-key daily_cap_micros + rate_limit_rpm bound blast radius; rotation supported. |
| Spend-cap bypass | Daily cap enforced as SUM(charge_micros) WHERE sub_key_id AND utc_day in the same transaction as the hold reservation (atomic check-and-reserve), so concurrent requests can't race past the cap. Cap gating happens before hold.create. |
| Forged AITP authorization | Mint POST /v1/aitp/verify — ed25519 verify vs the end-user's registered account_keys.pubkey; expiry window; Vend never trusts a client-asserted payer. |
| Replay / double-charge | AITP nonce single-use + idempotency_key + Vend idempotency_keys unique + metered_usage_gen unique (Relay id) + Mint idem_key. Same idem-key different body → 409 idempotency_conflict. |
| Charging on failure | Hold created before serve; capture only on Relay success; release on any failover exhaustion/error (ADR-0002). Fault-injection matrix: crash between serve and capture → recovery re-checks Relay outcome and never captures a failed generation. |
| Reserve drain via unbacked mint | mint gated on confirmed deposit only (deposits.status=confirmed + webhook idempotency); float alarm; no code path mints without a reserve_ref. |
| Dunning double-charge | Retry idempotency key derived from (case_id, attempt_no); webhook re-delivery dedup on webhook_events.id; one open dunning_cases per (end_user, trigger). |
| Malicious tenant policy | markup_bps bounded (max cap); platform fee floor enforced regardless of tenant policy; ZDR/model-allowlist enforced server-side at the edge, not trusted from the SDK. |
| Insider tampering | Append-only grants on usage/reserve/dunning/audit; money truth is Mint's hash-linked receipts + merkle root — Vend rows are reconciled against them, so a tampered Vend row is detected by drift (§8). |
Custody. End-user signing keys default to platform-managed (Mint KMS); self-custody optional for agents/enterprise tenants that sign client-side (per AITP-402 §2). Vend never holds raw signing keys in app memory beyond a signing call.
7. Compliance (reseller-of-record, KYC tiers)
Legal posture. AIT is a closed-loop, prepaid, 1:1-redeemable, non-tradeable credit (inherits Mint §7 / AITP-402 §1) — positioned under closed-loop / limited-purpose exemptions, not a security or money-transmission product. Confirm per jurisdiction with counsel before GA. Kill-criterion R3: keep strictly closed-loop; if a jurisdiction forces licensing before revenue, gate top-ups to that region and continue elsewhere.
Reseller-of-record (RoR) — tenants.ror_mode.
ror_mode=0(Vend is RoR): Vend is merchant-of-record for the end-user top-up; Stripe charge is on Vend's account; Vend issues the receipt/invoice and bears the card-processing + refund/chargeback liability; tenant receives net margin as a Minttransfer(no direct card relationship). Simplest for the founder; Vend owns tax/1099 surface for the tenant payout.ror_mode=1(tenant is RoR): via Stripe Connect, the end-user charge is on the tenant's connected account; Vend takes its platform fee as an application fee; the tenant is merchant-of-record and owns end-user tax/receipts. Vend still meters and settles the AIT, but the fiat merchant relationship is the tenant's. Needed for tenants with their own compliance / entity requirements.
KYC tiers (per tenant and per end-user; gate payouts, not spend):
- T0 — spend-only, no payout/redeem. Default for new end-users.
- T1 — email + card verified; low top-up + low payout cap.
- T2 — full KYC; higher caps, creator/redeem payouts, tenant treasury
withdrawal. Required for
redeemand for tenants taking real payouts. - Sanctions/PEP screening on every payout/redeem address; block on hit (Vx5 task). Screening also on tenant onboarding for RoR mode 1 (connected account KYC via Stripe Connect).
Tax & records. Tenant margin payouts and creator/model-author payouts tracked
for 1099-/DAC7-style reporting; deposit/redeem/dunning records retained as
financial records. PII minimized; per-app zdr flag propagates to Relay
data_collection=deny for inference content (a Relay concern, not the ledger).
8. Observability, reconciliation & SLOs
Metrics (OTel). Vend gateway overhead p50/p99 (target: thin, since Relay does
the heavy lift); hold→capture time; capture-vs-release ratio (success rate);
metered-request TPS; deposit→mint latency; dunning recovery rate; per-tenant
float cushion; drift (Vend tenant_reserve vs Mint reserve).
Recon jobs.
- (a) Segregation recon (continuous): for each tenant,
tenant_reserve.outstanding_ait_microsrecomputed from Mint balances+holds of that tenant's accounts must equal the stored value;backing ≥ outstanding. - (b) Vend↔Mint drift (continuous): every
metered_usagerow'scharge_microsmust match its Mintcapture_receipt; alert on any mismatch. - (c) Vend↔Relay drift (hourly):
metered_usage.provider_cost_microsvs Relay Cost API for a sampled/spot set; catch a mis-read cost. - (d) Dunning aging (hourly): cases past
next_retry_atstillopen; stuck cases page. - (e) Global conservation (continuous):
Σ tenant backing ≥ Σ tenant outstanding, and this must tie to Mint's ownGET /v1/reserve.
SLOs. Vend overhead p99 < 5 ms (excludes Relay/Mint round-trips) · capture
success path adds ≤1 Mint round-trip · zero conservation/segregation/
success-only violations (page immediately) · per-tenant float cushion ≥ buffer ·
deposit→credit p99 < webhook + one Mint mint round-trip · zero charges on failed
generations under chaos.
Solvency status page. Per-tenant reserve proof (outstanding vs backing)
and global reserve, sourced from Mint GET /v1/reserve filtered to tenant
accounts — the shareable solvency artifact from vend.md §9.
9. Test / conformance plan
AITP-402 conformance vectors (reused from mint-testkit, run per SDK lang).
Every Vend SDK (and the gateway itself) runs the golden vectors to claim
compliance: happy aitp-hold capture-on-success, aitp-hold release-on-failure,
aitp-transfer, expired auth, replayed nonce, bad signature, allowance-exceeded,
idempotent retry returns original receipt.
Vend-specific integration vectors.
- Success-only end-to-end: forced provider failure (all endpoints 500) →
hold.release,metered_usage.outcome=released, end-user balance unchanged. - Exact-cost capture: capture equals
provider_cost (Cost API) + markupto the µ$; no float drift. - Failover transparency: kill a provider mid-stream → Relay reroutes; single capture at the surviving endpoint's cost; ≤1 dropped token.
- Top-up → mint: Stripe webhook (incl. duplicate delivery) → exactly one
mint, µ$-exactnet_micros, tenant reserve updated. - Dunning: failed recharge → retry→soft-limit→suspend with no double-charge (assert single successful Stripe charge across duplicate webhooks); chargeback-after-spend → clawback opens a case, no negative reserve.
- Idempotency: SDK retry with same
idempotency_key→ same receipt, no second charge; same key + different body →409.
Property tests (random op storms).
- Tenant isolation: interleaved multi-tenant op storm; no query crosses
tenant_id; balances/usage never mix. - Per-tenant conservation:
backing ≥ outstandingper tenant holds through storms of mint/capture/release/chargeback. - Cross-tenant drain (R5): spend + chargeback storm in tenant A never reduces
tenant B's
backing_micros— the explicit ship-blocker gate. - Daily-cap monotonicity: concurrent requests never sum past a key's
daily_cap_micros.
Chaos. Kill mid-hold.capture (recovery must not double-capture or capture a
failed gen); kill mid-mint (idempotent on external_ref); kill mid-dunning
(no double-charge); partition Mint (Vend refuses to serve without a live hold —
fail closed, never charge blind); partition Relay (release the hold, bill nothing).
10. Open decisions (need a call before / during build)
- Platform-fee base — fee on margin (
markup_micros, pinned in §5) vs on gross (charge_micros). §5 pins margin; confirm before Vx4 turns on thetransfer, since it changes take-rate economics and the vend.md §7 example. - Reseller-of-record default — ship
ror_mode=0(Vend is MoR, simplest DX) only at GA, or offer Stripe Connectror_mode=1from Vx2? Affects KYC surface, chargeback liability, and tax reporting ownership. - Streaming settlement — Mint
stream.open/tick/closeper-token vs single up-front hold + one capture at stream close using final Cost-API cost. Per-token is more precise but more ops; default to single-capture pre-GA? - Per-tenant reserve segregation model — logical view over one shared Mint reserve (chosen here, cheaper) vs a physically separate reserve account tree per tenant (stronger isolation, higher ops cost). R5 gate must pass either way.
- Dunning schedule + soft-limit thresholds — retry backoff (+1h/+24h/+72h?), K retries before soft-limit, grace window before suspend, write-off horizon.
- BYOK revenue split — does the tenant share the
byok_fee, or is it platform-only? (Affects §5-② transfer legs.) - KYC tier caps — concrete top-up/payout caps per T0/T1/T2 and which jurisdictions gate at launch (ties to R3 kill-criterion).
- SDK languages at GA — TS/JS + Python first (the design-partner shape), or also Go/Rust for agent workloads on day one?