[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ECXA7RVH8P07N5BTJFYR3E":3,"skill-same:01M7ECXA7RVH8P07N5BTJFYR3E":49},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M7ECXA7RVH8P07N5BTJFYR3E","x402-pay-per-call-gateway",null,"jonahthan433\u002FCortexOS","jonahthan433","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211465495?v=4","01M7ECH9HPHGA89DCXHHJBTS3C","jonah.ai","01M7ECH9JCEM45DZMWPT7148S1",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fx402-pay-per-call-gateway\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# x402-pay-per-call-gateway\n\n# x402 Pay-Per-Call AI Gateway\n\nClass of work: an **OpenAI-compatible AI inference gateway** that charges per request\nin **USDC on Base** via the **x402 protocol** — no signup, no API keys, agents pay\nclient-side. Stack seen this session: FastAPI + uvicorn, Postgres + Redis\n(docker-compose, `network_mode: host`, iptables disabled deliberately), Coinbase CDP\nfacilitator for `\u002Fverify` + `\u002Fsettle`, and Bazaar discovery for agent discoverability.\n\n## Source of truth — fetch fresh, the protocol moves\nx402 is actively evolving. Before trusting field names, pull the live schema:\n- Repo moved: **`x402-foundation\u002Fx402`** (the old `coinbase\u002Fx402` is now a dev fork).\n- Live PaymentRequirements \u002F PaymentPayload schemas:\n  `typescript\u002Fpackages\u002Fcore\u002Fsrc\u002Fschemas\u002Findex.ts` (read via `raw.githubusercontent.com`).\n- Bazaar docs: `docs.cdp.coinbase.com\u002Fx402\u002Fbazaar` is JS-rendered (curl gets the SPA\n  shell) — inspect the SDK source instead (below).\n\n## PaymentRequirements schema (verified against x402-foundation main)\nTwo versions coexist:\n- **V1** (what most servers emit): fields `scheme, network, maxAmountRequired,\n  mimeType, payTo, asset, extra, resource`. The 402 *response* must carry top-level\n  `x402Version: 1` (it is a discriminated union on `x402Version` — strict V1 parsers\n  reject a body missing it).\n- **V2**: uses `amount` (not `maxAmountRequired`), drops `recipient`\u002F`mimeType`,\n  `resource`, and `network` MUST be CAIP-2 (`eip155:8453`).\n\n**Network format — CAIP-2:** `V1 network` is `NonEmptyString` (lax) but canonical is\n`eip155:8453` (Base mainnet) \u002F `eip155:84532` (Base Sepolia). `V2 network` *requires*\nCAIP-2. Set `X402_NETWORK=eip155:8453` for mainnet.\n**Asset:** Base USDC contract = `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`.\n**Amount:** USD → USDC atomic = `int(usd * 1_000_000)` (6 decimals). `$0.005` → `\"5000\"`.\n\n## 402 flow (custom middleware, verified working)\n1. Route not in price map, or free (`$0.00`) → pass through.\n2. No `X-PAYMENT` header → return `402` with the `PaymentRequirements` JSON\n   (top-level `x402Version:1`, `accepts:[{...}]`) + a `PAYMENT-REQUIRED` base64 header.\n3. `X-PAYMENT` present (base64 JSON `PaymentPayload`) → POST to facilitator\n   `{FACILITATOR}\u002Fverify` then `{FACILITATOR}\u002Fsettle` with body\n   `{x402Version:1, paymentPayload, paymentRequirements: accepts[0]}`. On success,\n   forward request + set `X-PAYMENT-RESPONSE` header.\nFacilitator URL: `https:\u002F\u002Fapi.cdp.coinbase.com\u002Fplatform\u002Fv2\u002Fx402` (verify + settle).\n\n**Client-side settlement needs NO wallet ETH — only a signing key.** The gateway\nforwards the signed PAYMENT-SIGNATURE to the facilitator, which executes the\non-chain USDC transfer itself (it covers gas). A payer wallet with USDC but 0 ETH\ncan still settle. The REAL blocker for paid E2E tests is always the **payer's\nprivate key** (EIP-3009\u002FEIP-712 authorization), never gas. Before claiming a\nwallet can't pay, check: (1) does anything on the server hold that key, (2) is\nthere any signing key at all. Finding a key on the server: scan for 64-hex blobs\nand derive addresses with viem `privateKeyToAccount` (host) or eth_utils `keccak`\n(CT venv) — NEVER print key material; `server_ecdsa.key`\u002F`test_buyer.key`\u002F\n`~\u002F.cortexcloud\u002F.session` may all be DIFFERENT wallets, all possibly empty.\nA funded Binance withdrawal (screenshot\u002Ftxid) proves funds, not spendability.\n\n**Dynamic pricing support:** For certain endpoints, the middleware calculates the\npayment amount dynamically based on request parameters:\n- **Chat\u002FResponses (`\u002Fx402\u002Fv1\u002Fchat\u002Fcompletions`, `\u002Fx402\u002Fv1\u002Fresponses`)**:\n  Extract `model` from request body, look up its input\u002Foutput cost per 1k tokens\n  from the model registry, apply 27.5% markup (midpoint of 25-30% range) for\n  1000 input + 1000 output tokens (2000 tokens total basis), format as 6-decimal\n  dollar string. Falls back to static price if model unknown.\n- **Image Generation (`\u002Fx402\u002Fv1\u002Fimages\u002Fgenerations`)**:\n  Extract `n` (number of images) from request body: price = $0.04 × n for n=1,\n  or $0.035 × n for n>1 (batch discount). Falls back to static price if parsing fails.\n- All other routes use static pricing from `ROUTE_PRICING`.\n\n## Bazaar discovery (Python SDK has parity — no TS needed)\n\n**Dynamic pricing support:** For certain endpoints, the middleware calculates the\npayment amount dynamically based on request parameters:\n- **Chat\u002FResponses (`\u002Fx402\u002Fv1\u002Fchat\u002Fcompletions`, `\u002Fx402\u002Fv1\u002Fresponses`)**:\n  Extract `model` from request body, look up its input\u002Foutput cost per 1k tokens\n  from the model registry, apply 27.5% markup (midpoint of 25-30% range) for\n  1000 input + 1000 output tokens (2000 tokens total basis), format as 6-decimal\n  dollar string. Falls back to static price if model unknown.\n- **Image Generation (`\u002Fx402\u002Fv1\u002Fimages\u002Fgenerations`)**:\n  Extract `n` (number of images) from request body: price = $0.04 × n for n=1,\n  or $0.035 × n for n>1 (batch discount). Falls back to static price if parsing fails.\n- All other routes use static pricing from `ROUTE_PRICING`.\n\n## Bazaar discovery (Python SDK has parity — no TS needed)\n`pip install x402[fastapi,evm,extensions]` (v2.14.0 this session). Module\n`x402.extensions.bazaar` provides:\n- `declare_discovery_extension(input=, input_schema=, path_params_schema=,\n  body_type=\"json\", output=OutputConfig(example=..., schema=...))` → returns\n  `{\"bazaar\": {...}}` to attach as route discovery metadata. For POST JSON routes use\n  `body_type=\"json\"` + `input` (example body) + `input_schema` (JSON Schema of\n  `model`\u002F`messages`).\n- `declare_mcp_discovery_extension(DeclareMcpDiscoveryConfig(tool_name=,\n  input_schema=, description=, transport=\"sse\", example=))` — **takes a single\n  `DeclareMcpDiscoveryConfig` object, NOT keyword args** (the param is `config`).\n  `transport` is a `Literal[\"sse\",\"streamable-http\"]` → pass the string `\"sse\"`.\n- `OutputConfig` dataclass: `example` + optional `schema`.\n\nMCP endpoint: serve SSE (`text\u002Fevent-stream`) handling `initialize` → `tools\u002Flist`\n→ `tools\u002Fcall`. For a *discovery-first* gateway, `tools\u002Fcall` should return the\nendpoint URL + PaymentRequirements so the **agent pays client-side** (don't proxy\nthe paid inference server-side or you defeat x402). A consolidated discovery doc at\n`GET \u002F.well-known\u002Fbazaar` (per-route extensions) is what Bazaar\u002Fcrawlers consume.\n\n## Middleware & streaming pitfalls (starlette 1.x — the big one)\n- **`stream: true` paid calls returning 200 + `text\u002Fevent-stream` with an EMPTY body** =\n  a BaseHTTPMiddleware receive-state-machine violation, not an upstream problem.\n  Journal shows `starlette\u002Fmiddleware\u002Fbase.py:57 RuntimeError: Unexpected message\n  received: http.request` wrapped in an anyio `ExceptionGroup`. Starlette 1.x wraps\n  `receive` in a strict one-shot state machine (one `http.request`, then only\n  `http.disconnect`); any middleware that re-injects `request._receive` (or triggers\n  a second `http.request`) kills the streaming task after 200 is committed.\n  - Do NOT re-inject `request._receive` after `await request.body()` — FastAPI\n    caches the body on `request._body`, so the route re-reads from cache without a\n    second receive() call. Re-injection is both unnecessary AND fatal for SSE.\n    **Grep `request._receive =` — there may be several sites** (body-read block\n    AND each dynamic-pricing block for chat\u002Fimages re-inject their own closure);\n    removing only one leaves SSE still broken. To isolate stack-vs-middleware,\n    add a temp bodyless SSE probe route OUTSIDE the paid path (`\u002F__sse_probe`,\n    StreamingResponse) — if it streams, the paying middleware is the culprit.\n  - If the middleware still conflicts (body read in dispatch + route body parse),\n    convert the middleware to **pure ASGI** (`async def __call__(scope, receive,\n    send)`) — that removes starlette's state machine entirely.\n  - Provider generators test fine standalone — always confirm the failure is at the\n    HTTP layer by checking for the wrapper's completion log before blaming upstream.\n  Full traceback + diagnosis sequence: `references\u002Ffastapi-streaming-and-middleware.md`.\n- **contextvars do NOT cross the BaseHTTPMiddleware task boundary.** A router that\n  `contextvars.ContextVar.set(...)` for the structured log shows `null` in the\n  middleware's post-`call_next` log line (downstream app runs in a separate anyio\n  task; parent never sees child's changes). Pass request-scoped data via\n  `request.state` (set in the route handler, read in the middleware) instead.\n- **CDP facilitator requires an `https:\u002F\u002F` resource** (schema regex `^https:\u002F\u002F.*$`).\n  You cannot local-test the paid flow by setting `X402_RESOURCE_BASE=http:\u002F\u002Flocalhost:8000`\n  — validation fails with `doesn't match schema due to: string doesn't match the\n  regular expression \"^https:\u002F\u002F.*$\"`. Keep the https resource; test through the public\n  URL. If you DO temporarily edit `.env`, `cp .env \u002Ftmp\u002F.env.bak.\u003Ctag>` FIRST and\n  verify the value after restore (`grep ^X402_RESOURCE_BASE`), and re-check the\n  service is `active` — a bash parse error in a chained ssh command can abort mid-way\n  and leave the service down.\n- **viem `privateKeyToAccount` requires a 0x-prefixed hex key.** `test_buyer.key` is\n  raw 64-hex — wrap as `pk.startsWith(\"0x\") ? pk : \"0x\" + pk` or you get\n  `invalid private key, expected hex or 32 bytes, got string`.\n- **Verify routes by LIVE curl, not `app.routes` introspection.** FastAPI 0.139\n  includes `_IncludedRouter` wrappers in `app.routes`; `[r.path for r in app.routes]`\n  raises `AttributeError: '_IncludedRouter' object has no attribute 'path'` even when\n  all routes are registered. `curl -s -o \u002Fdev\u002Fnull -w \"%{http_code}\" ...\u002Fx402\u002Fv1\u002Fmodels`\n  is the real check (use `getattr(r, \"path\", None)` if you must introspect).\n\n## Payment-proof verification hardening (Section 1 — DO NOT outsource to CDP)\nThe facilitator is NOT a server-side verifier: the CDP SDK only builds client\nauth headers, and `\u002Fvalidate`+`\u002Fsettle` confirm settlement. A gateway that gates\npurely on the facilitator round-trip will execute paid routes on forged\u002Freplayed\nproofs. Verify the EIP-712 `TransferAuthorization` **in-process first** with\n`eth_account` (recover signer == `authorization.from`, require your own price,\nchainId==8453, canonical USDC Base asset, payTo==WALLET_ADDRESS, validBefore\nwindow 30s-skew\u002F5min-future), Redis-SETNX nonce replay guard, fail closed to 402.\nFull checklist + ordering + the `[2:]` hex real-data pitfall + checksum-address\nand deployed-module testing norms: `references\u002Fpayment-verification-hardening.md`.\nThis extends the standalone local in-process verifier (payverify.py) that must\nrun BEFORE the CDP client is built.\n\n## Smart Routing Implementation (S2)\n\nThe smart routing system selects the optimal upstream provider for each request based on:\n- Current latency (tracked as rolling p95)\n- Error rate (rolling 60s window)\n- Cost (per-call pricing from ROUTE_PRICING)\n\n### Key Implementation Details\n\n1. **Provider Metrics Tracking**:\n   - Maintain rolling windows of latency measurements (last 100 requests)\n   - Track success\u002Ffailure outcomes for error rate calculation\n   - Use simple average of recent samples for responsiveness\n\n2. **Provider Selection Algorithm**:\n   - For models with multiple providers (e.g., Llama 3.3 70B on Groq and NVIDIA NIM):\n     - Fetch all active models matching the requested name via `ModelRegistryService.get_models_by_name()`\n     - For each provider, retrieve recent metrics:\n       * Average latency from sliding window\n       * Error rate = 1 - (successful requests \u002F total requests)\n     - Compute composite score: `(0.4 * normalized_latency) + (0.4 * error_rate) + (0.2 * normalized_cost)`\n     - Select provider with lowest score\n   - Weights prioritize latency and reliability over cost\n\n3. **Fallback Mechanism**:\n   - If primary provider fails with 429 or 5xx, check for configured `fallback_model` in model capabilities\n   - Attempt one retry with fallback provider before returning error to caller\n   - Fallback models are defined per-model in the capabilities field\n\n4. **Headers and Observability**:\n   - Add `X-Cortex-Provider` header to responses showing which provider was used\n   - Update Prometheus metrics with per-provider latency and error rates\n   - Structured logging includes `upstream_provider` and `upstream_latency_ms` fields\n\n5. **Integration Points**:\n   - Modified `ModelRouter` class in `\u002Fapp\u002Frouting\u002Frouter.py`\n   - Extended `ModelRegistryService` with `get_models_by_name()` method\n   - Updated `\u002Fx402\u002Fv1\u002Fchat\u002Fcompletions` and `\u002Fx402\u002Fv1\u002Fresponses` endpoints to use new routing\n   - Preserved existing retry logic and circuit breaker integration\n\n### Current State (as of this session)\n- Router already implements basic retry with exponential backoff\n- Circuit breaker per provider is active (20% error rate over 30s → 503+Retry-After)\n- Model registry supports multiple entries per model name (different providers)\n- Pricing is available via `ROUTE_PRICING` and model-specific costs in database\n- Implemented:\n  1. `get_models_by_name` in `ModelRegistryService`\n  2. Metrics collection and averaging in `ModelRouter`\n  3. Provider selection logic in routing methods\n  4. `X-Cortex-Provider` header injection\n  5. Foundation for `\u002Fcompare` endpoint (to be completed in S2)\n\n## Performance batch (S3–S6) & paid E2E harness\nCompleted 2026-08: provider connection pooling, per-provider circuit breaker,\nRedis response caching + request coalescing, per-payer rate limit, structured JSON\nlogging + Prometheus `\u002Fmetrics`. Implemented patterns, deploy\u002Fverification\ndiscipline for the LXC push loop, and the @x402\u002Ffetch paid test battery that\nreplaced the lost `node dist\u002Fcli.js` proxy: `references\u002Fperf-and-paid-e2e.md`.\n\n## Bazaar visibility root cause: the payTo wallet must be CDP-provisioned\n\"Zero Bazaar visibility even though settlements succeed\" has ONE canonical cause:\nthe `payTo`\u002F`WALLET_ADDRESS` is a **bare external EOA**. Settlement is permissionless\n(`transferWithAuthorization`), so an EOA settles fine, but **Bazaar indexing is tied to\nan account\u002Fdeveloper-linked payee**. Symptoms that all point here:\n- `GET {FACILITATOR}\u002Fsupported` → 200, `.get(\"extensions\")` lists `bazaar` ✓\n  (facilitator config is fine — don't chase it).\n- `POST {FACILITATOR}\u002Fsettle` returns a proper 4xx\u002FJSON (auth works), and\n  `EXTENSION-RESPONSES` header is **absent** — an upstream gap, do NOT try to force it.\n- Deploy has `X402_FACILITATOR_API_KEY_ID`\u002F`_SECRET` set, so \"setup is done\", yet no index.\n\n**Root cause check** — grep the codebase for wallet provisioning before assuming setup:\n`grep -rniE \"createWallet|\\.create\\(\" app\u002F site-packages\u002Fcdp\u002F` — if `WALLET_ADDRESS` is just a\nliteral in `.env` with no `create_account` path, it's an external EOA.\n\n**Migrating to a CDP wallet requires a Server Signer first.** The installed CDP SDK\n(`cdp.cdp_client.CdpClient`, `evm.create_account(name=...)`) can mint a wallet using the\nSAME key pair as the facilitator (`api_key_id`=`X402_FACILITATOR_API_KEY_ID`,\n`api_key_secret`=`X402_FACILITATOR_API_KEY_SECRET`), but creation **fails at auth** until a\nconsole-provisioned secret exists:\n```\nValueError: Wallet Secret not configured. Please set the CDP_WALLET_SECRET environment variable...\n```\n`CDP_WALLET_SECRET` is emitted when you generate a **Server Signer** in the CDP Developer\nPlatform console — a console action, not something an agent can mint from the facilitator\nkey. So the migration is: user creates Server Signer → pastes `CDP_WALLET_SECRET` → set\nenv → `cdp.evm.create_account(name=\"cortexcloud-payee\")` → set `WALLET_ADDRESS` to the\nwallet to the returned wallet address → restart. **Without a console-created Server Signer the\nwallet migration is blocked — this is a real stop-and-ask user checkpoint, not a fixable-in-code\ngap.** Changing `WALLET_ADDRESS` is a business change, flag it first.\n\n## Standalone diagnostic scripts must run from the project cwd\nPydantic `SettingsConfigDict(env_file=\".env\")` resolves relative to **cwd**. A probe script\nlaunched with `cd \u002Ftmp` (or any non-project dir) loads `.env` and resolves `settings.WALLET_ADDRESS`\nto `None`, `_cdp_auth_headers()` to `{}` → every CDP call 401s and you misread it as an auth\nfailure. **Always run inside the container with `cd \u002Fopt\u002FCortexCloudAPI && ...\u002Fpython probe.py`**,\nor the script silently reads unconfigured settings. (Observed: `payTo: None` + `cdp auth header\nkeys: {}` → the whole facilitator \"broken\" diagnosis was garbage until re-run from the project dir.)\n\n## Dashboard\u002Flive-stats accuracy — the two-wallet drift and dead-counter traps\n- **Wrong-wallet constant:** a landing-page `\u002Factivity` (or any stats) endpoint that hardcodes a\n  `MERCHANT = 0x...` literal can drift from `settings.WALLET_ADDRESS` — it then queries on-chain\n  USDC Transfers for the WRONG wallet, finds nothing, and falls back to a **fabricated placeholder**\n  settlement. Grep for the hardcoded address and compare to `.env`'s `WALLET_ADDRESS` in the same\n  pass; derive live metrics from `settings.WALLET_ADDRESS`, never a copy.\n- **Dead counter:** a stats endpoint that *reads* a tally key it expects the middleware to *write*\n  returns permanent zeros. `grep -rn \"\u003Ckey>:\" app\u002F --include=*.py` — if the only hit is the reader\n  (middleware never `HINCRBY`s it), the pipeline is dead, not slow. Fix the writer or drop the field.\n- **SSR vs hydration — diagnose before fixing:** the user's \"widgets render 0\u002Fblank on no-JS fetch\"\n  can be either (a) normal Next.js static-export behavior (values hardcoded in the JS bundle \u002F\n  client-rendered; no-JS HTML has none) or (b) a dead metrics pipeline. Determine WHICH before\n  touching anything: grep the built JS for the fetch target + the hardcoded `{value:...}` defaults;\n  grep backend for the counter writer. Hardcoded marketing numbers (e.g. `180ms` median first\n  token, `40+` models) are not measured — per the user's rules, DON'T fabricate; omit or label.\n\n## PUBLIC surface when toggling out of single-tenant mode (2026-09)\nThe middleware has TWO coexisting gates: the `PRIVATE_API_KEY` blanket check (single-tenant mode) and the `_PATH_PRICING` per-route x402 check (public mode). When moving from one to the other, **edit the blanket block, don't delete it** — replace `if path != \"\u002Fhealth\"` with an explicit allowlist:\n```python\n_PUBLIC_PATHS = (\n    \"\u002Fhealth\", \"\u002Fopenapi.json\", \"\u002Fllms.txt\", \"\u002Ffavicon.ico\",\n    \"\u002F.well-known\u002Fx402.json\", \"\u002F.well-known\u002Fbazaar\", \"\u002F.well-known\u002Fopenid-configuration\",\n    \"\u002Fv1\u002Fcapabilities\", \"\u002Fv1\u002Fbackends\", \"\u002Fmcp\",\n)\nif settings.PRIVATE_API_KEY:\n    path = request.url.path\n    if (path != \"\u002Fhealth\"\n        and path not in _PUBLIC_PATHS\n        and not path.startswith(\"\u002F.well-known\u002F\")\n        and not path.startswith(\"\u002Fmcp\")):\n        # ... 401 ...\n```\nThen REMOVE `PRIVATE_API_KEY` from env and confirm `X402_ENABLED=true`. The price table already 402s paid routes; the only behavioral change is that discovery + MCP become public. Verify externally: `\u002Fopenapi.json`, `\u002Fllms.txt`, `\u002F.well-known\u002Fx402.json`, `\u002F.well-known\u002Fbazaar`, `\u002Fv1\u002Fcapabilities`, `\u002Fv1\u002Fbackends` all return 200; `\u002Fv1\u002Foptimize` (paid) returns 402 with the correct `payment-required` challenge; `\u002Finternal\u002Fmetrics` (admin) returns 401 even. Keep admin routes unauthenticated-by-default UNLESS you wire a dedicated bearer path.\n\n## `systemctl reset-failed` BEFORE restarting after a boot-loop burst (2026-09)\nAfter ~5–8 fast `systemctl restart cortexcloud` failures (e.g. the `enforce_secrets_in_production` validator rejecting a missing `CDP_WALLET_SECRET`), systemd rate-limits further restarts. The next restart — even with a corrected env — silently fails with `Failed with result 'exit-code'` and the service stays DOWN. Always `systemctl reset-failed cortexcloud` BEFORE restarting after a burst of failures; confirm with `NRestarts=0` after the restart.\n\n## Safety rules (the user's standing constraints for CortexCloud)\n- **Wallet\u002Fpayment logic is high-risk.** The recipient `WALLET_ADDRESS` receives REAL\n  USDC on Base mainnet — explain any change to payment\u002Fnetwork code before applying.\n- **First public exposure needs explicit go-ahead** (DNS A + router 80\u002F443 forward +\n  user says \"go\"). Caddy certs fail with NXDOMAIN until DNS exists — that is expected\n  and NOT \"exposed\".\n- **Bazaar\u002Fx402scan indexing needs a real on-chain USDC tx** (even small). Per the\n  user's rule, confirm before triggering the first settle that indexes a route.\n  x402scan.com\u002Fresources\u002Fregister is URL-based + auto-validates schema (simpler);\n  Bazaar is the higher-priority surface (native MCP for agent frameworks).\n- Don't silently change `POSTGRES_PASSWORD` (weak default `postgres` must match\n  docker-compose) — flag it, leave it.\n- DB model *registry rows* (e.g. seeding Gemini\u002FGroq\u002FOpenRouter\u002FNVIDIA models) are NOT\n  a migration — safe to insert via the app's `ModelRegistryService`, no schema change.\n\nSee `references\u002Fx402-schema-notes.md` for the exact verified 402 JSON and SDK call\nshapes captured this session. The authoritative v2 challenge body + headless\n`validatePaymentRequiredDetailed` recipe + the 405 method-agnostic fix are in\n`references\u002Fx402scan-v2-validator.md`.\n\n## x402scan discovery & registration (the part that actually blocks listing)\nThis consumed the most time in-session and is the #1 cause of \"No valid x402 response\nfound (HTTP 405)\" failures. Full contract + audit\u002Fregister workflow in\n`references\u002Fx402scan-discovery.md`. Key points:\n- **Discovery precedence is OpenAPI-FIRST, then `\u002F.well-known\u002Fx402` (NO `.json`).**\n  x402scan reads `https:\u002F\u002Fyourdomain.com\u002Fopenapi.json` before any well-known\n  manifest. Its compatibility fallback is `GET \u002F.well-known\u002Fx402` — NOT\n  `\u002F.well-known\u002Fx402.json`. A gateway that only serves the `.json` manifest (e.g.\n  from `build_manifest`) is INVISIBLE to x402scan beyond whatever openapi.json\n  contains. \"x402scan only shows 13\" = the served openapi.json is stale\u002Fsmall —\n  fix openapi.json, not the manifest.\n- **The `\u002F.well-known\u002Fx402` CONTENT matters — v1 resource-list schema, not your v2 manifest (2026-08, verified from the x402scan-mcp npm bundle).** `discover_resources` parses the bare path with `DiscoveryDocumentSchema = {version: z.number().refine(v=>v===1), resources: z.array(z.string().url()), ownershipProofs?: [urls], instructions?: string}`. Serving the rich v2 pricing manifest (`{\"version\":2, endpoints:[...]}`) there FAILS the zod parser **silently** — the tool reports `\"Found llms.txt but no structured x402 discovery document\"` and falls back to llms.txt. tryponcho.com fails the same probe, so it's strict-parser behavior, not your domain. **Serve BOTH:** `\u002F.well-known\u002Fx402` = v1 doc `{\"version\":1, \"resources\":[\"https:\u002F\u002F\u003Corigin>\u002Fv1\u002Foptimize\", ...]}` (URLs only); `\u002F.well-known\u002Fx402.json` = the rich v2 manifest (registration\u002Fbazaar consumers). Probe order the tool uses: `\u002F.well-known\u002Fx402` → DNS TXT `_x402.\u003Chostname>` (via cloudflare-dns.com) → `llms.txt`.\n- **Headless verification of x402 discovery tools:** spawn `npx -y x402scan-mcp@latest` as stdio and drive JSON-RPC (`initialize` → `notifications\u002Finitialized` → `tools\u002Flist` → `tools\u002Fcall` `{name:\"discover_resources\", arguments:{url:\"\u003Corigin>\"}}`). Parse the returned JSON: `source:\"well-known\"` = structured doc parsed; `source:\"llms-txt\"` = parser failed (check `attemptedSources` — it lists every path probed). Other tools: `query_endpoint` (probe 402 prices without paying), `validate_payment`, `execute_call` (auto-paid), `check_balance`, `authed_call` (SIWX).\n- **Keep `llms.txt` discovery links ABSOLUTE and CURRENT.** It's the fallback discovery source for crawlers — a stale path there (observed: dead `\u002Fx402\u002Fv1\u002Fmcp` after the MCP moved to `\u002Fmcp`) misleads every tool that falls through to it. Absolute URLs for all `.well-known` + `\u002Fopenapi.json` links.\n- **Static openapi override trap:** `app.openapi = lambda: _OPENAPI_SPEC` (loaded\n  from a committed file at import) means `app.openapi()` returns the STALE spec —\n  a regeneration script that calls it silently reproduces the old count. Bypass\n  with the unbound class method: `spec = FastAPI.openapi(app)`. Regeneration\n  recipe: build from live routers with `FastAPI.openapi(app)`, then stamp every\n  paid path from `ROUTE_PRICING` (single source of truth) with `x-payment-info`\n  (`{mode:\"fixed\",currency:\"USD\",amount:price}`), add `responses[\"402\"]`, add\n  `x-discovery.ownershipProofs: [merchant_wallet]`, write openapi.json, commit,\n  RESTART (spec is served from memory), verify live count via\n  `curl \u002Fopenapi.json`. See `references\u002Fopenapi-regen-for-x402scan.md`.\n- **OpenAPI at `\u002Fopenapi.json` is canonical.** Override FastAPI's auto-spec with\n  `app.openapi = lambda: SPEC` (the auto-spec leaks dashboard\u002Fadmin routes and shadows\n  a custom `\u002Fopenapi.json` route). Per paid op declare `x-payment-info` with STRUCTURED\n  `price` (`{mode:\"fixed\",currency:\"USD\",amount:\"0.005\"}`) and `protocols:[{\"x402\":{}}]`\n  (array of OBJECTS, not strings), plus `responses[\"402\"]`. Free op -> `security: []`.\n  Add `info.contact.email` (Poncho ownership) and `info.x-guidance` (agent usage text).\n- **405 root cause = paywall fires after method routing.** x402scan probes\n  HEAD\u002FGET\u002FPOST\u002FOPTIONS and a HEAD status-capture; POST-only routes 405 on the others.\n  Fix: match `ROUTE_PRICING` by **PATH only** and return 402 for ANY method on paid\n  routes (see reference for the exact `_PATH_PRICING` snippet). Verified: all methods\n  -> 402 (paid) \u002F 200 (free).\n- **The SAME 405 hits FREE routes too — and the path-only paywall does NOT fix\n  those.** FastAPI 0.139 does not auto-add HEAD to GET routes, so HEAD\u002FOPTIONS on\n  \u002Fhealth, dashboard, admin, \u002Fllms.txt, and free \u002Fx402\u002Fv1 GETs 405. Fix is a\n  SEPARATE outermost ProbeMiddleware (rewrite HEAD->GET, 200+Allow for OPTIONS).\n  See `references\u002Fx402scan-discovery.md` \"CRITICAL FIX #2\" for the code + the two\n  build pitfalls (raw_headers is a list; don't re-inject request._receive).\n- **Local `discover` audit ≠ live crawler.** `npx @agentcash\u002Fdiscovery discover`\n  reads the SPEC (exit 0, zero errors) and does NOT method-probe — a change that\n  405s every live route still passes the CLI. Verify with LIVE curl HEAD\u002FOPTIONS\n  probes after any middleware\u002Frouting change; the user's x402scan error list (405\n  on everything) was only visible from the server-side crawl.\n- **Audit before registering:** `npx -y @agentcash\u002Fdiscovery@latest discover\n  \"https:\u002F\u002Fapi.cortexcloud.org\"` (needs node>=18). Clear L2\u002FL3\u002FL4 warnings; `FAVICON_MISSING`\n  is cosmetic and does NOT block.\n- **Registration IS completable by the agent — no SIWX needed for the base listing.**\n  Verified 2026-08: `https:\u002F\u002Fwww.x402scan.com\u002Fresources\u002Fregister` (and\n  `https:\u002F\u002Fwww.mppscan.com\u002Fregister`) are simple origin forms — type the bare\n  hostname (no `https:\u002F\u002F`), the page live-probes every endpoint for ~20-25s, then\n  the button enables as `Add API (N resources)` (or `0 valid resources` + a\n  per-endpoint error list you must fix first). No wallet\u002FSIWX sign-in was required\n  to list on either registry. Full flow + the \"No valid x402 response found\"\n  amount-type bug + validator-source decoding: `references\u002Fagentcash-registration.md`.\n- **\"No valid x402 response found\" on the registration probe despite a real 402** =\n  check `accepts[].amount` TYPE: the probe validates the live challenge with\n  `PaymentRequiredV2Schema` where `amount` is `z.string().min(1)` — a numeric\n  `20000` fails, `\"20000\"` passes. The earlier \"registration needs SIWX wallet\n  auth\" note was wrong — that session's blocker was a schema-failing challenge,\n  not auth.\n- **x402scan requires an x402 v2 challenge WITH a Bazaar input schema.** This is the\n  #1 cause of \"No valid x402 response found (HTTP 402)\" even when the endpoint already\n  returns 402. The discovery lib runs `@agentcash\u002Fdiscovery`'s\n  `validatePaymentRequiredDetailed(payload)` on the LIVE 402 body; if it returns\n  `summary.errorCount > 0` the endpoint is rejected. Requirements (verified against the\n  npm package source `node_modules\u002F@agentcash\u002Fdiscovery\u002Fdist\u002Findex.js` —\n  `validatePaymentRequiredDetailed` ~line 16530, `PaymentRequiredV2Schema` ~line 16186,\n  `extractSchemas2` for the schema path):\n  - Emit **`x402Version: 2`**. v1 is accepted by the parser but emits a WARN\n    \"v1 not supported by agentcash\"; v2 is what agentcash wants.\n  - `accepts[]` entry MUST carry: `scheme`, `network` (CAIP-2 `eip155:8453`),\n    `asset` (`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`), `amount` (**STRING of\n    atomic USDC**, e.g. `\"5000\"` — v2 uses `amount`, NOT `maxAmountRequired`),\n    `payTo` (wallet), and `maxTimeoutSeconds` (integer, e.g. 60). Missing any → hard error.\n  - `resource` is an **object** `{url, description, mimeType}` in v2 (v1 used a string URL).\n  - **Input schema is MANDATORY** (hard error `SCHEMA_INPUT_MISSING` if absent). v2 path:\n    `extensions.bazaar.schema.properties.input.properties.body` (or `.queryParams`).\n    Output schema path: `extensions.bazaar.schema.properties.output.properties.example`\n    (missing → `SCHEMA_OUTPUT_MISSING`, downgraded to a WARN, so it does NOT block).\n  - Exact verified body + headless validator recipe + issue table:\n    `references\u002Fx402scan-v2-validator.md`.\n- **OpenAPI `x-payment-info.protocols` MUST be `[{\"x402\": {}}]` (array of OBJECTS), NOT\n  `[\"x402\"]` (array of strings).** The string form makes x402scan's audit emit\n  `L2_PROTOCOLS_MISSING_ON_PAID` + `L2_PRICE_MISSING_ON_PAID`. `price` must also be the\n  structured object `{mode:\"fixed\",currency:\"USD\",amount:\"0.005\"}` (not a bare number).\n- **Audit BEFORE registering with the `@agentcash\u002Fdiscovery` CLI (needs node>=18):**\n  `npx -y @agentcash\u002Fdiscovery@latest discover \"https:\u002F\u002Fapi.cortexcloud.org\"` lists\n  routes + L2\u002FL3\u002FL4 warnings; `npx -y @agentcash\u002Fdiscovery@latest check\n  \"https:\u002F\u002Fapi.cortexcloud.org\u002Fx402\u002Fv1\u002Fchat\u002Fcompletions\"` validates the LIVE 402 body via\n  `validatePaymentRequiredDetailed`. A clean run prints `paid  [x402]` with no errors.\n  `FAVICON_MISSING` is cosmetic and does NOT block.\n- Cloudflare Tunnel gotcha: after adding\u002Ffixing a route, Cloudflare may serve a STALE\n  404 (cached pre-fix) — verify with `?cb=1`; a DNS\u002FRead-only API token can't purge it.\n\n## Real paid E2E + on-chain tx proof (first real settlement verified 2026-08-08)\nFull recipe: `references\u002Freal-paid-e2e-tx-proof.md`. Key facts:\n- **On-chain tx-hash retrieval: BaseScan V1 API is deprecated and Etherscan V2\n  refuses Base on the free plan.** The working method is `eth_getLogs` on\n  `https:\u002F\u002Fmainnet.base.org` filtering USDC `Transfer(from=buyer, to=payTo)` (viem\n  snippet in the reference; ~40 min window = `latest - 1200n` at 2s\u002Fblock).\n- `x402_payments` has NO tx-hash column — eth_getLogs is the only on-chain proof\n  link; verify exact atomic amount (`20000` units = $0.02).\n- **Never inline `node -e` through nested ssh quotes** — escaped quotes mangle a\n  hex key and reproduce the \"invalid private key\" error on a VALID file. Write the\n  `.mjs` locally, scp → `pct push` → run by path.\n- Paid `\u002Fv1\u002Foptimize` returns `{job_id, status:\"queued\", price_usd}` → poll\n  `GET \u002Fv1\u002Fjobs\u002F{id}` until terminal; ledger row lands `status=\"settled\"` with the\n  EIP-3009 nonce.\n\n## All-modes paid test harness + money-path bug classes (hit 2026-08-08)\nRecipe + script shapes: `references\u002Fpaid-endpoint-testing.md`. The tests cost real\nUSDC (test buyer wallet → merchant) and found TWO charge-without-value bugs:\n\n- **BUG CLASS — settle happens BEFORE body validation.** In a middleware stack\n  [x402 payment gate → rate limit → input validation], the gate settles (CDP\n  settle + `_record_payment`) before the inner validation rejects a malformed\n  body. Proof: a paid `\u002Fv1\u002Foptimize` with `{mode, problem:{problem_type:\"qubo\"}}`\n  (missing `n`\u002F`data`) got 422 **and still settled $0.05** — ledger had 2 rows for\n  1 successful run. **Fix (one guard, both settle branches):** after parsing the\n  body in the middleware, if the request carries payment credentials\n  (`payment_signature` OR (`mpp and authorization`)), validate the body against the\n  route's input schema FIRST and return 422 before any settle. Verify by running\n  the paid flow with a malformed body → expect 422 AND paid-count unchanged.\n  This applies to MPP (`mpp.charge`) and x402 paths alike — they share the hole.\n- **BUG CLASS — backend auto-routing picks a device that cannot run the job.**\n  Quantum discovery accepted any ONLINE QPU; a paid quantum run charged $0.85 then\n  failed `CreateQuantumTask: Device ...\u002Fquera\u002FAquila supports ['braket.ir.ahs.program']`\n  — Aquila is AHS-only (analog), can't run the QUBO\u002FIsing IR. **Fix:** filter\n  discovered devices by `deviceCapabilities` — require one of\n  `jaqcd`\u002F`annealing`\u002F`openqasm` (gate\u002Fannealing IRs), skip AHS-only devices.\n  General lesson: any solver\u002Fbackend discovery must be **capability-filtered, not\n  just availability-filtered**, and a paid job that fails on a bad route is a\n  charge-without-value bug, not an ops note.\n- **One-off live-execution toggle discipline:** to test a gated path (e.g.\n  `QUANTUM_LIVE_EXECUTION=false` default), add the env to the systemd unit,\n  `daemon-reload` + restart, run the test, REMOVE the env, restart — verify the\n  flag is gone (`systemctl show \u003Cunit> -p Environment`) before reporting done.\n  The margin guard + cost cap stay on during the test (they are the safety net,\n  not the thing being tested).\n- **Test-buyer wallet facts:** `test_buyer.key` (raw 64-hex, no `0x`) on the CT;\n  eth_account derives the address; the x402 Python SDK needs the real import\n  paths (`from x402 import x402Client, prefer_network` \u002F\n  `from x402.http.x402_http_client import x402HTTPClient` \u002F\n  `from x402.mechanisms.evm.exact import ExactEvmScheme` — top-level\n  `from x402 import ExactEvmScheme` raises ImportError).\n- **BUG CLASS #3 — settle happens BEFORE solver-availability is checked.**\n  With the body guard in place, an explicit `mode=quantum` while all QPUs are\n  offline charged $0.85, then the runner failed \"no available solver for\n  requested mode\". **Fix (approved, deployed):** in the SAME money-path guard\n  block, after body validation, call `mode_has_available_solver(mode)` (registry\n  helper: any `for_mode(mode)` solver with `availability().available`) and return\n  `409 {\"error\":\"no available solver for requested mode\",\"mode\":...}` BEFORE any\n  settle — covers x402 and MPP branches (guard sits before `if not\n  payment_signature:`). Live proof: quantum attempt → 409, ledger byte-identical\n  before\u002Fafter. **The money path is only complete with all three guards:**\n  body shape → 422, mode whitelist (`auto|classical|hybrid|quantum`) → 422,\n  solver availability → 409. Any paid path that can fail AFTER settle is a\n  charge-without-value bug.\n- **TEST-ISOLATION LANDMINE — pytest conftest truncating PRODUCTION PG.**\n  A session-scoped `_clean_tables` fixture doing `TRUNCATE x402_payments\n  RESTART IDENTITY CASCADE` against the app's real DATABASE_URL silently wiped\n  real settled-payment rows on every `pytest` run (found when the paid-test\n  ledger went 4 → 0 after a suite run). **Fix (verified):** dedicated\n  `cortexcloud_test` DB — conftest sets `os.environ[\"DATABASE_URL\"]` to\n  `postgresql+asyncpg:\u002F\u002Fpostgres:\u003Cpw>@127.0.0.1:5432\u002Fcortexcloud_test` BEFORE\n  importing app modules (engine binds at import); reads the real password from\n  `.env` (pytest doesn't export it — fallback \"postgres\" silently connects with\n  the wrong password → confusing 44-error walls); a session autouse fixture\n  does `import app.models` FIRST (populates Base.metadata) then\n  `Base.metadata.create_all` via `engine.begin()` + `run_sync`. Create the DB\n  once: `createdb cortexcloud_test`. Prove isolation with a sentinel row in the\n  PROD table → run suite → sentinel must survive; assert \"count unchanged\"\n  (not \"== 0\") in tests since the session-scoped truncate leaves rows from\n  earlier tests.\n- **Monitoring-preference (user): recurring alerts must stay MINIMAL.** The\n  10-min infra watchdog was removed on request — the only accepted recurring\n  CortexCloud alerts are the paid-call watchdog (every 30m, silent-ok) and the\n  weekly GTM funnel report (Mon 09:00). Don't add more cron reminders without\n  asking.\n- **PRICING ARCHITECTURE — one effective price, everywhere (2026-08).**\n  `charged = max(list_price, provider_cost × MARKUP)` must be computed with the\n  REQUEST's variables, and the SAME value must appear in: the 402 challenge\n  amount, the job's `price_usd`, the estimate decision block, and\n  `\u002Fv1\u002Fbackends` effective prices. Classic drift bugs: the optimize route\n  stored the flat LIST price while the middleware charged effective (job showed\n  $0.05, charged $0.85); the 402 challenge used `price_for_mode(mode)` without\n  `n` so size-tier prices never reached the amount. **Fix:** one function\n  `effective_price_usd(mode, provider_cost, n)` (size tiers for classical\u002Fauto:\n  n≤20 $0.05 \u002F ≤200 $0.10 \u002F else $0.25), thread `n` through middleware + route,\n  and make the margin guard + backend decision prices use EFFECTIVE (not list)\n  — otherwise a provider cost above list but below effective passes the guard\n  while the sale is still profitable, and cost bumps silently underprice.\n  Size-tier prices only apply when the request actually carries `n`; without it\n  fall back to the list floor (keeps `\u002Fv1\u002Fbackends` stable).\n- **Pricing honesty for quantum:** cost must be a conservative buffer over the\n  OBSERVED per-run bill (fixed shots → flat cost is valid), not a stale\n  constant; keep `sellable = cost ≤ effective` so ionq-class providers surface\n  at $6.80 with `sellable_at_mode_price=false` instead of silently subsidizing.\n\n## Volume & distribution (making money — the BlockRun playbook)\nA clean x402scan listing alone earns nothing. The top servers (BlockRun 96k tx,\ndTelecom ~$2\u002Fcall voice, Cluster Protocol 685 buyers) win on DISTRIBUTION, not\npricing: an MCP server agents install in one line\n(`claude mcp add \u003Cname> -- npx -y @\u003Corg>\u002Fmcp`), auto-paying via `@x402\u002Ffetch`.\nFunnel instrumentation (landing beacon → referrals table → paid\u002Fwallets\u002Frepeat\nmetrics → weekly report, no fabricated numbers): `references\u002Fgtm-funnel-instrumentation.md`.\n- Ship `templates\u002Fx402-mcp-server-index.ts` (verified: builds, boots, 15 tools,\n  live calls) — copy, swap endpoints\u002Fprices, publish to npm, done.\n- Builder codes (`BuilderCodeClientExtension(\"bc_...\")`, `@x402\u002Fextensions`) are\n  client-side attribution strings — no registration, attach your own code.\n- Verified client stack (packages @2.20.0, 2026-08): `@x402\u002Ffetch`\n  `wrapFetchWithPayment(fetch, client)` auto-handles 402 → sign → facilitator\n  settle → retry. Client = `x402Client().register('eip155:8453',\n  new ExactEvmScheme(viemAccount, { rpcUrl }))` where the signer is a viem\n  `LocalAccount` (`privateKeyToAccount('0x...')`); RPC default\n  `https:\u002F\u002Fmainnet.base.org`. The payment leg CANNOT be end-to-end tested\n  without a wallet funded with USDC — test the free endpoint (e.g. \u002Fmodels)\n  to prove the full MCP path instead. npm publish of the MCP package is\n  headless-BLOCKED by the user's passkey-only 2FA — must publish from his\n  Lenovo (fingerprint) or via iPhone FaceID.\n- Price unique data 5-10x above commodity; keep chat\u002Fembeddings cheap as traffic.\n- Market pricing ground truth (x402 median $0.028\u002Fcall, Braket QPU costs,\n  Gurobi\u002FCPLEX benchmarks, recommended pricing shape):\n  `references\u002Fpricing-market-benchmarks.md`.\n- Full evidence table + resources-page data-extraction recipe:\n  `references\u002Fx402scan-marketplace-volume.md`.\n- **BlockRun deep-dive** (their 92-model registry, x402scan profile showing\n  RESOURCE-level 9-resource registration, 1.05-margin\u002F$0.002-floor pricing\n  formula, ClawRouter 4-tier classifier, Cloud Run stack): \n  `references\u002Fblockrun-competitive-intel.md`.\n- **Beyond x402scan — other x402 marketplaces** (the402.ai, agoragentic.com,\n  orbisapi, hugen.tokyo): registration endpoints, the `\u002Fapi` prefix gotcha,\n  Agora's Agent Trap Shield (human-approval gate on AI-initiated listings),\n  and the402's webhook_url requirement. See\n  `references\u002Fmarketplace-registration.md` + runnable starter\n  `templates\u002Fthe402-onboard.mjs`.\n- **Provider webhooks for marketplaces (the402.ai relay — built + verified):**\n  marketplaces dispatch purchased jobs to YOUR webhook and health-check it.\n  `POST \u002Fx402\u002Fv1\u002Fwebhook` on the gateway: HMAC-SHA256 verify\n  (`sha256=\u003Chex>` of `${timestamp}.${rawBody}`, 5-min replay guard, compare via\n  `hmac.compare_digest`), execute the `brief` with `ModelRouter.route_chat_completion`\n  (same path as paid routes — reuse, don't reimplement; `model_validate(brief)` not\n  `**brief`), deliver to `callback_url` with `X-API-Key`. **Fail closed:** no\n  `THE402_WEBHOOK_SECRET` env → 503; the path-only paywall means unlisted paths are\n  automatically exempt (no exclusion list). Full contract, activation steps, and\n  deploy pitfalls (pct pull writes to HOST \u002Ftmp — stream via `pct exec ... cat`;\n  502 for ~5s after restart) in `references\u002Fthe402-webhook-relay.md`.\n- **openapi.json prices are static and drift**: sync every op's\n  `x-payment-info.price.amount` from `ROUTE_PRICING` in the regen script, then\n  RESTART (the app serves the spec from memory).\n\n## Landing page \u002F storefront (CortexCloud — user's anti-slop rules)\nThe landing page is NOT a build: it is a single static file at\n`\u002Fopt\u002FCortexCloudAPI\u002Fsite\u002Findex.html` served per-request by FastAPI\n(FileResponse at `\u002F`) — edit the file, done. No restart, no build step.\nBackup before replacing (`cp index.html index.html.bak.\u003Ctag>`); the app also\nserves `\u002Fdocs`, `\u002Fopenapi.json`, `\u002Frobots.txt`, `\u002Fsitemap.xml` from the app.\n- **HARD user rules (stated repeatedly):** zero AI slop — no fake\n  live-settlement tables\u002Fstats, no invented testimonials, no fake customer\n  logos, no \"LIVE\" indicators (the site has zero traffic; never fake liveness),\n  no blob\u002Fgradient scroll-animation theater. Real data only: prices from\n  `ROUTE_PRICING`, real wallet address, real links (npm package is\n  `@cortexcloud\u002Fmcp` — the old page linked a wrong `@cortexcloud.org\u002Fmcp`).\n- **Preferred structure (user: \"similar to api.jarvisclaw.ai\"):** light theme;\n  sticky nav → hero (badge, headline with one gradient-accent phrase, sub, 2\n  CTAs, protocol pills `MCP · OpenAI-compatible · x402 · REST`) + dark terminal\n  mock of the 402→pay→200 flow labeled \"example flow\" (NOT live) → numbered\n  5-step pipeline (Agent→Route→Execute→Settle→Receipt) → API category card\n  card grid with REAL endpoint counts + prices → 3-step get started → footer with\n  wallet + builder code. System font stack, single file (~18KB).\n- **Theme toggle + mobile (added 2026-08):** CSS custom properties for the whole\n  palette (`:root[data-theme=\"dark\"]` overrides), a ~10-line pre-paint script in\n  `\u003Chead>` (`localStorage` pref, else `prefers-color-scheme`) to avoid flash, and a\n  ☀️\u002F🌙 button swapping `document.documentElement.dataset.theme`. Mobile ≤900px: pure\n  CSS media queries — hero stacks, pipeline goes vertical with ↓ arrows, cards\n  2-col ≤480px; the nav links collapse into a ☰ hamburger (toggle `.open` class,\n  ~6 lines of JS). Total JS stays ~22 lines, no deps.\n- **Logo\u002Ffavicon swap:** no ImageMagick\u002FPIL on this box — use **ffmpeg** for image\n  work. Crop the emblem from a full lockup, scale to 512 PNG for nav\u002Ffooter and\n  32×32 ICO for favicon: `ffmpeg -i in.jpg -vf \"crop=W:H:X:Y,scale=512:512\" -frames:v 1 out.png`\n  then `ffmpeg -i emblem.png -vf scale=32:32 -frames:v 1 favicon.ico`. Push into the\n  site dir (`\u002Fopt\u002FCortexCloudAPI\u002Fsite\u002F`), update the 2 `\u003Cimg src>` refs (nav +\n  footer), add `border-radius` so a black-background emblem reads as an intentional\n  app-icon tile on the light theme. Keep old assets as `.bak` in site\u002F. The full\n  lockup file can be saved as `logo-full.png` for future OG\u002Fsocial use.\n- **User strips sections aggressively** (removed the pricing table, live\n  widget, and diagram on request) — ship the leanest honest version first; he\n  removes more, rarely adds.\n\n## AgentCash merchant discovery — the merchants.md workflow (discovery hardening)\nGuide of record: `https:\u002F\u002Fagentcash.dev\u002Fmerchants.md` (curl it — the site renders\nJS for some pages, but merchants.md is plain markdown). Decision tree: classify the\nAPI (greenfield \u002F existing \u002F has-x402 \u002F has-MPP \u002F both) and follow the branch. For a\nlive x402 API the branch is \"expand to both protocols + discovery hardening\". Full\nsession detail + exact pympp wiring: `references\u002Fmpp-agentcash-discovery.md`. Key facts:\n- **`npx -y @agentcash\u002Fdiscovery@latest discover \u003Corigin>` = LIVE spec validation.**\n  Clean output (routes + `paid ... [x402]`, no warnings) means the discovery doc is\n  done. **`check \u003Corigin>` is a REGISTRY-side lookup** — it prints \"Not found — no\n  spec data\" for ANY unregistered origin, even a registered one (verified with\n  tryponcho.com). Do NOT chase `check` failures pre-registration.\n- **Legacy flat `x-payment-info` triggers warnings.** `{scheme, network, asset, price,\n  price_atomic_usdc, decimals}` (the old CortexCloud shape) → `L2_PAYMENT_INFO_LEGACY`\n  + `L2_PROTOCOLS_MISSING_ON_PAID`. Canonical shape:\n  `{price: {mode: \"fixed\", currency: \"USD\", amount: \"0.020000\"}, protocols: [{x402: {}}]}`\n  — OpenAPI amount is DECIMAL USD; runtime x402 `accepts[].amount` stays atomic\n  (`0.02` → `\"20000\"`). Keep the legacy keys alongside the canonical ones for\n  backward compat with existing x402scan listings (it parsed the flat fields).\n- **Runtime 402 must fire BEFORE body\u002Fquery validation** (\"Expected 402, got 400\" is\n  a top registration failure). Probe with a garbage body, expect 402 not 400.\n- **`x-discovery.ownershipProofs` format is undocumented** — optional; the validator\n  never flags its absence. Ownership verification happens via `info.contact.email`\n  at registration time. Don't invent a proof format.\n- Registration is browser-completable (no SIWX) — the only \"manual\" part is the\n  user rule: never register without explicit approval; show the listing preview\n  first. Both x402scan and mppscan forms accept a bare hostname and live-probe\n  all endpoints before enabling Add (see references\u002Fagentcash-registration.md).\n\n## MPP (Machine Payments Protocol) via pympp — dual-protocol expansion\nOfficial Python SDK: `pip install \"pympp[tempo]\"` **plus `aiosqlite` separately**\n(the extra does NOT pull it; missing → `No module named 'aiosqlite'` at first use).\nFull verified server wiring, event hooks, and the two-wallet myth:\n`references\u002Fmpp-agentcash-discovery.md`. Key facts:\n- **pympp server needs NO private key.** `recipient` is just the payee ADDRESS\n  (e.g. `settings.WALLET_ADDRESS`); pympp verifies credentials on-chain via Tempo\n  RPC (default `https:\u002F\u002Frpc.tempo.xyz`, chain 4217). `MPP_OPERATOR_KEY`\u002Ffee-payer\n  belong to the Node `@agentcash\u002Frouter` \u002F gas-sponsorship — omit both and clients\n  pay their own gas. The user CANNOT \"give you a key\" because there is none to store.\n- `MPP_SECRET_KEY` is required (HMAC for stateless challenge IDs; `openssl rand -hex\n  32`; persist across restarts — systemd drop-in, since pympp reads os.environ\n  directly, not the app's .env). **realm must be set EXPLICITLY to the public\n  origin** (`realm=\"api.cortexcloud.org\"`) — auto-detect yields `localhost`.\n- Server flow: `mpp = Mpp.create(method=tempo(currency=TEMPO_USDC,\n  intents={\"charge\": ChargeIntent()}, recipient=...), realm=..., secret_key=...,\n  store=await SQLiteStore.create(path))`; then `mpp.charge(authorization=\n  request.headers.get(\"authorization\"), amount=\"0.02\")` returns a `Challenge`\n  (→ 402 + `WWW-Authenticate: ch.to_www_authenticate(realm)`) or\n  `(credential, receipt)` (→ proceed, record `Payment` with `payer=credential.source`).\n- Tempo USDC: `0x20C000000000000000000000b9537d11c60E8b50`, 6 decimals, chain 4217.\n- **Dual-protocol 402**: return BOTH `payment-required` (x402 v2) AND a genuine\n  `WWW-Authenticate` MPP challenge, `x-payment-protocol: \"x402, mpp\"`. Garbage MPP\n  credential → 402 re-challenge (never 500). OpenAPI protocols:\n  `[{x402: {}}, {mpp: {method: \"tempo\", intent: \"charge\", currency: TEMPO_USDC}}]`.\n- Lazy-init the Mpp singleton on first paid request (logs `MPP enabled: realm=...`)\n  so missing config degrades to x402-only, not a boot failure.\n- **Gitignore the replay store file** (`mpp-store.sqlite`) — it's runtime state, a\n  `git add -A` WILL capture it.\n- Paid MPP E2E needs REAL Tempo USDC — verify challenge format + rejection paths\n  (garbage credential → 402) instead; say so honestly.\n\n## Adding new x402-gated endpoints (verified process)\nWhen adding new payment-gated endpoints to an x402 gateway:\n\n1. **Implement the endpoint handler** in the appropriate route file:\n   - Include proper input\u002Foutput schemas for BAZAR discovery (required to avoid SCHEMA_INPUT_MISSING)\n   - Handle request\u002Fresponse formatting according to the upstream API specification\n   - Add proper error handling and logging\n   - For dynamic pricing (chat\u002Fresponses, embeddings, image generation), extract parameters from request body to calculate correct x402 challenge\n\n2. **Update pricing configuration**:\n   - Add route\u002Fmethod to `ROUTE_PRICING` with the appropriate USD price string (e.g., `\"POST \u002Fx402\u002Fv1\u002Fsearch\": \"$0.015\"`)\n   - Add descriptive text to `ROUTE_DESCRIPTIONS` for the x402 challenge\n   - Ensure the `usd_to_usdc_atomic` helper function is present for converting prices\n\n3. **Register the route** in the main application:\n   - Import the router in the x402-enabled section\n   - Add `app.include_router(new_router, prefix=\"\u002Fx402\u002Fv1\", tags=[\"x402 Feature Name\"])`\n   - Ensure the import is inside the x402-enabled conditional block\n\n4. **Update OpenAPI specification**:\n   - Add the new endpoint under `paths` with proper `operationId`, `summary`, `description`\n   - Include `x-payment-info` with structured price (`{mode: \"fixed\", currency: \"USD\", amount: \"0.015\"}`) and `protocols: [{\"x402\": {}}]`\n   - Add `requestBody` schema with required fields marked as `\"required\": true`\n   - Add `responses` with both `200` (after payment) and `402` (payment required) responses\n   - For GET endpoints with query parameters, ensure required parameters are marked as `\"required\": true` in the schema\n\n5. **Set x402 environment variables** (if not already configured):\n   - Configure `X402_ENABLED=true` and `WALLET_ADDRESS=\u003Cyour_address>`\n   - Reload service configuration and restart the service\n\n6. **Restart the service** and verify it's active\n\n7. **Test the endpoint**:\n   - Verify it returns HTTP 402 with the v2 challenge in the JSON body AND the\n     `payment-required` base64 header. WWW-Authenticate is fine ONLY when it\n     carries a REAL MPP challenge (pympp `Challenge.to_www_authenticate(realm)`)\n     — a bare\u002Fempty WWW-Authenticate trips the audit's unconditional MPP check;\n     a genuine one validates clean and is required for MPP agents (verified\n     2026-08: `discover` clean with `x-payment-protocol: x402, mpp`)\n   - Verify it processes requests correctly when valid payment headers are provided (returns 200 with actual data)\n   - Check that the OpenAPI spec includes the new endpoint with correct x402 payment info\n   - Use `curl -v` to inspect headers and response body\n\n8. **Update documentation** (if applicable):\n   - Ensure the endpoint appears in the public-facing documentation\n   - Verify x402scan can discover and validate the endpoint\n\n### Dynamic pricing implementation details\nFor endpoints requiring dynamic pricing based on request parameters:\n\n**Chat\u002FResponses (`\u002Fx402\u002Fv1\u002Fchat\u002Fcompletions`, `\u002Fx402\u002Fv1\u002Fresponses`)**:\n- Extract `model` from request body\n- Look up model's input\u002Foutput cost per 1k tokens from model registry\n- Calculate base cost: (input_cost_per_1k + output_cost_per_1k) for standard token amounts (typically 1000 each)\n- Apply markup (typically 27.5% as midpoint of 25-30% range)\n- Format as 6-decimal dollar string for x402 challenge\n- Fall back to static price if model unknown or error occurs\n- Preserve request body after reading for downstream handlers\n\n**Image Generation (`\u002Fx402\u002Fv1\u002Fimages\u002Fgenerations`)**:\n- Extract `n` (number of images) from request body\n- Pricing: $0.04 per image for n=1, or $0.035 × n for n>1 (batch discount)\n- Total price = n × price_per_image\n- Fall back to static price if parsing fails\n\n**All other routes**: Use static pricing from `ROUTE_PRICING`\n\n### Verification steps for new endpoints\n1. Request without payment headers → examine 402 challenge amount (should match calculated\u002Fstatic price)\n2. Request with known parameters → verify amount matches expected calculation\n3. Request with unknown\u002Finvalid parameters → should fall back to static price\n4. After successful payment, verify endpoint returns expected data\n5. Confirm OpenAPI spec shows correct pricing and schemas\n\n### Dynamic pricing implementation details\nFor endpoints requiring dynamic pricing based on request parameters:\n\n**Chat\u002FResponses (`\u002Fx402\u002Fv1\u002Fchat\u002Fcompletions`, `\u002Fx402\u002Fv1\u002Fresponses`)**:\n- Extract `model` from request body\n- Look up model's input\u002Foutput cost per 1k tokens from model registry\n- Calculate base cost: (input_cost_per_1k + output_cost_per_1k) for standard token amounts (typically 1000 each)\n- Apply markup (typically 27.5% as midpoint of 25-30% range)\n- Format as 6-decimal dollar string for x402 challenge\n- Fall back to static price if model unknown or error occurs\n- Preserve request body after reading for downstream handlers\n\n**Image Generation (`\u002Fx402\u002Fv1\u002Fimages\u002Fgenerations`)**:\n- Extract `n` (number of images) from request body\n- Pricing: $0.04 per image for n=1, or $0.035 × n for n>1 (batch discount)\n- Total price = n × price_per_image\n- Fall back to static price if parsing fails\n\n**All other routes**: Use static pricing from `ROUTE_PRICING`\n\n### Verification steps for new endpoints\n1. Request without payment headers → examine 402 challenge amount (should match calculated\u002Fstatic price)\n2. Request with known parameters → verify amount matches expected calculation\n3. Request with unknown\u002Finvalid parameters → should fall back to static price\n4. After successful payment, verify endpoint returns expected data\n5. Confirm OpenAPI spec shows correct pricing and schemas\n",{},"main","38b32c99e7ed0b8e215d638e92cfa452c1ec3079","skills\u002Fimported\u002Fmlops\u002Fx402-pay-per-call-gateway","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS","https:\u002F\u002Fgithub.com\u002Fjonahthan433","AI Consultant","2026-10-24 05:13:39",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add jonahthan433\u002FCortexOS --skill x402-pay-per-call-gateway",{"tool":35,"command":36},"bunx","bunx skills add jonahthan433\u002FCortexOS --skill x402-pay-per-call-gateway",{"tool":38,"command":39},"pnpm","pnpm dlx skills add jonahthan433\u002FCortexOS --skill x402-pay-per-call-gateway","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fx402-pay-per-call-gateway\u002FSKILL.md",true,[43],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"skill.json","REFERENCE","参考文档",597,"https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fx402-pay-per-call-gateway\u002Fskill.json",[50,56,62,68,74,80],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M7EDQZDQX3Q8Y7GCQX6KN9V7","opportunity-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fsales\u002Fopportunity-brief\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M7EDQYA0V9Y99VKBREJJ3MRT","morning-intel","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fmorning-intel\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7EDQVX1JVY0B6PDHKKGM19G","decision-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fdecision-brief\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M7EDQV1GENZAC2SZSD8KZ3GM","weekly-review","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fproductivity\u002Fweekly-review\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M7EDQT2KETJ1Y3CGVN9EKW2J","system-health","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fsystem-health\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M7EDQQN2JK3XPWMS1M4T0F3K","backup-restore","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fbackup-restore\u002FSKILL.md",[],[]]