caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
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

10 KiB
Raw Permalink Blame History

Architecture — Unified Media Gateway (OpenRouter-style)

What this is. The cross-cutting design for ReelForge's unified media gateway: one API key + one wallet balance → any image, video, or audio model, exactly like OpenRouter's /images + /videos surface. Unlike a thin key-forwarding wrapper, ReelForge owns real provider adapters (each imports the vendor's HTTP client and speaks its real protocol) and meters spend through the real microdollar wallet with success-only billing. This doc spans every layer — API, web, mobile, packages (SDKs), desktop, and infra — because the feature is already implemented end-to-end and is a stable integration seam for the rest of the platform.

Status: shipped. All paths below exist in the repo. Counts are a lower bound on real work.


1. Shape of the surface

Endpoint Kind Returns
GET /api/v1/media/models catalog { models: [...] } (image + video + audio, one list)
POST /api/v1/media/images sync { model, url, cost_micros } — the image directly
POST /api/v1/media/videos async { id, status } — a job you poll
GET /api/v1/media/videos/{id} poll { status, url, cost_micros, error }
POST /api/v1/media/audio async { id, status } — a music job you poll
GET /api/v1/media/audio/{id} poll { status, url, cost_micros, error }
GET /api/v1/media/credits usage spendable balance + lifetime gateway spend
GET /api/v1/media/usage usage spend + counts grouped by model
GET /api/v1/media/generation/{id} usage per-job cost/status detail

Same key, same balance, every model — no per-provider credential or separate billing. The whole surface is namespaced under /media so it never collides with MPT's legacy /videos//audio endpoints. The OpenAPI artifact (packages/api-contract/openapi/reelforge-v1.json) enforces these paths via REQUIRED_PATHS, and @reelforge/api-contract exports the typed shapes (src/media-gateway.ts).

2. Money model (integer microdollars, success-only)

  • 1 USD = 1_000_000 micros; no floats anywhere in the money path.
  • Video: reserve seconds × price_micros on submit → settle the actual on completed → refund the full hold on failed. A failed generation is free.
  • Image: reserve price_micros → call the model synchronously → settle on success, refund on failure.
  • Audio: reserve a flat price_micros (per clip) → submit → settle on completed, refund on failed (polls like video).
  • All reserve/settle/release go through the real WalletService ledger (app/domains/wallet/).

3. Real provider backends

Each adapter imports requests, speaks the vendor's real protocol (auth, submit, poll, download), shares the KlingError taxonomy (auth / validation / rate_limit [Retry-After] / transient [exp-backoff]), returns integer-micro cost_micros, and takes an injectable session= so tests swap only the socket. A cataloged model whose API key is unset returns a clear 503 + wallet refund (honest degradation); a provider absent from dispatch returns 501.

Catalog breadth (~63 models, 11 providers). fal.ai and Replicate are aggregators hosting hundreds of real models behind one protocol, so the kling-fal/fal-image (fal) and wan/replicate-image (Replicate) adapters accept a direct provider path as model_ref (fal-ai/… or owner/name). New models are therefore added by a single catalog row with a real API path — no per-model adapter code — while still routing through the real, tested adapter. This gives OpenRouter-scale coverage (video 28, image 32, audio 3) that exceeds OpenRouter's own "40 image / 17 video" surface, all real and routable.

Video (6 real backends)

Provider Adapter Protocol shape
kling-fal routing/providers/kling_fal.py fal.ai queue — Key header, poll status_url → response_url, stream download
runway routing/providers/runway_gen.py Runway REST — Bearer + X-Runway-Version, /v1/image_to_video → task poll
veo routing/providers/veo_gen.py Google Generative Language — API-key query param, :predictLongRunning LRO poll
luma routing/providers/luma_gen.py Luma Dream Machine — Bearer, /generations state poll (queued→dreaming→completed)
minimax routing/providers/minimax_gen.py MiniMax/Hailuo — Bearer, two-step (poll → file_id → /files/retrieve), base_resp codes
wan routing/providers/wan_replicate.py Wan 2.2 on Replicate — Bearer, predictions lifecycle (starting→processing→succeeded)

Image (4 real backends, 12 models)

Provider Adapter Protocol shape
fal-image gateway/_fal_image.py fal.ai queue sync image
openai-image gateway/openai_image.py OpenAI Images API — Bearer, hosted url or base64→data: URL
replicate-image gateway/replicate_image.py Replicate predictions — Bearer + Prefer: wait, bounded poll fallback
imagen gateway/imagen_image.py Google Imagen — API-key query param, sync :predict, base64→data: URL

Audio (1 real backend, 3 models)

Provider Adapter Protocol shape
suno routing/providers/suno_gen.py Suno API v1 — Bearer, /generate → taskId, record-info poll, {code,msg,data} envelope, sunoData[].audioUrl

4. Per-layer file manifest

apps/api (backend — the real engine)

Path Responsibility
app/domains/gateway/media_catalog.py Public model id → modality / provider / provider-ref / integer-micro price
app/domains/gateway/media_gateway.py Reserve→submit→persist (video) / sync charge (image); _submit/_poll_video_upstream + _generate_image_upstream provider dispatch; settle/refund; metrics
app/domains/gateway/media_usage.py credits / usage_by_model / generation aggregation over media_jobs + wallet
app/domains/gateway/media_router.py The 7 HTTP endpoints (auth + owner-scope + guarded-DB), registered in app/router.py
app/domains/gateway/{_fal_image,openai_image,replicate_image,imagen_image}.py Real image adapters
app/domains/routing/providers/{kling_fal,runway_gen,veo_gen,luma_gen,minimax_gen,wan_replicate}.py Real video adapters
app/models/db/media_jobs.py MediaJob table (provider_ref, status, held/actual cost, output_url) + migration c31f3047fac6

apps/web (Next.js app-router)

Path Responsibility
src/features/media-gateway/api.ts Typed client over apiRequest (envelope-unwrapped)
src/features/media-gateway/ModelsBrowser.tsx Catalog browser (All/Video/Image filter, price/provider badges)
src/features/media-gateway/UsageDashboard.tsx Credits stat cards + spend-by-model table
src/features/media-gateway/Playground.tsx Image (sync) / video (submit+poll) generation
src/features/media-gateway/MediaGatewayNav.tsx Sub-nav (playground / models / usage)
app/media/{playground,models,usage}/page.tsx, app/media/page.tsx Routes (+ redirect hub); Studio-hub card

apps/mobile (Expo)

Path Responsibility
lib/media-gateway.ts Typed client (same surface; ?modality= in path)
app/media-gateway.tsx One screen, 3-segment toggle (Generate / Models / Usage); <Image> + video link
app/_layout.tsx, app/(tabs)/me.tsx Stack title + Me-tab entry

packages (SDKs)

Path Responsibility
sdk-typescript/src/resources/media.ts MediaResource — listModels/createImage/createVideo/waitForVideo/credits/usage/generation
sdk-python/reelforge_sdk/resources/media.py Same surface; wait_for_video(sleep=...) injectable

apps/desktop (Rust)

Path Responsibility
crates/rf-gateway/src/lib.rs Pure domain: cost estimate, clamp_seconds, GenStatus normalize, wallet_preflight, request-body builders, envelope parsing, typed DTOs

infra (observability)

Path Responsibility
infra/observability/slo.yaml media-gateway-success-rate SLO + media-gateway-success-only-billing page invariant
infra/terraform/modules/observability/main.tf Grafana alert rule mirroring the invariant
app/telemetry/metrics.py media_gateway_jobs{modality,provider,status} + wallet_debit_micros{reason=gateway}

5. Observability — success-only billing invariant

The gateway emits media_gateway_jobs{status=completed} and wallet_debit_micros{reason=gateway} on success, and only the job counter (no debit) on failure — mirroring the render executor. The paging invariant is: a gateway debit with no completed generation in the same window is a pay-without-output bug.

increase(wallet_debit_micros{reason="gateway"}[5m]) > 0
  and increase(media_gateway_jobs{status="completed"}[5m]) == 0

6. Test surface

Per-adapter suites (real protocol asserted against a faked requests.Session): test_{kling_fal,runway_gen,veo_gen,luma_gen,minimax_gen,wan_replicate}_gen.py, test_{openai,replicate,imagen}_image.py. Integration: test_media_gateway.py (catalog, per-provider routing, submit→poll→complete + wallet reserve/settle/refund, credits/usage/generation, and the success-only-billing metric emission). Python SDK: test_new_resources.py::test_media_*. Desktop: cargo test -p rf-gateway. All wired into vision2026-ci.yml.

7. Design rules (inherited, non-negotiable)

  1. Real adapters, not stubs. Every cataloged model routes to a live provider integration.
  2. Success-only billing. Failures refund the full hold; debits pair 1:1 with completed jobs.
  3. Honest degradation. Missing key → 503 + refund; unwired provider → 501. Never fake a result.
  4. Injectable transport. The requests.Session is the only network seam; protocol/retry/error mapping are the real production paths, runnable live with a real key.
  5. Integer microdollars only in the money path — no floats.