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.
223 lines
11 KiB
Markdown
223 lines
11 KiB
Markdown
# apps/relay — a full OpenRouter platform in Rust (source-of-truth plan)
|
|
|
|
> Side product, independent of ReelForge (`apps/api`). A from-zero, fully-Rust
|
|
> OpenRouter clone: unified OpenAI-compatible inference API across every provider,
|
|
> a credits wallet we sell with a fee, BYOK, smart routing, analytics, and a
|
|
> Web3 payment rail. Goal: **copy OpenRouter fully, then beat it.**
|
|
>
|
|
> `relay` is a placeholder name — swap freely.
|
|
|
|
---
|
|
|
|
## 1. Fit into the repo
|
|
|
|
Root `Cargo.toml` is a workspace (edition 2021, MIT, `resolver = 2`) with
|
|
`apps/desktop` + `apps/desktop/crates/*`. `relay` is a **standalone workspace**
|
|
(a web service: axum/tokio/reqwest, not GPUI), **excluded** from the root
|
|
workspace so it never triggers the `apps/desktop` GPUI/Metal build:
|
|
|
|
```toml
|
|
# root Cargo.toml
|
|
[workspace]
|
|
exclude = ["apps/relay"]
|
|
```
|
|
|
|
`apps/relay/Cargo.toml` is its own `[workspace]` over `crates/*`. Tests run with
|
|
`cargo test` **inside `apps/relay`** (never `cargo` at the repo root).
|
|
|
|
Independent product, but it inherits two ratified invariants:
|
|
- **ADR-0001 — integer-microdollar money** (no floats, checked arithmetic).
|
|
- **ADR-0002 — success-only billing** (never charge on a failed generation).
|
|
|
|
No code shared with `apps/api` (different language) — only the money math and,
|
|
optionally, the same Neon/Postgres + Cloudflare infra.
|
|
|
|
---
|
|
|
|
## 2. Full OpenRouter parity surface ("copy fully")
|
|
|
|
**Inference API (OpenAI-compatible):** `POST /api/v1/chat/completions`
|
|
(+ `/completions`, `/embeddings`), SSE streaming, tool/function calling,
|
|
structured outputs (`json_schema`), multimodal (image/audio inputs),
|
|
prompt-caching passthrough, `transforms` (middle-out), model suffixes
|
|
`:free` `:nitro` `:floor` `:online`.
|
|
|
|
**Routing controls:** the `provider` object — `order`, `allow_fallbacks`,
|
|
`require_parameters`, `data_collection`, `ignore`, `quantizations`,
|
|
`sort` (price/latency/throughput).
|
|
|
|
**Catalog:** `GET /models`, `/models/:author/:slug/endpoints` — 300+ models,
|
|
per-endpoint pricing (prompt/completion/image/request), context length,
|
|
capabilities, uptime/latency/throughput.
|
|
|
|
**Cost API:** `GET /generation?id=` (exact spend per request), `/credits`, `/key`.
|
|
|
|
**Keys & billing:** prepaid credits (Stripe **+ crypto**), pay-per-token with
|
|
markup, **BYOK with a % fee**, provisioning/management API keys, per-key spend +
|
|
rate limits, free tier.
|
|
|
|
**Auth/apps:** OAuth PKCE (`/auth/keys`) so third-party apps mint user keys;
|
|
app attribution (`HTTP-Referer`/`X-Title`) + rankings.
|
|
|
|
**Data policy:** logging opt-out / ZDR flags per key.
|
|
|
|
**Analytics:** activity, usage by model/app, latency/throughput.
|
|
|
|
### 2b. UI-confirmed surface (from the OpenRouter Credits page)
|
|
|
|
The credits dashboard we mirror 1:1:
|
|
- **Total available / pay-as-you-go balance** (microdollar-exact, shown as $).
|
|
- **Buy Credits** with a **Use crypto** toggle · **Add Credits** · **Redeem Promo Code**.
|
|
- **Auto Top-Up** — buy credits when balance drops below a threshold; multiple
|
|
payment methods tried in order on failure.
|
|
- **Recent Transactions / History** — each with **Receipt** + **Get invoice**.
|
|
- **Enterprise billing** contact path.
|
|
- Left-nav account surfaces to reach parity on: Overview, **API Keys**,
|
|
**Guardrails**, **BYOK**, **Routing**, **Presets**, **Plugins**,
|
|
**Observability**, **Classifiers**, **Activity**, **Logs**, **Credits**,
|
|
**Management Keys**, **Privacy**, **Preferences**; product nav: **Models**,
|
|
**Benchmarks**, **Chat**, **Rankings**, **Apps**, **Docs**.
|
|
|
|
**Credit semantics:** one balance, **spendable on anything** (any model/provider).
|
|
We take a fee/markup on top of raw provider cost (BYOK charges a smaller % fee).
|
|
Success-only: a failed request never debits.
|
|
|
|
---
|
|
|
|
## 3. How we beat them
|
|
|
|
1. **Rust tail latency** — sub-millisecond gateway overhead, streaming-first,
|
|
huge concurrency on one box; publish a p99-overhead SLO their Node stack can't match.
|
|
2. **Data-driven provider onboarding** — a `ProviderManifest` (declarative
|
|
paths/field-maps/dialect, like the Python `AsyncMediaConfig` pattern) so a new
|
|
provider is **config, not code**. New model live in minutes.
|
|
3. **Speculative hedged routing** — fire to 2 endpoints, take first token, cancel
|
|
the loser, under a hard cost cap. Lower p99 than pure-fallback OpenRouter.
|
|
4. **Semantic response cache** — normalized prompt-cache across providers +
|
|
optional embedding-keyed cache → real cost savings passed to users.
|
|
5. **Predictive failover on live SLO** — per-endpoint health/uptime scoring,
|
|
route away **before** errors, not after.
|
|
6. **Governance OpenRouter lacks** — orgs/RBAC, team budgets, guardrails
|
|
(PII/moderation/context caps) as first-class middleware.
|
|
7. **Self-hostable open core** + first-class **local providers** (vLLM/Ollama) so
|
|
enterprises route private + public from one API.
|
|
8. **Transparent, lower fees** — microdollar-exact per-token accounting, no rounding games.
|
|
9. **Web3 payment rail** (see §6) — crypto deposits, per-model creator payouts, and
|
|
machine-native x402 agent payments. OpenRouter has none of this.
|
|
|
|
---
|
|
|
|
## 4. Rust workspace (`apps/relay/crates/*`)
|
|
|
|
| Crate | Role |
|
|
|---|---|
|
|
| `relay-server` (bin) | axum HTTP: OpenAI-compatible + platform routes, SSE, tower middleware stack |
|
|
| `relay-core` | domain types, **microdollar money**, error model |
|
|
| `relay-providers` | data-driven adapters (`ProviderManifest` engine) — OpenAI, Anthropic, Google, Mistral, Groq, DeepSeek, xAI, Together, Fireworks, Cohere, vLLM/Ollama… |
|
|
| `relay-normalize` | request/response + streaming normalization across provider dialects |
|
|
| `relay-router` | policy: sort (price/latency/throughput), fallbacks, hedging, provider prefs, model suffixes |
|
|
| `relay-catalog` | model+endpoint registry, live pricing sync, capabilities, uptime |
|
|
| `relay-billing` | credits ledger (append-only microdollar), metering, markup, BYOK fee, Stripe/crypto topup, **success-only** |
|
|
| `relay-keys` | API + provisioning/management keys (argon2 hash, scopes, spend/rate limits) |
|
|
| `relay-cache` | prompt cache + optional semantic cache (redis) |
|
|
| `relay-auth` | JWT, OAuth PKCE, orgs/RBAC |
|
|
| `relay-guardrails` | moderation, PII, context limits, `middle-out` transform |
|
|
| `relay-tokenize` | tokenizer registry (HF `tokenizers`) for exact count/pricing |
|
|
| `relay-analytics` | usage rollups, app attribution, activity API |
|
|
| `relay-web3` | per-account/provider/model addresses, crypto deposit watcher, x402 agent payments, creator payouts/settlement (see §6) |
|
|
| `relay-store` | `sqlx` Postgres (Neon) + redis seam + migrations |
|
|
| `relay-telemetry` | `tracing` → OpenTelemetry |
|
|
| `relay-testkit` | fake transports, golden dialect fixtures |
|
|
|
|
**Stack:** tokio · axum · tower · reqwest(stream) · sqlx(Postgres) ·
|
|
deadpool-redis · serde · jsonwebtoken · argon2 · tokenizers ·
|
|
tracing/opentelemetry · figment(config) · (web3) alloy/ethers-rs + stablecoin
|
|
SDKs. Injectable HTTP transport per provider (fake in tests, real in prod) — same
|
|
discipline as the Python adapters.
|
|
|
|
---
|
|
|
|
## 5. Phased build
|
|
|
|
- **RP0 — Working proxy:** standalone workspace + server, `/v1/models` +
|
|
`/v1/chat/completions` → one OpenAI-compatible provider, SSE, API-key auth,
|
|
microdollar ledger + usage log. **Gate:** real streamed completion, billed exactly.
|
|
- **RP1 — Multi-provider + normalize:** 10 providers via manifests,
|
|
stream/tool/`json_schema` normalization, model suffixes. **Gate:** identical
|
|
response shape across 3 dialects.
|
|
- **RP2 — Routing:** fallbacks, provider prefs, price/latency/throughput sort,
|
|
hedging, live per-endpoint pricing sync. **Gate:** kill a provider mid-stream →
|
|
transparent failover.
|
|
- **RP3 — Billing platform:** Stripe + crypto topups, credits, BYOK-with-fee,
|
|
auto top-up, promo codes, receipts/invoices, provisioning/management keys,
|
|
spend/rate limits. **Gate:** success-only invariant holds under failure injection.
|
|
- **RP4 — Platform:** analytics API, app attribution + rankings, orgs/RBAC/budgets,
|
|
OAuth PKCE, guardrails/presets/plugins surfaces. **Gate:** third-party app mints
|
|
a user key end-to-end.
|
|
- **RP5 — Beat-them:** semantic cache, quality/SLO-aware routing, predictive
|
|
failover, self-host mode, local providers.
|
|
- **RP6 — Web3 rail:** per-account deposit addresses, per-provider/model payout
|
|
addresses + revenue share, x402 agent payments, non-custodial settlement (see §6).
|
|
- **RP7 — Hardening/GA:** load + chaos tests, OTel dashboards, SLOs, blue-green.
|
|
|
|
**Success metrics:** p99 gateway overhead < 5ms · failover < 1 dropped token ·
|
|
cache cost-savings % · BYOK-fee & markup GMV · provider-onboard time
|
|
(manifest → live) in minutes · zero success-only billing violations under chaos ·
|
|
(web3) crypto-deposit → credit latency, creator-payout accuracy.
|
|
|
|
---
|
|
|
|
## 6. Web3 payment rail — addresses per account / provider / model
|
|
|
|
**Principle:** the **microdollar ledger stays the single source of truth**
|
|
(mirrors ADR-0001/0002). Crypto is a *rail in and out*; on-chain is settlement,
|
|
the off-chain ledger is authoritative. Prefer **stablecoins**, non-custodial
|
|
where possible, with KYC thresholds and clear compliance boundaries.
|
|
|
|
Three address levels:
|
|
|
|
1. **Per-account deposit address (on-ramp).**
|
|
Each account gets a crypto deposit address (HD-derived or an
|
|
account-abstraction smart wallet). Incoming stablecoin is watched by
|
|
`relay-web3`'s deposit watcher and **auto-credited** to the microdollar ledger
|
|
at the observed FX. This is the crypto path behind "Use crypto → Add Credits"
|
|
and Auto Top-Up. Withdrawals supported for creators.
|
|
|
|
2. **Per-provider / per-model payout address (creator economy).**
|
|
Every provider and model in `relay-catalog` can register a **payout address**.
|
|
When a request bills, `relay-billing` splits it: platform fee → us, provider
|
|
cost → provider, and an optional **revenue share → the model author's address**.
|
|
This lets open-model authors (and providers) get paid automatically when their
|
|
model is used — a marketplace OpenRouter doesn't have. Users can also **tip /
|
|
"send AI tokens" directly** to a model or provider address.
|
|
|
|
3. **x402 machine-native agent payments (pay-per-call).**
|
|
Expose **HTTP 402** on the inference endpoints so autonomous agents can pay
|
|
per request in stablecoin with **no pre-funded account** — the agent hits the
|
|
endpoint, gets a `402` with a payment challenge, pays, and the call proceeds.
|
|
This is the "agents send AI tokens to a model" flow, standardized. (See the
|
|
x402 / agent-payments protocol.)
|
|
|
|
**`relay-web3` responsibilities:** address derivation/management, deposit
|
|
watcher + confirmations, FX snapshot → microdollar credit, x402 challenge/verify
|
|
middleware, per-model/provider revenue-split ledger entries, payout/settlement
|
|
batches, and a reconciliation invariant (on-chain settled == ledger movements).
|
|
|
|
**Data model additions:** `web3_accounts(account_id, address, chain, kind)`,
|
|
`payout_addresses(entity_type=provider|model, entity_id, address, share_bps)`,
|
|
`deposits(tx_hash, address, token, amount, fx_micros, credited_ledger_id)`,
|
|
`x402_payments(request_id, tx_hash, amount, verified_at)`.
|
|
|
|
**Compliance caveats (must design in, not bolt on):** custody vs non-custodial
|
|
posture, KYC/AML thresholds, sanctioned-address screening, stablecoin-only to
|
|
avoid volatility on the ledger, and jurisdictional limits on payouts. Ledger
|
|
remains authoritative; crypto never bypasses success-only billing.
|
|
|
|
---
|
|
|
|
## 7. Build harness
|
|
|
|
Runs as its own multi-agent workflow chain (RP0 → RP7), TDD, same
|
|
recon → design → build → review → fix shape as the ReelForge waves. RP0 is
|
|
already in flight; later phases chain after it, read results between phases.
|