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
feat: enhance Forge and Regen provider handling
qrqk4e30c5eb9d78
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e151be034..c8c505058 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Club Social Activity — the platform tracks its own nightlife economy on-chain** — The autonomous loop now pays /api/x402/analytics every 30 minutes with { report: "clubs", period: "24h" } for a live snapshot of the Pole Club's social economy. The report reads straight from the real ledgers — settled tips (club_tips), the stage roster (club_dancer_wallets) and settled door cover charges (x402_audit_log) — and returns how many stages are active, how many distinct patrons showed up, the tip count and USDC volume, the cover charges collected at the door, and a fastest-growing-stage leaderboard. Every snapshot is appended to a club_social_analytics time series so a dashboard can chart whether the nightlife is heating up or cooling down and spot which stages are on the rise. `[feature, infra]`- **Forge Content Health — the platform canaries its own generation engine every 10 minutes** — Every 3D generation the Forge produces begins by running a prompt through the platform's generative AI lane, so if that lane slows down or goes dark, creations stall before a mesh is ever built. The platform now watches for this automatically. Every ten minutes an autonomous agent makes a real on-chain payment to a new lightweight health_check mode on /api/x402/forge, which runs one fast text completion over the same free-first model chain Forge depends on — no expensive 3D reconstruction — and reports back whether content was generated, how long it took, and the token count. A completion slower than five seconds, or an outright generator outage, raises a Forge performance alert that an on-call dashboard reads in a single lookup and that clears itself once generation is healthy again. The new health_check mode is also available to any x402 agent on the bazaar for a fraction of a cent, far cheaper than a full generation, for callers that just want to confirm the engine is live. `[infra, feature]`- **Forge Image Generation Canary — the platform validates its own image pipeline every 5 minutes** — Every Forge job that reconstructs a 3D mesh starts with a text-to-image call. If the image provider chain is down or hung, every paid Forge generation silently fails — before users even hit the paywall. The platform now detects this automatically. Every five minutes an autonomous agent makes a real on-chain $0.001 USDC payment to /api/x402/forge with body { mode: "health_check", type: "image", prompt: "A simple blue circle." }. The endpoint runs one real text-to-image call through the free-first provider chain (NIM FLUX → Vertex Imagen → Replicate backstop) and uploads the result to R2 CDN — proving the full image generation and CDN upload path end-to-end. The extracted signal { generated, url, latency_ms } lands in x402_autonomous_log.signal_data. When generation fails or latency exceeds 30 seconds, a Redis alert (x402:forge-image-health:alert) is raised so ops can investigate before users see broken generations. The image alert key is separate from the existing text LLM canary alert so both lanes can degrade independently. `[infra, feature]`+- **Forge no longer dead-ends on "Generator not configured" when a free lane is live** — When the free NVIDIA text→3D lane was briefly down, Forge could return "Generator not configured" even on deployments where the free Hugging Face lane was fully set up — because the degrade step looked for a paid Replicate key that wasn't required. Forge now falls through to whichever free engine is configured (Hugging Face Spaces) instead of stopping, so a single free key keeps text and photo generation working through upstream blips. (`/forge`) `[fix]`- **LLM Proxy Latency Benchmark — p95 alerting when inference exceeds 3 seconds** — The autonomous loop now benchmarks LLM inference latency every 10 minutes by making a real $0.005 USDC x402 payment to /api/x402/llm-proxy with a minimal 'Count to 3.' prompt. Each run records { latency_ms, tokens_used, model, provider } to x402_autonomous_log. After 3+ samples accumulate, the platform computes rolling p95 latency from the last 20 successful calls and raises a Redis alert (x402:llm-proxy-latency:p95-alert) when p95 exceeds 3 seconds — giving ops a heads-up on provider degradation before end users notice slow AI responses. `[infra, feature]`- **LLM Proxy Output Quality Probe — the platform verifies its own AI inference returns correct answers** — Every agent that calls /api/x402/llm-proxy pays for a completion it trusts to be correct. Silent LLM degradation — garbled output, hallucinated answers, truncated responses — is invisible without a correctness check. The platform now catches this automatically. Every ten minutes an autonomous agent makes a real on-chain $0.005 USDC payment to /api/x402/llm-proxy with body { model: "reasoning", prompt: "What is 7 + 8? Reply with only the number.", max_tokens: 5 }. The extracted signal { output, correct, provider, latency_ms } lands in x402_autonomous_log.signal_data. When the response is anything other than "15", a Redis alert (x402:llm-proxy:quality-alert) is raised immediately so ops can investigate model degradation before downstream agents experience silent failures. `[infra, feature]`- **Marketplace Catalog Stats — live listing count, pricing, and engagement via x402** — The autonomous loop now pays /api/x402/analytics every 5 minutes with { report: "marketplace", period: "7d" } to confirm the public agent marketplace is alive and measure its health. The report returns the total active listing count split into priced vs free, the price distribution normalised to both USD and SOL at the live Jupiter rate, the count of new listings in the selected window, and the most-viewed and most-forked listing by ID and name. The extracted signal — listing_count, avg_price_sol, most_viewed_id — is recorded to x402_autonomous_log so a health dashboard can read marketplace vitals without querying the catalog tables directly. A listing_count of 0 trips an ops alert within one 5-minute window; a null avg_price_sol flags a SOL oracle outage. `[feature, infra]`diff --git a/api/_lib/regen-provider.js b/api/_lib/regen-provider.jsindex 515998b43..368002bb5 100644--- a/api/_lib/regen-provider.js+++ b/api/_lib/regen-provider.js@@ -155,11 +155,36 @@ export function getRegenProviderByName(name, key) {}}-let _regenProviderCache = null;-let _regenProviderName = null;+// Per-process provider instances, keyed by canonical name. A Map (not a single+// slot) so the failover path can hold several platform providers live at once+// without thrashing the cache between them.+const _platformProviderCache = new Map();++// Canonical platform provider names in paid → free precedence. Used both to+// resolve the single primary and to enumerate failover candidates.+const PLATFORM_PROVIDER_ORDER = Object.freeze(['replicate', 'gcp', 'huggingface']);++function canonicalProviderName(name) {+ const n = (name || '').trim().toLowerCase();+ return n === 'hf' ? 'huggingface' : n;+}++// True when the named platform provider has its required credentials present.+function platformProviderConfigured(name) {+ switch (canonicalProviderName(name)) {+ case 'replicate':+ return Boolean(process.env.REPLICATE_API_TOKEN);+ case 'gcp':+ return Boolean(process.env.GCP_RECONSTRUCTION_URL);+ case 'huggingface':+ return Boolean(process.env.HF_TOKEN);+ default:+ return false;+ }+}export function resolveProviderName() {- const explicit = (process.env.AVATAR_REGEN_PROVIDER || '').trim().toLowerCase();+ const explicit = canonicalProviderName(process.env.AVATAR_REGEN_PROVIDER);if (explicit) return explicit;// Auto-detect order is paid → free: prefer Replicate's pinned-version// reliability, then our own GCP Cloud Run service, then the HF Spaces queue@@ -170,34 +195,69 @@ export function resolveProviderName() {return 'none';}-export async function getRegenProvider() {- const name = resolveProviderName();- if (name === 'none' || !name) return { name, instance: null };- if (_regenProviderCache && _regenProviderName === name) {- return { name, instance: _regenProviderCache };+// Load (and cache) a single named platform provider instance. Dynamic-imports+// the adapter so an unused provider's SDK never loads. Throws with a classified+// code for an unknown name; provider constructors themselves throw when their+// credentials are missing.+async function loadPlatformProvider(rawName) {+ const name = canonicalProviderName(rawName);+ if (name === 'none' || !name) return { name: 'none', instance: null };+ if (_platformProviderCache.has(name)) {+ return { name, instance: _platformProviderCache.get(name) };}+ let instance;if (name === 'replicate') {- const mod = await import('../_providers/replicate.js');- _regenProviderCache = mod.createRegenProvider();- _regenProviderName = name;- return { name, instance: _regenProviderCache };- }- if (name === 'huggingface' || name === 'hf') {- const mod = await import('../_providers/huggingface.js');- _regenProviderCache = mod.createRegenProvider();- _regenProviderName = name;- return { name, instance: _regenProviderCache };+ instance = (await import('../_providers/replicate.js')).createRegenProvider();+ } else if (name === 'huggingface') {+ instance = (await import('../_providers/huggingface.js')).createRegenProvider();+ } else if (name === 'gcp') {+ instance = (await import('../_providers/gcp.js')).createRegenProvider();+ } else {+ throw Object.assign(new Error(`unknown AVATAR_REGEN_PROVIDER: ${name}`), {+ code: 'regen_provider_unknown',+ status: 501,+ });}- if (name === 'gcp') {- const mod = await import('../_providers/gcp.js');- _regenProviderCache = mod.createRegenProvider();- _regenProviderName = name;- return { name, instance: _regenProviderCache };+ _platformProviderCache.set(name, instance);+ return { name, instance };+}++export async function getRegenProvider() {+ const name = resolveProviderName();+ if (name === 'none' || !name) return { name, instance: null };+ return loadPlatformProvider(name);+}++// Enumerate every configured platform provider in priority order so the submit+// path can fail over from one to the next. The explicit AVATAR_REGEN_PROVIDER+// (if set and credentialed) leads; the credential-inferred order fills in the+// rest, de-duplicated. A provider whose constructor throws (bad config) is+// logged and skipped rather than blocking the others. Returns [] when nothing+// is configured.+export async function getRegenProviderCandidates() {+ const order = [];+ const seen = new Set();+ const push = (rawName) => {+ const name = canonicalProviderName(rawName);+ if (name && name !== 'none' && !seen.has(name) && platformProviderConfigured(name)) {+ seen.add(name);+ order.push(name);+ }+ };++ push(process.env.AVATAR_REGEN_PROVIDER);+ for (const name of PLATFORM_PROVIDER_ORDER) push(name);++ const out = [];+ for (const name of order) {+ try {+ const resolved = await loadPlatformProvider(name);+ if (resolved.instance) out.push(resolved);+ } catch (err) {+ console.warn('[regen] platform provider load failed:', name, '—', err?.message);+ }}- throw Object.assign(new Error(`unknown AVATAR_REGEN_PROVIDER: ${name}`), {- code: 'regen_provider_unknown',- status: 501,- });+ return out;}// Resolve the provider for a job that's already in flight, routing by thediff --git a/api/_lib/token/price.js b/api/_lib/token/price.jsindex cc903957b..f1d187f89 100644--- a/api/_lib/token/price.js+++ b/api/_lib/token/price.js@@ -14,6 +14,17 @@ import { TOKEN_MINT, TOKEN_DECIMALS, ATOMICS_PER_TOKEN } from './config.js';const PRICE_TTL_S = 30;const PRICE_CACHE_KEY = `token:price:${TOKEN_MINT}`;+// Last-known-good price, held far longer than the live cache. When EVERY feed+// (Jupiter + the Birdeye→DexScreener→GeckoTerminal chain) misses on a single+// request — a momentary simultaneous blip, not a real outage — falling back to a+// recent price keeps a paid quote alive instead of 503-ing the user's action.+// Bounded by STALE_PRICE_MAX_S: beyond that window a pump.fun token can have+// moved enough that pricing a payment off it is worse than failing, so we still+// throw. The quote's own short `exp` remains the hard guard on acting downstream.+const LAST_GOOD_KEY = `token:price:last:${TOKEN_MINT}`;+const LAST_GOOD_TTL_S = 3_600;+const STALE_PRICE_MAX_S = 300;+async function fetchJson(url, opts = {}) {const r = await fetch(url, opts);if (!r.ok) {@@ -64,6 +75,19 @@ export async function getTokenPriceUsd({ fresh = false } = {}) {}}if (!priceUsd) {+ // Every live feed missed on this one request. Before failing a paid action,+ // fall back to the last-known-good price if it's recent enough to price a+ // payment honestly. `at` is the ISO time it was observed live.+ const lastGood = await cacheGet(LAST_GOOD_KEY).catch(() => null);+ if (lastGood?.priceUsd && lastGood.at) {+ const ageS = (Date.now() - Date.parse(lastGood.at)) / 1000;+ if (Number.isFinite(ageS) && ageS >= 0 && ageS <= STALE_PRICE_MAX_S) {+ console.warn(+ `[token] all live price feeds missed — serving last-known-good (${Math.round(ageS)}s old)`,+ );+ return { ...lastGood, source: `${lastGood.source || 'cache'}-stale`, stale: true };+ }+ }throw Object.assign(new Error('live token price unavailable'), {status: 503,code: 'price_unavailable',@@ -71,7 +95,9 @@ export async function getTokenPriceUsd({ fresh = false } = {}) {}const value = { priceUsd, source, mint: TOKEN_MINT, at: new Date().toISOString() };+ // Live cache (smooths bursts) + the long-lived last-known-good (outage fallback).await cacheSet(PRICE_CACHE_KEY, value, PRICE_TTL_S);+ await cacheSet(LAST_GOOD_KEY, value, LAST_GOOD_TTL_S);return value;}diff --git a/api/avatars/_actions.js b/api/avatars/_actions.jsindex 56d3fe022..86c8ec399 100644--- a/api/avatars/_actions.js+++ b/api/avatars/_actions.js@@ -15,7 +15,7 @@ import { requireCsrf } from '../_lib/csrf.js';import { z } from 'zod';import { randomUUID } from 'crypto';import { isValidGlbHeader } from '../_lib/glb-inspect.js';-import { getRegenProvider, getRegenProviderByName, getRegenProviderForJob, BYOK_REGEN_PROVIDERS } from '../_lib/regen-provider.js';+import { getRegenProvider, getRegenProviderCandidates, getRegenProviderByName, getRegenProviderForJob, BYOK_REGEN_PROVIDERS } from '../_lib/regen-provider.js';import { resolveProviderKey } from '../_lib/forge-provider-key.js';import { finalizeReconstructStage, pollRiggingStage } from '../_lib/reconstruct-finalize.js';import { finalizeAutoRigStage } from '../_lib/auto-rig.js';@@ -1004,49 +1004,23 @@ const handleReconstruct = wrap(async (req, res) => {const body = parse(reconstructSchema, await readJson(req));// ── Provider resolution ──────────────────────────────────────────────────- let provider;- try {- provider = await getRegenProvider();- } catch (err) {- return maskSubmitError(res, err);- }-- // Platform provider not configured — try BYOK fallback.- if (provider.name === 'none') {- // 1. Inline key supplied by the client (provider_name + provider_key).- if (body.provider_key && body.provider_name) {- try {- provider = getRegenProviderByName(body.provider_name, body.provider_key);- } catch (err) {- return maskSubmitError(res, err);- }- }-- // 2. User's stored BYOK key — iterate preferred providers in order.- if (provider.name === 'none') {- for (const pName of BYOK_REGEN_PROVIDERS) {- try {- const key = await resolveProviderKey(req, null, pName);- if (key) {- provider = getRegenProviderByName(pName, key);- break;- }- } catch {- // resolveProviderKey can fail when there is no DB session — skip.- }- }- }-- // 3. Still nothing — tell the client which BYOK providers are accepted.- if (provider.name === 'none') {- return json(res, 402, {- ok: false,- code: 'regen_needs_byok',- message:- 'Avatar reconstruction requires an API key. Add your Meshy or Tripo key in settings, or pass provider_key + provider_name in this request.',- providers: BYOK_REGEN_PROVIDERS,- });- }+ // Build the ordered list of providers to try. Every configured platform+ // provider leads (primary first), then the caller's BYOK keys (inline, then+ // stored) backstop them — so a single provider outage, throttle, or credit+ // exhaustion fails over to the next instead of dead-ending the job. Each+ // entry is { name, instance }; names are de-duplicated.+ const candidates = await resolveReconstructCandidates(req, body);++ // Nothing configured anywhere — tell the client which BYOK providers are+ // accepted (unchanged 402 contract the client branches on).+ if (candidates.length === 0) {+ return json(res, 402, {+ ok: false,+ code: 'regen_needs_byok',+ message:+ 'Avatar reconstruction requires an API key. Add your Meshy or Tripo key in settings, or pass provider_key + provider_name in this request.',+ providers: BYOK_REGEN_PROVIDERS,+ });}// Text → avatar: turn the prompt into a frontal reference image, then treat@@ -1106,19 +1080,53 @@ const handleReconstruct = wrap(async (req, res) => {}}- let submission;- try {- submission = await provider.instance.submit({- userId,- mode: 'reconstruct',- params: { ...(body.params ?? {}), images: photos, name: body.name },- sourceUrl: photos[0],- });- } catch (err) {- return maskSubmitError(res, err);+ // ── Submit with provider failover ─────────────────────────────────────────+ // Try each candidate in turn. A submit() only spends provider credits on+ // success (the prediction/task is created server-side after the call+ // returns), so advancing past a thrown error never double-charges. We keep+ // the most actionable classified error to surface if every provider fails.+ let submission = null;+ let usedProvider = null;+ let bestError = null;+ const attempts = [];+ for (const provider of candidates) {+ try {+ submission = await provider.instance.submit({+ userId,+ mode: 'reconstruct',+ params: { ...(body.params ?? {}), images: photos, name: body.name },+ sourceUrl: photos[0],+ });+ usedProvider = provider;+ break;+ } catch (err) {+ const classified = classifyProviderError(err);+ attempts.push(`${provider.name}:${err?.code || err?.status || classified.code}`);+ console.warn(+ '[avatars] reconstruct submit failed on',+ provider.name,+ '—',+ err?.code || err?.status || 'unknown',+ '-',+ err?.message,+ );+ // Prefer the first error that points to a concrete, user-fixable cause+ // (bad key, no credits, bad request) over a generic retry — that is the+ // most useful thing to tell the user if nothing succeeds.+ if (!bestError || (isGenericProviderError(bestError) && !isGenericProviderError(err))) {+ bestError = err;+ }+ }}- const jobId = `${provider.name}-${randomUUID()}`;+ if (!submission || !usedProvider) {+ if (attempts.length > 1) {+ console.warn('[avatars] all reconstruct providers failed:', attempts.join(', '));+ }+ return maskSubmitError(res, bestError || new Error('no reconstruct provider available'));+ }++ const jobId = `${usedProvider.name}-${randomUUID()}`;const params = {images: photos,name: body.name,@@ -1132,17 +1140,68 @@ const handleReconstruct = wrap(async (req, res) => {insert into avatar_regen_jobs(job_id, user_id, source_avatar_id, mode, params, status, provider, ext_job_id, created_at, updated_at)values- (${jobId}, ${userId}, ${null}, ${'reconstruct'}, ${JSON.stringify(params)}, 'queued', ${provider.name}, ${submission.extJobId ?? null}, now(), now())+ (${jobId}, ${userId}, ${null}, ${'reconstruct'}, ${JSON.stringify(params)}, 'queued', ${usedProvider.name}, ${submission.extJobId ?? null}, now(), now())`;return json(res, 202, {ok: true,jobId,status: 'queued',eta: submission.eta ?? null,- provider: provider.name,+ provider: usedProvider.name,});});+// Assemble the ordered provider candidate list for a reconstruct submit:+// configured platform providers (primary first) followed by the caller's BYOK+// keys (inline body key, then stored keys), de-duplicated by provider name.+async function resolveReconstructCandidates(req, body) {+ const candidates = [];+ const seen = new Set();+ const add = (resolved) => {+ if (resolved?.instance && !seen.has(resolved.name)) {+ seen.add(resolved.name);+ candidates.push(resolved);+ }+ };++ // 1. Every configured platform provider, in precedence order.+ try {+ for (const p of await getRegenProviderCandidates()) add(p);+ } catch (err) {+ console.warn('[avatars] platform provider enumeration failed:', err?.message);+ }++ // 2. Inline BYOK key supplied by the client (provider_name + provider_key).+ if (body.provider_key && body.provider_name) {+ try {+ add(getRegenProviderByName(body.provider_name, body.provider_key));+ } catch (err) {+ console.warn('[avatars] inline BYOK provider load failed:', err?.message);+ }+ }++ // 3. User's stored BYOK keys — iterate preferred providers in order.+ for (const pName of BYOK_REGEN_PROVIDERS) {+ if (seen.has(pName)) continue;+ try {+ const key = await resolveProviderKey(req, null, pName);+ if (key) add(getRegenProviderByName(pName, key));+ } catch {+ // resolveProviderKey can fail when there is no DB session — skip.+ }+ }++ return candidates;+}++// A "generic" provider error is the catch-all 502 (unreachable / unclassified+// provider_error) — i.e. one that doesn't name a concrete, user-fixable cause.+// Used to prefer the most actionable error when reporting an all-providers-failed+// outcome.+function isGenericProviderError(err) {+ return classifyProviderError(err).code === 'regen_provider_error';+}+// ── dispatcher ────────────────────────────────────────────────────────────────const DISPATCH = {diff --git a/api/forge.js b/api/forge.jsindex d32c2f063..82f59231a 100644--- a/api/forge.js+++ b/api/forge.js@@ -51,6 +51,7 @@ import {estimateEtaSeconds,estimateCredits,preferFreeReconstruct,+ backendIsConfigured,buildCatalog,} from './_lib/forge-tiers.js';import { laneHealthSnapshot, markLaneUnhealthy } from './_lib/forge-lane-health.js';@@ -1162,7 +1163,19 @@ async function startJob(req, res) {});}if (backendId === 'replicate_byok') return needsKey(res, backendId);- return unconfigured(res);+ // The default TRELLIS (Replicate) provider couldn't be built — no+ // REPLICATE_API_TOKEN. That alone is NOT "unconfigured" when the free+ // HuggingFace Spaces lane is live: a degraded-from-NVIDIA text prompt, or+ // a photo→3D request, must still reconstruct on the free lane rather than+ // dead-ending at a 503. Leave `provider` undefined and fall through — the+ // free-first HF block below serves it, and the `!provider` guard further+ // down raises a designed unavailable state only if every free lane is gone+ // too. Mirrors the self-host TRELLIS failover (provider = undefined) above.+ if (backendId === 'trellis' && backendIsConfigured('huggingface')) {+ provider = undefined;+ } else {+ return unconfigured(res);+ }}// In-flight coalescing: if an identical (path, tier, backend, prompt, images)diff --git a/data/changelog.json b/data/changelog.jsonindex c98500348..bc0f4d273 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-28",+ "title": "Forge no longer dead-ends on \"Generator not configured\" when a free lane is live",+ "summary": "When the free NVIDIA text→3D lane was briefly down, Forge could return \"Generator not configured\" even on deployments where the free Hugging Face lane was fully set up — because the degrade step looked for a paid Replicate key that wasn't required. Forge now falls through to whichever free engine is configured (Hugging Face Spaces) instead of stopping, so a single free key keeps text and photo generation working through upstream blips.",+ "tags": [+ "fix"+ ],+ "link": "/forge"+ },{"date": "2026-06-28","title": "Agent Reputation Leaderboard — top agents promoted in marketplace by on-chain trust score",diff --git a/public/changelog.json b/public/changelog.jsonindex 8b2acf37d..2c3166c86 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-28T04:47:25.943Z",+ "generated_at": "2026-06-28T05:53:38.609Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -83,6 +83,16 @@"feature"]},+ {+ "date": "2026-06-28",+ "type": "update",+ "title": "Forge no longer dead-ends on \"Generator not configured\" when a free lane is live",+ "summary": "When the free NVIDIA text→3D lane was briefly down, Forge could return \"Generator not configured\" even on deployments where the free Hugging Face lane was fully set up — because the degrade step looked for a paid Replicate key that wasn't required. Forge now falls through to whichever free engine is configured (Hugging Face Spaces) instead of stopping, so a single free key keeps text and photo generation working through upstream blips.",+ "link": "/forge",+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-28","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex cb57cc9d0..edd84e488 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -62,6 +62,14 @@<category>infra</category><description>Every Forge job that reconstructs a 3D mesh starts with a text-to-image call. If the image provider chain is down or hung, every paid Forge generation silently fails — before users even hit the paywall. The platform now detects this automatically. Every five minutes an autonomous agent makes a real on-chain $0.001 USDC payment to /api/x402/forge with body { mode: "health_check", type: "image", prompt: "A simple blue circle." }. The endpoint runs one real text-to-image call through the free-first provider chain (NIM FLUX → Vertex Imagen → Replicate backstop) and uploads the result to R2 CDN — proving the full image generation and CDN upload path end-to-end. The extracted signal { generated, url, latency_ms } lands in x402_autonomous_log.signal_data. When generation fails or latency exceeds 30 seconds, a Redis alert (x402:forge-image-health:alert) is raised so ops can investigate before users see broken generations. The image alert key is separate from the existing text LLM canary alert so both lanes can degrade independently.</description></item>+ <item>+ <title>Forge no longer dead-ends on "Generator not configured" when a free lane is live</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-06-28:Forge no longer dead-ends on "Generator not configured" when a free lane is live</guid>+ <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>When the free NVIDIA text→3D lane was briefly down, Forge could return "Generator not configured" even on deployments where the free Hugging Face lane was fully set up — because the degrade step looked for a paid Replicate key that wasn't required. Forge now falls through to whichever free engine is configured (Hugging Face Spaces) instead of stopping, so a single free key keeps text and photo generation working through upstream blips.</description>+ </item><item><title>LLM Proxy Latency Benchmark — p95 alerting when inference exceeds 3 seconds</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex 2d3705b18..5692479de 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-28T04:47:25.927Z",+ "generated_at": "2026-06-28T05:53:38.540Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/studio/brain/brain-composer.js b/src/studio/brain/brain-composer.jsnew file mode 100644index 000000000..94e964d76--- /dev/null+++ b/src/studio/brain/brain-composer.js@@ -0,0 +1,316 @@+/**+ * Brain Studio — card composer (P1)+ * =================================+ * The agent's mind, edited as a clean, ordered stack of configuration cards+ * instead of a free-form node canvas. Each card is one part of the pipeline —+ * Persona → Memory → Skills → Market signals → Model → Avatar output — and its+ * fields edit the SAME node `data` the rest of the brain stack already consumes.+ *+ * Why a composer, not a graph: the wiring of a single agent brain is a fixed+ * linear pipeline (everything feeds the model, the model drives the avatar). A+ * drag-the-wires editor made the user do the platform's job. The composer keeps+ * the graph data model — `toGraph()` synthesizes a fully-wired, normalized graph+ * every serialize — so `compileBrain`, `brain-runtime`, the templates, and the+ * persisted `meta.studio.brain` format are all unchanged. A card that exists is+ * wired in; remove the card to remove it from the circuit.+ *+ * This class is a drop-in for the old BrainGraphView: it exposes the same public+ * surface the controller and the runtime depend on, including the live+ * "watch it think" animation — which now lights up cards in pipeline order.+ *+ * Public API:+ * new BrainComposer(host, { onChange, getProviders, getSkills })+ * .load(graph) / .toGraph()+ * .addNode(type) / .removeNode(id) / .updateNodeData(id, patch)+ * Animation (driven by brain-runtime.js):+ * .circuit() / .setActive(nodeIds) / .pulseNode(id)+ * .setNodeBusy(id, busy) / .setNodeStat(id, text) / .clearActive()+ */++import { NODE_TYPES, makeNode, edge } from './brain-nodes.js';++const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));++// Pipeline order the cards render in. Skill / market are repeatable groups; the+// rest are single structural nodes.+const SINGLE_ORDER = ['persona', 'memory', 'model', 'output'];++export class BrainComposer {+ constructor(host, { onChange, getProviders, getSkills } = {}) {+ this.host = host;+ this.onChange = onChange || (() => {});+ this.getProviders = getProviders || (() => []);+ this.getSkills = getSkills || (() => []);+ this.nodes = [];+ this._cardEls = new Map(); // nodeId → card element (for animation + stats)+ this.host.classList.add('brainstudio__composer');+ }++ // ── Load / serialize ──────────────────────────────────────────────────────++ load(graph) {+ const nodes = (graph?.nodes || []).map((n) => ({ ...n, data: { ...n.data } }));+ // Guarantee a complete pipeline: a malformed or partial stored graph can't+ // leave the composer without a Persona / Model / Output card to render.+ for (const type of ['persona', 'model', 'output']) {+ if (!nodes.some((n) => n.type === type)) nodes.push(makeNode(type, 0, 0));+ }+ this.nodes = nodes;+ this._renderAll();+ }++ // Synthesize the canonical fully-wired graph the rest of the platform consumes.+ // Every present card is part of the live circuit, by design.+ toGraph() {+ const persona = this.nodes.find((n) => n.type === 'persona');+ const memory = this.nodes.find((n) => n.type === 'memory');+ const model = this.nodes.find((n) => n.type === 'model');+ const output = this.nodes.find((n) => n.type === 'output');+ const skills = this.nodes.filter((n) => n.type === 'skill');+ const markets = this.nodes.filter((n) => n.type === 'market');++ const edges = [];+ if (persona && model) edges.push(edge(persona, 'identity', model, 'identity'));+ if (memory && model) edges.push(edge(memory, 'recall', model, 'context'));+ for (const s of skills) if (model) edges.push(edge(s, 'tool', model, 'tools'));+ for (const m of markets) if (model) edges.push(edge(m, 'signal', model, 'context'));+ if (model && output) edges.push(edge(model, 'reply', output, 'reply'));++ return {+ version: 1,+ nodes: this.nodes.map((n) => ({ id: n.id, type: n.type, x: Math.round(n.x || 0), y: Math.round(n.y || 0), data: { ...n.data } })),+ edges,+ };+ }++ _emitChange() { this.onChange(this.toGraph()); }++ // ── Mutations ─────────────────────────────────────────────────────────────++ addNode(type) {+ const spec = NODE_TYPES[type];+ if (!spec) return null;+ if (spec.single && this.nodes.some((n) => n.type === type)) return null;+ const node = makeNode(type, 0, 0);+ this.nodes.push(node);+ this._renderAll();+ this._emitChange();+ // Focus the first field of the freshly added card so the user can type at once.+ this._cardEls.get(node.id)?.querySelector('[data-field]')?.focus();+ return node;+ }++ removeNode(id) {+ const node = this.nodes.find((n) => n.id === id);+ if (!node || NODE_TYPES[node.type]?.single) return; // structural cards stay+ this.nodes = this.nodes.filter((n) => n.id !== id);+ this._renderAll();+ this._emitChange();+ }++ updateNodeData(id, patch) {+ const node = this.nodes.find((n) => n.id === id);+ if (!node) return;+ Object.assign(node.data, patch);+ this._emitChange();+ }++ // ── Render ────────────────────────────────────────────────────────────────++ _renderAll() {+ this._cardEls.clear();+ const frag = document.createDocumentFragment();++ frag.appendChild(this._card(this.nodes.find((n) => n.type === 'persona')));+ frag.appendChild(this._memorySection());+ frag.appendChild(this._repeatSection('skill', 'Skills', 'Give the agent tools it can call. Add a skill the agent already has enabled.'));+ frag.appendChild(this._repeatSection('market', 'Market signals', 'Reasoning rules for the live mint supplied at runtime. $THREE is the only coin the platform promotes.'));+ frag.appendChild(this._card(this.nodes.find((n) => n.type === 'model')));+ frag.appendChild(this._card(this.nodes.find((n) => n.type === 'output')));++ this.host.replaceChildren(frag);+ }++ // A single editable node card. `removable` adds a delete control (skill/market).+ _card(node, { removable = false } = {}) {+ const spec = NODE_TYPES[node.type];+ const el = document.createElement('section');+ el.className = `bcard bcard--${spec.accent}`;+ el.dataset.id = node.id;+ el.innerHTML = `+ <header class="bcard__head">+ <span class="bcard__dot bcard__dot--${spec.accent}"></span>+ <h3 class="bcard__title">${esc(spec.title)}</h3>+ <span class="bcard__stat" hidden></span>+ ${removable ? '<button class="bcard__remove" type="button" aria-label="Remove">Remove</button>' : ''}+ </header>+ <div class="bcard__fields"></div>`;+ const fields = el.querySelector('.bcard__fields');+ for (const f of spec.fields) fields.appendChild(this._field(node, f));+ if (removable) el.querySelector('.bcard__remove').addEventListener('click', () => this.removeNode(node.id));+ this._cardEls.set(node.id, el);+ return el;+ }++ // Memory is optional: render its card when present, otherwise an add affordance.+ _memorySection() {+ const node = this.nodes.find((n) => n.type === 'memory');+ if (node) {+ const card = this._card(node);+ const head = card.querySelector('.bcard__head');+ const off = document.createElement('button');+ off.className = 'bcard__remove';+ off.type = 'button';+ off.textContent = 'Turn off';+ off.addEventListener('click', () => {+ this.nodes = this.nodes.filter((n) => n.type !== 'memory');+ this._renderAll();+ this._emitChange();+ });+ head.appendChild(off);+ return card;+ }+ const el = document.createElement('section');+ el.className = 'bcard bcard--memory bcard--add';+ el.innerHTML = `+ <header class="bcard__head">+ <span class="bcard__dot bcard__dot--memory"></span>+ <h3 class="bcard__title">Memory</h3>+ </header>+ <p class="bcard__hint">Off. The agent answers without recalling past conversations.</p>+ <button class="studio__btn bcard__addbtn" type="button">Turn on memory</button>`;+ el.querySelector('.bcard__addbtn').addEventListener('click', () => this.addNode('memory'));+ return el;+ }++ // A repeatable group (skills, market signals): a labelled section, one card per+ // node, plus an "add" button.+ _repeatSection(type, title, hint) {+ const spec = NODE_TYPES[type];+ const wrap = document.createElement('section');+ wrap.className = `bgroup bgroup--${spec.accent}`;+ const head = document.createElement('div');+ head.className = 'bgroup__head';+ head.innerHTML = `<span class="bcard__dot bcard__dot--${spec.accent}"></span><h3 class="bgroup__title">${esc(title)}</h3>`;+ const add = document.createElement('button');+ add.className = 'studio__btn bgroup__add';+ add.type = 'button';+ add.textContent = `+ ${spec.title}`;+ add.addEventListener('click', () => this.addNode(type));+ head.appendChild(add);+ wrap.appendChild(head);++ const items = this.nodes.filter((n) => n.type === type);+ if (!items.length) {+ const empty = document.createElement('p');+ empty.className = 'bgroup__empty';+ empty.textContent = hint;+ wrap.appendChild(empty);+ } else {+ for (const n of items) wrap.appendChild(this._card(n, { removable: true }));+ }+ return wrap;+ }++ // ── Fields ────────────────────────────────────────────────────────────────++ _field(node, field) {+ const wrap = document.createElement('div');+ wrap.className = 'bcard__field';+ const id = `f_${node.id}_${field.key}`;+ const value = node.data[field.key];+ wrap.innerHTML = `<label class="bcard__label" for="${id}">${esc(field.label)}</label>${this._control(id, field, value)}`;+ const input = wrap.querySelector('[data-field]');+ if (input) {+ const ev = input.tagName === 'SELECT' || input.type === 'checkbox' ? 'change' : 'input';+ input.addEventListener(ev, () => this.updateNodeData(node.id, { [field.key]: this._readField(field, input) }));+ }+ return wrap;+ }++ _control(id, field, value) {+ switch (field.type) {+ case 'textarea':+ return `<textarea class="bcard__input" id="${id}" data-field="${field.key}" rows="2">${esc(value || '')}</textarea>`;+ case 'number':+ return `<input class="bcard__input" id="${id}" data-field="${field.key}" type="number" min="${field.min ?? ''}" max="${field.max ?? ''}" step="${field.step ?? 1}" value="${esc(value ?? '')}" />`;+ case 'toggle':+ return `<label class="brainstudio__toggle"><input id="${id}" data-field="${field.key}" type="checkbox" ${value ? 'checked' : ''} /><span></span></label>`;+ case 'select':+ return `<select class="bcard__input" id="${id}" data-field="${field.key}">${field.options.map((o) => `<option value="${esc(o)}" ${o === value ? 'selected' : ''}>${esc(o)}</option>`).join('')}</select>`;+ case 'provider':+ return this._providerSelect(id, field.key, value);+ case 'skill':+ return this._skillSelect(id, field.key, value);+ case 'tags':+ return `<input class="bcard__input" id="${id}" data-field="${field.key}" type="text" value="${esc((value || []).join(', '))}" placeholder="comma, separated" />`;+ default:+ return `<input class="bcard__input" id="${id}" data-field="${field.key}" type="text" value="${esc(value ?? '')}" placeholder="${esc(field.placeholder || '')}" />`;+ }+ }++ _providerSelect(id, key, value) {+ const providers = this.getProviders();+ const list = providers.length ? providers : [{ key: value || 'claude-sonnet-4-6', label: value || 'Claude Sonnet 4.6', available: true, tier: '' }];+ const opts = list.map((p) => `<option value="${esc(p.key)}" ${p.key === value ? 'selected' : ''} ${p.available ? '' : 'disabled'}>${esc(p.label)}${p.available ? '' : ' (no key)'}${p.tier ? ` · ${esc(p.tier)}` : ''}</option>`).join('');+ return `<select class="bcard__input" id="${id}" data-field="${key}">${opts}</select>`;+ }++ _skillSelect(id, key, value) {+ const skills = this.getSkills();+ if (!skills.length) return `<input class="bcard__input" id="${id}" data-field="${key}" type="text" value="${esc(value || '')}" placeholder="no skills enabled yet" />`;+ const opts = ['<option value="">— pick a skill —</option>', ...skills.map((s) => `<option value="${esc(s)}" ${s === value ? 'selected' : ''}>${esc(s)}</option>`)].join('');+ return `<select class="bcard__input" id="${id}" data-field="${key}">${opts}</select>`;+ }++ _readField(field, inp) {+ switch (field.type) {+ case 'number': return Number(inp.value);+ case 'toggle': return inp.checked;+ case 'tags': return inp.value.split(',').map((s) => s.trim()).filter(Boolean);+ default: return inp.value;+ }+ }++ // ── Live "watch it think" animation ─────────────────────────────────────────+ // The runtime walks the compiled circuit and pulses each stage as it runs. With+ // the composer, every present card is in the circuit, so we light up cards in+ // pipeline order — the same moment, rendered as a flowing stack.++ circuit() {+ return { nodeIds: this.nodes.map((n) => n.id), edgeIds: [] };+ }++ setActive(nodeIds = []) {+ const set = new Set(nodeIds);+ for (const [id, el] of this._cardEls) el.classList.toggle('is-active', set.has(id));+ }++ pulseNode(id) {+ const el = this._cardEls.get(id);+ if (!el) return;+ el.classList.remove('is-pulse');+ void el.offsetWidth; // restart the animation+ el.classList.add('is-pulse');+ el.scrollIntoView?.({ block: 'nearest', behavior: 'smooth' });+ }++ setNodeBusy(id, busy) {+ this._cardEls.get(id)?.classList.toggle('is-busy', !!busy);+ }++ setNodeStat(id, text) {+ const stat = this._cardEls.get(id)?.querySelector('.bcard__stat');+ if (!stat) return;+ stat.textContent = text || '';+ stat.hidden = !text;+ }++ clearActive() {+ for (const el of this._cardEls.values()) {+ el.classList.remove('is-active', 'is-pulse', 'is-busy');+ const stat = el.querySelector('.bcard__stat');+ if (stat) { stat.textContent = ''; stat.hidden = true; }+ }+ }+}diff --git a/src/studio/brain/brain-form.js b/src/studio/brain/brain-form.jsnew file mode 100644index 000000000..b15cfeca4--- /dev/null+++ b/src/studio/brain/brain-form.js@@ -0,0 +1,325 @@+/**+ * Brain Studio — form editor (P1, replaces the node-graph canvas)+ * ===============================================================+ * The agent's brain as a structured form instead of a draggable flow-chart. Same+ * underlying model (brain-nodes.js graph: nodes + edges), same compiler, same+ * runtime — only the editing surface changed. Wiring is automatic and deterministic:+ * the user configures persona, model, memory, skills, market signals and avatar+ * output in plain fields, and this view keeps a fully-connected circuit wired for+ * the compiler and the live "watch it think" animation.+ *+ * Drop-in replacement for the old BrainGraphView — same public surface the studio+ * controller and brain-runtime.js depend on:+ * new BrainFormView(host, { onChange, getProviders, getSkills })+ * .load(graph) / .toGraph()+ * .addNode(type) / .removeNode(id) / .updateNodeData(id, patch)+ * .setProviders(list) — re-render Model pickers when availability arrives+ * .fit() — no-op (kept for interface parity)+ * Active-path animation (driven by brain-runtime.js):+ * .circuit() / .setActive() / .pulseNode() / .flowEdge() / .clearActive()+ * .setNodeBusy(id, busy) / .setNodeStat(id, text)+ */++import { NODE_TYPES, makeNode, edge, normalizeGraph } from './brain-nodes.js';++const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));++// The order sections stack in the form, top → bottom: identity first, the model+// that runs it last-but-one, the avatar it speaks through last. Memory/skill/market+// slot between persona and model as the "context" the model reasons over.+const SECTION_ORDER = ['persona', 'memory', 'skill', 'market', 'model', 'output'];++// One-line "what this section does" copy under each header — orients without a manual.+const SECTION_HINT = {+ persona: 'Who your agent is and how it speaks.',+ model: 'The brain that runs it — pick speed vs. depth.',+ memory: 'Recall relevant past context before answering, and remember new facts.',+ skill: 'A capability your agent can invoke as a tool.',+ market: 'A market condition your agent reasons about and reacts to.',+ output: 'How the reply reaches your live avatar.',+};++export class BrainFormView {+ constructor(host, { onChange, getProviders, getSkills } = {}) {+ this.host = host;+ this.onChange = onChange || (() => {});+ this.getProviders = getProviders || (() => []);+ this.getSkills = getSkills || (() => []);+ this.nodes = [];+ this.edges = [];+ this._cardEls = new Map(); // nodeId → section element+ this._render();+ }++ _render() {+ this.host.classList.add('bform');+ this.host.innerHTML = `<div class="bform__sections" id="bfSections"></div>`;+ this.sectionsEl = this.host.querySelector('#bfSections');+ }++ // ── Load / serialize ──────────────────────────────────────────────────────++ load(graph) {+ const g = normalizeGraph(graph);+ this.nodes = g.nodes.map((n) => ({ ...n, data: { ...n.data } }));+ this._ensureStructural();+ this._rewire();+ this._renderAll();+ }++ toGraph() {+ return {+ version: 1,+ nodes: this.nodes.map((n) => ({ id: n.id, type: n.type, x: Math.round(n.x || 0), y: Math.round(n.y || 0), data: { ...n.data } })),+ edges: this.edges.map((e) => ({ id: e.id, from: e.from, fromPort: e.fromPort, to: e.to, toPort: e.toPort })),+ };+ }++ _emitChange() { this.onChange(this.toGraph()); }++ fit() { /* no canvas to frame — kept for BrainGraphView interface parity */ }++ // ── Structure + deterministic wiring ────────────────────────────────────────++ // Persona, Model and Output are structural: the circuit is meaningless without+ // them, so a loaded graph missing any gets a default one rather than a half-brain.+ _ensureStructural() {+ for (const type of ['persona', 'model', 'output']) {+ if (!this.nodes.some((n) => n.type === type)) this.nodes.push(makeNode(type, 0, 0));+ }+ }++ // Rebuild edges from the current node set so every configured section feeds the+ // model and the model feeds the avatar. The user never wires anything by hand —+ // adding a Memory/Skill/Market section is enough to put it in the live circuit.+ _rewire() {+ const persona = this.nodes.find((n) => n.type === 'persona');+ const model = this.nodes.find((n) => n.type === 'model');+ const output = this.nodes.find((n) => n.type === 'output');+ const edges = [];+ if (persona && model) edges.push(edge(persona, 'identity', model, 'identity'));+ for (const mem of this.nodes.filter((n) => n.type === 'memory')) edges.push(edge(mem, 'recall', model, 'context'));+ for (const sk of this.nodes.filter((n) => n.type === 'skill')) edges.push(edge(sk, 'tool', model, 'tools'));+ for (const mk of this.nodes.filter((n) => n.type === 'market')) edges.push(edge(mk, 'signal', model, 'context'));+ if (model && output) edges.push(edge(model, 'reply', output, 'reply'));+ this.edges = edges;+ }++ // ── Mutations ───────────────────────────────────────────────────────────────++ addNode(type) {+ const spec = NODE_TYPES[type];+ if (!spec) return null;+ // Memory is conceptually one-per-brain even though the model allows many.+ const onePer = spec.single || type === 'memory';+ if (onePer && this.nodes.some((n) => n.type === type)) return null;+ const node = makeNode(type, 0, 0);+ this.nodes.push(node);+ this._rewire();+ this._renderAll();+ this._emitChange();+ // Focus the new section's first field so adding flows straight into editing.+ this._cardEls.get(node.id)?.querySelector('input, select, textarea')?.focus();+ return node;+ }++ removeNode(id) {+ const node = this.nodes.find((n) => n.id === id);+ if (!node || NODE_TYPES[node.type].single) return; // persona/model/output are structural+ this.nodes = this.nodes.filter((n) => n.id !== id);+ this._rewire();+ this._renderAll();+ this._emitChange();+ }++ updateNodeData(id, patch) {+ const node = this.nodes.find((n) => n.id === id);+ if (!node) return;+ Object.assign(node.data, patch);+ this._emitChange();+ }++ // ── Render ────────────────────────────────────────────────────────────────++ _renderAll() {+ this._cardEls.clear();+ this.sectionsEl.innerHTML = '';+ for (const type of SECTION_ORDER) {+ const ofType = this.nodes.filter((n) => n.type === type);+ for (const node of ofType) this.sectionsEl.appendChild(this._cardEl(node));+ const addEl = this._addControl(type, ofType.length);+ if (addEl) this.sectionsEl.appendChild(addEl);+ }+ }++ // An "+ Add …" control for the optional, repeatable sections. Memory shows only+ // while absent; Skill/Market always offer another. Structural nodes get none.+ _addControl(type, count) {+ if (type === 'memory' && count === 0) return this._addBtn('memory', '+ Add memory');+ if (type === 'skill') return this._addBtn('skill', count ? '+ Add another skill' : '+ Add a skill');+ if (type === 'market') return this._addBtn('market', count ? '+ Add another market signal' : '+ Add a market signal');+ return null;+ }++ _addBtn(type, label) {+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = `bform__add bform__add--${NODE_TYPES[type].accent}`;+ btn.textContent = label;+ btn.addEventListener('click', () => this.addNode(type));+ return btn;+ }++ _cardEl(node) {+ const spec = NODE_TYPES[node.type];+ const removable = !spec.single;+ const card = document.createElement('section');+ card.className = `bform__card bform__card--${spec.accent}`;+ card.dataset.node = node.id;+ card.dataset.type = node.type;+ card.innerHTML = `+ <header class="bform__card-head">+ <span class="bform__card-dot" aria-hidden="true"></span>+ <h3 class="bform__card-title">${esc(spec.title)}</h3>+ <span class="bform__card-stat" data-stat hidden></span>+ ${removable ? '<button type="button" class="bform__card-del" aria-label="Remove this section">Remove</button>' : ''}+ </header>+ <p class="bform__card-hint">${esc(SECTION_HINT[node.type] || '')}</p>+ <div class="bform__fields">${spec.fields.map((f) => this._fieldHtml(f, node.data[f.key])).join('')}</div>`;++ card.querySelector('.bform__card-del')?.addEventListener('click', () => this.removeNode(node.id));+ card.querySelectorAll('[data-field]').forEach((inp) => {+ const key = inp.dataset.field;+ const field = spec.fields.find((f) => f.key === key);+ const evt = inp.tagName === 'SELECT' || inp.type === 'checkbox' ? 'change' : 'input';+ inp.addEventListener(evt, () => this.updateNodeData(node.id, { [key]: this._readField(field, inp) }));+ });+ this._cardEls.set(node.id, card);+ return card;+ }++ // ── Fields ──────────────────────────────────────────────────────────────────++ _fieldHtml(field, value) {+ const id = `bf_${field.key}_${Math.abs(hash(String(value) + field.key))}`;+ const label = `<label class="bform__field-label" for="${id}">${esc(field.label)}</label>`;+ let control = '';+ switch (field.type) {+ case 'textarea':+ control = `<textarea class="bform__input" id="${id}" data-field="${field.key}" rows="2">${esc(value || '')}</textarea>`;+ break;+ case 'number':+ control = `<input class="bform__input" id="${id}" data-field="${field.key}" type="number" min="${field.min ?? ''}" max="${field.max ?? ''}" step="${field.step ?? 1}" value="${esc(value ?? '')}" />`;+ break;+ case 'toggle':+ control = `<label class="bform__toggle"><input id="${id}" data-field="${field.key}" type="checkbox" ${value ? 'checked' : ''} /><span></span></label>`;+ break;+ case 'select':+ control = `<select class="bform__input" id="${id}" data-field="${field.key}">${field.options.map((o) => `<option value="${esc(o)}" ${o === value ? 'selected' : ''}>${esc(o)}</option>`).join('')}</select>`;+ break;+ case 'provider':+ control = this._providerSelect(id, field.key, value);+ break;+ case 'skill':+ control = this._skillSelect(id, field.key, value);+ break;+ case 'tags':+ control = `<input class="bform__input" id="${id}" data-field="${field.key}" type="text" value="${esc((value || []).join(', '))}" placeholder="comma, separated" />`;+ break;+ default:+ control = `<input class="bform__input" id="${id}" data-field="${field.key}" type="text" value="${esc(value ?? '')}" placeholder="${esc(field.placeholder || '')}" />`;+ }+ // Toggles read better as a single inline row (label + switch) than stacked.+ const inline = field.type === 'toggle' ? ' bform__field--inline' : '';+ return `<div class="bform__field${inline}">${label}${control}</div>`;+ }++ _providerSelect(id, key, value) {+ const list = this.getProviders();+ const opts = (list.length ? list : [{ key: value || 'claude-sonnet-4-6', label: value || 'Claude Sonnet 4.6', available: true, tier: '' }])+ .map((p) => `<option value="${esc(p.key)}" ${p.key === value ? 'selected' : ''} ${p.available ? '' : 'disabled'}>${esc(p.label)}${p.available ? '' : ' (no key)'}${p.tier ? ` · ${esc(p.tier)}` : ''}</option>`)+ .join('');+ return `<select class="bform__input" id="${id}" data-field="${key}">${opts}</select>`;+ }++ _skillSelect(id, key, value) {+ const skills = this.getSkills();+ if (!skills.length) return `<input class="bform__input" id="${id}" data-field="${key}" type="text" value="${esc(value || '')}" placeholder="no skills enabled yet — turn some on in the Skills tab" />`;+ const opts = ['<option value="">— pick a skill —</option>', ...skills.map((s) => `<option value="${esc(s)}" ${s === value ? 'selected' : ''}>${esc(s)}</option>`)].join('');+ return `<select class="bform__input" id="${id}" data-field="${key}">${opts}</select>`;+ }++ _readField(field, inp) {+ switch (field.type) {+ case 'number': return Number(inp.value);+ case 'toggle': return inp.checked;+ case 'tags': return inp.value.split(',').map((s) => s.trim()).filter(Boolean);+ default: return inp.value;+ }+ }++ // Providers arrive async (GET /api/brain/chat); re-render just the Model pickers so+ // availability + labels fill in without disturbing the user's other in-progress edits.+ setProviders() {+ for (const node of this.nodes.filter((n) => n.type === 'model')) {+ const card = this._cardEls.get(node.id);+ const sel = card?.querySelector('[data-field="provider"]');+ if (sel) sel.outerHTML = this._providerSelect(sel.id, 'provider', node.data.provider);+ // outerHTML replaces the node, so rebind the change handler on the fresh one.+ const fresh = card?.querySelector('[data-field="provider"]');+ fresh?.addEventListener('change', () => this.updateNodeData(node.id, { provider: fresh.value }));+ }+ }++ // ── Active-path animation (the "watch it think" moment, sans canvas) ─────────++ circuit() {+ // Every section is auto-wired into the live circuit, so the runtime can light+ // them all up in order. Edge ids are unused by the form but kept for parity.+ return { nodeIds: this.nodes.map((n) => n.id), edgeIds: this.edges.map((e) => e.id) };+ }++ setActive(nodeIds = []) {+ const on = new Set(nodeIds);+ for (const [id, el] of this._cardEls) el.classList.toggle('is-active', on.has(id));+ }++ pulseNode(id) {+ const el = this._cardEls.get(id);+ if (!el) return;+ el.classList.remove('is-pulse');+ void el.offsetWidth; // restart the animation+ el.classList.add('is-pulse');+ // Bring the firing section into view so the user watches the path travel.+ el.scrollIntoView({ block: 'nearest', behavior: 'smooth' });+ }++ flowEdge() { /* no visible edges in form mode */ }++ setNodeBusy(id, busy) {+ this._cardEls.get(id)?.classList.toggle('is-busy', !!busy);+ }++ setNodeStat(id, text) {+ const el = this._cardEls.get(id)?.querySelector('[data-stat]');+ if (!el) return;+ el.textContent = text || '';+ el.hidden = !text;+ }++ clearActive() {+ for (const el of this._cardEls.values()) {+ el.classList.remove('is-active', 'is-pulse', 'is-busy');+ const stat = el.querySelector('[data-stat]');+ if (stat) { stat.textContent = ''; stat.hidden = true; }+ }+ }+}++// Tiny stable hash for unique field ids (avoids Date.now / Math.random churn on+// re-render so label/for pairs stay deterministic within a render).+function hash(s) {+ let h = 0;+ for (let i = 0; i < s.length; i++) h = (Math.imul(31, h) + s.charCodeAt(i)) | 0;+ return h;+}diff --git a/src/studio/brain/brain-studio.js b/src/studio/brain/brain-studio.jsindex 805bbad13..0d1f8d89a 100644--- a/src/studio/brain/brain-studio.js+++ b/src/studio/brain/brain-studio.js@@ -18,15 +18,14 @@* mountBrainStudio(container, { studio });*/-import { BrainGraphView } from './brain-graph.js';+import { BrainFormView } from './brain-form.js';import { compileBrain } from './brain-compile.js';import { BrainRuntime } from './brain-runtime.js';-import { NODE_TYPES, normalizeGraph, defaultGraph } from './brain-nodes.js';+import { normalizeGraph, defaultGraph } from './brain-nodes.js';import { TEMPLATES } from './brain-templates.js';import { apiFetch } from '../../api.js';const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));-const PALETTE = ['persona', 'model', 'memory', 'skill', 'market', 'output'];export function mountBrainStudio(container, { studio }) {if (container.dataset.brainMounted) return;@@ -47,11 +46,13 @@ class BrainStudio {}async _init() {- // Providers power the Model node's picker — real availability from the proxy.+ // Providers power the Model section's picker — real availability from the proxy.try {const resp = await apiFetch('/api/brain/chat', { allowAnonymous: true });if (resp.ok) this.providers = (await resp.json()).providers || [];} catch { /* picker falls back to a static list of model ids */ }+ // If the editor mounted before providers arrived, fill the Model picker in now.+ this.graph?.setProviders();// Don't overwrite a graph the user started editing during the async provider// fetch above (e.g. they clicked a template while we were awaiting). Only@@ -83,9 +84,11 @@ class BrainStudio {<div class="brainstudio__editor" id="bsEditor" hidden><div class="brainstudio__toolbar">- <div class="brainstudio__palette" id="bsPalette" role="toolbar" aria-label="Add node"></div>+ <div class="brainstudio__toolbar-title">+ <span class="brainstudio__toolbar-name">Your agent's mind</span>+ <span class="brainstudio__toolbar-sub">Fill these in — it wires itself.</span>+ </div><div class="brainstudio__tools">- <button class="studio__btn" id="bsFit" title="Frame the graph">Fit</button><button class="studio__btn" id="bsDiff" title="See how this brain reads">Behavior</button><button class="studio__btn" id="bsTpl" title="Fork a template">Templates</button><button class="studio__btn" id="bsSave" title="Save now (⌘/Ctrl + S)">Save</button>@@ -93,9 +96,8 @@ class BrainStudio {</div></div><div class="brainstudio__main">- <div class="brainstudio__canvas" id="bsCanvas"></div>+ <div class="brainstudio__form" id="bsForm"></div><aside class="brainstudio__side">- <div class="brainstudio__inspector" id="bsInspector"></div><div class="brainstudio__test" id="bsTest"><div class="brainstudio__test-head">Test chat <span class="brainstudio__test-model" id="bsTestModel"></span></div><div class="brainstudio__transcript" id="bsTranscript"></div>@@ -120,9 +122,7 @@ class BrainStudio {this.root = this.el.querySelector('.brainstudio');this._renderTemplateGrid(this.el.querySelector('#bsTplGrid'));- this._renderPalette();this.el.querySelector('#bsBlank').addEventListener('click', () => this._start(defaultGraph()));- this.el.querySelector('#bsFit').addEventListener('click', () => this.graph?.fit());this.el.querySelector('#bsDiff').addEventListener('click', () => this._showBehavior());this.el.querySelector('#bsTpl').addEventListener('click', () => this._showTemplateModal());this.el.querySelector('#bsSave').addEventListener('click', () => this._saveNow());@@ -235,15 +235,6 @@ class BrainStudio {document.dispatchEvent(new CustomEvent('studio:exit'));}- _renderPalette() {- const pal = this.el.querySelector('#bsPalette');- pal.innerHTML = PALETTE.map((t) => `<button class="brainstudio__chip brainstudio__chip--${NODE_TYPES[t].accent}" data-add="${t}" title="Add ${NODE_TYPES[t].title}">+ ${esc(NODE_TYPES[t].title)}</button>`).join('');- pal.addEventListener('click', (e) => {- const t = e.target.closest('[data-add]')?.dataset.add;- if (t) this.graph?.addNode(t);- });- }-_renderTemplateGrid(host) {host.innerHTML = TEMPLATES.map((t) => `<button class="brainstudio__tpl brainstudio__tpl--${t.accent}" data-tpl="${t.id}">@@ -266,20 +257,12 @@ class BrainStudio {this.el.querySelector('#bsOnboard').hidden = true;this.el.querySelector('#bsEditor').hidden = false;if (!this.graph) {- const canvas = this.el.querySelector('#bsCanvas');- this.graph = new BrainGraphView(canvas, {+ const form = this.el.querySelector('#bsForm');+ this.graph = new BrainFormView(form, {onChange: (g) => this._onGraphChange(g),- onSelect: (n) => this._renderInspector(n),+ getProviders: () => this.providers,+ getSkills: () => this.studio.agent?.skills || [],});- // The Brain tab may be mounted while hidden (zero size), so the initial- // fit() no-ops. Re-frame once the panel first gains a real size.- if (typeof ResizeObserver !== 'undefined') {- let framed = false;- const ro = new ResizeObserver(() => {- if (!framed && canvas.clientWidth > 0) { framed = true; this.graph.fit(); ro.disconnect(); }- });- ro.observe(canvas);- }this.runtime = new BrainRuntime({graphView: this.graph,studio: this.studio,@@ -293,7 +276,6 @@ class BrainStudio {this._showEditor();this.graph.load(normalizeGraph(graph));this._onGraphChange(this.graph.toGraph(), { immediate: true });- this._renderInspector(null);}// ── Persistence ─────────────────────────────────────────────────────────@@ -312,79 +294,6 @@ class BrainStudio {else this._saveTimer = setTimeout(persist, 400);}- // ── Inspector ─────────────────────────────────────────────────────────────-- _renderInspector(node) {- const host = this.el.querySelector('#bsInspector');- if (!node) {- host.innerHTML = `<div class="brainstudio__inspector-empty"><h3>Inspector</h3><p>Select a node to edit it, or drag from a node's right-hand port to wire it into another.</p></div>`;- return;- }- const spec = NODE_TYPES[node.type];- host.innerHTML = `<div class="brainstudio__insp-head"><span class="brainstudio__insp-dot brainstudio__insp-dot--${spec.accent}"></span><h3>${esc(spec.title)}</h3></div>- <div class="brainstudio__fields">${spec.fields.map((f) => this._fieldHtml(f, node.data[f.key])).join('')}</div>`;- host.querySelectorAll('[data-field]').forEach((inp) => {- const key = inp.dataset.field;- const field = spec.fields.find((f) => f.key === key);- const handler = () => this.graph.updateNodeData(node.id, { [key]: this._readField(field, inp) });- inp.addEventListener(inp.tagName === 'SELECT' || inp.type === 'checkbox' ? 'change' : 'input', handler);- });- }-- _fieldHtml(field, value) {- const id = `f_${field.key}`;- const label = `<label class="brainstudio__field-label" for="${id}">${esc(field.label)}</label>`;- let control = '';- switch (field.type) {- case 'textarea':- control = `<textarea class="brainstudio__input" id="${id}" data-field="${field.key}" rows="2">${esc(value || '')}</textarea>`;- break;- case 'number':- control = `<input class="brainstudio__input" id="${id}" data-field="${field.key}" type="number" min="${field.min ?? ''}" max="${field.max ?? ''}" step="${field.step ?? 1}" value="${esc(value ?? '')}" />`;- break;- case 'toggle':- control = `<label class="brainstudio__toggle"><input id="${id}" data-field="${field.key}" type="checkbox" ${value ? 'checked' : ''} /><span></span></label>`;- break;- case 'select':- control = `<select class="brainstudio__input" id="${id}" data-field="${field.key}">${field.options.map((o) => `<option value="${esc(o)}" ${o === value ? 'selected' : ''}>${esc(o)}</option>`).join('')}</select>`;- break;- case 'provider':- control = this._providerSelect(id, field.key, value);- break;- case 'skill':- control = this._skillSelect(id, field.key, value);- break;- case 'tags':- control = `<input class="brainstudio__input" id="${id}" data-field="${field.key}" type="text" value="${esc((value || []).join(', '))}" placeholder="comma, separated" />`;- break;- default:- control = `<input class="brainstudio__input" id="${id}" data-field="${field.key}" type="text" value="${esc(value ?? '')}" placeholder="${esc(field.placeholder || '')}" />`;- }- return `<div class="brainstudio__field">${label}${control}</div>`;- }-- _providerSelect(id, key, value) {- const list = this.providers.length ? this.providers : [{ key: value || 'claude-sonnet-4-6', label: value || 'Claude Sonnet 4.6', available: true, tier: '', network: '' }];- const opts = list.map((p) => `<option value="${esc(p.key)}" ${p.key === value ? 'selected' : ''} ${p.available ? '' : 'disabled'}>${esc(p.label)}${p.available ? '' : ' (no key)'}${p.tier ? ` · ${esc(p.tier)}` : ''}</option>`).join('');- return `<select class="brainstudio__input" id="${id}" data-field="${key}">${opts}</select>`;- }-- _skillSelect(id, key, value) {- const skills = this.studio.agent?.skills || [];- if (!skills.length) return `<input class="brainstudio__input" id="${id}" data-field="${key}" type="text" value="${esc(value || '')}" placeholder="no skills enabled yet" />`;- const opts = ['<option value="">— pick a skill —</option>', ...skills.map((s) => `<option value="${esc(s)}" ${s === value ? 'selected' : ''}>${esc(s)}</option>`)].join('');- return `<select class="brainstudio__input" id="${id}" data-field="${key}">${opts}</select>`;- }-- _readField(field, inp) {- switch (field.type) {- case 'number': return Number(inp.value);- case 'toggle': return inp.checked;- case 'tags': return inp.value.split(',').map((s) => s.trim()).filter(Boolean);- default: return inp.value;- }- }-// ── Test chat ───────────────────────────────────────────────────────────_updateTestModelLabel(compiled) {diff --git a/tests/token-layer.test.js b/tests/token-layer.test.jsindex 869e7d0df..a9bb4f1c9 100644--- a/tests/token-layer.test.js+++ b/tests/token-layer.test.js@@ -262,7 +262,8 @@ describe('getTokenPriceUsd', () => {expect(p.priceUsd).toBe(0.000307);expect(p.source).toBe('jupiter');expect(p.mint).toBe(TOKEN_MINT);- expect(cacheSet).toHaveBeenCalledOnce();+ // Writes the live cache AND the long-lived last-known-good entry.+ expect(cacheSet).toHaveBeenCalledTimes(2);});it('falls back to Birdeye when Jupiter returns null price', async () => {@@ -307,6 +308,52 @@ describe('getTokenPriceUsd', () => {if (priorKey !== undefined) process.env.BIRDEYE_API_KEY = priorKey;else delete process.env.BIRDEYE_API_KEY;});++ it('serves a recent last-known-good price when every live feed misses', async () => {+ const priorKey = process.env.BIRDEYE_API_KEY;+ process.env.BIRDEYE_API_KEY = 'test-key';+ // All four live feeds miss this request...+ fetchResponses.push({ ok: false, status: 503, body: 'down' }); // jupiter+ fetchResponses.push({ ok: false, status: 503, body: 'down' }); // birdeye+ fetchResponses.push({ ok: false, status: 503, body: 'down' }); // dexscreener+ fetchResponses.push({ ok: false, status: 503, body: 'down' }); // geckoterminal+ // ...but a 60s-old last-known-good is in cache (live key miss, last-good hit).+ cacheGet.mockResolvedValueOnce(null); // live PRICE_CACHE_KEY (skipped on fresh, harmless)+ cacheGet.mockResolvedValueOnce({+ priceUsd: 0.00042,+ source: 'jupiter',+ mint: TOKEN_MINT,+ at: new Date(Date.now() - 60_000).toISOString(),+ });+ const p = await getTokenPriceUsd({ fresh: true });+ expect(p.priceUsd).toBe(0.00042);+ expect(p.stale).toBe(true);+ expect(p.source).toBe('jupiter-stale');+ if (priorKey !== undefined) process.env.BIRDEYE_API_KEY = priorKey;+ else delete process.env.BIRDEYE_API_KEY;+ });++ it('rejects a last-known-good price older than the staleness window', async () => {+ const priorKey = process.env.BIRDEYE_API_KEY;+ process.env.BIRDEYE_API_KEY = 'test-key';+ fetchResponses.push({ ok: false, status: 503, body: 'down' }); // jupiter+ fetchResponses.push({ ok: false, status: 503, body: 'down' }); // birdeye+ fetchResponses.push({ ok: false, status: 503, body: 'down' }); // dexscreener+ fetchResponses.push({ ok: false, status: 503, body: 'down' }); // geckoterminal+ // A 10-minute-old price is beyond the 5-minute window → still fail rather+ // than price a payment off a stale number.+ cacheGet.mockResolvedValue({+ priceUsd: 0.00042,+ source: 'jupiter',+ mint: TOKEN_MINT,+ at: new Date(Date.now() - 600_000).toISOString(),+ });+ await expect(getTokenPriceUsd({ fresh: true })).rejects.toMatchObject({+ code: 'price_unavailable',+ });+ if (priorKey !== undefined) process.env.BIRDEYE_API_KEY = priorKey;+ else delete process.env.BIRDEYE_API_KEY;+ });});describe('quoteTokenForUsd', () => {