# uRouter reseller integration

This is the explicitly enrolled reseller contract. Ordinary personal inference keys gain no management authority. Deployment features remain subject to operator configuration.

## 1. Enrollment and credentials

An authenticated owner manages the single management key in this dashboard. Guests and ordinary inference keys cannot administer tenants or payments. Keep management credentials on your backend. Rotation atomically revokes the previous key for new actions; preserve accepted request and payment identities.

```sh
export SERVICE_ORIGIN="https://api.urouter.net"
export RESELLER_MANAGEMENT_KEY="YOUR_SERVER_SIDE_MANAGEMENT_KEY"
curl "$SERVICE_ORIGIN/v1/reseller" \
  -H "Authorization: Bearer $RESELLER_MANAGEMENT_KEY"
```

## 2. Create and map customers

Resolve your own authenticated customer to an external ID unique within your workspace. Create/retrieve that subaccount idempotently; never trust an arbitrary incoming subaccount ID or claim an existing personal account by matching its email. Customer API keys are scoped to their financial owner and never carry management authority.

```sh
curl "$SERVICE_ORIGIN/v1/reseller/subaccounts" \
  -H "Authorization: Bearer $RESELLER_MANAGEMENT_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: customer-example-001" \
  -d '{"name":"Example customer","external_id":"your-customer-123"}'
```

## 3. Final customer catalog and pricing

Forward the customer-safe catalog, including every rate dimension, billing unit, capabilities, options, availability and opaque version. Prices already include the saved markup exactly once. Owner-only pricing previews expose wholesale and projected margin separately. Customer caches must vary by tenant, policy, catalog, restrictions and branding; account-aware responses use no-store. Missing prices stay unavailable or quote-required, never zero.

```sh
curl "$SERVICE_ORIGIN/v1/reseller/catalog?kind=text&limit=25" \
  -H "Authorization: Bearer $RESELLER_MANAGEMENT_KEY"
# Continue with ?after=<URL-encoded next_cursor>. These prices are final.
# Owner-only comparison: GET /v1/reseller/pricing/models
# PUT /v1/reseller/pricing {"markup_bps":2500}
# 25% markup: $0.40 wholesale becomes $0.50 customer charge.
```

## 4. Customer keys and funding

Provision deposit instructions explicitly; GET only reads the existing route. A confirmed, independently verified crypto credit increases the customer’s balance once and creates no earnings. Provider creation or reconciliation failures remain pending or unavailable. Address ownership survives archival and display-name changes. Use signed events or poll the live deposit history; do not credit from a browser claim.

```sh
curl "$SERVICE_ORIGIN/v1/reseller/subaccounts/$CUSTOMER_ID/deposit-addresses" \
  -X POST -H "Authorization: Bearer $RESELLER_MANAGEMENT_KEY" \
  -H "Content-Type: application/json" -H "Idempotency-Key: address-example-001" -d '{}'
# Poll GET on the same path. A read never creates a route.
# Create a customer inference key with POST .../$CUSTOMER_ID/api-keys {"name":"Gateway"}.
# GET .../$CUSTOMER_ID/deposits returns actual confirmed credits, never promised credit.
```

## 5. Customer gateway and quotes

Your gateway authenticates the customer and uses its inference credential server-side. Proxy supported compatible APIs, streams, function calls, images, video and speech without buffering or changing tool-call structure. Customer account endpoints expose their own final charges and holds only. Quote the exact payload before variable media, use its ID in X-Price-Quote and respect expiry. Quotes do not reserve or dispatch. A saved quote policy is retained while its wholesale catalog quote remains valid. Already admitted requests keep their original snapshot.

```sh
curl "$SERVICE_ORIGIN/v1/chat/completions" \
  -H "Authorization: Bearer $CUSTOMER_INFERENCE_KEY" \
  -H "Content-Type: application/json" -H "Idempotency-Key: inference-example-001" \
  -d '{"model":"EXACT_AVAILABLE_MODEL_ID","messages":[{"role":"user","content":"Hello"}],"max_tokens":512,"stream":true,"stream_options":{"include_usage":true}}'
# Customer account: /v1/account/balance, /usage, /deposits, /deposit-addresses.
# Receipts: /v1/account/receipts/<request_id>; icons: /v1/assets/models/<encoded_model_id>.
# GET /v1/services returns indicative separate service rates; execution is not exposed.
# Variable media: POST /v1/quotes {"kind":"video","payload":{"model":"EXACT_VIDEO_MODEL_ID","prompt":"A synthetic test scene","duration_seconds":5}}.
# Submit the identical payload with X-Price-Quote: <quote id> before its expiry.
# Music availability follows deployment policy; disabled music remains unavailable.
```

## 6. Recovery and authorized files

Persist correlation and idempotency references. Execution, settlement and delivery can complete separately. A timeout or unavailable file is not proof that generation failed or cost nothing. Poll the original request/job and retrieve its authorized relative resource paths using the customer credential. Serve files under your own verified origin and preserve content types, expiry, cancellation and access checks. Do not regenerate automatically after an ambiguous outcome.

```sh
# Keep request IDs, job IDs, idempotency keys and quote IDs.
# GET /v1/requests/<request_id>
# GET /v1/video/generations/<job_id>
# GET /v1/audio/speech/jobs/<job_id>
# Download only the owned relative artifact paths returned by the job.
# Execution, financial settlement and file delivery have distinct states.
# Never regenerate after an outcome_unknown or a delivery failure.
```

## 7. Settled earnings and corrections

Earnings are settled customer charges minus the contracted wholesale cost under the admitted policy. Promotional credit and speculative reservations cannot create withdrawable profit. Customer liabilities, supplier expense and earnings reconcile in one financial transaction. Linked corrections preserve the original history; after a payout they can create a reseller deficit that blocks withdrawals and offsets future earnings.

```sh
curl "$SERVICE_ORIGIN/v1/reseller/balance" -H "Authorization: Bearer $RESELLER_MANAGEMENT_KEY"
curl "$SERVICE_ORIGIN/v1/reseller/earnings?range=month&bucket=day" -H "Authorization: Bearer $RESELLER_MANAGEMENT_KEY"
# Supported earnings buckets: day, model, none.
# Use /subaccounts/{id}/usage for customer usage, earnings and model breakdown.
# A deposit or open reservation earns $0. Paid, measured settlement creates earnings.
# Linked corrections can create a deficit after payout; future earnings offset it.
```

## 8. Approved native USDC withdrawals

An owner with a fresh session approves destinations and sets bounded payout authority. The management key may select an approved destination but cannot change it, its own privileges or treasury settings. The requested amount includes the disclosed fee. Withdrawals require both entitlement and liquid backing; the net transfers as native USDC on Base. Queued, submitted and review states retain the commitment. Retries reconcile the same signed transaction. Only proved nonpayment can restore it. Read withdrawal-policy before review and submit expected_fee_usd with the exact reviewed fee. A changed fee fails before new acceptance; an accepted action replays its original terms.

```sh
# First approve a destination and set payout limits in the owner dashboard.
# Management keys can select approved IDs, never replace destinations or privileges.
# Grant earnings:read to review payout terms and withdrawals:write only when required.
curl "$SERVICE_ORIGIN/v1/reseller/withdrawals" \
  -H "Authorization: Bearer $RESELLER_MANAGEMENT_KEY" \
  -H "Content-Type: application/json" -H "Idempotency-Key: withdrawal-example-001" \
  -d '{"destination_id":"APPROVED_DESTINATION_UUID","amount_usd":"10.000000","expected_fee_usd":"FEE_FROM_POLICY"}'
# Read GET /v1/reseller/withdrawal-policy first; persist the reviewed fee with the action.
# amount_usd includes the disclosed fee; net is sent as native USDC on Base (8453).
# Poll /withdrawals/{id}. Queued/submitted/review are reserved, not failed.
# Do not execute this example with real funds during development.
```

## 9. Signed events and polling

Configure an endpoint on the verified API origin and copy its signing secret once. Verify HMAC-SHA256 over timestamp, a period and the raw body with a constant-time comparison; reject stale timestamps and deduplicate stable event IDs. Delivery is at-least-once with bounded retries. Events expose owner-only settlement details, so do not forward their payloads blindly to customers. Polling remains a supported fallback.

```sh
# Verify raw request bytes before JSON parsing.
# expected = HMAC-SHA256(signing_secret, timestamp + "." + raw_body)
# Compare the v1=<hex> signature in constant time.
# Reject timestamps outside your clock-skew window, deduplicate stable event IDs.
# Headers: X-Event-ID, X-Event-Timestamp, X-Event-Signature.
# Events: deposit.credited, usage.settled, usage.corrected, withdrawal.*.
# Delivery is at-least-once, bounded retries; polling remains supported.
```

## Implementation prompt

Implement a server-side reseller integration using https://urouter.net/assets/docs/resellers.md and https://urouter.net/assets/docs/openapi.json. This is reseller mode; ordinary personal inference keys have no management authority. First verify enrollment at https://api.urouter.net/v1/reseller. Store the single rotatable management key only on the server. Bind your authenticated customer identity to its scoped external ID and subaccount; never accept an arbitrary caller-supplied subaccount ID. Create/retrieve the customer idempotently, provision its inference key and deposit instructions, observe confirmed credits by signed webhook or polling. Proxy the complete customer-safe catalog from /v1/reseller/catalog, including all billing dimensions and pagination; these are final customer prices. Wholesale plus markup is calculated once on the platform. Do not apply markup again. Keep /pricing/models, markup, wholesale, earnings and management credentials out of customer responses and caches. Use the customer's credential for /v1/models, /v1/account/*, /v1/quotes, supported text/tool-call/streamed inference, images, video and speech. Preserve streaming without buffering, cancellation, tool calls, content types, request IDs and idempotency keys. Honor quote expiry and X-Price-Quote for the identical payload. For text quotes, select chat_completions, responses, messages or completions in the protocol field. Keep the request body and any anthropic-version or anthropic-beta headers identical to the ones used for the quote. Recover accepted requests/jobs and proxy authorized relative file paths under your verified public origin without an upstream login. Preserve unknown financial outcomes; never automatically generate or pay again. Use /earnings and /balance for settled funded margin only. Payouts require a dashboard-approved destination, earnings:read to review terms, explicit withdrawals:write permission and enabled bounded authority; review the amount, fee and net, retain the same idempotency key and poll the accepted withdrawal. A timeout is not a failed payment. Use the customer-only branded documentation pack for your customers; it excludes management and wholesale fields. Use fixtures and synthetic money for implementation and verification; this prompt does not authorize any real deposit, provider spend or payout. Disabled features remain disabled. Operational enrollment, verified origins, fee policy and treasury configuration must be supplied, never invented.

## Brandable customer pack

Generate the customer-only OpenAPI/LLM/reference/prompt pack with `node scripts/generate-reseller-docs.mjs --output OUTPUT_DIR --name "YOUR_BRAND" --api-origin https://YOUR_VERIFIED_API_ORIGIN --support-url https://YOUR_SUPPORT_URL`. Use the verified branding returned by your workspace. Serve all generated files under your own origin. The customer-template download uses example.invalid fake values for review, never live configuration.
