Skip to content

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.

refactor: remove BrainGraphView and integrate BrainComposer for agent design

qrqk1d4e899485b2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c8c505058..ebc3136a4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,9 +6,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-28
+- **$THREE payments ride out brief price-feed blips instead of failing** — Paid actions priced in $THREE (Forge high tier, spins, marketplace) no longer fail when every live price feed happens to miss on the same request. The price layer now keeps a recent last-known-good price and serves it through a momentary simultaneous outage of Jupiter and the backup feeds, so a quote is never rejected over a transient blip. Prices older than five minutes are still refused — a payment is never priced off a stale number. (`/three-token`) `[fix]`
- **Agent Reputation Leaderboard — top agents promoted in marketplace by on-chain trust score** — The platform now autonomously ranks the top 10 three.ws agents by behavioral trust score every 30 minutes via a real x402 payment to the agent-reputation endpoint. Scores are synthesized from real on-chain pump.fun agent-payments activity, distribution/buyback success, and signed Solana attestations — not a subjective rating. The top 10 are promoted to the front of the marketplace recommended feed and marked with a ◈ Top Trust badge. The ranking is also stored as an oracle signal (topic: agent_reputation_leaderboard) for downstream systems to query. Full snapshot history is written to agent_reputation_leaderboard_snapshots so trust trends are auditable over time. (`/marketplace`) `[feature, improvement]`
- **API Key Validity Health — the platform verifies its own access keys every hour** — A lapsed or missing access key for the autonomous loop means every self-call in the pipeline hits the paywall cold — legitimate tool calls start failing, recovery is manual, and the outage is invisible until someone investigates why the spend log went quiet. The platform now detects this automatically. Every hour an autonomous agent makes a real on-chain payment to a new /api/x402/api-key-health endpoint with body { scope: "autonomous_loop" }. The endpoint checks whether any active subscription key covers the requested scope, falling back to the INTERNAL_API_KEY env var, and returns { valid, scopes, expires_at }. The extracted signal surfaces hours_until_expiry in x402_autonomous_log.signal_data. When expiry is within 24 hours the storeValue hook writes a Redis alert (x402:api-key-health:expiry-alert) so the ops surface can surface the warning before the key lapses. `[infra, feature]`
- **Auth Session Lifecycle Health — the platform canaries its own JWT auth pipeline every 30 minutes** — A broken auth subsystem — a JWT signer that stops working, a verifier that accepts expired tokens, or a misconfigured issuer — can lock users out silently or, worse, leave a security hole open. The platform now detects both within 30 minutes. Every half-hour an autonomous agent makes a real on-chain payment to a new /api/x402/auth-health endpoint and runs a four-step session lifecycle canary: mint a canary access token, verify it with the full JWT verifier, issue a replacement token and re-verify it (the rotation path), and confirm that an already-expired token is rejected. Each step is timed independently; a failure names exactly which step broke and why. The result — all_pass, failed_step, and per-step latency — is recorded as an actionable signal so ops can read auth health off a single log row without a separate query. `[infra, security]`
+- **Avatar generation rides out engine outages by failing over between backends** — Describe-it-to-3D and Instant Agent Genesis no longer dead-end with "the avatar engine rejected this job" when one 3D backend has a hiccup. A request now tries every configured engine in turn — and your own Meshy or Tripo key as a backstop — before giving up, so a single provider's cold start, throttle, or outage is invisible to you. On the rare moment every engine is down at once, the error now points you straight to the selfie scanner and offers a one-tap retry instead of stranding the build. (`/create/prompt`) `[fix]`
- **Changelog Telegram bot health check** — The autonomous x402 loop now pings the changelog Telegram bot every 5 minutes by paying $0.001 USDC to the new /api/x402/telegram-health endpoint. It verifies the bot can reach the Telegram API, measures round-trip latency, and raises a Redis alert when it can't — so ops knows immediately when $THREE holders would miss a changelog entry. `[infra, feature]`
- **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]`
diff --git a/api/_lib/regen-provider.js b/api/_lib/regen-provider.js
index 368002bb5..fbcc3fec5 100644
--- a/api/_lib/regen-provider.js
+++ b/api/_lib/regen-provider.js
@@ -175,7 +175,10 @@ function platformProviderConfigured(name) {
case 'replicate':
return Boolean(process.env.REPLICATE_API_TOKEN);
case 'gcp':
- return Boolean(process.env.GCP_RECONSTRUCTION_URL);
+ // The gcp adapter needs both the service URL (endpoint) and the auth
+ // key — requiring both here keeps a URL-only deploy out of the failover
+ // rotation instead of enumerating a provider whose constructor throws.
+ return Boolean(process.env.GCP_RECONSTRUCTION_URL && process.env.GCP_RECONSTRUCTION_KEY);
case 'huggingface':
return Boolean(process.env.HF_TOKEN);
default:
diff --git a/api/agents/suggest-spec.js b/api/agents/suggest-spec.js
new file mode 100644
index 000000000..21c6e9269
--- /dev/null
+++ b/api/agents/suggest-spec.js
@@ -0,0 +1,174 @@
+// POST /api/agents/suggest-spec { prompt?: string }
+//
+// The "describe it, don't fill it in" engine behind the Create-Agent wizard.
+// A signed-in user types one sentence (or nothing at all — "surprise me") and
+// gets back a COMPLETE, ready-to-ship agent spec: name, description, tags,
+// optional skills, marketplace category, greeting, persona/system-prompt, a
+// fitting starter body, and a voice. The wizard pours it straight into its
+// form so the whole flow becomes review-and-tweak instead of type-everything.
+//
+// Real model, real provider chain (api/_lib/llm.js — free providers first, paid
+// backstop last), real spend metering. No canned responses, no fake data.
+//
+// $THREE (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump) is the only coin three.ws
+// promotes; the generator is instructed never to name or invent any other token.
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { llmComplete, llmConfigured, LlmUnavailableError } from '../_lib/llm.js';
+
+// Mirrors the optional skill set in src/create-agent.js (OPTIONAL_SKILLS). Core
+// skills are always-on and not chosen here, so they're intentionally omitted.
+const OPTIONAL_SKILLS = [
+ { id: 'wave', desc: 'Waves at people on greet or on request.' },
+ { id: 'dance', desc: 'Plays a dance animation loop on cue.' },
+ { id: 'pump-fun', desc: 'Read-only Solana market data: tokens, bonding curves, trending, rug-risk.' },
+ { id: 'explain-gltf', desc: 'Narrates mesh, material, and animation info from the 3D scene.' },
+ { id: 'web-search', desc: 'Looks things up on the live web when asked.' },
+];
+const OPTIONAL_SKILL_IDS = new Set(OPTIONAL_SKILLS.map((s) => s.id));
+
+// Mirrors CATEGORIES in src/create-agent.js / api/marketplace/[action].js.
+const CATEGORIES = [
+ 'academic', 'career', 'copywriting', 'design', 'education', 'emotions',
+ 'entertainment', 'games', 'general', 'life', 'marketing', 'office',
+ 'programming', 'translation',
+];
+const CATEGORY_SET = new Set(CATEGORIES);
+
+// Mirrors STARTERS in src/create-agent.js — the real, shipped GLB bodies the
+// wizard can pre-select. The model picks the one that best fits the vibe.
+const STARTERS = [
+ { id: 'default', vibe: 'a friendly, approachable humanoid host (good default)' },
+ { id: 'cz', vibe: 'a sharp, confident finance/markets persona' },
+ { id: 'robot', vibe: 'a playful, expressive robot — tech, games, fun' },
+ { id: 'soldier', vibe: 'a serious, disciplined, tactical character' },
+];
+const STARTER_SET = new Set(STARTERS.map((s) => s.id));
+
+// Field bounds — kept just inside the wizard's own input maxlengths so a
+// generated value never lands truncated in the form.
+const LIMITS = { name: 48, description: 240, greeting: 160, persona: 1800, tag: 24 };
+
+function buildSystem() {
+ const skillLines = OPTIONAL_SKILLS.map((s) => ` - "${s.id}": ${s.desc}`).join('\n');
+ return [
+ 'You are the agent-design copilot for three.ws, a platform where people deploy 3D AI agents with their own on-chain identity and wallet.',
+ 'Given a short brief (or none at all), design ONE complete, polished, marketplace-ready agent. Be specific and characterful — never generic filler like "a helpful assistant".',
+ '',
+ 'Return ONLY a single JSON object, no prose, no code fences, with exactly these keys:',
+ '{',
+ ' "name": string — a punchy display name, 2–48 chars (e.g. "Market Oracle", "Nova", "Zen Coach"). Letters, numbers, spaces only.',
+ ' "description": string — one or two sentences, <=240 chars, says what it does and who it is for.',
+ ' "tags": string[] — 3 to 6 lowercase discovery tags, each one or two words, no "#".',
+ ' "skills": string[] — zero or more skill ids chosen ONLY from this list, matched to the agent\'s purpose:',
+ skillLines,
+ ` "category": string — exactly one of: ${CATEGORIES.join(', ')}.`,
+ ' "greeting": string — the agent\'s first-person opening line to a visitor, <=160 chars, in character.',
+ ' "persona": string — the agent\'s system prompt / character profile, 120–600 chars: voice, expertise, how it behaves, what it refuses. Written as instructions to the agent ("You are…").',
+ ` "avatar_starter": string — the best-fitting starter body id, one of: ${STARTERS.map((s) => `"${s.id}" (${s.vibe})`).join(', ')}.`,
+ ' "voice": "browser"',
+ '}',
+ '',
+ 'Rules:',
+ '- The ONLY coin or token you may ever name is $THREE. Never mention, invent, or recommend any other coin, token, ticker, or contract address — not in the name, description, tags, persona, or greeting.',
+ '- Pick skills only when they genuinely fit the brief; an art critic does not need market data, a trader does not need to dance.',
+ '- Output must be valid JSON parseable by JSON.parse. No trailing commas, no comments, no surrounding text.',
+ ].join('\n');
+}
+
+// Pull the first balanced JSON object out of a model response, tolerating code
+// fences or stray prose around it. Returns the parsed object or null.
+function parseSpec(text) {
+ if (!text) return null;
+ let s = String(text).trim();
+ const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/i);
+ if (fence) s = fence[1].trim();
+ const start = s.indexOf('{');
+ const end = s.lastIndexOf('}');
+ if (start === -1 || end <= start) return null;
+ const slice = s.slice(start, end + 1);
+ try {
+ return JSON.parse(slice);
+ } catch {
+ return null;
+ }
+}
+
+const clampStr = (v, max) => (typeof v === 'string' ? v.trim().replace(/\s+/g, ' ').slice(0, max) : '');
+
+// Validate + clamp the raw model object into a spec the wizard can trust. Every
+// field is defended: bad/missing values fall back to safe defaults so the user
+// always gets a usable result, never a broken form.
+function normalize(raw) {
+ const out = {};
+ out.name = clampStr(raw?.name, LIMITS.name).replace(/[^\p{L}\p{N} ]/gu, '').trim() || 'New Agent';
+ out.description = clampStr(raw?.description, LIMITS.description);
+ out.greeting = clampStr(raw?.greeting, LIMITS.greeting);
+ out.persona = clampStr(raw?.persona, LIMITS.persona);
+
+ const tags = Array.isArray(raw?.tags) ? raw.tags : [];
+ out.tags = [...new Set(
+ tags
+ .map((t) => clampStr(t, LIMITS.tag).toLowerCase().replace(/^#/, '').replace(/[^a-z0-9 +-]/g, '').trim())
+ .filter(Boolean),
+ )].slice(0, 8);
+
+ const skills = Array.isArray(raw?.skills) ? raw.skills : [];
+ out.skills = [...new Set(skills.filter((s) => OPTIONAL_SKILL_IDS.has(s)))];
+
+ out.category = CATEGORY_SET.has(raw?.category) ? raw.category : 'general';
+ out.avatar_starter = STARTER_SET.has(raw?.avatar_starter) ? raw.avatar_starter : 'default';
+ out.voice = raw?.voice === 'custom' ? 'custom' : 'browser';
+ return out;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in to generate an agent');
+ const userId = session?.id ?? bearer.userId;
+
+ const rl = await limits.agentSuggest(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (!llmConfigured()) {
+ return error(res, 503, 'llm_unavailable', 'Agent generation is offline right now. Fill the form in manually — it only takes a minute.');
+ }
+
+ const body = await readJson(req).catch(() => ({}));
+ const prompt = clampStr(body?.prompt, 600);
+ const userMsg = prompt
+ ? `Brief: ${prompt}`
+ : 'No brief given — invent one distinctive, genuinely useful agent a person would be excited to deploy. Surprise me.';
+
+ let completion;
+ try {
+ completion = await llmComplete({
+ system: buildSystem(),
+ user: userMsg,
+ maxTokens: 700,
+ timeoutMs: 30_000,
+ track: { userId, tool: 'agent_suggest_spec' },
+ });
+ } catch (err) {
+ if (err instanceof LlmUnavailableError) {
+ return error(res, 503, 'llm_unavailable', 'Agent generation is offline right now. Fill the form in manually.');
+ }
+ if (err?.code === 'daily_spend_cap_exceeded') {
+ return error(res, 429, 'daily_spend_cap_exceeded', err.message);
+ }
+ return error(res, 502, 'generation_failed', 'The model could not be reached. Try again in a moment.');
+ }
+
+ const parsed = parseSpec(completion.text);
+ if (!parsed) {
+ return error(res, 502, 'generation_failed', 'The generator returned an unreadable result. Try again or tweak your description.');
+ }
+
+ return json(res, 200, { spec: normalize(parsed), provider: completion.provider });
+});
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index 86c8ec399..aa266181f 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, getRegenProviderCandidates, getRegenProviderByName, getRegenProviderForJob, BYOK_REGEN_PROVIDERS } from '../_lib/regen-provider.js';
+import { 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';
@@ -431,14 +431,16 @@ const handleRegenerate = wrap(async (req, res) => {
const rows = await sql`select id, name, storage_key from avatars where id = ${body.sourceAvatarId} and owner_id = ${userId} and deleted_at is null limit 1`;
if (!rows[0]) return error(res, 404, 'not_found', 'source avatar not found or not owned');
- let provider;
+ // Platform provider failover: try every configured provider (primary first),
+ // retrying transient faults, so a single outage / throttle / cold start
+ // doesn't dead-end the job. Mirrors the reconstruct submit path.
+ let candidates;
try {
- provider = await getRegenProvider();
+ candidates = await getRegenProviderCandidates();
} catch (err) {
return maskSubmitError(res, err);
}
-
- if (provider.name === 'none') {
+ if (candidates.length === 0) {
return error(
res,
501,
@@ -447,35 +449,60 @@ const handleRegenerate = wrap(async (req, res) => {
);
}
- // Real provider — submit the job, persist the external id.
const sourceUrl = publicUrl(rows[0].storage_key);
- let submission;
- try {
- submission = await provider.instance.submit({
- userId,
- sourceAvatarId: body.sourceAvatarId,
- mode: body.mode,
- params: body.params ?? {},
- sourceUrl,
- sourceStorageKey: rows[0].storage_key,
- });
- } catch (err) {
- return maskSubmitError(res, err);
+ let submission = null;
+ let usedProvider = null;
+ let bestError = null;
+ const attempts = [];
+ for (const provider of candidates) {
+ try {
+ submission = await submitWithTransientRetry(provider.instance, {
+ userId,
+ sourceAvatarId: body.sourceAvatarId,
+ mode: body.mode,
+ params: body.params ?? {},
+ sourceUrl,
+ sourceStorageKey: rows[0].storage_key,
+ });
+ usedProvider = provider;
+ break;
+ } catch (err) {
+ attempts.push(`${provider.name}:${err?.code || err?.status || classifyProviderError(err).code}`);
+ console.warn(
+ '[avatars] regenerate submit failed on',
+ provider.name,
+ '—',
+ err?.code || err?.status || 'unknown',
+ '-',
+ err?.message,
+ );
+ // Keep the most actionable error to surface if every provider fails.
+ if (!bestError || (isGenericProviderError(bestError) && !isGenericProviderError(err))) {
+ bestError = err;
+ }
+ }
+ }
+
+ if (!submission || !usedProvider) {
+ if (attempts.length > 1) {
+ console.warn('[avatars] all regenerate providers failed:', attempts.join(', '));
+ }
+ return maskSubmitError(res, bestError || new Error('no regenerate provider available'));
}
- const jobId = `${provider.name}-${randomUUID()}`;
+ const jobId = `${usedProvider.name}-${randomUUID()}`;
await sql`
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}, ${body.sourceAvatarId}, ${body.mode}, ${JSON.stringify(body.params ?? {})}, 'queued', ${provider.name}, ${submission.extJobId ?? null}, now(), now())
+ (${jobId}, ${userId}, ${body.sourceAvatarId}, ${body.mode}, ${JSON.stringify(body.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,
});
});
@@ -1091,7 +1118,7 @@ const handleReconstruct = wrap(async (req, res) => {
const attempts = [];
for (const provider of candidates) {
try {
- submission = await provider.instance.submit({
+ submission = await submitWithTransientRetry(provider.instance, {
userId,
mode: 'reconstruct',
params: { ...(body.params ?? {}), images: photos, name: body.name },
@@ -1202,6 +1229,43 @@ function isGenericProviderError(err) {
return classifyProviderError(err).code === 'regen_provider_error';
}
+// Infra faults worth one quick retry against the *same* provider before failing
+// over or giving up: transport errors and upstream 5xx. These are the cold-start
+// and transient-network failures behind most "engine rejected the job" 502s — a
+// single bounded retry clears them without the user noticing, and on a
+// single-provider deployment it's the only second chance there is. Deterministic
+// faults (bad key, no credits, bad input, throttle, a provider 4xx) are never
+// retried here: an identical second call won't change the outcome.
+export function isTransientProviderError(err) {
+ if (!err) return false;
+ if (err.code === 'provider_unreachable' || err.code === 'provider_timeout') return true;
+ const upstream = Number(err.providerStatus) || 0;
+ if (err.code === 'provider_error') {
+ // No upstream status (couldn't even parse a response) or a 5xx → transient.
+ // A concrete provider 4xx (e.g. 422 bad image) is deterministic — don't retry.
+ return upstream === 0 || upstream >= 500;
+ }
+ const status = Number(err.status) || 0;
+ return status === 503 || status === 504;
+}
+
+const SUBMIT_RETRY_DELAY_MS = 1500;
+
+// Submit one provider job, retrying once on a transient infra fault. The retry
+// is safe against double-charging: a provider only spends credits / creates the
+// upstream prediction on a successful return, so a thrown error means nothing
+// was queued. Non-transient errors propagate immediately for the caller to
+// classify (and, in the failover loop, fail over to the next provider).
+export async function submitWithTransientRetry(instance, request) {
+ try {
+ return await instance.submit(request);
+ } catch (err) {
+ if (!isTransientProviderError(err)) throw err;
+ await new Promise((resolve) => setTimeout(resolve, SUBMIT_RETRY_DELAY_MS));
+ return instance.submit(request);
+ }
+}
+
// ── dispatcher ────────────────────────────────────────────────────────────────
const DISPATCH = {
diff --git a/data/changelog.json b/data/changelog.json
index bc0f4d273..2f4afc7f6 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,24 @@
{
"$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": "Avatar generation rides out engine outages by failing over between backends",
+ "summary": "Describe-it-to-3D and Instant Agent Genesis no longer dead-end with \"the avatar engine rejected this job\" when one 3D backend has a hiccup. A request now tries every configured engine in turn — and your own Meshy or Tripo key as a backstop — before giving up, so a single provider's cold start, throttle, or outage is invisible to you. On the rare moment every engine is down at once, the error now points you straight to the selfie scanner and offers a one-tap retry instead of stranding the build.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/create/prompt"
+ },
+ {
+ "date": "2026-06-28",
+ "title": "$THREE payments ride out brief price-feed blips instead of failing",
+ "summary": "Paid actions priced in $THREE (Forge high tier, spins, marketplace) no longer fail when every live price feed happens to miss on the same request. The price layer now keeps a recent last-known-good price and serves it through a momentary simultaneous outage of Jupiter and the backup feeds, so a quote is never rejected over a transient blip. Prices older than five minutes are still refused — a payment is never priced off a stale number.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/three-token"
+ },
{
"date": "2026-06-28",
"title": "Forge no longer dead-ends on \"Generator not configured\" when a free lane is live",
diff --git a/pages/create-agent.html b/pages/create-agent.html
index c06f5c457..912505b39 100644
--- a/pages/create-agent.html
+++ b/pages/create-agent.html
@@ -395,6 +395,210 @@
display: block;
}
+ /* ── Magic generator (zero-typing entry) ───────────────────────── */
+ .magic {
+ position: relative;
+ border-radius: 14px;
+ padding: 18px 18px 16px;
+ margin: 0 0 26px;
+ background:
+ radial-gradient(120% 140% at 0% 0%, rgba(255, 255, 255, 0.06), transparent 55%),
+ var(--panel-2);
+ border: 1px solid var(--border-strong);
+ overflow: hidden;
+ }
+ .magic::before {
+ content: '';
+ position: absolute;
+ inset: 0;
+ border-radius: 14px;
+ padding: 1px;
+ background: linear-gradient(120deg, rgba(255, 255, 255, 0.28), transparent 40%, transparent 60%, rgba(255, 255, 255, 0.18));
+ -webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
+ -webkit-mask-composite: xor;
+ mask-composite: exclude;
+ pointer-events: none;
+ opacity: 0.55;
+ }
+ .magic-head {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ margin: 0 0 4px;
+ }
+ .magic-head svg {
+ width: 17px;
+ height: 17px;
+ color: var(--text);
+ flex: none;
+ }
+ .magic-title {
+ font-family: var(--font-display);
+ font-size: 15px;
+ font-weight: 600;
+ margin: 0;
+ letter-spacing: -0.01em;
+ }
+ .magic-sub {
+ color: var(--muted);
+ font-size: 12.5px;
+ margin: 0 0 13px;
+ line-height: 1.5;
+ }
+ .magic-row {
+ display: flex;
+ gap: 9px;
+ align-items: stretch;
+ }
+ .magic-input {
+ flex: 1;
+ background: #0c0c0c;
+ border: 1px solid var(--border-strong);
+ border-radius: 10px;
+ color: var(--text);
+ font: inherit;
+ font-size: 14px;
+ padding: 11px 13px;
+ resize: none;
+ min-height: 46px;
+ line-height: 1.45;
+ transition: border-color 0.16s, box-shadow 0.16s;
+ outline: none;
+ }
+ .magic-input:focus {
+ border-color: rgba(255, 255, 255, 0.5);
+ box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.06);
+ }
+ .magic-input::placeholder {
+ color: #555;
+ }
+ .magic-go {
+ flex: none;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 7px;
+ padding: 0 18px;
+ min-width: 128px;
+ border-radius: 10px;
+ border: 0;
+ background: var(--accent);
+ color: var(--accent-ink);
+ font: inherit;
+ font-size: 13.5px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: transform 0.12s, opacity 0.16s, box-shadow 0.16s;
+ }
+ .magic-go svg {
+ width: 15px;
+ height: 15px;
+ }
+ .magic-go:hover {
+ box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.08);
+ }
+ .magic-go:active {
+ transform: translateY(1px);
+ }
+ .magic-go:disabled {
+ opacity: 0.6;
+ cursor: default;
+ box-shadow: none;
+ }
+ .magic-spin {
+ width: 14px;
+ height: 14px;
+ border: 2px solid rgba(0, 0, 0, 0.25);
+ border-top-color: var(--accent-ink);
+ border-radius: 50%;
+ animation: magic-rot 0.7s linear infinite;
+ display: none;
+ }
+ .magic-go[aria-busy='true'] .magic-spin {
+ display: inline-block;
+ }
+ .magic-go[aria-busy='true'] .magic-go-icon {
+ display: none;
+ }
+ @keyframes magic-rot {
+ to {
+ transform: rotate(360deg);
+ }
+ }
+ .magic-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 7px;
+ margin: 12px 0 0;
+ align-items: center;
+ }
+ .magic-chips .lead {
+ font-size: 11.5px;
+ color: var(--faint);
+ margin-right: 1px;
+ }
+ .magic-chip {
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--border-strong);
+ border-radius: 999px;
+ color: var(--muted);
+ font: inherit;
+ font-size: 12px;
+ padding: 5px 11px;
+ cursor: pointer;
+ transition: color 0.14s, border-color 0.14s, background 0.14s;
+ }
+ .magic-chip:hover {
+ color: var(--text);
+ border-color: rgba(255, 255, 255, 0.4);
+ background: rgba(255, 255, 255, 0.07);
+ }
+ .magic-chip.surprise {
+ margin-left: auto;
+ color: var(--text);
+ }
+ .magic-msg {
+ font-size: 12.5px;
+ margin: 11px 0 0;
+ min-height: 1px;
+ line-height: 1.5;
+ }
+ .magic-msg.err {
+ color: var(--err);
+ }
+ .magic-msg.ok {
+ color: var(--ok);
+ }
+ .magic-divider {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ margin: 0 0 22px;
+ color: var(--faint);
+ font-size: 11.5px;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ }
+ .magic-divider::before,
+ .magic-divider::after {
+ content: '';
+ flex: 1;
+ height: 1px;
+ background: var(--border);
+ }
+ @media (max-width: 560px) {
+ .magic-row {
+ flex-direction: column;
+ }
+ .magic-go {
+ min-width: 0;
+ padding: 11px 18px;
+ }
+ .magic-chip.surprise {
+ margin-left: 0;
+ }
+ }
+
/* ── Tag / chip input ───────────────────────────────────────────── */
.tagbox {
display: flex;
@@ -1108,10 +1312,54 @@
<p class="panel-eyebrow">Step 1 of 5</p>
<h2 class="panel-title">The basics</h2>
<p class="panel-help">
- Give your agent a name and a short description. This is what people
- see first in the marketplace and on its profile.
+ Describe your agent in a sentence and we'll fill in everything —
+ name, skills, body, personality. Then review and ship.
</p>
+ <div class="magic">
+ <div class="magic-head">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M5 3v4M3 5h4M6 17v4M4 19h4M13 3l2.5 6.5L22 12l-6.5 2.5L13 21l-2.5-6.5L4 12l6.5-2.5L13 3z" />
+ </svg>
+ <h3 class="magic-title">Build it for me</h3>
+ </div>
+ <p class="magic-sub">
+ One line is enough. No idea? Tap an example or “Surprise me”.
+ </p>
+ <div class="magic-row">
+ <textarea
+ class="magic-input"
+ id="magic-input"
+ rows="1"
+ maxlength="600"
+ autocomplete="off"
+ placeholder="e.g. a witty crypto market analyst that explains charts in plain English"
+ aria-label="Describe your agent"
+ ></textarea>
+ <button type="button" class="magic-go" id="magic-go">
+ <span class="magic-go-icon" aria-hidden="true">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M5 3v4M3 5h4M13 4l2 5 5 2-5 2-2 5-2-5-5-2 5-2 2-5z" />
+ </svg>
+ </span>
+ <span class="magic-spin" aria-hidden="true"></span>
+ <span class="magic-go-label">Generate</span>
+ </button>
+ </div>
+ <div class="magic-chips" id="magic-chips">
+ <span class="lead">Try:</span>
+ <button type="button" class="magic-chip" data-example="a calm meditation and breathing coach that guides short sessions">Meditation coach</button>
+ <button type="button" class="magic-chip" data-example="a sharp Solana market analyst that reads bonding curves and flags rug risk">Market analyst</button>
+ <button type="button" class="magic-chip" data-example="a playful 3D art critic that reviews glTF models and gives honest feedback">3D art critic</button>
+ <button type="button" class="magic-chip" data-example="an upbeat onboarding host that welcomes newcomers and shows them around">Onboarding host</button>
+ <button type="button" class="magic-chip surprise" id="magic-surprise">✦ Surprise me</button>
+ </div>
+ <p class="magic-msg" id="magic-msg" role="status" aria-live="polite"></p>
+ </div>
+
+ <div class="magic-divider">or build it by hand</div>
+
+
<div class="field">
<label class="field-label" for="f-name">
<span
diff --git a/public/brain-studio.css b/public/brain-studio.css
index fbc3758de..f8fd3a326 100644
--- a/public/brain-studio.css
+++ b/public/brain-studio.css
@@ -1,7 +1,7 @@
-/* Brain Studio (P1) — the visual, programmable agent brain.
- * Mounts inside the Agent Studio shell's Brain tab. Uses platform design tokens
- * (public/tokens.css). Scoped under .brainstudio / .bgraph so it never touches
- * the shell's own (.studio-*) styles. */
+/* Brain Studio (P1) — the programmable agent brain, edited as an ordered stack of
+ * configuration cards (the composer). Mounts inside the Agent Studio shell's Brain
+ * tab. Uses platform design tokens (public/tokens.css). Scoped under .brainstudio /
+ * .bcard / .bgroup so it never touches the shell's own (.studio-*) styles. */
.brainstudio {
--node-persona: #8b8bff;
@@ -59,103 +59,64 @@
.brainstudio__tpl-tag { font-size: var(--text-sm); color: var(--ink-dim); }
/* ── Toolbar ────────────────────────────────────────────────────────────── */
-.brainstudio__toolbar { display: flex; align-items: center; gap: var(--space-sm); padding: var(--space-sm); flex-wrap: wrap; border-bottom: 1px solid var(--surface-2); }
-.brainstudio__palette { display: flex; gap: var(--space-2xs); flex-wrap: wrap; }
+.brainstudio__toolbar { display: flex; align-items: center; gap: var(--space-sm); padding: var(--space-sm) var(--space-md); flex-wrap: wrap; border-bottom: 1px solid var(--surface-2); }
+.brainstudio__toolbar-title { display: flex; flex-direction: column; gap: 1px; }
+.brainstudio__toolbar-name { font-size: var(--text-md); font-weight: var(--weight-semibold); color: var(--ink-bright); }
+.brainstudio__toolbar-sub { font-size: var(--text-sm); color: var(--ink-dim); }
.brainstudio__tools { margin-left: auto; display: flex; gap: var(--space-2xs); }
-.brainstudio__chip {
- padding: var(--space-3xs) var(--space-sm); border-radius: var(--radius-pill); cursor: pointer;
- border: 1px solid var(--surface-3); background: var(--surface-1); color: var(--ink-dim);
- font-size: var(--text-sm); font-weight: var(--weight-medium); transition: color .15s, border-color .15s, background .15s; font-family: inherit;
-}
-.brainstudio__chip:hover { color: var(--ink); background: var(--surface-2); }
-.brainstudio__chip--persona:hover { border-color: var(--node-persona); }
-.brainstudio__chip--model:hover { border-color: var(--node-model); }
-.brainstudio__chip--memory:hover { border-color: var(--node-memory); }
-.brainstudio__chip--skill:hover { border-color: var(--node-skill); }
-.brainstudio__chip--market:hover { border-color: var(--node-market); }
-.brainstudio__chip--output:hover { border-color: var(--node-output); }
-
-/* ── Main split: canvas + side ──────────────────────────────────────────── */
+
+/* ── Main split: composer + side ────────────────────────────────────────── */
.brainstudio__main { flex: 1; display: grid; grid-template-columns: 1fr minmax(280px, 360px); gap: var(--space-sm); min-height: 0; padding: var(--space-sm); }
-.brainstudio__canvas {
- position: relative; overflow: hidden; border-radius: var(--radius-lg);
- border: 1px solid var(--surface-2); background-color: var(--bg-1);
- background-image: radial-gradient(var(--surface-3) 1px, transparent 1px);
- background-size: 22px 22px; touch-action: none; cursor: grab;
-}
-.brainstudio__canvas.is-panning { cursor: grabbing; }
+.brainstudio__form { overflow: auto; min-height: 0; padding-right: var(--space-2xs); }
.brainstudio__side { display: flex; flex-direction: column; gap: var(--space-sm); min-height: 0; }
-/* ── Graph ──────────────────────────────────────────────────────────────── */
-.bgraph { position: absolute; inset: 0; overflow: hidden; }
-.bgraph__world { position: absolute; inset: 0; transform-origin: 0 0; }
-.bgraph__edges { position: absolute; left: 0; top: 0; width: 8000px; height: 8000px; overflow: visible; pointer-events: none; }
-.bgraph__nodes { position: absolute; inset: 0; }
-.bgraph__hint { position: absolute; left: 50%; bottom: 10px; transform: translateX(-50%); font-size: var(--text-sm); color: var(--ink-dim); background: var(--surface-1); padding: 2px 10px; border-radius: var(--radius-pill); pointer-events: none; }
-
-.bedge { fill: none; stroke: var(--surface-3); stroke-width: 2; transition: stroke .2s; }
-.bedge-hit { fill: none; stroke: transparent; stroke-width: 14; pointer-events: stroke; cursor: pointer; }
-.bedge.is-active { stroke: var(--accent); stroke-width: 2.5; filter: drop-shadow(0 0 4px var(--accent)); }
-.bedge--ghost { stroke: var(--accent); stroke-dasharray: 5 4; opacity: .7; }
-.bedge.is-flow { stroke-dasharray: 7 6; animation: bflow .6s linear infinite; }
-@keyframes bflow { to { stroke-dashoffset: -26; } }
-
-.bnode {
- position: absolute; left: 0; top: 0; box-sizing: border-box;
- border-radius: var(--radius-md); border: 1px solid var(--surface-3);
- background: var(--surface-glass); backdrop-filter: blur(8px);
- box-shadow: 0 6px 24px rgba(0, 0, 0, 0.35); user-select: none;
+/* ── Composer: the brain as an ordered stack of configuration cards ──────── */
+.brainstudio__composer { display: flex; flex-direction: column; gap: var(--space-sm); }
+
+.bcard {
+ box-sizing: border-box; border-radius: var(--radius-lg);
+ border: 1px solid var(--surface-2); background: var(--surface-1);
transition: box-shadow .15s, border-color .15s;
}
-.bnode.is-selected { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent), 0 8px 28px rgba(0, 0, 0, 0.45); }
-.bnode.is-active { border-color: var(--accent); }
-.bnode.is-pulse { animation: bpulse .7s ease-out; }
-@keyframes bpulse { 0% { box-shadow: 0 0 0 0 var(--accent); } 100% { box-shadow: 0 0 0 14px transparent; } }
-.bnode.is-busy .bnode__head::after { content: ''; width: 8px; height: 8px; border-radius: 50%; background: var(--node-memory); margin-left: auto; animation: bbusy .8s ease-in-out infinite; }
+.bcard.is-active { border-color: var(--accent); }
+.bcard.is-pulse { animation: bpulse .7s ease-out; }
+@keyframes bpulse { 0% { box-shadow: 0 0 0 0 var(--accent); } 100% { box-shadow: 0 0 0 12px transparent; } }
+.bcard.is-busy .bcard__dot { animation: bbusy .8s ease-in-out infinite; }
@keyframes bbusy { 0%, 100% { opacity: .3; } 50% { opacity: 1; } }
-.bnode__head { display: flex; align-items: center; gap: var(--space-2xs); height: 34px; padding: 0 var(--space-sm); border-bottom: 1px solid var(--surface-2); cursor: grab; border-radius: var(--radius-md) var(--radius-md) 0 0; }
-.bnode__head::before { content: ''; width: 8px; height: 8px; border-radius: 2px; background: var(--accent); }
-.bnode--persona .bnode__head::before { background: var(--node-persona); }
-.bnode--model .bnode__head::before { background: var(--node-model); }
-.bnode--memory .bnode__head::before { background: var(--node-memory); }
-.bnode--skill .bnode__head::before { background: var(--node-skill); }
-.bnode--market .bnode__head::before { background: var(--node-market); }
-.bnode--output .bnode__head::before { background: var(--node-output); }
-.bnode__title { font-size: var(--text-sm); font-weight: var(--weight-semibold); color: var(--ink); }
-.bnode__del { margin-left: auto; border: 0; background: transparent; color: var(--ink-faint); cursor: pointer; font-size: var(--text-base); line-height: 1; padding: 2px 4px; border-radius: 4px; }
-.bnode__del:hover { color: var(--node-output); background: var(--surface-2); }
-.bnode__summary { padding: var(--space-2xs) var(--space-sm); font-size: var(--text-sm); color: var(--ink-dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.bnode__ports { display: flex; justify-content: space-between; padding-bottom: var(--space-2xs); }
-.bnode__col { display: flex; flex-direction: column; gap: 6px; }
-.bport { display: flex; align-items: center; gap: 5px; height: 20px; font-size: var(--text-2xs); color: var(--ink-faint); cursor: crosshair; padding: 0 var(--space-2xs); }
-.bport--out { flex-direction: row-reverse; }
-.bport__dot { width: 11px; height: 11px; border-radius: 50%; background: var(--bg-1); border: 2px solid var(--ink-dim); transition: transform .1s, border-color .15s; }
-.bport:hover .bport__dot { transform: scale(1.25); }
-.bport--signal .bport__dot { border-color: var(--node-persona); }
-.bport--context .bport__dot { border-color: var(--node-memory); }
-.bport--tool .bport__dot { border-color: var(--node-skill); }
-.bnode__stat { padding: 2px var(--space-sm) var(--space-2xs); font-size: var(--text-2xs); color: var(--node-model); }
-
-/* ── Inspector ──────────────────────────────────────────────────────────── */
-.brainstudio__inspector { background: var(--surface-1); border: 1px solid var(--surface-2); border-radius: var(--radius-lg); padding: var(--space-md); overflow: auto; max-height: 48%; }
-.brainstudio__inspector-empty h3, .brainstudio__insp-head h3 { margin: 0 0 var(--space-2xs); font-size: var(--text-md); color: var(--ink); }
-.brainstudio__inspector-empty p { margin: 0; color: var(--ink-dim); font-size: var(--text-sm); }
-.brainstudio__insp-head { display: flex; align-items: center; gap: var(--space-2xs); margin-bottom: var(--space-sm); }
-.brainstudio__insp-dot { width: 10px; height: 10px; border-radius: 3px; background: var(--accent); }
-.brainstudio__insp-dot--persona { background: var(--node-persona); }
-.brainstudio__insp-dot--model { background: var(--node-model); }
-.brainstudio__insp-dot--memory { background: var(--node-memory); }
-.brainstudio__insp-dot--skill { background: var(--node-skill); }
-.brainstudio__insp-dot--market { background: var(--node-market); }
-.brainstudio__insp-dot--output { background: var(--node-output); }
-.brainstudio__fields { display: flex; flex-direction: column; gap: var(--space-sm); }
-.brainstudio__field { display: flex; flex-direction: column; gap: var(--space-3xs); }
-.brainstudio__field-label { font-size: var(--text-sm); color: var(--ink-dim); }
-.brainstudio__input { width: 100%; box-sizing: border-box; padding: var(--space-2xs) var(--space-sm); background: var(--bg-1); color: var(--ink); border: 1px solid var(--surface-3); border-radius: var(--radius-md); font-size: var(--text-sm); font-family: inherit; }
-.brainstudio__input:focus { outline: none; border-color: var(--accent); }
-textarea.brainstudio__input { resize: vertical; }
-.brainstudio__toggle { position: relative; display: inline-block; width: 38px; height: 22px; }
+.bcard__head { display: flex; align-items: center; gap: var(--space-2xs); padding: var(--space-sm) var(--space-md) var(--space-2xs); }
+.bcard__dot { width: 10px; height: 10px; border-radius: 3px; background: var(--accent); flex: none; }
+.bcard__dot--persona { background: var(--node-persona); }
+.bcard__dot--model { background: var(--node-model); }
+.bcard__dot--memory { background: var(--node-memory); }
+.bcard__dot--skill { background: var(--node-skill); }
+.bcard__dot--market { background: var(--node-market); }
+.bcard__dot--output { background: var(--node-output); }
+.bcard__title { margin: 0; font-size: var(--text-md); font-weight: var(--weight-semibold); color: var(--ink-bright); }
+.bcard__stat { font-size: var(--text-2xs); color: var(--node-model); margin-left: var(--space-2xs); }
+.bcard__remove { margin-left: auto; border: 1px solid transparent; background: transparent; color: var(--ink-faint); cursor: pointer; font-size: var(--text-sm); padding: 2px 8px; border-radius: var(--radius-md); transition: color .15s, background .15s; font-family: inherit; }
+.bcard__remove:hover { color: var(--node-output); background: var(--surface-2); }
+.bcard__hint { margin: 0 var(--space-md) var(--space-2xs); font-size: var(--text-sm); color: var(--ink-dim); }
+.bcard--add { border-style: dashed; }
+.bcard__addbtn { margin: 0 var(--space-md) var(--space-md); }
+.bcard__fields { display: flex; flex-direction: column; gap: var(--space-sm); padding: var(--space-2xs) var(--space-md) var(--space-md); }
+.bcard__field { display: flex; flex-direction: column; gap: var(--space-3xs); }
+.bcard__field:has(.brainstudio__toggle) { flex-direction: row; align-items: center; justify-content: space-between; }
+.bcard__label { font-size: var(--text-sm); color: var(--ink-dim); }
+.bcard__input { width: 100%; box-sizing: border-box; padding: var(--space-2xs) var(--space-sm); background: var(--bg-1); color: var(--ink); border: 1px solid var(--surface-3); border-radius: var(--radius-md); font-size: var(--text-sm); font-family: inherit; }
+.bcard__input:focus { outline: none; border-color: var(--accent); }
+textarea.bcard__input { resize: vertical; }
+
+/* Repeatable groups: Skills, Market signals */
+.bgroup { display: flex; flex-direction: column; gap: var(--space-sm); border: 1px solid var(--surface-2); border-radius: var(--radius-lg); padding: var(--space-sm) var(--space-md) var(--space-md); background: var(--surface-1); }
+.bgroup__head { display: flex; align-items: center; gap: var(--space-2xs); }
+.bgroup__title { margin: 0; font-size: var(--text-md); font-weight: var(--weight-semibold); color: var(--ink-bright); }
+.bgroup__add { margin-left: auto; padding: var(--space-3xs) var(--space-sm); }
+.bgroup__empty { margin: 0; font-size: var(--text-sm); color: var(--ink-dim); }
+.bgroup .bcard { background: var(--bg-1); }
+
+/* ── Toggle (shared by composer cards) ──────────────────────────────────── */
+.brainstudio__toggle { position: relative; display: inline-block; width: 38px; height: 22px; flex: none; }
.brainstudio__toggle input { opacity: 0; width: 0; height: 0; }
.brainstudio__toggle span { position: absolute; inset: 0; background: var(--surface-3); border-radius: var(--radius-pill); transition: background .15s; cursor: pointer; }
.brainstudio__toggle span::before { content: ''; position: absolute; width: 16px; height: 16px; left: 3px; top: 3px; background: var(--ink); border-radius: 50%; transition: transform .15s; }
@@ -217,15 +178,11 @@ textarea.brainstudio__input { resize: vertical; }
/* ── Responsive ─────────────────────────────────────────────────────────── */
@media (max-width: 1024px) {
- .brainstudio__main { grid-template-columns: 1fr; grid-template-rows: minmax(260px, 1fr) auto; }
- .brainstudio__side { flex-direction: row; }
- .brainstudio__inspector { max-height: none; flex: 1; }
+ .brainstudio__main { grid-template-columns: 1fr; grid-template-rows: auto minmax(260px, 1fr); }
+ .brainstudio__form { max-height: 50vh; }
.brainstudio__test { flex: 1; }
}
-@media (max-width: 720px) {
- .brainstudio__side { flex-direction: column; }
-}
@media (prefers-reduced-motion: reduce) {
- .bedge.is-flow { animation: none; }
- .bnode.is-pulse, .bnode.is-busy .bnode__head::after { animation: none; }
+ .bcard.is-pulse, .bcard.is-busy .bcard__dot { animation: none; }
+ .bcard.is-active { box-shadow: 0 0 0 1px var(--accent); }
}
diff --git a/public/changelog.json b/public/changelog.json
index 2c3166c86..0f86da7e7 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-06-28T05:53:38.609Z",
+ "generated_at": "2026-06-28T05:57:27.534Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-28",
+ "type": "update",
+ "title": "$THREE payments ride out brief price-feed blips instead of failing",
+ "summary": "Paid actions priced in $THREE (Forge high tier, spins, marketplace) no longer fail when every live price feed happens to miss on the same request. The price layer now keeps a recent last-known-good price and serves it through a momentary simultaneous outage of Jupiter and the backup feeds, so a quote is never rejected over a transient blip. Prices older than five minutes are still refused — a payment is never priced off a stale number.",
+ "link": "/three-token",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-06-28",
"type": "update",
@@ -39,6 +49,16 @@
"security"
]
},
+ {
+ "date": "2026-06-28",
+ "type": "update",
+ "title": "Avatar generation rides out engine outages by failing over between backends",
+ "summary": "Describe-it-to-3D and Instant Agent Genesis no longer dead-end with \"the avatar engine rejected this job\" when one 3D backend has a hiccup. A request now tries every configured engine in turn — and your own Meshy or Tripo key as a backstop — before giving up, so a single provider's cold start, throttle, or outage is invisible to you. On the rare moment every engine is down at once, the error now points you straight to the selfie scanner and offers a one-tap retry instead of stranding the build.",
+ "link": "/create/prompt",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-06-28",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index edd84e488..ad727c92c 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>$THREE payments ride out brief price-feed blips instead of failing</title>
+ <link>https://three.ws/three-token</link>
+ <guid isPermaLink="false">2026-06-28:$THREE payments ride out brief price-feed blips instead of failing</guid>
+ <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Paid actions priced in $THREE (Forge high tier, spins, marketplace) no longer fail when every live price feed happens to miss on the same request. The price layer now keeps a recent last-known-good price and serves it through a momentary simultaneous outage of Jupiter and the backup feeds, so a quote is never rejected over a transient blip. Prices older than five minutes are still refused — a payment is never priced off a stale number.</description>
+ </item>
<item>
<title>Agent Reputation Leaderboard — top agents promoted in marketplace by on-chain trust score</title>
<link>https://three.ws/marketplace</link>
@@ -30,6 +38,14 @@
<category>infra</category>
<description>A broken auth subsystem — a JWT signer that stops working, a verifier that accepts expired tokens, or a misconfigured issuer — can lock users out silently or, worse, leave a security hole open. The platform now detects both within 30 minutes. Every half-hour an autonomous agent makes a real on-chain payment to a new /api/x402/auth-health endpoint and runs a four-step session lifecycle canary: mint a canary access token, verify it with the full JWT verifier, issue a replacement token and re-verify it (the rotation path), and confirm that an already-expired token is rejected. Each step is timed independently; a failure names exactly which step broke and why. The result — all_pass, failed_step, and per-step latency — is recorded as an actionable signal so ops can read auth health off a single log row without a separate query.</description>
</item>
+ <item>
+ <title>Avatar generation rides out engine outages by failing over between backends</title>
+ <link>https://three.ws/create/prompt</link>
+ <guid isPermaLink="false">2026-06-28:Avatar generation rides out engine outages by failing over between backends</guid>
+ <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Describe-it-to-3D and Instant Agent Genesis no longer dead-end with &quot;the avatar engine rejected this job&quot; when one 3D backend has a hiccup. A request now tries every configured engine in turn — and your own Meshy or Tripo key as a backstop — before giving up, so a single provider's cold start, throttle, or outage is invisible to you. On the rare moment every engine is down at once, the error now points you straight to the selfie scanner and offers a one-tap retry instead of stranding the build.</description>
+ </item>
<item>
<title>Changelog Telegram bot health check</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 5692479de..45540b783 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-28T05:53:38.540Z",
+ "generated_at": "2026-06-28T05:57:27.436Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/create-agent.js b/src/create-agent.js
index 3baba0062..855efde97 100644
--- a/src/create-agent.js
+++ b/src/create-agent.js
@@ -119,6 +119,10 @@ const state = {
const $ = (id) => document.getElementById(id);
const el = {};
+// Set by wireTagInput so the magic generator can repaint the tag chips after it
+// rewrites state.tags wholesale (the per-keystroke renderer lives in a closure).
+let tagRenderer = () => {};
+
// ── Boot ────────────────────────────────────────────────────────────────────
async function boot() {
diff --git a/src/create-prompt.js b/src/create-prompt.js
index 05f76c816..3070f1a93 100644
--- a/src/create-prompt.js
+++ b/src/create-prompt.js
@@ -204,7 +204,14 @@ function mapSubmitError(status, data) {
if (code === 'txt2img_billing') return 'The image engine is temporarily unavailable (provider billing). Try again later.';
if (code === 'txt2img_unreachable') return 'Couldn\'t reach the image engine. Check your connection and try again.';
if (code === 'txt2img_error') return 'Couldn\'t render a reference image from that prompt. Try rewording it.';
- if (code === 'regen_provider_error') return 'The avatar engine rejected this job. Try again in a moment.';
+ if (code === 'regen_needs_byok')
+ return 'Avatar generation needs a 3D engine key on this deployment. Add a Meshy or Tripo key in <a href="/settings">settings</a>, or try the <a href="/create/selfie">selfie scanner</a>.';
+ // Reached only after the server has tried every configured backend (platform
+ // providers + your BYOK keys) and all of them failed — so this is a genuine
+ // transient outage, not a single-provider hiccup. Offer the photo path as an
+ // immediate alternative rather than leaving the user to guess.
+ if (code === 'regen_provider_error')
+ return 'The avatar engines are all busy right now. Try again in a moment, or use the <a href="/create/selfie">selfie scanner</a> instead.';
return description || `The avatar engine returned ${status}. Try again.`;
}
@@ -388,9 +395,17 @@ function failBuild(err) {
log.error('[create-prompt]', err);
const message =
err instanceof ApiError ? err.message : 'Something went wrong. Try again.';
- setError(buildError, `<span>${message}</span> <button type="button" id="build-retry" class="cancel-build" style="margin-left:10px">Edit prompt</button>`);
- const retry = document.getElementById('build-retry');
- if (retry) retry.addEventListener('click', resetToCompose);
+ // Two recovery paths: "Try again" re-submits the same prompt in place (the
+ // textarea still holds it) for transient engine outages; "Edit prompt" returns
+ // to compose to reword. Both keep the user moving instead of stranding them.
+ setError(
+ buildError,
+ `<span>${message}</span>` +
+ ` <button type="button" id="build-retry-now" class="cancel-build" style="margin-left:10px">Try again</button>` +
+ ` <button type="button" id="build-edit" class="cancel-build" style="margin-left:8px">Edit prompt</button>`,
+ );
+ document.getElementById('build-retry-now')?.addEventListener('click', () => start());
+ document.getElementById('build-edit')?.addEventListener('click', resetToCompose);
}
// ── Elapsed clock ────────────────────────────────────────────────────────────
diff --git a/src/forge-studio/create-prompt.js b/src/forge-studio/create-prompt.js
index 36fe7b16e..5f1c6e574 100644
--- a/src/forge-studio/create-prompt.js
+++ b/src/forge-studio/create-prompt.js
@@ -153,7 +153,10 @@ function mapSubmitError(status, data) {
if (code === 'txt2img_billing') return 'The image engine is temporarily unavailable (provider billing). Try again later.';
if (code === 'txt2img_unreachable') return 'Couldn\'t reach the image engine. Check your connection and try again.';
if (code === 'txt2img_error') return 'Couldn\'t render a reference image from that prompt. Try rewording it.';
- if (code === 'regen_provider_error') return 'The avatar engine rejected this job. Try again in a moment.';
+ if (code === 'regen_needs_byok')
+ return 'Avatar generation needs a 3D engine key on this deployment. Add a Meshy or Tripo key in <a href="/settings">settings</a>, or try the <a href="/create/selfie">selfie scanner</a>.';
+ if (code === 'regen_provider_error')
+ return 'The avatar engines are all busy right now. Try again in a moment, or use the <a href="/create/selfie">selfie scanner</a> instead.';
return description || `The avatar engine returned ${status}. Try again.`;
}
diff --git a/src/genesis.js b/src/genesis.js
index a487d21f0..d461124f1 100644
--- a/src/genesis.js
+++ b/src/genesis.js
@@ -419,7 +419,8 @@ function mapReconstructError(status, data) {
const code = typeof data?.error === 'string' ? data.error : data?.code;
if (status === 429 || code === 'txt2img_rate_limited') return 'The avatar engine is busy. Wait a moment and try again.';
if (code === 'txt2img_error') return "Couldn't render from that prompt. Try rewording it.";
- if (code === 'regen_provider_error') return 'The avatar engine rejected this job. Try again shortly.';
+ if (code === 'regen_needs_byok') return 'Avatar generation needs a 3D engine key on this deployment. Add a Meshy or Tripo key in settings, or use the selfie scanner.';
+ if (code === 'regen_provider_error') return 'The avatar engines are all busy right now. Try again shortly.';
if (status === 413) return 'That photo is too large. Try a smaller image.';
return apiError(data, `The avatar engine returned ${status}. Try again.`);
}
diff --git a/src/studio/brain/brain-composer.js b/src/studio/brain/brain-composer.js
index 94e964d76..e3b60e7a9 100644
--- a/src/studio/brain/brain-composer.js
+++ b/src/studio/brain/brain-composer.js
@@ -31,10 +31,6 @@ import { NODE_TYPES, makeNode, edge } from './brain-nodes.js';
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[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;
@@ -258,11 +254,23 @@ export class BrainComposer {
_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" />`;
+ if (!skills.length) return `<input class="bcard__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="bcard__input" id="${id}" data-field="${key}">${opts}</select>`;
}
+ // Model availability is fetched async (GET /api/brain/chat) and can land after the
+ // composer first renders. Refresh the Model card's picker in place — targeted, so a
+ // user mid-edit on another card keeps focus and unsaved text.
+ setProviders() {
+ const model = this.nodes.find((n) => n.type === 'model');
+ const sel = model && this._cardEls.get(model.id)?.querySelector('[data-field="provider"]');
+ if (!sel) return;
+ const fresh = document.createRange().createContextualFragment(this._providerSelect(sel.id, 'provider', model.data.provider)).firstElementChild;
+ fresh.addEventListener('change', () => this.updateNodeData(model.id, { provider: fresh.value }));
+ sel.replaceWith(fresh);
+ }
+
_readField(field, inp) {
switch (field.type) {
case 'number': return Number(inp.value);
diff --git a/src/studio/brain/brain-form.js b/src/studio/brain/brain-form.js
deleted file mode 100644
index b15cfeca4..000000000
--- a/src/studio/brain/brain-form.js
+++ /dev/null
@@ -1,325 +0,0 @@
-/**
- * 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) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[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-graph.js b/src/studio/brain/brain-graph.js
deleted file mode 100644
index d7a866b24..000000000
--- a/src/studio/brain/brain-graph.js
+++ /dev/null
@@ -1,431 +0,0 @@
-/**
- * Brain Studio — visual node-graph editor (P1)
- * ============================================
- * A dependency-free node editor built on DOM nodes + an SVG edge layer inside a
- * pan/zoom world. We deliberately did NOT pull in Rete.js / litegraph / React
- * Flow: the main app is vanilla and we cannot add npm deps in this environment,
- * AND keeping the renderer ours means the saved format is ours (brain-nodes.js),
- * never a library's internal schema leaking into the DB — and the live "thinking"
- * animation can address our own nodes/edges directly. ~1 file, zero deps, full
- * control of the screenshot moment.
- *
- * Public API:
- * new BrainGraphView(host, { onChange, onSelect })
- * .load(graph) — render a normalized graph
- * .toGraph() — serialize current state
- * .addNode(type) — drop a node at viewport centre
- * .removeNode(id) / .removeEdge(id)
- * .select(id|null)
- * .fit() — frame all nodes
- * Active-path animation (driven by brain-runtime.js):
- * .setActive(nodeIds, edgeIds) / .pulseNode(id) / .flowEdge(id) / .clearActive()
- */
-
-import { NODE_TYPES, canConnect, makeNode } from './brain-nodes.js';
-
-const NODE_W = 208;
-const HEADER_H = 34;
-const PORT_ROW = 26;
-const PORT_PAD = 10;
-
-const escapeHtml = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
-
-export class BrainGraphView {
- constructor(host, { onChange, onSelect } = {}) {
- this.host = host;
- this.onChange = onChange || (() => {});
- this.onSelect = onSelect || (() => {});
- this.nodes = [];
- this.edges = [];
- this.selectedId = null;
- this.scale = 1;
- this.tx = 0;
- this.ty = 0;
- this._nodeEls = new Map();
- this._linking = null; // { from, fromPort, kind, ghost }
- this._render();
- }
-
- _render() {
- this.host.classList.add('bgraph');
- this.host.innerHTML = `
- <div class="bgraph__world" id="bgWorld">
- <svg class="bgraph__edges" id="bgEdges" aria-hidden="true"></svg>
- <div class="bgraph__nodes" id="bgNodes"></div>
- </div>
- <div class="bgraph__hint" id="bgHint"></div>`;
- this.world = this.host.querySelector('#bgWorld');
- this.svg = this.host.querySelector('#bgEdges');
- this.nodesEl = this.host.querySelector('#bgNodes');
- this._bindCanvas();
- }
-
- // ── Load / serialize ──────────────────────────────────────────────────────
-
- load(graph) {
- this.nodes = graph.nodes.map((n) => ({ ...n, data: { ...n.data } }));
- this.edges = graph.edges.map((e) => ({ ...e }));
- this.selectedId = null;
- this._renderAll();
- // Frame the graph on first load so the user always sees their circuit.
- requestAnimationFrame(() => this.fit());
- }
-
- toGraph() {
- return {
- version: 1,
- nodes: this.nodes.map((n) => ({ id: n.id, type: n.type, x: Math.round(n.x), y: Math.round(n.y), 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()); }
-
- // ── Geometry ────────────────────────────────────────────────────────────
-
- _nodeHeight(node) {
- const spec = NODE_TYPES[node.type];
- const rows = Math.max(spec.inputs.length, spec.outputs.length);
- return HEADER_H + Math.max(rows, 1) * PORT_ROW + PORT_PAD;
- }
-
- _portAnchor(node, portId, dir) {
- const spec = NODE_TYPES[node.type];
- const list = dir === 'out' ? spec.outputs : spec.inputs;
- const idx = list.findIndex((p) => p.id === portId);
- if (idx === -1) return null; // stale edge referencing a port removed from the spec
- const y = node.y + HEADER_H + idx * PORT_ROW + PORT_ROW / 2 + PORT_PAD / 2;
- const x = dir === 'out' ? node.x + NODE_W : node.x;
- return { x, y };
- }
-
- // ── Full render ─────────────────────────────────────────────────────────
-
- _renderAll() {
- this.nodesEl.innerHTML = '';
- this._nodeEls.clear();
- for (const node of this.nodes) this._renderNode(node);
- this._renderEdges();
- this._applyTransform();
- }
-
- _renderNode(node) {
- const spec = NODE_TYPES[node.type];
- const el = document.createElement('div');
- el.className = `bnode bnode--${spec.accent}`;
- el.dataset.id = node.id;
- el.style.width = `${NODE_W}px`;
- el.style.height = `${this._nodeHeight(node)}px`;
- el.style.transform = `translate(${node.x}px, ${node.y}px)`;
- el.innerHTML = `
- <div class="bnode__head"><span class="bnode__title">${escapeHtml(spec.title)}</span>${spec.single ? '' : '<button class="bnode__del" title="Delete node" aria-label="Delete node">×</button>'}</div>
- <div class="bnode__summary">${escapeHtml(this._summary(node))}</div>
- <div class="bnode__ports">
- <div class="bnode__col bnode__col--in">${spec.inputs.map((p) => this._portHtml(p, 'in')).join('')}</div>
- <div class="bnode__col bnode__col--out">${spec.outputs.map((p) => this._portHtml(p, 'out')).join('')}</div>
- </div>`;
- this.nodesEl.appendChild(el);
- this._nodeEls.set(node.id, el);
- this._bindNode(el, node);
- }
-
- _portHtml(port, dir) {
- return `<span class="bport bport--${dir} bport--${port.kind}" data-port="${port.id}" data-dir="${dir}" data-kind="${port.kind}" title="${escapeHtml(port.label)} (${port.kind})"><i class="bport__dot"></i><span class="bport__label">${escapeHtml(port.label)}</span></span>`;
- }
-
- _summary(node) {
- const d = node.data;
- switch (node.type) {
- case 'persona': return d.role || 'identity';
- case 'model': return d.provider || 'pick a model';
- case 'memory': return `recall ${d.topK} · write ${d.write ? 'on' : 'off'}`;
- case 'skill': return d.skill || 'pick a skill';
- case 'market': return `${d.trigger}${d.level ? ` @ ${d.level}` : ''}`;
- case 'output': return [d.speak && 'speak', d.emotion && 'emote', d.lipsync && 'lip-sync'].filter(Boolean).join(' · ') || 'silent';
- default: return '';
- }
- }
-
- refreshNode(id) {
- const node = this.nodes.find((n) => n.id === id);
- const el = this._nodeEls.get(id);
- if (!node || !el) return;
- el.querySelector('.bnode__summary').textContent = this._summary(node);
- }
-
- _renderEdges() {
- const parts = [];
- for (const e of this.edges) {
- const fromNode = this.nodes.find((n) => n.id === e.from);
- const toNode = this.nodes.find((n) => n.id === e.to);
- if (!fromNode || !toNode) continue;
- const a = this._portAnchor(fromNode, e.fromPort, 'out');
- const b = this._portAnchor(toNode, e.toPort, 'in');
- if (!a || !b) continue; // port removed from spec; normalizeGraph will drop it on next load
- parts.push(`<path class="bedge" data-id="${e.id}" d="${this._curve(a, b)}" />`);
- parts.push(`<path class="bedge-hit" data-id="${e.id}" d="${this._curve(a, b)}" />`);
- }
- this.svg.innerHTML = parts.join('');
- this.svg.querySelectorAll('.bedge-hit').forEach((p) => {
- p.addEventListener('click', (ev) => { ev.stopPropagation(); this.removeEdge(p.dataset.id); });
- });
- }
-
- _curve(a, b) {
- const dx = Math.max(40, Math.abs(b.x - a.x) * 0.5);
- return `M ${a.x} ${a.y} C ${a.x + dx} ${a.y}, ${b.x - dx} ${b.y}, ${b.x} ${b.y}`;
- }
-
- // ── Node interaction ──────────────────────────────────────────────────────
-
- _bindNode(el, node) {
- const head = el.querySelector('.bnode__head');
- head.addEventListener('pointerdown', (e) => this._startDrag(e, node, el));
- el.addEventListener('pointerdown', () => this.select(node.id));
- el.querySelector('.bnode__del')?.addEventListener('click', (e) => { e.stopPropagation(); this.removeNode(node.id); });
- el.querySelectorAll('.bport').forEach((portEl) => {
- portEl.addEventListener('pointerdown', (e) => {
- e.stopPropagation();
- if (portEl.dataset.dir === 'out') this._startLink(e, node, portEl);
- });
- // Connection on in-ports is handled by _startLink's global pointerup via
- // elementFromPoint — no per-port listener needed here.
- });
- }
-
- _startDrag(e, node, el) {
- e.preventDefault();
- const startX = e.clientX, startY = e.clientY;
- const ox = node.x, oy = node.y;
- const move = (ev) => {
- node.x = ox + (ev.clientX - startX) / this.scale;
- node.y = oy + (ev.clientY - startY) / this.scale;
- el.style.transform = `translate(${node.x}px, ${node.y}px)`;
- this._renderEdges();
- };
- const up = () => {
- window.removeEventListener('pointermove', move);
- window.removeEventListener('pointerup', up);
- this._emitChange();
- };
- window.addEventListener('pointermove', move);
- window.addEventListener('pointerup', up);
- }
-
- _startLink(e, node, portEl) {
- e.preventDefault();
- const kind = portEl.dataset.kind;
- const a = this._portAnchor(node, portEl.dataset.port, 'out');
- const ghost = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- ghost.setAttribute('class', 'bedge bedge--ghost');
- ghost.setAttribute('pointer-events', 'none'); // must not intercept elementFromPoint at release
- this.svg.appendChild(ghost);
- this._linking = { from: node.id, fromPort: portEl.dataset.port, kind, a, ghost };
- this.host.querySelector('#bgHint').textContent = `Connecting ${kind} — drop on a matching input`;
- const move = (ev) => {
- const pt = this._toWorld(ev.clientX, ev.clientY);
- ghost.setAttribute('d', this._curve(a, pt));
- };
- const up = (ev) => {
- window.removeEventListener('pointermove', move);
- window.removeEventListener('pointerup', up);
- const target = document.elementFromPoint(ev.clientX, ev.clientY);
- const portTarget = target?.closest?.('.bport--in');
- if (portTarget) {
- const nodeEl = portTarget.closest('.bnode');
- this._tryConnect(nodeEl?.dataset.id, portTarget.dataset.port, portTarget.dataset.kind);
- }
- ghost.remove();
- this._linking = null;
- this.host.querySelector('#bgHint').textContent = '';
- };
- window.addEventListener('pointermove', move);
- window.addEventListener('pointerup', up);
- }
-
- _tryConnect(toId, toPort, toKind) {
- if (!this._linking || !toId) return;
- const { from, fromPort, kind } = this._linking;
- if (from === toId) return;
- if (!canConnect(kind, toKind)) {
- this.host.querySelector('#bgHint').textContent = `Can't connect ${kind} → ${toKind}`;
- setTimeout(() => { this.host.querySelector('#bgHint').textContent = ''; }, 1400);
- return;
- }
- // One edge per input port (latest wins) — keeps the circuit unambiguous.
- this.edges = this.edges.filter((e) => !(e.to === toId && e.toPort === toPort));
- const id = `e_${from}.${fromPort}-${toId}.${toPort}`;
- if (!this.edges.some((e) => e.id === id)) {
- this.edges.push({ id, from, fromPort, to: toId, toPort });
- this._renderEdges();
- this._emitChange();
- }
- }
-
- // ── Mutations ─────────────────────────────────────────────────────────────
-
- addNode(type) {
- const spec = NODE_TYPES[type];
- if (spec.single && this.nodes.some((n) => n.type === type)) {
- this.host.querySelector('#bgHint').textContent = `Only one ${spec.title} node allowed`;
- setTimeout(() => { this.host.querySelector('#bgHint').textContent = ''; }, 1400);
- return null;
- }
- // Drop at the centre of the current viewport, in world coords.
- const rect = this.host.getBoundingClientRect();
- const c = this._toWorld(rect.left + rect.width / 2, rect.top + rect.height / 2);
- const node = makeNode(type, c.x - NODE_W / 2, c.y - 40);
- this.nodes.push(node);
- this._renderNode(node);
- this._applyTransform();
- this.select(node.id);
- this._emitChange();
- return node;
- }
-
- removeNode(id) {
- const node = this.nodes.find((n) => n.id === id);
- if (!node) return;
- if (NODE_TYPES[node.type].single) return; // persona/output are structural
- this.nodes = this.nodes.filter((n) => n.id !== id);
- this.edges = this.edges.filter((e) => e.from !== id && e.to !== id);
- this._nodeEls.get(id)?.remove();
- this._nodeEls.delete(id);
- if (this.selectedId === id) this.select(null);
- this._renderEdges();
- this._emitChange();
- }
-
- removeEdge(id) {
- this.edges = this.edges.filter((e) => e.id !== id);
- this._renderEdges();
- this._emitChange();
- }
-
- updateNodeData(id, patch) {
- const node = this.nodes.find((n) => n.id === id);
- if (!node) return;
- Object.assign(node.data, patch);
- this.refreshNode(id);
- this._emitChange();
- }
-
- select(id) {
- this.selectedId = id;
- for (const [nid, el] of this._nodeEls) el.classList.toggle('is-selected', nid === id);
- this.onSelect(id ? this.nodes.find((n) => n.id === id) : null);
- }
-
- // ── Pan / zoom ──────────────────────────────────────────────────────────
-
- _bindCanvas() {
- this.host.addEventListener('pointerdown', (e) => {
- if (e.target.closest('.bnode') || e.target.closest('.bport')) return;
- this.select(null);
- const sx = e.clientX, sy = e.clientY, otx = this.tx, oty = this.ty;
- this.host.classList.add('is-panning');
- const move = (ev) => { this.tx = otx + (ev.clientX - sx); this.ty = oty + (ev.clientY - sy); this._applyTransform(); };
- const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); this.host.classList.remove('is-panning'); };
- window.addEventListener('pointermove', move);
- window.addEventListener('pointerup', up);
- });
- this.host.addEventListener('wheel', (e) => {
- e.preventDefault();
- const rect = this.host.getBoundingClientRect();
- const mx = e.clientX - rect.left, my = e.clientY - rect.top;
- const before = this._toWorld(e.clientX, e.clientY);
- const factor = e.deltaY < 0 ? 1.1 : 1 / 1.1;
- this.scale = Math.max(0.3, Math.min(2, this.scale * factor));
- // keep the point under the cursor fixed
- this.tx = mx - before.x * this.scale;
- this.ty = my - before.y * this.scale;
- this._applyTransform();
- }, { passive: false });
- }
-
- _toWorld(clientX, clientY) {
- const rect = this.host.getBoundingClientRect();
- return { x: (clientX - rect.left - this.tx) / this.scale, y: (clientY - rect.top - this.ty) / this.scale };
- }
-
- _applyTransform() {
- this.world.style.transform = `translate(${this.tx}px, ${this.ty}px) scale(${this.scale})`;
- }
-
- fit() {
- if (!this.nodes.length) return;
- const xs = this.nodes.map((n) => n.x);
- const ys = this.nodes.map((n) => n.y);
- const minX = Math.min(...xs) - 40;
- const minY = Math.min(...ys) - 40;
- const maxX = Math.max(...this.nodes.map((n) => n.x + NODE_W)) + 40;
- const maxY = Math.max(...this.nodes.map((n) => n.y + this._nodeHeight(n))) + 40;
- const rect = this.host.getBoundingClientRect();
- if (!rect.width) return;
- this.scale = Math.max(0.4, Math.min(1.2, Math.min(rect.width / (maxX - minX), rect.height / (maxY - minY))));
- this.tx = (rect.width - (maxX - minX) * this.scale) / 2 - minX * this.scale;
- this.ty = (rect.height - (maxY - minY) * this.scale) / 2 - minY * this.scale;
- this._applyTransform();
- }
-
- // ── Active-path animation (the "watch it think" moment) ─────────────────────
-
- setActive(nodeIds = [], edgeIds = []) {
- const ns = new Set(nodeIds);
- for (const [id, el] of this._nodeEls) el.classList.toggle('is-active', ns.has(id));
- const es = new Set(edgeIds);
- this.svg.querySelectorAll('.bedge').forEach((p) => p.classList.toggle('is-active', es.has(p.dataset.id)));
- }
-
- pulseNode(id) {
- const el = this._nodeEls.get(id);
- if (!el) return;
- el.classList.remove('is-pulse');
- void el.offsetWidth; // restart animation
- el.classList.add('is-pulse');
- }
-
- flowEdge(id) {
- const p = this.svg.querySelector(`.bedge[data-id="${CSS.escape(id)}"]`);
- if (p) { p.classList.add('is-active', 'is-flow'); }
- }
-
- setNodeBusy(id, busy) {
- this._nodeEls.get(id)?.classList.toggle('is-busy', !!busy);
- }
-
- setNodeStat(id, text) {
- const el = this._nodeEls.get(id);
- if (!el) return;
- let stat = el.querySelector('.bnode__stat');
- if (!stat) {
- stat = document.createElement('div');
- stat.className = 'bnode__stat';
- el.appendChild(stat);
- }
- stat.textContent = text || '';
- stat.hidden = !text;
- }
-
- clearActive() {
- for (const el of this._nodeEls.values()) el.classList.remove('is-active', 'is-pulse', 'is-busy');
- this.svg.querySelectorAll('.bedge').forEach((p) => p.classList.remove('is-active', 'is-flow'));
- }
-
- // Find the live circuit (nodes + edges reachable upstream from output) — used to
- // pre-highlight the path the runtime will walk.
- circuit() {
- const incoming = new Map();
- for (const e of this.edges) { if (!incoming.has(e.to)) incoming.set(e.to, []); incoming.get(e.to).push(e); }
- const out = this.nodes.find((n) => n.type === 'output');
- if (!out) return { nodeIds: [], edgeIds: [] };
- const nodeIds = new Set(); const edgeIds = new Set(); const stack = [out.id];
- while (stack.length) {
- const id = stack.pop();
- if (nodeIds.has(id)) continue;
- nodeIds.add(id);
- for (const e of incoming.get(id) || []) { edgeIds.add(e.id); stack.push(e.from); }
- }
- return { nodeIds: [...nodeIds], edgeIds: [...edgeIds] };
- }
-}
diff --git a/src/studio/brain/brain-runtime.js b/src/studio/brain/brain-runtime.js
index 32d926b66..0605316bf 100644
--- a/src/studio/brain/brain-runtime.js
+++ b/src/studio/brain/brain-runtime.js
@@ -22,7 +22,7 @@ import { getNodeRunner } from './brain-nodes.js';
export class BrainRuntime {
/**
* @param {object} o
- * @param {import('./brain-graph.js').BrainGraphView} o.graphView
+ * @param {import('./brain-composer.js').BrainComposer} o.graphView
* @param {import('../agent-studio-store.js').default} o.studio
* @param {() => object} o.getCompiled returns compileBrain() of the live graph
* @param {() => object} o.getGraph returns the raw graph (node ids for animation)
diff --git a/src/studio/brain/brain-studio.js b/src/studio/brain/brain-studio.js
index 0d1f8d89a..74a0091bb 100644
--- a/src/studio/brain/brain-studio.js
+++ b/src/studio/brain/brain-studio.js
@@ -3,7 +3,7 @@
* ==============================
* The visible, programmable agent brain. Mounts into the studio shell's Brain tab
* container and wires together:
- * • BrainGraphView — the visual node-graph editor
+ * • BrainComposer — the card-stack brain editor (persona → … → output)
* • compileBrain — graph → real persona_prompt + provider/tool config
* • BrainRuntime — streaming test chat against the real LLM proxy + live
* memory + active-path animation + avatar reactions
@@ -18,7 +18,7 @@
* mountBrainStudio(container, { studio });
*/
-import { BrainFormView } from './brain-form.js';
+import { BrainComposer } from './brain-composer.js';
import { compileBrain } from './brain-compile.js';
import { BrainRuntime } from './brain-runtime.js';
import { normalizeGraph, defaultGraph } from './brain-nodes.js';
@@ -76,7 +76,7 @@ class BrainStudio {
<div class="brainstudio__onboard" id="bsOnboard">
<div class="brainstudio__onboard-inner">
<h1>Build your agent's mind</h1>
- <p>Wire persona, model, memory, skills and trading reasoning into a living circuit. Watch it light up as it thinks.</p>
+ <p>Fill in persona, model, memory, skills and market reasoning. It wires itself — watch it light up as it thinks.</p>
<div class="brainstudio__templates" id="bsTplGrid"></div>
<button class="studio__btn studio__btn-primary" id="bsBlank">Start from blank</button>
</div>
@@ -258,7 +258,7 @@ class BrainStudio {
this.el.querySelector('#bsEditor').hidden = false;
if (!this.graph) {
const form = this.el.querySelector('#bsForm');
- this.graph = new BrainFormView(form, {
+ this.graph = new BrainComposer(form, {
onChange: (g) => this._onGraphChange(g),
getProviders: () => this.providers,
getSkills: () => this.studio.agent?.skills || [],
@@ -338,9 +338,9 @@ class BrainStudio {
_friendlyError(err) {
const m = err?.message || 'stream error';
- if (/sign in/i.test(m)) return 'Sign in to use this model, or pick a free one in the Model node.';
+ if (/sign in/i.test(m)) return 'Sign in to use this model, or pick a free one in the Model card.';
if (/rate|429|too many/i.test(m)) return 'Rate limited — slow down a moment and try again.';
- if (/not_configured|no api key/i.test(m)) return 'That model has no API key configured. Pick another in the Model node.';
+ if (/not_configured|no api key/i.test(m)) return 'That model has no API key configured. Pick another in the Model card.';
return `Couldn't reach the model: ${m}`;
}
@@ -374,7 +374,7 @@ class BrainStudio {
_showTemplateModal() {
const card = this.el.querySelector('#bsModalCard');
card.innerHTML = `<div class="brainstudio__modal-head"><h2>Fork a brain</h2><button class="brainstudio__modal-x" aria-label="Close">×</button></div>
- <p class="brainstudio__modal-sub">Replaces the current graph. Your current brain is saved until you save over it.</p>
+ <p class="brainstudio__modal-sub">Replaces the current brain. Your current brain is saved until you save over it.</p>
<div class="brainstudio__templates" id="bsModalTpl"></div>`;
this._renderTemplateGrid(card.querySelector('#bsModalTpl'));
card.querySelector('.brainstudio__modal-x').addEventListener('click', () => this._closeModal());
diff --git a/tests/api/avatars-submit-retry.test.js b/tests/api/avatars-submit-retry.test.js
new file mode 100644
index 000000000..39f6fde7e
--- /dev/null
+++ b/tests/api/avatars-submit-retry.test.js
@@ -0,0 +1,76 @@
+// Verifies the avatar submit resilience layer: a transient infra fault (network
+// drop, upstream 5xx, cold start) is retried once against the same provider, so
+// a single hiccup no longer dead-ends a reconstruct/regenerate job — while
+// deterministic faults (bad key, no credits, bad input, a provider 4xx) fail
+// fast without a wasted retry or double charge.
+
+import { describe, it, expect, vi } from 'vitest';
+import { isTransientProviderError, submitWithTransientRetry } from '../../api/avatars/_actions.js';
+
+const err = (props) => Object.assign(new Error(props.message || 'x'), props);
+
+describe('isTransientProviderError — only infra faults retry', () => {
+ it.each([
+ ['provider_unreachable', { code: 'provider_unreachable', status: 502 }],
+ ['provider_timeout', { code: 'provider_timeout', status: 504 }],
+ ['provider_error with no upstream status', { code: 'provider_error', status: 502 }],
+ ['provider_error with upstream 500', { code: 'provider_error', status: 502, providerStatus: 500 }],
+ ['provider_error with upstream 503', { code: 'provider_error', status: 502, providerStatus: 503 }],
+ ['bare 503 envelope', { status: 503 }],
+ ['bare 504 envelope', { status: 504 }],
+ ])('transient: %s', (_label, props) => {
+ expect(isTransientProviderError(err(props))).toBe(true);
+ });
+
+ it.each([
+ ['insufficient_credits', { code: 'insufficient_credits', status: 402 }],
+ ['invalid_key', { code: 'invalid_key', status: 401 }],
+ ['rate_limited', { code: 'rate_limited', status: 429 }],
+ ['invalid_request', { code: 'invalid_request', status: 400 }],
+ ['mode_unconfigured', { code: 'mode_unconfigured', status: 501 }],
+ ['provider_error with upstream 422', { code: 'provider_error', status: 502, providerStatus: 422 }],
+ ['provider_error with upstream 400', { code: 'provider_error', status: 502, providerStatus: 400 }],
+ ['null', null],
+ ])('deterministic: %s', (_label, props) => {
+ expect(isTransientProviderError(props ? err(props) : null)).toBe(false);
+ });
+});
+
+describe('submitWithTransientRetry — one retry on transient, none on deterministic', () => {
+ it('retries once and succeeds after a transient failure', async () => {
+ const submit = vi
+ .fn()
+ .mockRejectedValueOnce(err({ code: 'provider_unreachable', status: 502 }))
+ .mockResolvedValueOnce({ extJobId: 'job-123', eta: 60 });
+ const out = await submitWithTransientRetry({ submit }, { mode: 'reconstruct' });
+ expect(out.extJobId).toBe('job-123');
+ expect(submit).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not retry a deterministic failure — fails fast', async () => {
+ const submit = vi.fn().mockRejectedValue(err({ code: 'insufficient_credits', status: 402 }));
+ await expect(submitWithTransientRetry({ submit }, {})).rejects.toMatchObject({
+ code: 'insufficient_credits',
+ });
+ expect(submit).toHaveBeenCalledTimes(1);
+ });
+
+ it('surfaces the second error when the retry also fails transiently', async () => {
+ const submit = vi
+ .fn()
+ .mockRejectedValueOnce(err({ code: 'provider_unreachable', status: 502 }))
+ .mockRejectedValueOnce(err({ code: 'provider_error', status: 502, message: 'still down' }));
+ await expect(submitWithTransientRetry({ submit }, {})).rejects.toMatchObject({
+ code: 'provider_error',
+ });
+ expect(submit).toHaveBeenCalledTimes(2);
+ });
+
+ it('passes the request through unchanged on the first attempt', async () => {
+ const submit = vi.fn().mockResolvedValue({ extJobId: 'ok' });
+ const request = { userId: 'u1', mode: 'reconstruct', sourceUrl: 'https://x/img.png' };
+ await submitWithTransientRetry({ submit }, request);
+ expect(submit).toHaveBeenCalledTimes(1);
+ expect(submit).toHaveBeenCalledWith(request);
+ });
+});
diff --git a/tests/api/reconstruct-failover.test.js b/tests/api/reconstruct-failover.test.js
new file mode 100644
index 000000000..13d202b38
--- /dev/null
+++ b/tests/api/reconstruct-failover.test.js
@@ -0,0 +1,83 @@
+// Provider failover for the reconstruct (selfie / text → 3D) submit path.
+//
+// getRegenProviderCandidates() enumerates every configured platform provider in
+// precedence order so handleReconstruct can fail over from one to the next
+// instead of dead-ending at a 502 when a single provider is down, throttled, or
+// out of credits. These tests pin the ordering, de-duplication, and the
+// "nothing configured" empty result.
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { getRegenProviderCandidates } from '../../api/_lib/regen-provider.js';
+
+const PROVIDER_ENV = [
+ 'AVATAR_REGEN_PROVIDER',
+ 'REPLICATE_API_TOKEN',
+ 'GCP_RECONSTRUCTION_URL',
+ 'GCP_RECONSTRUCTION_KEY',
+ 'HF_TOKEN',
+];
+
+describe('getRegenProviderCandidates — failover ordering', () => {
+ let saved;
+
+ beforeEach(() => {
+ saved = {};
+ for (const k of PROVIDER_ENV) {
+ saved[k] = process.env[k];
+ delete process.env[k];
+ }
+ });
+
+ afterEach(() => {
+ for (const k of PROVIDER_ENV) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+ });
+
+ it('returns no candidates when nothing is configured', async () => {
+ const candidates = await getRegenProviderCandidates();
+ expect(candidates).toEqual([]);
+ });
+
+ it('returns the single configured platform provider', async () => {
+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';
+ const names = (await getRegenProviderCandidates()).map((c) => c.name);
+ expect(names).toEqual(['replicate']);
+ });
+
+ it('enumerates multiple configured providers in paid → free order', async () => {
+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';
+ process.env.GCP_RECONSTRUCTION_URL = 'https://recon.example.com';
+ process.env.GCP_RECONSTRUCTION_KEY = 'gcp_test_key';
+ const names = (await getRegenProviderCandidates()).map((c) => c.name);
+ expect(names).toEqual(['replicate', 'gcp']);
+ });
+
+ it('puts the explicit AVATAR_REGEN_PROVIDER first, then the rest, de-duplicated', async () => {
+ process.env.AVATAR_REGEN_PROVIDER = 'gcp';
+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';
+ process.env.GCP_RECONSTRUCTION_URL = 'https://recon.example.com';
+ process.env.GCP_RECONSTRUCTION_KEY = 'gcp_test_key';
+ const names = (await getRegenProviderCandidates()).map((c) => c.name);
+ expect(names).toEqual(['gcp', 'replicate']);
+ // No provider appears twice even though gcp is named explicitly and inferred.
+ expect(new Set(names).size).toBe(names.length);
+ });
+
+ it('skips a provider whose credentials are absent', async () => {
+ // URL present but KEY missing — the gcp constructor throws and the
+ // candidate is skipped rather than blocking replicate.
+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';
+ process.env.GCP_RECONSTRUCTION_URL = 'https://recon.example.com';
+ const names = (await getRegenProviderCandidates()).map((c) => c.name);
+ expect(names).toEqual(['replicate']);
+ });
+
+ it('each candidate exposes a usable instance', async () => {
+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';
+ const candidates = await getRegenProviderCandidates();
+ expect(candidates).toHaveLength(1);
+ expect(typeof candidates[0].instance?.submit).toBe('function');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 4c9e5cc4c..9605a1e6a 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1755,6 +1755,14 @@
"src": "/avatar-studio/",
"dest": "/avatar-studio.html"
},
+ {
+ "src": "/avatar-engines",
+ "dest": "/avatar-engines.html"
+ },
+ {
+ "src": "/avatar-engines/",
+ "dest": "/avatar-engines.html"
+ },
{
"src": "/cosmos",
"dest": "/cosmos.html"
@@ -2164,6 +2172,10 @@
"src": "/api/agents/check-name",
"dest": "/api/agents/check-name"
},
+ {
+ "src": "/api/agents/suggest-spec",
+ "dest": "/api/agents/suggest-spec"
+ },
{
"src": "/api/agents/identity-check",
"dest": "/api/agents/identity-check"