videogen/docs/apps-vision/prism-media-gateway.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

387 lines
24 KiB
Markdown

# Prism — universal media-generation gateway ("OpenRouter for media")
> **Status:** Sx0 implemented; the Mint success-only settlement core of Sx1 is
> implemented in `apps/prism-media-gateway`. **Slug:**
> `prism-media-gateway`. The live service exposes the image/video catalog,
> authenticated generation, equivalent-route failover, BYOK overrides, hard cost
> caps, provider polling, owner-scoped spend readback, durable Mint holds,
> exact-cost capture, zero-charge release, and pinned-key receipt attestation.
> **One-liner:** One OpenAI-compatible endpoint for *every* media model (image,
> video, audio, voice, avatar, 3D, LoRA/workflows) across every provider —
> public cloud **and** your own local GPU / render farm — with failover,
> price-arbitrage, success-only billing, and a creator marketplace, all settling
> on Mint (AIT / AITP-402).
---
## 1. Problem & thesis
Text inference has a neutral aggregator (OpenRouter): one key, one schema, 300+
models, automatic failover and price sorting. **Media inference has none.**
Developers who want image/video/audio/voice/avatar generation are hard-locked
into a single stack — Fal *or* Replicate *or* a provider's native SDK — each with
its own auth, request shape, polling model, pricing unit, and failure semantics.
Adding a new model or provider is a *code* change, not a *config* change. There is
no failover when a provider is down mid-render, no arbitrage across equivalent
models, and — critically — **no way to route the same job to your own GPU when
it's cheaper or private, and burst to public cloud when it isn't.**
**Thesis:** Media inference is the fastest-growing GPU workload. Fal and Replicate
are each scaling to hundreds of millions in run-rate with *no neutral layer above
them*. The gap is real and the window is open. Prism is the OpenRouter-shaped
aggregator for media — but its durable edge is the one thing pure-cloud
aggregators structurally cannot copy: a **local-GPU + render-farm hybrid** ("route
private and public from one API") plus a **LoRA / workflow creator marketplace**.
And every dollar of spend, markup, and creator payout settles on **Mint**, making
Prism a demand generator for the payments rail for the agent economy.
The strategic bet is layered:
1. **Wedge:** the unified media API + failover/arbitrage (thin-margin aggregator).
2. **Moat:** hybrid private/public routing (local farm) + creator LoRA/workflow
marketplace (supply we own, not resell).
3. **Platform:** Mint becomes the settlement rail under Prism, Relay, and
ReelForge — the billion-dollar layer is the *money*, not the *pixels*.
---
## 2. Why now
- **Provider fragmentation peaked.** Fal, Replicate, Runway, Luma, Kling, Minimax,
Veo, HeyGen, ElevenLabs, Suno, ComfyUI/Wan — each is a silo. Devs stitch 3-5 of
them by hand. That's exactly the pre-OpenRouter LLM situation, one year later.
- **Model half-life is weeks.** A new SOTA image/video model ships monthly. Teams
that hard-code one provider re-integrate constantly. "New model = config not
code" is now a real pain, not a nice-to-have.
- **GPU price volatility + privacy pressure.** Studios and agencies want to keep
IP (characters, unreleased assets) on their own hardware but burst to cloud for
scale. No aggregator offers a single API across both.
- **We already built the hard 80%.** ReelForge ships **11+ real media adapters**,
a license/cost routing policy, a desktop Rust render farm with ComfyUI/Wan local
providers, and a gateway with provisioning keys + markup. Relay is a working
OpenRouter-shaped gateway (manifests, hedged routing, BYOK, credits-with-fee).
Mint specifies the settlement primitives. Prism is mostly a *unified public API
surface + billing wiring* over infra that already exists.
---
## 3. The narrowest wedge + first customer
**Wedge:** "**One image/video endpoint with failover and a cost cap.**" Not all
modalities, not the marketplace, not local — just: a single `POST /v1/media/
generations` that accepts an OpenAI-style request, routes across 3-4 equivalent
image/video models, fails over on error/timeout, never charges for a failed
generation, and returns exact spend. One key, config-selectable model.
**First customer:** an **indie AI-app / agency dev team already on Fal or
Replicate** who has been bitten by (a) a provider outage that killed a render
batch, or (b) a price hike / model deprecation that forced a re-integration. They
don't want to leave their stack — they want a *seatbelt*: failover + arbitrage +
one bill. Prism is a drop-in with BYOK, so switching cost is near zero and the
value (uptime + cheaper equivalent routes) is immediate.
**First 10 customers** come from ReelForge's own developer domain
(`apps/api/app/domains/developer`, `gateway/provisioning.py`) — teams already
issuing provisioning keys — plus Relay's early gateway users who ask "can I also
call image/video models here?" That question *is* the product.
---
## 4. How it reuses ReelForge / Relay / Mint (concrete)
### 4.1 ReelForge (`apps/api`) — the media substrate
- **Routing domain** (`app/domains/routing/`): reuse `policy.py` verbatim as the
admissibility + ordering core — `FALLBACK_NONE` / `FALLBACK_EQUIVALENT`, the
`Candidate` dataclass (model_id, provider_key, capability, `est_cost_micros`,
`latency_band`, `health_state`), max-cost caps, and consent-gated substitution.
This is Prism's arbitrage + failover brain, already tested and money-safe.
`license_class.py` gives per-model license policy (commercial-use gating);
`registry.py` in `providers/` is the adapter registry.
- **11+ real media adapters** (`app/domains/routing/providers/`): `image.py`,
`kling_fal.py`, `luma_gen.py`, `minimax_gen.py`, `runway_gen.py`, `veo_gen.py`,
`suno_gen.py`, `wan_replicate.py`, `wan_camera.py`, `sadtalker.py`, `heygen.py`,
`elevenlabs.py`, `tts.py`, `pixelle.py`, plus `openrouter.py` — these become
Prism's provider back-ends **unchanged**. `async_media.py` gives the poll/webhook
pattern every media provider needs.
- **Gateway domain** (`app/domains/gateway/`): `media_gateway.py`,
`media_router.py`, `media_catalog.py`, `media_usage.py` already implement an
OpenRouter-style media surface internally. `provisioning.py` gives daily-capped
reseller keys (`ProvisioningKey`, `check_spend`, `remaining`) and
`apply_markup` (base_cost + markup_bps, integer µ$). Prism *is* this domain
promoted to a public, standalone, documented product surface.
- **Wallet domain** (`app/domains/wallet/`): integer-microdollar ledger
(ADR-0001) for spend accounting until Mint is the settlement layer.
- **Characters / identity / LoRA** (`app/domains/characters`, `identity`): the
identity-lock + LoRA path is the seed inventory for the creator marketplace —
Prism can serve *hosted LoRAs / character locks* as first-class routable models.
- **Desktop render farm** (`apps/desktop`, Rust + ComfyUI/Wan): the **local
provider**. Prism registers a user's desktop farm as a private `provider_key`
with its own `latency_band`/`health_state`, so the *same* policy engine can
route a job to local GPU (private, cheap) or burst to Fal/Replicate (scale).
This hybrid is the moat and reuses code that already exists.
### 4.2 Relay (`apps/relay`, Rust) — the gateway shape
- **ProviderManifest + hedged routing:** adopt Relay's manifest model and hedged
request pattern for the *public* API layer (OpenAI-compatible schema, SSE/poll,
BYOK-with-fee, per-key rate limits, `/generation?id=` exact-cost readback).
Prism's public surface mirrors Relay's `/api/v1/*` conventions so a dev who
knows OpenRouter/Relay already knows Prism.
- **Success-only billing (ADR-0002):** Relay's charge-on-success discipline maps
directly onto media, where failures are common and expensive — never bill a
failed or timed-out render. This is a headline selling point vs raw providers.
- **BYOK + credits-with-fee wallet:** reuse the two monetization modes (prepaid
credits with markup, or bring-your-own provider key for a % fee).
### 4.3 Mint (`apps/mint`, AIT / AITP-402) — the settlement rail
- **Spend & markup settle in AIT:** every Prism generation debits the caller's AIT
balance and credits the provider/creator, tracked in integer microdollars
(1 AIT = 1,000,000 µ$), preserving conservation-of-supply.
- **Holds / escrow → success-only billing generalized:** open an AITP-402 **hold**
at request time for the max-cost cap; on success, settle the exact amount and
release the remainder; on failure, void the hold (nothing charged). This is the
native primitive for ADR-0002 on top of a real payment protocol.
- **AITP-402 machine-payment handshake:** agents call Prism with no pre-funded
session — Prism issues the 402 **Challenge**, the agent returns an
**Authorization**, Prism **verifies + settles** per call. This makes Prism a
first-class endpoint in the agent economy: an autonomous agent can generate
media and pay per invocation.
- **Streams / allowances:** metered/streaming payments for long renders and
delegated allowances for org treasuries funding many sub-agents.
- **Hash-linked receipts:** every generation emits a signed, hash-linked receipt —
verifiable spend + provenance (which model, which provider, which license
class), auditable without a chain. Doubles as content-provenance for compliance.
- **Creator payouts:** marketplace LoRA/workflow authors get paid in AIT via
Mint's payout primitive, with fraud controls reused from ReelForge `clipmarket`.
---
## 5. Architecture sketch (prose + text diagram)
Prism is a thin, standalone **public API surface** in front of ReelForge's routing
+ gateway domains, speaking Relay's OpenAI-compatible conventions, settling on
Mint. It adds no new inference code — it *composes* existing adapters.
**Request lifecycle (image/video/audio/voice/avatar/3D/LoRA-workflow):**
1. Caller hits `POST /v1/media/generations` (OpenAI-shaped) with a model alias
(e.g. `image/flux`, `video/kling`, `voice/elevenlabs`, or a marketplace
`lora:@author/style`) + routing prefs (`fallback`, `max_cost`, `prefer:local`).
2. **Auth & key:** provisioning key (markup mode) or BYOK (fee mode); per-key
daily cap checked via `provisioning.check_spend`.
3. **Hold:** Prism opens an AITP-402 hold on Mint for `max_cost` (µ$).
4. **Route:** the routing `policy.py` engine resolves `Candidate`s across
equivalent models/providers — public (Fal/Replicate/Runway/…) and private
(desktop render farm) — ordered by cost/latency/health, honoring license class
and `prefer:local`.
5. **Execute (hedged, success-only):** call the top adapter; on error/timeout,
fail over to the next Candidate within the cost cap. Async providers use the
`async_media` poll/webhook pattern.
6. **Settle:** on success, settle exact spend on Mint (release hold remainder),
split provider cost + Prism markup + creator royalty (if marketplace model),
emit hash-linked receipt. On failure, void the hold — **nothing charged**.
7. **Readback:** `GET /v1/generation?id=` returns exact spend, provider used,
license class, and receipt hash.
```
┌──────────────────────────────────────────┐
dev / AI-app / agent │ PRISM (public API) │
│ one key │ OpenAI-compatible media surface │
▼ │ /v1/media/generations /v1/models │
┌───────────┐ │ /v1/generation?id= /v1/marketplace │
│ Client │─────────▶│ │
└───────────┘ │ Auth+keys (gateway/provisioning) ┐ │
▲ │ Routing policy (routing/policy) │ reuse │
│ receipt+cost │ Adapter registry (11+ providers) │ RF │
│ │ Marketplace (LoRA/workflow) ┘ │
│ └───────┬───────────────┬──────────────────┘
│ │ │
│ public cloud│ private │ local
│ ▼ ▼
│ ┌──────────────────────┐ ┌───────────────────────┐
│ │ Fal · Replicate · │ │ Desktop render farm │
│ │ Runway · Luma · Kling│ │ (Rust + ComfyUI / Wan) │
│ │ Veo · Minimax · Suno │ │ user-owned GPU │
│ │ HeyGen · ElevenLabs │ └───────────────────────┘
│ └──────────────────────┘
│
│ every debit/credit/hold/payout + receipt
▼
┌──────────────────────────────────────────────────────────────┐
│ MINT — AIT settlement (AITP-402: holds, streams, receipts) │
│ spend · markup · BYOK fee · creator payouts · agent 402 pay │
└──────────────────────────────────────────────────────────────┘
```
**Deployment:** standalone service (mirrors Relay's posture — excluded from the
desktop GPUI/Metal workspace), on Neon/Postgres + Cloudflare + RunPod GPU, with
the desktop farm connecting as a private provider over an authenticated tunnel.
---
## 6. Monetization (all settling on Mint)
- **Markup mode (prepaid AIT):** caller buys AIT; Prism charges provider base cost
+ `markup_bps` (`apply_markup`, integer µ$). Target 8-15% — thin, but volume is
the whole media-inference market.
- **BYOK fee mode:** caller brings their Fal/Replicate/OpenAI key; Prism takes a
flat % (Relay's model) for routing, failover, and unified billing. Higher-trust,
lower-margin, sticky.
- **Arbitrage spread:** when Prism routes an equivalent job to a cheaper provider
under a cost cap, it can keep part of the delta (transparently) — a margin
pure-passthrough aggregators can't earn.
- **Marketplace take-rate:** LoRA/workflow/character-lock authors set a per-call
royalty; Prism takes a marketplace cut, creator paid in AIT via Mint payouts.
This is *owned supply* — the highest-margin, most defensible revenue.
- **Local-farm rebate / private routing premium:** enterprises pay a subscription
for private routing (keep IP on-prem, burst to cloud) — a seat/subscription line
on top of usage.
- **Agent 402 metering:** per-call AITP-402 settlement opens agent-economy volume
(autonomous agents generating media), each call a settled AIT transfer.
Every one of these is a transaction *on Mint*, which is the strategic point:
Prism's job is to drive settlement volume through the rail.
---
## 7. Moat & network effects
- **Hybrid private/public routing (structural moat).** Pure-cloud aggregators
(a hypothetical "OpenRouter for media" built by Fal/Replicate themselves, or a
neutral SaaS) *cannot* route to a user's own GPU — they have no render-farm
client. We already ship the desktop Rust farm + ComfyUI/Wan. "One API for your
GPU and the cloud" is the wedge rivals can't copy without building our client.
- **Creator marketplace (supply we own).** LoRAs, workflows, and character-locks
hosted on Prism are inventory no reseller has. Two-sided: more creators →
more unique routable models → more devs → more creator revenue. Payouts on Mint
make onboarding frictionless.
- **Provider-disintermediation defense.** Aggregator margins are thin and
providers can undercut. Our defense is (a) owned supply (marketplace + local
farm), and (b) the *switching cost of unified billing + receipts + failover*.
Devs don't leave a seatbelt that also cuts their bill.
- **Settlement lock-in via Mint.** Once spend, payouts, and agent-payments run in
AIT with hash-linked receipts, Prism, Relay, and ReelForge share one balance and
one audit log. The rail is the moat; Prism is one of several demand sources.
- **Data flywheel.** Cross-provider cost/latency/health/quality telemetry (from
`media_usage.py` + routing `health_state`) makes Prism's arbitrage smarter than
any single-provider view — a compounding advantage.
---
## 8. GTM — first 100 users
1. **Warm base (0-20):** ReelForge developer-domain teams and Relay early gateway
users already holding provisioning keys. Offer: "add image/video/voice to the
key you already have, with failover." Zero new signup.
2. **BYOK seatbelt (20-50):** target indie AI-app / agency devs on Fal/Replicate in
public communities (r/StableDiffusion, Fal/Replicate Discords, Twitter/X build
circles). Hook: BYOK drop-in, one line to add failover + a cost cap + one bill.
Publish a live "provider uptime + price arbitrage" dashboard as content.
3. **Model-launch surfing (50-80):** every time a new SOTA image/video model ships,
Prism adds it as *config* and posts "call the new model through your existing
Prism key today." Be the fastest neutral place to try new models.
4. **Marketplace seed (80-100):** invite ReelForge character/LoRA creators to list
hosted LoRAs/workflows for per-call royalties (paid in AIT). Their audiences
become Prism demand; devs come for the exclusive models.
5. **Agent-economy beachhead (parallel):** publish the AITP-402 media endpoint so
agent frameworks can generate + pay per call — seeds the payments-rail thesis.
Content spine: a public **media-model leaderboard** (cost/latency/quality across
providers) — the same growth loop OpenRouter used, applied to media.
---
## 9. Key risks + kill-criteria
| Risk | Mitigation | Kill-criteria |
|---|---|---|
| **Aggregator margin compression** — passthrough margins race to zero. | Shift value to owned supply (marketplace + local farm) and unified-billing lock-in, not raw markup. | If, by Sx3, >70% of revenue is thin passthrough markup with <5% blended margin and no marketplace traction → pivot to marketplace-only or fold into Relay. |
| **Provider disintermediation** — Fal/Replicate ship their own aggregation or block resale. | BYOK mode (we route *their* key, not resell), owned local-farm + marketplace supply. | If top-2 providers ToS-ban aggregation *and* BYOK, and they are >60% of volume → the neutral-aggregator thesis is dead; retreat to local-farm + marketplace niche. |
| **Local-farm hybrid too niche** — few users have GPUs. | Position local as enterprise/studio private-routing tier, not the mass wedge; the mass wedge is failover+arbitrage. | If <5% of paid volume ever touches private routing by Sx4 → keep it as an enterprise line, don't over-invest. |
| **Media schema fragmentation** — no clean OpenAI-shaped standard for video/3D. | Define a small canonical media request/response envelope; adapters normalize. | If normalization cost exceeds adapter-per-provider maintenance and the surface fragments → narrow to image+video only. |
| **Mint availability** — generation must not run for free when settlement is unavailable. | Prism fails closed before provider I/O, persists replayable money commands, and reports degraded readiness. | If Mint cannot meet the gateway's availability target, keep Prism private until the rail does; do not introduce an unmetered fallback. |
| **Quality parity of "equivalent" routes** — a cheaper model is worse. | License/quality class gating; consent-gated substitution (never silently downgrade). | If failover routinely degrades output and users disable it → arbitrage value collapses; reprice around uptime only. |
---
## 10. Phased roadmap (Sx0 → Sx4 with acceptance gates)
- **Sx0 — Surface & spec (plans → thin API).**
Deliver: canonical media request/response envelope; promote `gateway/media_*`
to a public `/v1/media/*` surface; wire `routing/policy.py` for
`FALLBACK_EQUIVALENT` across image + video only; BYOK + provisioning-key auth.
**Gate:** one key generates image+video across ≥3 providers with automatic
failover on a forced provider outage; exact spend readback works.
**Implemented:** the standalone FastAPI surface and Docker image reuse the live
ReelForge catalog/policy/adapters; the catalog spans more than three providers,
forced-outage failover and owner-scoped readback are verified locally. Live
multi-provider credential smoke runs remain an operator deployment check.
- **Sx1 — Success-only billing + arbitrage.**
Deliver: ADR-0002 hold/settle/void on Mint; cost-cap routing;
transparent arbitrage spread; `/v1/models` leaderboard (cost/latency/health from
`media_usage`). **Gate:** zero charges on failed renders across a 1k-request soak;
measurable % of jobs routed to a cheaper equivalent under cap; public leaderboard
live.
**Implemented settlement core:** durable owner/correlation-bound Mint holds are
required before provider I/O; provider submission ownership is atomic across
concurrent processes; successful terminal jobs replay exact-cost capture and
failed jobs replay full release with stable idempotency keys; signed Mint
terminal attestations are verified against pinned Ed25519 keys and the exact
durable money intent before a receipt projection is returned. Restart,
concurrency, lost-response, exact-capture, and zero-charge failure cases are
covered locally. The 1k-request live soak, transparent spread accounting, and
public leaderboard remain in Sx1.
- **Sx2 — Modalities + local hybrid.**
Deliver: audio (Suno/ElevenLabs/TTS), voice, avatar (HeyGen/SadTalker); register
the **desktop render farm** as a private provider with `prefer:local` routing.
**Gate:** a single request routes to local GPU when available and bursts to cloud
otherwise, with correct per-route billing and health-based failover; ≥5 modalities
live.
- **Sx3 — Marketplace settlement expansion.**
Deliver: extend Mint billing to streams and creator
LoRA/workflow marketplace with per-call royalties + AIT payouts (fraud controls
from `clipmarket`); hash-linked receipts as content-provenance. **Gate:** all
spend/markup/payouts settle in AIT with conservation-of-supply intact; ≥25
marketplace models listed; ≥1 creator paid out; receipts independently verifiable.
- **Sx4 — Agent economy + enterprise private routing.**
Deliver: public AITP-402 media endpoint (agents pay per call, no session);
enterprise private-routing tier (on-prem farm + cloud burst, SSO, audit export);
allowances/streams for org treasuries. **Gate:** ≥1 external agent framework
generates+pays per call via AITP-402; ≥1 paying enterprise on private routing;
blended take-rate + marketplace margin above the passthrough kill-line.
---
## 11. Success metrics
- **North star:** AIT settlement volume flowing through Prism per week (ties Prism
to the platform payments thesis).
- **Adoption:** active keys; generations/day; # of distinct models routed;
time-to-add a newly launched model (target: same day, config-only).
- **Reliability value:** failover save rate (% requests rescued from a failed
primary); $ saved by arbitrage (cheaper equivalent under cap).
- **Billing integrity:** 0 charges on failed generations (ADR-0002); receipt
verification rate 100%.
- **Marketplace:** # creators, # listed models, marketplace GMV, creator payout $.
- **Hybrid:** % of paid volume through private/local routing; # enterprise private
tenants.
- **Margin health:** blended take-rate and marketplace margin vs the aggregator
kill-line (>5% blended, marketplace share rising).
---
## 12. Relationship to the platform thesis
Prism is not the endgame — it is the **highest-leverage demand generator for the
payments rail**. Media inference is the fastest-growing GPU workload, so routing it
through Mint pushes the most transaction volume through AIT / AITP-402 the fastest.
ReelForge (video), Relay (text inference), and Prism (all media) become three
demand faces on one settlement layer, with marketplaces (creators, models, compute)
settling on it. The billion-dollar company is the **rail under the agent economy**;
Prism is the fastest way to make that rail indispensable to developers.