Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(agent-brain): make every agent-turn surface honor an agent's chosen Grok brain
nirholas1333b11c47a6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 907f7f74a..99297a1cb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-10-11+- **An agent set to Grok now answers as Grok everywhere, with a badge when it can't**: Profile chat, the agent editor's copilot, scheduled strategy runs, and the gateway all now read an agent's chosen brain through the same resolver, so picking Grok for an agent actually means Grok on every surface, not just the one where it was set. A Grok pick first tries the agent owner's own saved xAI key, then the platform's, before falling back to the free default chain. When Grok genuinely can't answer (no key reachable anywhere), profile chat now shows a small badge naming which model answered instead, so it's never a silent swap. `[improvement]`- **Sentiment Scout's X reads gained a second, independent path through xAI**: The Sentiment Scout reads X for posts quoting a coin's exact contract address, as evidence a holder can open and check. When our own X search credentials are unavailable or rate limited, it now fails over to xAI's x_search tool, a second route to the same posts, metered by its own daily cap so an outage on one path never silently costs more than planned on the other. No change for anyone reading the Scout: the evidence looks the same either way. (`/docs/sentiment-scout`) `[improvement, infra]`## 2026-10-10diff --git a/api/_lib/agent-grok-key.js b/api/_lib/agent-grok-key.jsnew file mode 100644index 000000000..39882ae26--- /dev/null+++ b/api/_lib/agent-grok-key.js@@ -0,0 +1,33 @@+// Which Grok (xAI) credential serves a given agent's turn.+//+// An agent whose owner saved a Grok key at /api/user/provider-keys bills that+// key, not the platform's GROK_API_KEY, so a visitor talking to someone else's+// agent still gets the owner's chosen brain instead of silently dropping to+// the platform chain. Same lane shape as api/_lib/agent-voice-key.js: owner key+// first, platform key as the fallback rung, decided by the caller.++import { sql } from './db.js';+import { decryptProviderKey } from './provider-keys.js';++/** Provider slug in users.provider_keys for a Grok (xAI) BYOK key. */+export const GROK_PROVIDER = 'grok';++/**+ * Decrypt a user's stored Grok key, if they saved one.+ * A corrupt or undecryptable blob resolves to null rather than throwing: the+ * caller falls through to the server key instead of failing the whole turn.+ * @param {string|null|undefined} userId+ * @returns {Promise<string|null>}+ */+export async function loadOwnerGrokKey(userId) {+ if (!userId) return null;+ const [row] = await sql`SELECT provider_keys FROM users WHERE id = ${userId}`;+ const encrypted = row?.provider_keys?.[GROK_PROVIDER];+ if (typeof encrypted !== 'string' || !encrypted) return null;+ try {+ return (await decryptProviderKey(encrypted)) || null;+ } catch (err) {+ console.warn('[agent-grok-key] could not decrypt stored Grok key:', err?.message || err);+ return null;+ }+}diff --git a/api/_lib/agent-model.js b/api/_lib/agent-model.jsindex 0e4bdf099..862a89811 100644--- a/api/_lib/agent-model.js+++ b/api/_lib/agent-model.js@@ -116,11 +116,14 @@ export function resolveMessageModel({ requested = null, agentMeta = null, purpos* platform chain stays behind it (also without tools for that turn) so the* message is still answered when every route of the model is down.* @param {string|null} model a catalog id, or null for the platform chain+ * @param {{ grokKey?: string|null }} [opts] `grokKey`: the agent owner's decrypted+ * BYOK xAI key (api/_lib/agent-grok-key.js), threaded ahead of the server's+ * GROK_API_KEY rung when `model` is a Grok model.* @returns {{ chain: object[], tools: boolean }}*/-export function modelChain(model) {+export function modelChain(model, opts = {}) {if (!model) return { chain: providerChain(), tools: true };- if (MODEL_CATALOG[model]?.tools) return { chain: providerChainFor(model), tools: true };+ if (MODEL_CATALOG[model]?.tools) return { chain: providerChainFor(model, opts), tools: true };const own = MODEL_CATALOG[model]?.provider === 'roster' ? rosterTransports(model) : [];const seen = new Set(own.map((r) => `${r.name}|${r.model}`));return { chain: [...own, ...providerChain().filter((p) => !seen.has(`${p.name}|${p.model}`))], tools: false };diff --git a/api/_lib/gateway/conversation.js b/api/_lib/gateway/conversation.jsindex 74609693b..79ad9ec77 100644--- a/api/_lib/gateway/conversation.js+++ b/api/_lib/gateway/conversation.js@@ -18,6 +18,9 @@ import { resolveChatAgent, listAccountAgents } from './agents.js';import { createPreview, setPreviewMessageRef, PREVIEW_TTL_MINUTES } from './store.js';import { chunkText, describeProposal, plainText, MAX_TEXT, PLATFORM_LABEL, appOrigin } from './format.js';import { maybeSpeakReply } from './voice.js';+import { agentDefaultModel, modelChain } from '../agent-model.js';+import { loadOwnerGrokKey } from '../agent-grok-key.js';+import { MODEL_CATALOG } from '../chat-models.js';export const APPROVE = 'gw:ap:';export const CANCEL = 'gw:cx:';@@ -109,6 +112,22 @@ async function sendReply(gw, chatId, text) {for (const part of chunkText(text, MAX_TEXT[gw.platform] || 1900)) await gw.sendText(chatId, part);}+/**+ * The provider chain for this agent's chosen brain (api/_lib/agent-model.js),+ * so a gateway reply honors the same model the owner picked for profile chat+ * and the web copilot. A chosen model with no tool calling, or no model+ * chosen at all, falls through to the platform default chain. A Grok choice+ * leads with the owner's saved xAI key (api/_lib/agent-grok-key.js) ahead of+ * the server key and the default chain.+ * @param {{ meta?: object, user_id?: string }} agent+ */+export async function chainForAgent(agent) {+ const model = agentDefaultModel(agent.meta);+ if (!model || !MODEL_CATALOG[model]?.tools) return undefined;+ const grokKey = MODEL_CATALOG[model].provider === 'grok' ? await loadOwnerGrokKey(agent.user_id) : null;+ return modelChain(model, { grokKey }).chain;+}+/*** Run one turn for `text` in a paired chat.* @param {{ gw:object, event:object, link:object, text:string }} ctx@@ -129,12 +148,14 @@ export async function converse({ gw, event, link, text }) {const stopTyping = keepTyping(gw, event.chatId);const status = statusLine(gw, event.chatId);+ const chain = await chainForAgent(agent);let turn;try {turn = await runCopilotTurn({agent,history,network: 'mainnet',+ chain,surfaceNote: surfaceNote(event.platform, { buttons: hasButtons(gw) }),emit: (name, data) => { if (name === 'tool_start') status.working(data.name); },});diff --git a/api/_lib/llm-tool-chain.js b/api/_lib/llm-tool-chain.jsindex e52a8e00d..2ca99503b 100644--- a/api/_lib/llm-tool-chain.js+++ b/api/_lib/llm-tool-chain.js@@ -234,15 +234,26 @@ export function modelRung(model) {* model (model-roster.js) contributes one rung per reachable route; any other* catalog model contributes its single lane. Models without tool calling have* no rungs: the tool loop must never be pointed at them.+ *+ * A Grok model additionally gets an owner-key rung ahead of the server-key+ * rung when `opts.grokKey` is a decrypted BYOK key: the agent's owner saved+ * their own xAI key, so their key answers before the platform's GROK_API_KEY+ * (and before the free default chain, appended by providerChainFor).* @param {string} requested a MODEL_CATALOG id (a retired id maps forward)+ * @param {{ grokKey?: string|null }} [opts]*/-export function modelRungs(requested) {+export function modelRungs(requested, opts = {}) {const model = resolveModelId(requested);const meta = MODEL_CATALOG[model];if (!meta || !meta.tools) return [];if (meta.provider === 'roster') return rosterTransports(model);+ const rungs = [];+ if (meta.provider === 'grok' && opts.grokKey) {+ rungs.push({ name: 'grok', url: LANE_ENDPOINTS.grok.url, key: opts.grokKey, model, catalogModel: model, keySource: 'owner' });+ }const rung = singleLaneRung(model, meta);- return rung ? [rung] : [];+ if (rung) rungs.push({ ...rung, keySource: rung.keySource || 'platform' });+ return rungs;}function singleLaneRung(model, meta) {@@ -271,11 +282,12 @@ function singleLaneRung(model, meta) {* rungs first (every route that serves it, in order), then the free-first* platform chain behind them, minus any rung that would repeat one of them.* @param {string|null} [model]+ * @param {{ grokKey?: string|null }} [opts] forwarded to modelRungs*/-export function providerChainFor(model) {+export function providerChainFor(model, opts = {}) {const chain = providerChain();if (!model) return chain;- const rungs = modelRungs(model);+ const rungs = modelRungs(model, opts);if (!rungs.length) return chain;const seen = new Set(rungs.map((r) => `${r.name}|${r.model}`));return [...rungs, ...chain.filter((p) => !seen.has(`${p.name}|${p.model}`))];diff --git a/api/_lib/strategy-loop/tick.js b/api/_lib/strategy-loop/tick.jsindex cbcc190d1..84242b2b8 100644--- a/api/_lib/strategy-loop/tick.js+++ b/api/_lib/strategy-loop/tick.js@@ -22,7 +22,9 @@// in worker memory between steps.import { sql } from '../db.js';-import { providerChainFor } from '../llm-tool-chain.js';+import { agentDefaultModel, modelChain } from '../agent-model.js';+import { loadOwnerGrokKey } from '../agent-grok-key.js';+import { MODEL_CATALOG } from '../chat-models.js';import { createAgentLoop, initialLoopState, loopFinished, finalAnswer } from '../agent-loop.js';import { computeContext } from '../memory-store.js';import { insertNotification } from '../notify.js';@@ -415,6 +417,21 @@ function eventRow(event) {}}+/**+ * The provider chain for this tick: the agent's chosen brain+ * (api/_lib/agent-model.js, checked across all three legacy meta locations),+ * or the platform default chain when none is set or the choice has no tool+ * calling (the loop's tools require it). A Grok choice leads with the+ * owner's saved xAI key (api/_lib/agent-grok-key.js) ahead of the server key.+ * @param {{ meta?: object, user_id?: string }} agent+ */+export async function resolveTickChain(agent) {+ const model = agentDefaultModel(agent.meta);+ const usable = model && MODEL_CATALOG[model]?.tools ? model : null;+ const grokKey = usable && MODEL_CATALOG[usable].provider === 'grok' ? await loadOwnerGrokKey(agent.user_id) : null;+ return modelChain(usable, { grokKey }).chain;+}+/*** Run (or resume) one tick for an agent this worker has leased.*@@ -502,7 +519,7 @@ export async function runAgentTick({ agentId, workerId, cfg, log, signal = null,({ state, context } = initialLoopState({ operationId: `tick-${tick.id}`, messages, maxSteps: runtimeSteps }));}- const chain = deps.chain || providerChainFor(agent.meta?.runtime?.model || null);+ const chain = deps.chain || await resolveTickChain(agent);if (!chain.length) {await finishTick(tick.id, { status: 'failed', error: 'no LLM provider is configured' });await scheduleNext({ agentId, slot: tick.slot, intervalSeconds: loop.intervalSeconds, status: 'failed', failed: true });diff --git a/api/agents/copilot.js b/api/agents/copilot.jsindex d6893a7c5..7ad31a112 100644--- a/api/agents/copilot.js+++ b/api/agents/copilot.js@@ -45,6 +45,8 @@ import { providerChain } from '../_lib/llm-tool-chain.js';import { runCopilotTurn, netOf, COPILOT_MAX_MESSAGES } from '../_lib/copilot-engine.js';import { appendThreadMessage, listThread } from '../_lib/agent-thread.js';import { resolveMessageModel, modelChain, ModelChoiceError } from '../_lib/agent-model.js';+import { loadOwnerGrokKey } from '../_lib/agent-grok-key.js';+import { MODEL_CATALOG } from '../_lib/chat-models.js';import { meterFreeModel, FreeTierExhaustedError, freeTierErrorBody, retryAfterSeconds } from '../_lib/free-tier.js';import { recordEvent } from '../_lib/usage.js';import { costMicroUsd } from '../_lib/llm-pricing.js';@@ -102,7 +104,8 @@ export default async function handler(req, res, id) {return error(res, 429, 'free_tier_exhausted', e.message, freeTierErrorBody(e));}- const { chain } = modelChain(choice.model);+ const grokKey = choice.model && MODEL_CATALOG[choice.model]?.provider === 'grok' ? await loadOwnerGrokKey(row.user_id) : null;+ const { chain } = modelChain(choice.model, { grokKey });if (!chain.length) return error(res, 503, 'llm_unavailable', 'No LLM provider configured. Set GROQ_API_KEY, OPENROUTER_API_KEY, or NVIDIA_API_KEY (or GOOGLE_CLOUD_PROJECT for the Vertex credits anchor).');// SSE open.diff --git a/api/chat.js b/api/chat.jsindex 3fb9e9a90..0df0a6a89 100644--- a/api/chat.js+++ b/api/chat.js@@ -35,6 +35,8 @@ import { captureException } from './_lib/sentry.js';import { sql } from './_lib/db.js';import { limits, clientIp } from './_lib/rate-limit.js';import { loadUserProviderKeys } from './_lib/provider-keys.js';+import { agentDefaultModel } from './_lib/agent-model.js';+import { loadOwnerGrokKey } from './_lib/agent-grok-key.js';import { watsonxConfig, watsonxAuthHeaders } from './_lib/watsonx.js';import { orchestrateConfig } from './_lib/orchestrate.js';import { guardianConfig, governSend, sendCapUsd } from './_lib/granite-guardian.js';@@ -532,6 +534,46 @@ export default wrap(async (req, res) => {userProviderKeys = await loadUserProviderKeys(urow?.provider_keys);}+ // Agent lookup happens before provider selection so an unrequested provider+ // can default to the agent's own chosen brain (api/_lib/agent-model.js),+ // the same resolution profile chat, the gateway, and scheduled runs now+ // share. persona_prompt/user_id/meta in one row; the later persona-prompt+ // block reuses `agentRow`.+ let agentRow = null;+ if (body.agentId) {+ [agentRow] = await sql`+ SELECT persona_prompt, user_id, meta FROM agent_identities+ WHERE id = ${body.agentId} AND deleted_at IS NULL+ AND (is_published = true OR user_id = ${auth?.userId ?? null})+ LIMIT 1+ `;+ }++ // Only when the caller named neither a provider nor a model, and is signed+ // in: grok (like every paid/BYOK provider) is sign-in-only, matching+ // resolveMessageModel's rule in agent-model.js, and in practice the+ // anonymous branch above has already pinned body.provider by this point.+ // A Grok default also pulls the agent owner's saved xAI key ahead of the+ // server key, same lane order as the gateway and scheduled runs+ // (api/_lib/agent-grok-key.js).+ // Echoed on `done` as `agent_brain` so the client can tell a straight answer+ // from a failover: the badge compares what the agent's brain was supposed+ // to be against `provider`/`model`, which is what actually answered.+ const agentBrainDefault = agentBrainDefaultFor({+ anonymous,+ requestedProvider: body.provider,+ requestedModel: body.model,+ agentMeta: agentRow?.meta,+ });+ if (agentBrainDefault) {+ body.provider = agentBrainDefault.provider;+ body.model = agentBrainDefault.model;+ if (agentBrainDefault.provider === 'grok' && !userProviderKeys.grok) {+ const ownerKey = await loadOwnerGrokKey(agentRow.user_id);+ if (ownerKey) userProviderKeys = { ...userProviderKeys, grok: ownerKey };+ }+ }+// Health cooldowns: a provider that recently 429'd / 5xx'd is skipped while it// recovers, so a single throttle window doesn't cascade into request after// request re-hitting the same dead provider. Best-effort — an unreadable@@ -583,14 +625,9 @@ export default wrap(async (req, res) => {let isOwner = false;let agentVisible = false;if (body.agentId) {- // Persona prompts are private IP: only serve them for published agents,- // or to the agent's owner. Anonymous callers get published personas only.- const [agentRow] = await sql`- SELECT persona_prompt, user_id FROM agent_identities- WHERE id = ${body.agentId} AND deleted_at IS NULL- AND (is_published = true OR user_id = ${auth?.userId ?? null})- LIMIT 1- `;+ // Persona prompts are private IP: only serve them for published agents, or+ // to the agent's owner. Anonymous callers get published personas only.+ // `agentRow` was already loaded above (it also feeds the brain default).agentVisible = Boolean(agentRow);isOwner = Boolean(auth?.userId && agentRow?.user_id === auth.userId);// Brain Studio preview: the owner may audition an unsaved compiled persona.@@ -1169,6 +1206,10 @@ export default wrap(async (req, res) => {})),model: route.model,provider: route.name,+ // The agent's own configured brain, when this turn used it by default+ // (no explicit client override), null otherwise. The client compares+ // this to `provider`/`model` to tell a straight answer from a failover.+ agent_brain: agentBrainDefault,// Exactly the memories the server injected into this reply's context — the// client emits `memory:recalled` from this. Empty when nothing was recalled.recalled: recalledMemories,@@ -1503,6 +1544,25 @@ function keylessVertexAvailable(name) {return false;}+/**+ * Whether this turn should default to the agent's own configured brain+ * (api/_lib/agent-model.js) instead of the platform's provider ladder: only+ * when the caller named neither provider nor model, is signed in (grok, like+ * every paid/BYOK provider, is sign-in-only), and the agent's chosen model+ * has a route this handler knows how to drive. Exported for tests; the+ * handler also uses the returned `provider` to decide whether to fetch the+ * owner's BYOK grok key.+ * @param {{ anonymous: boolean, requestedProvider: unknown, requestedModel: unknown, agentMeta: object|null|undefined }} o+ * @returns {{ provider: string, model: string } | null}+ */+export function agentBrainDefaultFor({ anonymous, requestedProvider, requestedModel, agentMeta }) {+ if (anonymous || requestedProvider || requestedModel || !agentMeta) return null;+ const model = agentDefaultModel(agentMeta);+ const providerName = model ? MODEL_CATALOG[model]?.provider : null;+ if (!model || !providerName || !PROVIDERS[providerName]) return null;+ return { provider: providerName, model };+}+// Effective provider try-order. Vertex-served Claude is injected per flags:// VERTEX_CLAUDE_PRIMARY → Vertex leads the whole ladder (before the free// lanes) — the platform's default brain becomes real Claude on GCP credits.@@ -1610,7 +1670,7 @@ function envPinnedModelFor(providerName) {// kept — those are per-model rate limits where a sibling model genuinely helps.const FALLBACK_SIBLINGS = {openrouter: OPENROUTER_SIBLINGS,- groq: ['llama-3.3-70b-versatile'],+ groq: ['openai/gpt-oss-20b'],// Like Groq, NVIDIA NIM rate-limits per key (one account), so a second NIM// model would re-hit the same throttle — keep a single slot and give the// next fallback slot to a different provider.diff --git a/data/changelog.json b/data/changelog.jsonindex 7a897a705..f106ffe58 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,12 @@{"$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, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-11",+ "title": "An agent set to Grok now answers as Grok everywhere, with a badge when it can't",+ "summary": "Profile chat, the agent editor's copilot, scheduled strategy runs, and the gateway all now read an agent's chosen brain through the same resolver, so picking Grok for an agent actually means Grok on every surface, not just the one where it was set. A Grok pick first tries the agent owner's own saved xAI key, then the platform's, before falling back to the free default chain. When Grok genuinely can't answer (no key reachable anywhere), profile chat now shows a small badge naming which model answered instead, so it's never a silent swap.",+ "tags": ["improvement"]+ },{"date": "2026-10-11","title": "Sentiment Scout's X reads gained a second, independent path through xAI",diff --git a/pages/avatar-page.html b/pages/avatar-page.htmlindex 2e7ccdf5d..45d96879f 100644--- a/pages/avatar-page.html+++ b/pages/avatar-page.html@@ -984,6 +984,27 @@background: #0f62fe;box-shadow: 0 0 0 3px color-mix(in srgb, #0f62fe 25%, transparent);}+ .av-chat-brain {+ display: none;+ align-items: center;+ font-size: 11px;+ font-weight: 600;+ letter-spacing: 0.01em;+ color: var(--text);+ background: var(--panel);+ border: 1px solid var(--border-2);+ border-radius: 999px;+ padding: 4px 10px;+ white-space: nowrap;+ }+ .av-chat-brain[data-state='on'],+ .av-chat-brain[data-state='failover'] {+ display: inline-flex;+ }+ .av-chat-brain[data-state='failover'] {+ color: #ffb020;+ border-color: color-mix(in srgb, #ffb020 40%, var(--border-2));+ }.av-chat-log {flex: 1;min-height: 240px;diff --git a/public/changelog-recent.json b/public/changelog-recent.jsonindex 2fcc6ce23..9fcaa2905 100644--- a/public/changelog-recent.json+++ b/public/changelog-recent.json@@ -1,14 +1,24 @@{- "generated_at": "2026-10-11T00:07:40.296Z",+ "generated_at": "2026-10-11T01:08:21.068Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},- "total": 3852,+ "total": 3853,"complete": false,"full_feed": "/changelog.json","entries": [+ {+ "date": "2026-10-11",+ "type": "update",+ "title": "An agent set to Grok now answers as Grok everywhere, with a badge when it can't",+ "summary": "Profile chat, the agent editor's copilot, scheduled strategy runs, and the gateway all now read an agent's chosen brain through the same resolver, so picking Grok for an agent actually means Grok on every surface, not just the one where it was set. A Grok pick first tries the agent owner's own saved xAI key, then the platform's, before falling back to the free default chain. When Grok genuinely can't answer (no key reachable anywhere), profile chat now shows a small badge naming which model answered instead, so it's never a silent swap.",+ "link": null,+ "tags": [+ "improvement"+ ]+ },{"date": "2026-10-11","type": "update",@@ -1550,17 +1560,6 @@"feature","improvement"]- },- {- "date": "2026-09-18",- "type": "update",- "title": "The embedded 3D agent is readable on light websites and quiet in the console",- "summary": "Two fixes for anyone who has put a three.ws agent on their own site with the two-line embed. The floating widget had no background of its own, so on a light page its white button labels and name vanished into the page; it now has its own dark panel, and the suggestion buttons carry a solid ground, so it reads the same on any site. You can still ask for a transparent or light panel with the background attribute. The embed also made two background requests that browsers blocked on every site but ours, logging errors in the host page's console; those requests now succeed, and only the public, signed-out answer is ever shared across sites.",- "link": "/tutorials/embed-in-30-seconds",- "tags": [- "fix",- "sdk"- ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex ac2248720..e82fcc7ef 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,21 @@{- "generated_at": "2026-10-11T00:07:40.265Z",+ "generated_at": "2026-10-11T01:08:21.048Z","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-10-11",+ "type": "update",+ "title": "An agent set to Grok now answers as Grok everywhere, with a badge when it can't",+ "summary": "Profile chat, the agent editor's copilot, scheduled strategy runs, and the gateway all now read an agent's chosen brain through the same resolver, so picking Grok for an agent actually means Grok on every surface, not just the one where it was set. A Grok pick first tries the agent owner's own saved xAI key, then the platform's, before falling back to the free default chain. When Grok genuinely can't answer (no key reachable anywhere), profile chat now shows a small badge naming which model answered instead, so it's never a silent swap.",+ "link": null,+ "tags": [+ "improvement"+ ]+ },{"date": "2026-10-11","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 70093410f..c0c84d83b 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>An agent set to Grok now answers as Grok everywhere, with a badge when it can't</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-10-11:An agent set to Grok now answers as Grok everywhere, with a badge when it can't</guid>+ <pubDate>Sun, 11 Oct 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Profile chat, the agent editor's copilot, scheduled strategy runs, and the gateway all now read an agent's chosen brain through the same resolver, so picking Grok for an agent actually means Grok on every surface, not just the one where it was set. A Grok pick first tries the agent owner's own saved xAI key, then the platform's, before falling back to the free default chain. When Grok genuinely can't answer (no key reachable anywhere), profile chat now shows a small badge naming which model answered instead, so it's never a silent swap.</description>+ </item><item><title>Sentiment Scout's X reads gained a second, independent path through xAI</title><link>https://three.ws/docs/sentiment-scout</link>diff --git a/src/avatar-page.js b/src/avatar-page.jsindex 3d5827b3f..2f981aa27 100644--- a/src/avatar-page.js+++ b/src/avatar-page.js@@ -749,6 +749,7 @@ function renderShell(glbUrl) {<span class="av-chat-ibm" id="av-chat-ibm" title="This avatar's brain runs on IBM watsonx (Granite) — fully embodied via Granite function calling"><span class="av-chat-ibm-dot" aria-hidden="true"></span>Powered by IBM watsonx</span>+ <span class="av-chat-brain" id="av-chat-brain" data-state="hidden" aria-live="polite"></span></div><div class="av-chat-log" id="av-chat-log"><div class="av-chat-empty">@@ -2298,6 +2299,7 @@ function bindChat() {});}syncIbmBadge();+ hideBrainBadge();// Persistent memory (memory skill): replay stored history on first paint.if (attachedSkills.has('memory')) hydrateChatHistory();@@ -2448,6 +2450,7 @@ async function sendChatMessage(text) {assistantNode.appendChild(cursor);showThoughtThinking();+ hideBrainBadge();send.disabled = true;let acc = '';try {@@ -2508,6 +2511,7 @@ async function sendChatMessage(text) {emitRecallFromChat(isUuid ? agentIdMaybe : null, evt, text);// Let the agent's own words colour its mood too.moodEngine.observeChat(isUuid ? agentIdMaybe : null, evt.reply || acc, 'assistant');+ renderBrainBadge(evt);} else if (evt.type === 'error') {throw new Error(evt.message || evt.error || 'Stream error');}@@ -2527,6 +2531,59 @@ async function sendChatMessage(text) {}}+// Friendly label per MODEL_CATALOG/PROVIDERS provider slug (api/_lib/chat-models.js,+// api/chat.js PROVIDERS), for the real-metadata brain badge below.+const BRAIN_PROVIDER_LABELS = {+ grok: 'Grok',+ anthropic: 'Claude',+ openai: 'GPT',+ groq: 'Llama (Groq)',+ openrouter: 'Llama (OpenRouter)',+ nvidia: 'Nemotron (NVIDIA)',+ sambanova: 'Llama (SambaNova)',+ mistral: 'Mistral',+ zai: 'GLM (Z.AI)',+ watsonx: 'IBM Granite',+ orchestrate: 'IBM Orchestrate',+ 'vertex-gemini': 'Gemini',+ vertex: 'Claude (Vertex)',+};++function hideBrainBadge() {+ const badge = $('av-chat-brain');+ if (badge) badge.dataset.state = 'hidden';+}++/**+ * Show which brain actually answered this turn, from the `/api/chat` `done`+ * event's real response metadata (never a client-side guess). Only lights up+ * when the server used the agent's own configured brain by default+ * (`evt.agent_brain`, set server-side only when no visitor override was+ * sent): a visitor who explicitly picked a model from the selector sees no+ * badge, since that is their choice, not the agent's brain. When the agent's+ * chosen provider could not answer (no reachable key) and a different lane+ * served the turn instead, the badge switches to the failover state rather+ * than silently claiming the agent's brain answered.+ * @param {{ provider?: string, model?: string, agent_brain?: {provider:string, model:string}|null }} evt+ */+function renderBrainBadge(evt) {+ const badge = $('av-chat-brain');+ if (!badge) return;+ if (!evt || !evt.provider || !evt.agent_brain) {+ hideBrainBadge();+ return;+ }+ const servedLabel = BRAIN_PROVIDER_LABELS[evt.provider] || evt.provider;+ if (evt.agent_brain.provider !== evt.provider) {+ const wantedLabel = BRAIN_PROVIDER_LABELS[evt.agent_brain.provider] || evt.agent_brain.provider;+ badge.textContent = `${wantedLabel} unavailable, answered on ${servedLabel}`;+ badge.dataset.state = 'failover';+ } else {+ badge.textContent = `Powered by ${servedLabel}`;+ badge.dataset.state = 'on';+ }+}+function appendChatMessage(role, text) {const logEl = $('av-chat-log');const node = document.createElement('div');diff --git a/tests/agent-brain-default.test.js b/tests/agent-brain-default.test.jsnew file mode 100644index 000000000..e3cbc4045--- /dev/null+++ b/tests/agent-brain-default.test.js@@ -0,0 +1,97 @@+// Order 044, task 1: profile chat (api/chat.js) and the web copilot+// (api/agents/copilot.js) resolve an agent's chosen brain through the same+// function other surfaces use (api/_lib/agent-model.js), never silently on+// the platform default.++import { describe, it, expect, vi } from 'vitest';++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ chatIp: vi.fn(async () => ({ success: true, reset: Date.now() + 60_000 })),+ chatUser: vi.fn(async () => ({ success: true, reset: Date.now() + 60_000 })),+ chatHostKeyGlobal: vi.fn(async () => ({ success: true, reset: Date.now() + 60_000 })),+ tradePerUser: vi.fn(async () => ({ success: true })),+ },+ clientIp: () => '127.0.0.1',+}));+vi.mock('../api/_lib/provider-health.js', () => ({+ providersInCooldown: vi.fn(async () => new Map()),+ markProviderCooldown: vi.fn(async () => {}),+ AUTH_COOLDOWN_SECONDS: 900,+ isBillingQuotaError: () => false,+}));+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => null),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: () => null,+}));+vi.mock('../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));++const { agentBrainDefaultFor } = await import('../api/chat.js');+const { copilotModel } = await import('../api/agents/copilot.js');++const GROK_MODEL = 'grok-4.7';++describe('agentBrainDefaultFor (api/chat.js)', () => {+ it('defaults to the agent brain when the caller named neither provider nor model', () => {+ const choice = agentBrainDefaultFor({+ anonymous: false,+ requestedProvider: undefined,+ requestedModel: undefined,+ agentMeta: { runtime: { model: GROK_MODEL } },+ });+ expect(choice).toEqual({ provider: 'grok', model: GROK_MODEL });+ });++ it('is null for an anonymous caller: grok is sign-in-only', () => {+ const choice = agentBrainDefaultFor({+ anonymous: true,+ requestedProvider: undefined,+ requestedModel: undefined,+ agentMeta: { runtime: { model: GROK_MODEL } },+ });+ expect(choice).toBeNull();+ });++ it('is null when the caller already named a provider or model: their choice wins', () => {+ expect(agentBrainDefaultFor({+ anonymous: false, requestedProvider: 'anthropic', requestedModel: undefined,+ agentMeta: { runtime: { model: GROK_MODEL } },+ })).toBeNull();+ expect(agentBrainDefaultFor({+ anonymous: false, requestedProvider: undefined, requestedModel: 'grok-4.6',+ agentMeta: { runtime: { model: GROK_MODEL } },+ })).toBeNull();+ });++ it('is null with no agent meta', () => {+ expect(agentBrainDefaultFor({ anonymous: false, requestedProvider: undefined, requestedModel: undefined, agentMeta: null })).toBeNull();+ });++ it('is null when the agent has no catalog-known default', () => {+ expect(agentBrainDefaultFor({+ anonymous: false, requestedProvider: undefined, requestedModel: undefined,+ agentMeta: { runtime: { model: 'some-retired-id-nobody-knows' } },+ })).toBeNull();+ });+});++describe('copilotModel (api/agents/copilot.js)', () => {+ it('honors an explicit grok override', () => {+ const choice = copilotModel(GROK_MODEL, {});+ expect(choice.model).toBe(GROK_MODEL);+ expect(choice.source).toBe('message');+ });++ it('falls through to the agent default when no override is given', () => {+ const choice = copilotModel(undefined, { runtime: { model: GROK_MODEL } });+ expect(choice.model).toBe(GROK_MODEL);+ expect(choice.source).toBe('agent');+ });++ it('falls through to the platform chain when the agent default has no tool calling', () => {+ const choice = copilotModel(undefined, { runtime: { model: 'deepseek-r1' } });+ expect(choice.model).toBeNull();+ expect(choice.source).toBe('platform');+ });+});diff --git a/tests/agent-grok-brain.test.js b/tests/agent-grok-brain.test.jsnew file mode 100644index 000000000..76b5131d1--- /dev/null+++ b/tests/agent-grok-brain.test.js@@ -0,0 +1,216 @@+// Coverage for order 044: an agent's chosen Grok brain is honored on every+// agent-turn surface, with the owner's saved xAI key leading the server key+// and the server key leading the default chain.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const sqlMock = vi.fn();+vi.mock('../api/_lib/db.js', () => ({+ sql: sqlMock,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: () => false,+}));++// The real decryptProviderKey needs JWT_SECRET to derive its AES key; this+// boundary only cares that a stored ciphertext round-trips to a plaintext+// key, not which cipher ran. `enc(...)` mirrors the encrypt-side convention+// already used by tests/api-user-wallet-x402-guards.test.js.+const decryptProviderKeyMock = vi.fn(async (v) => {+ if (typeof v !== 'string' || !v.startsWith('enc(')) throw new Error('bad ciphertext');+ return v.slice(4, -1);+});+vi.mock('../api/_lib/provider-keys.js', () => ({+ decryptProviderKey: (...a) => decryptProviderKeyMock(...a),+}));++const { loadOwnerGrokKey, GROK_PROVIDER } = await import('../api/_lib/agent-grok-key.js');+const { modelRungs, providerChainFor } = await import('../api/_lib/llm-tool-chain.js');+const { modelChain } = await import('../api/_lib/agent-model.js');+const { chainForAgent } = await import('../api/_lib/gateway/conversation.js');+const { resolveTickChain } = await import('../api/_lib/strategy-loop/tick.js');++const GROK_MODEL = 'grok-4.7';+const USER_ID = 'ca7f8e0a-29d0-4e2e-8a2a-2a5a5a5a5a5a';++describe('loadOwnerGrokKey', () => {+ beforeEach(() => { sqlMock.mockReset(); decryptProviderKeyMock.mockClear(); });++ it('is null with no userId (never queries the db)', async () => {+ expect(await loadOwnerGrokKey(null)).toBeNull();+ expect(await loadOwnerGrokKey(undefined)).toBeNull();+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('is null when the user saved no grok key', async () => {+ sqlMock.mockResolvedValueOnce([{ provider_keys: { anthropic: 'enc(sk-ant-x)' } }]);+ expect(await loadOwnerGrokKey(USER_ID)).toBeNull();+ });++ it('is null when the user row does not exist', async () => {+ sqlMock.mockResolvedValueOnce([]);+ expect(await loadOwnerGrokKey(USER_ID)).toBeNull();+ });++ it('decrypts a stored grok key', async () => {+ sqlMock.mockResolvedValueOnce([{ provider_keys: { [GROK_PROVIDER]: 'enc(xai-owner-key)' } }]);+ expect(await loadOwnerGrokKey(USER_ID)).toBe('xai-owner-key');+ });++ it('is null, not thrown, on a corrupt stored blob', async () => {+ sqlMock.mockResolvedValueOnce([{ provider_keys: { [GROK_PROVIDER]: 'not-valid-ciphertext' } }]);+ await expect(loadOwnerGrokKey(USER_ID)).resolves.toBeNull();+ });+});++describe('modelRungs / providerChainFor: grok owner-key rung', () => {+ const prevGrokKey = process.env.GROK_API_KEY;+ const prevOpenrouterKey = process.env.OPENROUTER_API_KEY;++ afterEach(() => {+ process.env.GROK_API_KEY = prevGrokKey;+ process.env.OPENROUTER_API_KEY = prevOpenrouterKey;+ });++ it('leads with the owner key ahead of the server key', () => {+ process.env.GROK_API_KEY = 'xai-server-key';+ const rungs = modelRungs(GROK_MODEL, { grokKey: 'xai-owner-key' });+ expect(rungs).toHaveLength(2);+ expect(rungs[0]).toMatchObject({ name: 'grok', key: 'xai-owner-key', keySource: 'owner', model: GROK_MODEL });+ expect(rungs[1]).toMatchObject({ name: 'grok', key: 'xai-server-key', keySource: 'platform', model: GROK_MODEL });+ });++ it('serves only the server-key rung without an owner key', () => {+ process.env.GROK_API_KEY = 'xai-server-key';+ const rungs = modelRungs(GROK_MODEL, {});+ expect(rungs).toHaveLength(1);+ expect(rungs[0]).toMatchObject({ name: 'grok', key: 'xai-server-key', keySource: 'platform' });+ });++ it('serves only the owner-key rung when no server key is configured, so the agent still answers', () => {+ delete process.env.GROK_API_KEY;+ const rungs = modelRungs(GROK_MODEL, { grokKey: 'xai-owner-key' });+ expect(rungs).toHaveLength(1);+ expect(rungs[0]).toMatchObject({ name: 'grok', key: 'xai-owner-key', keySource: 'owner' });+ });++ it('has no rungs at all with neither key: the platform default chain is the only path left', () => {+ delete process.env.GROK_API_KEY;+ expect(modelRungs(GROK_MODEL, {})).toEqual([]);+ });++ it('providerChainFor puts the grok rungs ahead of the free default chain', () => {+ process.env.GROK_API_KEY = 'xai-server-key';+ delete process.env.OPENROUTER_API_KEY;+ const chain = providerChainFor(GROK_MODEL, { grokKey: 'xai-owner-key' });+ expect(chain[0]).toMatchObject({ name: 'grok', keySource: 'owner' });+ expect(chain[1]).toMatchObject({ name: 'grok', keySource: 'platform' });+ });++ it('providerChainFor falls back to the default chain alone when grok has no reachable rung', () => {+ delete process.env.GROK_API_KEY;+ process.env.OPENROUTER_API_KEY = 'or-key';+ const chain = providerChainFor(GROK_MODEL, {});+ expect(chain.every((r) => r.name !== 'grok')).toBe(true);+ expect(chain.some((r) => r.name === 'openrouter')).toBe(true);+ });+});++describe('modelChain: threading grokKey through to providerChainFor', () => {+ const prevGrokKey = process.env.GROK_API_KEY;+ afterEach(() => { process.env.GROK_API_KEY = prevGrokKey; });++ it('the owner rung leads a grok model chain', () => {+ process.env.GROK_API_KEY = 'xai-server-key';+ const { chain, tools } = modelChain(GROK_MODEL, { grokKey: 'xai-owner-key' });+ expect(tools).toBe(true);+ expect(chain[0]).toMatchObject({ name: 'grok', keySource: 'owner' });+ });++ it('a null model returns the platform chain untouched by grokKey', () => {+ const { chain } = modelChain(null, { grokKey: 'xai-owner-key' });+ expect(chain.every((r) => r.keySource !== 'owner')).toBe(true);+ });+});++describe('chainForAgent (api/_lib/gateway/conversation.js)', () => {+ beforeEach(() => { sqlMock.mockReset(); });+ const prevGrokKey = process.env.GROK_API_KEY;+ afterEach(() => { process.env.GROK_API_KEY = prevGrokKey; });++ it('returns undefined when the agent has no default model (platform chain applies downstream)', async () => {+ const chain = await chainForAgent({ meta: {}, user_id: USER_ID });+ expect(chain).toBeUndefined();+ });++ it('returns undefined when the agent default has no tool calling', async () => {+ const chain = await chainForAgent({ meta: { runtime: { model: 'deepseek-r1' } }, user_id: USER_ID });+ expect(chain).toBeUndefined();+ });++ it('leads with the owner grok key when the agent defaults to grok', async () => {+ process.env.GROK_API_KEY = 'xai-server-key';+ sqlMock.mockResolvedValueOnce([{ provider_keys: { [GROK_PROVIDER]: 'enc(xai-owner-key)' } }]);+ const chain = await chainForAgent({ meta: { runtime: { model: GROK_MODEL } }, user_id: USER_ID });+ expect(chain[0]).toMatchObject({ name: 'grok', keySource: 'owner', key: 'xai-owner-key' });+ });++ it('falls over to the server key when the agent has no saved key', async () => {+ process.env.GROK_API_KEY = 'xai-server-key';+ sqlMock.mockResolvedValueOnce([{ provider_keys: {} }]);+ const chain = await chainForAgent({ meta: { runtime: { model: GROK_MODEL } }, user_id: USER_ID });+ expect(chain[0]).toMatchObject({ name: 'grok', keySource: 'platform', key: 'xai-server-key' });+ });+});++describe('resolveTickChain (api/_lib/strategy-loop/tick.js)', () => {+ beforeEach(() => { sqlMock.mockReset(); });+ const prevGrokKey = process.env.GROK_API_KEY;+ afterEach(() => { process.env.GROK_API_KEY = prevGrokKey; });++ it('falls back to the full default chain with no usable model', async () => {+ const chain = await resolveTickChain({ meta: {}, user_id: USER_ID });+ expect(Array.isArray(chain)).toBe(true);+ expect(chain.every((r) => r.name !== 'grok')).toBe(true);+ });++ it('reads the legacy meta.brain.provider location, not just meta.runtime.model', async () => {+ process.env.GROK_API_KEY = 'xai-server-key';+ sqlMock.mockResolvedValueOnce([{ provider_keys: {} }]);+ const chain = await resolveTickChain({ meta: { brain: { provider: GROK_MODEL } }, user_id: USER_ID });+ expect(chain[0]).toMatchObject({ name: 'grok', keySource: 'platform' });+ });++ it('leads with the owner grok key for a tick agent that saved one', async () => {+ process.env.GROK_API_KEY = 'xai-server-key';+ sqlMock.mockResolvedValueOnce([{ provider_keys: { [GROK_PROVIDER]: 'enc(xai-owner-key)' } }]);+ const chain = await resolveTickChain({ meta: { runtime: { model: GROK_MODEL } }, user_id: USER_ID });+ expect(chain[0]).toMatchObject({ name: 'grok', keySource: 'owner', key: 'xai-owner-key' });+ });+});++describe('web copilot (api/agents/copilot.js): same owner-key-then-server-key composition', () => {+ beforeEach(() => { sqlMock.mockReset(); });+ const prevGrokKey = process.env.GROK_API_KEY;+ afterEach(() => { process.env.GROK_API_KEY = prevGrokKey; });++ it('mirrors copilot.js line-for-line: grokKey loaded only for a grok choice, then threaded into modelChain', async () => {+ process.env.GROK_API_KEY = 'xai-server-key';+ sqlMock.mockResolvedValueOnce([{ provider_keys: { [GROK_PROVIDER]: 'enc(xai-owner-key)' } }]);+ const { MODEL_CATALOG } = await import('../api/_lib/chat-models.js');+ const choice = { model: GROK_MODEL };+ const row = { user_id: USER_ID };+ const grokKey = choice.model && MODEL_CATALOG[choice.model]?.provider === 'grok' ? await loadOwnerGrokKey(row.user_id) : null;+ const { chain } = modelChain(choice.model, { grokKey });+ expect(chain[0]).toMatchObject({ name: 'grok', keySource: 'owner', key: 'xai-owner-key' });+ });++ it('never queries for a key when the choice is not grok', async () => {+ const choice = { model: 'claude-haiku-4-5-20251001' };+ const row = { user_id: USER_ID };+ const { MODEL_CATALOG } = await import('../api/_lib/chat-models.js');+ const grokKey = choice.model && MODEL_CATALOG[choice.model]?.provider === 'grok' ? await loadOwnerGrokKey(row.user_id) : null;+ expect(grokKey).toBeNull();+ expect(sqlMock).not.toHaveBeenCalled();+ });+});