Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
docs(aws): update the agent payment sessions doc for the builder center submission
nirholas39c7188da9d1
diff --git a/docs/aws-builder-center-agent-payment-sessions.md b/docs/aws-builder-center-agent-payment-sessions.mdindex 5b0032680..413dbca7f 100644--- a/docs/aws-builder-center-agent-payment-sessions.md+++ b/docs/aws-builder-center-agent-payment-sessions.md@@ -55,9 +55,9 @@ A private key fuses all three into one secret. Split them apart and the design glogs everything```-The developer creates a session: a budget envelope with a total, a per-transaction ceiling, a host allowlist, a network, and an expiry. In return they get a bearer token, once.+The developer creates a session: a budget envelope with a total, a per-transaction ceiling, a host allowlist and denylist, an optional approval threshold, an optional rolling daily cap per rail, a network, and an expiry. In return they get a bearer token, once.-They hand that token to the agent. The agent can now call paid endpoints. It cannot exceed the budget, cannot pay a host outside the allowlist, cannot spend after the expiry, and cannot sign anything itself, because the platform's wallet does the signing and the agent never sees a key.+They hand that token to the agent. The agent can now call paid endpoints. It cannot exceed the budget, cannot pay a host outside the allowlist (or on the denylist), cannot spend after the expiry, cannot push a single payment over the approval threshold without the owner saying yes, and cannot sign anything itself, because the platform's wallet does the signing and the agent never sees a key.Custody sits with the platform. Authority sits with the developer. Execution sits with the agent. Compromising the agent gets an attacker exactly one thing: the remaining budget, spendable only at hosts you already approved, only until the session expires.@@ -65,7 +65,7 @@ That is not zero. It is a number you chose in advance, which is the entire point## The data model-Two tables. The session is the policy plus the counter, and the execution log is the immutable audit trail.+Two core tables (plus a small reservation table that backs the rolling per-rail cap). The session is the policy plus the counter, and the execution log is the immutable audit trail. The `CREATE TABLE` below is abridged to the policy columns.```sqlcreate table if not exists payment_sessions (@@ -78,6 +78,9 @@ create table if not exists payment_sessions (spent_usdc bigint not null default 0 check (spent_usdc >= 0),max_per_tx_usdc bigint check (max_per_tx_usdc > 0),allowed_hosts text[] not null default '{}',+ blocked_hosts text[] not null default '{}',+ approval_threshold_usdc bigint check (approval_threshold_usdc > 0),+ per_rail_daily_usdc jsonb not null default '{}'::jsonb,network text not null default 'solana' check (network in ('solana', 'base')),connector_ref text,@@ -178,7 +181,7 @@ Small thing, easy to skip, and it matters: an agent should not burn budget disco### Phase 2: the governor-Now the policy runs, in order, cheapest and most decisive first: status, then expiry, then the allowlist, then the per-transaction ceiling, then the budget.+Now the policy runs, in order, cheapest and most decisive first: status, then expiry, then the allowlist, then the denylist (an explicit block always beats a broad allow), then the per-transaction ceiling, then the rolling per-rail daily cap, then the budget, and last the approval threshold. A call over the threshold is not rejected: it is parked in the owner's approval inbox and the agent gets a `202` with a poll link, then the exact same reserve-and-settle path resumes if the owner approves.The allowlist check is the one worth showing, because the subdomain rule is where these go wrong:@@ -198,7 +201,7 @@ The verdict is then `canonical.some((entry) => hostMatches(targetHost, entry))`.`targetHost.endsWith('.' + entry)` and not `targetHost.endsWith(entry)`. Without the dot, an allowlist entry of `example.com` also authorizes `evil-example.com`, and an attacker who can steer your agent to a URL just needs to register the right domain. That is exactly why this is a named function with a test behind it rather than an inline `endsWith`. Hosts are normalized through the URL parser first, so `HTTPS://Example.COM:443/x` and `example.com` compare equal.-These predicates live in [`api/_lib/pay/policy.js`](https://github.com/nirholas/three.ws/blob/main/api/_lib/pay/policy.js) and are shared with the dry-run simulator, so a simulated verdict and an enforced one can never disagree.+These predicates live in [`api/_lib/pay/policy.js`](https://github.com/nirholas/three.ws/blob/main/api/_lib/pay/policy.js) and are chained by one `evaluateCall()` that the dry-run simulator calls too, so a simulated verdict and an enforced one can never disagree. Every verdict, allow or deny, also carries a policy digest and an HMAC signature (keyed by `PAY_VERDICT_HMAC_KEY`, separate from the token secret) stored with its execution row, so a verdict cannot be edited after the fact without breaking the signature.### Phase 3: the atomic reservation@@ -242,17 +245,18 @@ if (!updated) {const remaining = fresh ? BigInt(fresh.budget_usdc) - BigInt(fresh.spent_usdc) : 0n;// The SQL predicate already decided; budgetVerdict only phrases the failure,// using the same wording the simulator shows for a predicted shortfall.- throwVerdict(+ throwSigned(budgetVerdict(amount, remaining) ?? {code: 'insufficient_budget',message: 'Session was not active when the payment was reserved',detail: { need_usd: atomicsToUsd(amount), remaining_usd: atomicsToUsd(remaining) },},+ { policyDigest, requestHash, timestamp },);}```-`throwVerdict` raises a `SpendGovernorError` carrying the machine-readable `code` the API layer maps to a status (`insufficient_budget` becomes a `402`).+`throwSigned` raises a `SpendGovernorError` carrying the machine-readable `code` the API layer maps to a status (`insufficient_budget` becomes a `402`) plus the signed verdict. When a per-rail daily cap is set, a rolling-window reservation is taken first in its own advisory-locked statement and released if this `UPDATE` then loses the race.No advisory locks, no transaction retry loop, no distributed lock service. One statement whose `WHERE` clause is the invariant. If you take one thing from this article, take this: **write the budget check as a predicate in the `UPDATE`, not as a `SELECT` before it.**@@ -280,17 +284,21 @@ This is the section most write-ups skip, and it is the one that decides whetherA payment has three possible outcomes, not two, and the third is the interesting one.-**Rejected before settlement.** The service answers `402` again. No funds moved, so the reservation is safe to release and the budget goes back:+**Rejected after signing.** The service answers `402` again. It is tempting to read that as "no funds moved" and release the reservation. We used to, and it was wrong: the signed transfer was already handed to the host, and a host that is also the fee payer can co-sign and broadcast it, then answer `402`. So the reservation stays spent and the failed execution is recorded:```jsif (paid.status === 402) {- await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});+ // The signed transfer was already handed to the host. A host that is also+ // the fee payer can co-sign and broadcast it, then answer 402, so a 402+ // is not proof nothing landed: the reservation stays spent.// ... record the failed execution ...- return error(res, 402, 'payment_rejected',- 'Service rejected the payment before settlement. Budget has been restored.');+ return { ok: false, status: 402, code: 'payment_rejected',+ message: 'Service answered 402 after the signed payment was submitted. The budget stays reserved because the transfer may still land.' };}```+The release path (`rollbackReservation`, which also frees the rail-daily reservation) is reserved for failures that happen before anything is signed.+**Settled.** Log the tx hash, return the result, done.**Unknown.** The request was submitted and the connection died before an answer came back. The transaction may have landed on-chain. It may not have. We cannot know from here.@@ -379,6 +387,7 @@ Create a session with the policy you are willing to live with:"expiry_seconds": 86400,"max_per_tx_usd": 0.50,"allowed_hosts": ["api.example.com", "data.provider.io"],+ "approval_threshold_usd": 0.25,"network": "solana"}```diff --git a/docs/ops/llm-lanes.md b/docs/ops/llm-lanes.mdindex 51661a0d5..731238942 100644--- a/docs/ops/llm-lanes.md+++ b/docs/ops/llm-lanes.md@@ -23,8 +23,8 @@ production are routinely dead and a chain that depends on them fails:| 1b | Groq `openai/gpt-oss-120b` | `GROQ_API_KEY` | free | **serving** (200, ~1.4s, 2026-09-04). Added 2026-09-04. Same key, separate 8,000 tok/min bucket, because Groq meters per model id. || 2 | Cerebras `llama-3.3-70b` | `CEREBRAS_API_KEY` | free | not configured in prod || 3 | OpenRouter `:free` routes, one rung per key | `OPENROUTER_API_KEY`, `OPENROUTER_FALLBACK_KEYS` | free | **model id was dead 2026-09-04**: `openai/gpt-oss-20b:free` was retired and 404'd all five rungs at once (fixed, now `google/gemma-4-31b-it:free`). The account is separately capped at 1,000 free-model requests/DAY across every key (they share one owner), and was at 0 remaining when measured. |-| 4 | NVIDIA NIM `nvidia/nemotron-3-super-120b-a12b` | `NVIDIA_API_KEY` | free | **serving** (200, 1.8s-10.5s on a full-size prompt, 2026-09-04). Carried the whole platform on 2026-09-04 when Groq was token-capped, OpenRouter was dead, and both paid anchors were on billing holds. |-| 4b | NVIDIA NIM `nvidia/nemotron-3-ultra-550b-a55b` | `NVIDIA_API_KEY` | free | **serving** (200, 1.8s through `llmComplete`, 2026-10-08). Added 2026-10-08. A separate NIM function on the same key, so it survives the Super function being throttled, queued, or retired. |+| 4 | NVIDIA NIM `nvidia/nemotron-3-super-120b-a12b` | `NVIDIA_API_KEY` (+ `NVIDIA_FALLBACK_KEYS`, one rung each) | free | **retired upstream 2026-10-24**: NVIDIA stopped serving the Super function while still listing it, so it answers 404 (it served 200 in 1.8s-10.5s on 2026-09-04, when it carried the whole platform with Groq token-capped, OpenRouter dead and both paid anchors on billing holds). It is still pinned in `llm.js`, so the chain attempts it and falls through to 4b. Chat, the tool chain, `/brain` and the CAD and anatomy writers no longer default to it: `PROVIDER_MODEL_DEFAULTS.nvidia` is now the Lightning model (14b), with Ultra (4b) as its fallback. |+| 4b | NVIDIA NIM `nvidia/nemotron-3-ultra-550b-a55b` | `NVIDIA_API_KEY` | free | **serving** (200, 1.8s through `llmComplete`, 2026-10-08). Added 2026-10-08. A separate NIM function on the same key, so it survives the Super function being throttled, queued, or retired (which is what happened on 2026-10-24). || 5 | SambaNova `Meta-Llama-3.3-70B-Instruct` | `SAMBANOVA_API_KEY` | free | added 2026-08-05; skipped when the key is unset || 6 | Mistral `mistral-small-latest` (Experiment tier) | `MISTRAL_API_KEY` | free | added 2026-08-05; skipped when the key is unset || 7 | Z.AI `glm-4.7-flash` | `ZAI_API_KEY` | free | added 2026-08-05; skipped when the key is unset |@@ -43,7 +43,7 @@ production are routinely dead and a chain that depends on them fails:| 17 | Anthropic first-party | `ANTHROPIC_API_KEY` | paid | **absent** (no key anywhere) || 18 | OpenRouter Claude mirror | `OPENROUTER_CLAUDE_MIRROR_MODEL` | paid | off by default (see below) || 19 | OpenAI `gpt-5.4-nano` | `OPENAI_API_KEY` | paid | **dead**: 429 `billing_not_active` |-| 20 | xAI Grok `grok-4.3`, reasoning off (`GROK_BUDGET_MODEL`) | `GROK_API_KEY` (or `XAI_API_KEY`) | paid | not configured in prod: no key in `.env`, `.env.local`, the `three-ws-api` service, or Secret Manager (checked 2026-10-11). A caller's own xAI key leads the chain instead, on `grok-4.7` unless they name a model. See [Grok model ids](#grok-model-ids). The same key, once set, also lights up a second rung of a different chain: X search for the Sentiment Scout fails over to xAI's `x_search` tool when the X bearer rung cannot answer (`searchMintPostsViaXai` in `api/_lib/x-search.js`, documented in [docs/sentiment-scout.md](../sentiment-scout.md#x-search-budget)). |+| 20 | xAI Grok `grok-4.3`, reasoning off (`GROK_BUDGET_MODEL`) | `GROK_API_KEY` (or `XAI_API_KEY`) | paid | not configured in prod: no key in `.env`, `.env.local`, the `three-ws-api` service, or Secret Manager (checked 2026-10-11). A caller's own xAI key leads the chain instead, on `grok-4.7` unless they name a model; an agent whose owner saved a Grok key at `/api/user/provider-keys` bills that key for every visitor's turn (`api/_lib/agent-grok-key.js`), with the platform rung as the fallback. See [Grok model ids](#grok-model-ids). The same key, once set, also lights up a second rung of a different chain: X search for the Sentiment Scout fails over to xAI's `x_search` tool when the X bearer rung cannot answer (`searchMintPostsViaXai` in `api/_lib/x-search.js`, documented in [docs/sentiment-scout.md](../sentiment-scout.md#x-search-budget)). |The 2026-08-05 widening (SambaNova, Mistral, Z.AI, Cloudflare, LLM7,SiliconFlow) added six independent free quota pools; each is documented with@@ -64,6 +64,12 @@ requires the next rung to answer. A fallback that only catches a parse error isbypassed exactly when the provider fails, which is the defect class that testexists to prevent.+Every OpenRouter request, on any rung or surface, spreads the one shared+`OPENROUTER_ATTRIBUTION_HEADERS` constant (`api/_lib/openrouter-attribution.js`:+`HTTP-Referer`, `X-Title`, `X-OpenRouter-Title`) so all of it counts toward+three.ws's OpenRouter app page. Add new OpenRouter call sites the same way+instead of inlining header values.+`/brain` (`api/brain/chat.js`) runs its own chain with the same shape: requestedmodel → OpenRouter mirror of that model → free safety net (Groq → OpenRouter`:free` per key → NVIDIA → SambaNova → Mistral → Z.AI) → the Vertex Gemini@@ -191,6 +197,12 @@ How it works now:- The one unmetered `/brain` lane is watsonx. IBM bills its trial entitlementoutside per-token pricing, so there is no honest per-call number to record.+Wallet-paid inference is a separate path with its own price table, not a chain+rung: an unauthenticated `POST /api/v1/chat/completions` answers 402 with a Solana+x402 `upto` offer, escrows the cap, and settles measured tokens times the published+price (`api/_lib/metered-router.js`, prices in `api/_lib/pricing/inference-models.js`,+served by `GET /api/v1/models`). See [metered-router.md](../metered-router.md).+### The check```sh@@ -343,6 +355,7 @@ them:- [gcp-credits.md](gcp-credits.md): the credit program, the Vertex lanes, andthe revert runbook.- [gcp-production.md](gcp-production.md): the full production runbook.+- [metered-router.md](../metered-router.md): pay-per-request access over x402 `upto`.- `api/_lib/llm.js`: the chain itself, with the policy comment at the top.- `api/_lib/chat-models.js`: the model catalog, capability flags, and`isPaidModel()`; `GROK_MODELS` is the only place a Grok id is written.diff --git a/docs/page-performance.md b/docs/page-performance.mdindex 8296422b3..3a792d032 100644--- a/docs/page-performance.md+++ b/docs/page-performance.md@@ -94,14 +94,18 @@ node scripts/render-glb-poster.mjs public/avatars/default.glb public/avatars/defThat poster is 15 KB against a 748 KB model.-The same reasoning applies to the model-viewer bundle itself. It is 955 KB, and-a page whose landing state has no 3D on screen should not parse it on arrival:-that alone was `/forge`'s 1.5 s First Contentful Paint. Use+The same reasoning applies to the model-viewer bundle itself. It is close to a+megabyte, and a page whose landing state has no 3D on screen should not parse it+on arrival: that alone was `/forge`'s 1.5 s First Contentful Paint. Use[`src/shared/model-viewer-loader.js`](../src/shared/model-viewer-loader.js)-(`ensureModelViewer` / `ensureModelViewerOrFallback`, with CDN failover) at the-moment the page actually needs a viewer. Keep `/model-viewer-meshopt.js` as a-plain deferred script: it has to register the Meshopt decoder before any viewer-starts loading, and nearly every three.ws GLB is meshopt-compressed.+(`ensureModelViewer` / `ensureModelViewerOrFallback`) at the moment the page+actually needs a viewer. It pins one version (4.4.0) and races three CDNs+(jsDelivr, cdnjs, unpkg), abandoning a host after 12 s, and it registers the+Meshopt decoder (`/vendor/meshopt_decoder.js`) as the element is defined. Pages+that load model-viewer with a plain `<script>` tag instead must keep+`/model-viewer-meshopt.js` ahead of it as a plain script: it has to register the+decoder before any viewer starts loading, and nearly every three.ws GLB is+meshopt-compressed.## 3. Anything that arrives late needs its box reserved first