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(agents): resolve each agent's chosen brain in one place and show which model answered, billing owner-key calls at zero credits
nirholas39c9893ea1a3
diff --git a/api/_lib/agent-brain.js b/api/_lib/agent-brain.jsnew file mode 100644index 000000000..2deaa3e7f--- /dev/null+++ b/api/_lib/agent-brain.js@@ -0,0 +1,121 @@+// The one function every agent-turn surface asks "which brain answers for this+// agent, and what chain serves it".+//+// api/_lib/agent-model.js decides the model (per-message override, the agent's+// saved brain, else the platform chain) and builds a provider chain for it. This+// module adds the owner's side of it: when the chosen brain is a Grok model, the+// agent's owner key (Account, AI Provider Keys) leads, then the server's xAI key,+// then the default free-first chain, so the agent always answers.+//+// It also names the rung that actually served a turn (`brainBadge`), which is+// what the agent page shows: the real lane and key source from the response,+// plus whether the answer came from a failover rung instead of the chosen brain.+//+// Surfaces on this function: the profile copilot (api/agents/copilot.js), the+// chat gateways (api/_lib/gateway/conversation.js), the agent message API and+// MCP call_agent (api/_lib/agent-message.js), v1 runs (agents-v1/runs.js) and the+// strategy loop tick. The public X reply brain plugs in the same way.++import { sql } from './db.js';+import { MODEL_CATALOG, XAI_CHAT_COMPLETIONS_URL, routableGrokModelId } from './chat-models.js';+import { loadUserProviderKeys } from './provider-keys.js';+import { resolveMessageModel, modelChain, ModelChoiceError } from './agent-model.js';++/** Whether a catalog model id is served by xAI. */+export function isGrokModel(model) {+ return Boolean(model && MODEL_CATALOG[model]?.provider === 'grok');+}++/**+ * The owner's saved xAI key, or null. A read failure answers null so the chain+ * simply continues to the server key.+ * @param {string|null|undefined} userId+ */+export async function ownerGrokKey(userId) {+ if (!userId) return null;+ try {+ const [row] = await sql`SELECT provider_keys FROM users WHERE id = ${userId}`;+ const keys = await loadUserProviderKeys(row?.provider_keys);+ return typeof keys.grok === 'string' && keys.grok ? keys.grok : null;+ } catch {+ return null;+ }+}++/** Tag every rung with where its credential comes from: the owner, the server, or the platform chain. */+function tagKeySource(chain, model) {+ return chain.map((rung) => {+ if (rung.keySource) return rung;+ const serverGrok = rung.name === 'grok' && rung.catalogModel === model;+ return { ...rung, keySource: serverGrok ? 'server' : 'platform' };+ });+}++/**+ * Build the chain for a resolved model. Grok: owner key, server key, default+ * chain. Any other model: its own routes, then the default chain.+ * @param {string|null} model catalog id or null for the platform chain+ * @param {{ ownerKey?: string|null }} [o]+ * @returns {{ chain: object[], tools: boolean }}+ */+export function brainChain(model, { ownerKey = null } = {}) {+ const base = modelChain(model);+ let chain = tagKeySource(base.chain, model);+ if (isGrokModel(model) && ownerKey && base.tools) {+ const owned = {+ name: 'grok',+ url: XAI_CHAT_COMPLETIONS_URL,+ key: ownerKey,+ model: routableGrokModelId(model),+ catalogModel: model,+ keySource: 'owner',+ };+ chain = [owned, ...chain];+ }+ return { chain, tools: base.tools };+}++/**+ * Decide the brain for one agent turn.+ *+ * @param {object} o+ * @param {{ id?: string, user_id?: string|null, meta?: object }} o.agent+ * @param {string|null} [o.requested] per-message override+ * @param {'chat'|'run'} [o.purpose]+ * @param {boolean} [o.signedIn] false clamps paid models away (and the owner key is not used)+ * @param {boolean} [o.lenient] true: an agent default that cannot run tools falls back to the platform chain instead of throwing+ * @returns {Promise<{ model: string|null, source: 'message'|'agent'|'platform', tools: boolean, chain: object[] }>}+ * @throws {ModelChoiceError} an explicit override the caller has to fix+ */+export async function resolveAgentBrain({ agent, requested = null, purpose = 'chat', signedIn = true, lenient = false }) {+ let choice;+ try {+ choice = resolveMessageModel({ requested, agentMeta: agent?.meta, purpose, signedIn });+ } catch (e) {+ const fixable = lenient && !requested && e instanceof ModelChoiceError && e.code === 'model_lacks_tools';+ if (!fixable) throw e;+ choice = { model: null, source: 'platform', tools: true };+ }+ const ownerKey = signedIn && isGrokModel(choice.model) ? await ownerGrokKey(agent?.user_id) : null;+ const { chain, tools } = brainChain(choice.model, { ownerKey });+ return { model: choice.model, source: choice.source, tools: purpose === 'run' ? choice.tools : tools, chain };+}++/**+ * What the agent page shows for a served turn.+ * @param {{ model: string|null }} chosen the resolved brain+ * @param {{ provider?: string, name?: string, model?: string, catalogModel?: string, keySource?: string }|null} served the rung that answered+ * @returns {{ chosen: string|null, served: string|null, lane: string|null, keySource: string|null, failover: boolean }}+ */+export function brainBadge(chosen, served) {+ const lane = served?.provider || served?.name || null;+ const servedModel = served?.catalogModel || served?.model || null;+ const wanted = chosen?.model || null;+ return {+ chosen: wanted,+ served: servedModel,+ lane,+ keySource: served?.keySource || null,+ failover: Boolean(wanted && served && served.catalogModel !== wanted),+ };+}diff --git a/api/_lib/agent-loop.js b/api/_lib/agent-loop.jsindex a3a0b247c..bf31f98ed 100644--- a/api/_lib/agent-loop.js+++ b/api/_lib/agent-loop.js@@ -117,7 +117,8 @@ export function createAgentLoop({kind: 'model_call',provider: provider.name,model,- free: isFreeLane(provider.name, model),+ free: isFreeLane(provider.name, model) || provider.keySource === 'owner',+ keySource: provider.keySource || null,content: out.content,toolCalls: out.toolCalls.map((tc) => ({ id: tc.id, name: tc.name, args: tc.args })),usage: { input, output, estimated },diff --git a/api/_lib/agents-v1/billing.js b/api/_lib/agents-v1/billing.jsindex cefc38f08..b8ecd4048 100644--- a/api/_lib/agents-v1/billing.js+++ b/api/_lib/agents-v1/billing.js@@ -80,7 +80,8 @@ export async function admitCall({ userId, agent, model }) {* @returns {Promise<{ chargedUsd: number, shortfallUsd: number }>}*/export async function chargeCall({ userId, agentId, callId, event, model, free }) {- if (free) return { chargedUsd: 0, shortfallUsd: 0 };+ // A call on the owner's own provider key is billed by that provider, not in credits.+ if (free || event.keySource === 'owner') return { chargedUsd: 0, shortfallUsd: 0 };// The named paid model answered: bill its own metered cost.if (isPaidModel(model) && !event.free && event.costMicroUsd > 0) {const amountUsd = Math.ceil(event.costMicroUsd) / 1e6;diff --git a/api/_lib/agents-v1/messages.js b/api/_lib/agents-v1/messages.jsindex abed016ed..2f7433a75 100644--- a/api/_lib/agents-v1/messages.js+++ b/api/_lib/agents-v1/messages.js@@ -17,7 +17,8 @@import { randomUUID } from 'node:crypto';import { sql } from '../db.js';import { apiError, intParam, numParam, strParam, page } from './http.js';-import { ModelChoiceError, modelChain, resolveMessageModel } from '../agent-model.js';+import { ModelChoiceError, resolveMessageModel } from '../agent-model.js';+import { brainChain, ownerGrokKey } from '../agent-brain.js';import { isFreeLane } from '../llm-pricing.js';import { agentToolSchemas, agentToolHandlers } from '../agent-tools.js';import { agentSkillsForPrompt } from '../agent-custom-skills.js';@@ -102,8 +103,8 @@ export async function sendMessage(agent, userId, body) {const channel = channelParam(body.channel);const { free } = await admitCall({ userId, agent, model });- let { chain } = modelChain(model);- if (free) chain = chain.filter((p) => isFreeLane(p.name, p.catalogModel || p.model));+ let { chain } = brainChain(model, { ownerKey: await ownerGrokKey(agent.user_id || userId) });+ if (free) chain = chain.filter((p) => p.keySource === 'owner' || isFreeLane(p.name, p.catalogModel || p.model));if (!chain.length) {throw apiError(503, 'no_model_available', 'No model lane is available right now. Retry shortly, or name a paid model to use your credits.');}diff --git a/api/_lib/agents-v1/runs.js b/api/_lib/agents-v1/runs.jsindex eb002f7be..16e774cea 100644--- a/api/_lib/agents-v1/runs.js+++ b/api/_lib/agents-v1/runs.js@@ -21,7 +21,7 @@import { randomUUID } from 'node:crypto';import { sql } from '../db.js';import { apiError } from './http.js';-import { providerChainFor } from '../llm-tool-chain.js';+import { resolveAgentBrain } from '../agent-brain.js';import { isFreeLane } from '../llm-pricing.js';import { agentToolSchemas, agentToolHandlers } from '../agent-tools.js';import { debitCredits } from '../credits.js';@@ -274,10 +274,16 @@ export async function agentSystemPrompt(agentId) {return parts.join('\n\n');}-function chainFor(run) {- const chain = providerChainFor(run.model || null);+export async function chainFor(run) {+ const [agent] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${run.agent_id} LIMIT 1`;+ const { chain } = await resolveAgentBrain({+ agent: agent || { id: run.agent_id, user_id: run.user_id, meta: null },+ requested: run.model || null,+ purpose: 'run',+ lenient: true,+ });if (toNumber(run.budget_credits_usd) > 0) return chain;- return chain.filter((p) => isFreeLane(p.name, p.catalogModel || p.model));+ return chain.filter((p) => p.keySource === 'owner' || isFreeLane(p.name, p.catalogModel || p.model));}function toolsFor(run) {@@ -298,7 +304,7 @@ export async function stepRun(runId, { owner = `step:${randomUUID()}` } = {}) {if (run.cancel_requested_at) return finalize(run, 'cancelled', { note: 'cancelled by the owner' });- const chain = chainFor(run);+ const chain = await chainFor(run);if (!chain.length) {return finalize(run, 'failed', {error: toNumber(run.budget_credits_usd) > 0diff --git a/api/_lib/copilot-engine.js b/api/_lib/copilot-engine.jsindex a3b1aa983..2b7f4a884 100644--- a/api/_lib/copilot-engine.js+++ b/api/_lib/copilot-engine.js@@ -279,9 +279,10 @@ export function buildSystemPrompt({ agentName, persona, network }) {* @param {() => boolean} [opts.isActive] false once the caller has gone away* @param {string} [opts.surfaceNote] extra system guidance for the delivering surface* @param {Array} [opts.chain] provider chain override (defaults to providerChain())- * @returns {Promise<{ reply:string, proposals:object[], citations:object[], toolCalls:{name:string, summary:string}[] }>}+ * @param {(served:object) => void} [opts.onRound] called with the rung that served each model round+ * @returns {Promise<{ reply:string, proposals:object[], citations:object[], toolCalls:{name:string, summary:string}[], served:object|null }>}*/-export async function runCopilotTurn({ agent, history, network, emit = () => {}, isActive = () => true, surfaceNote = '', chain = providerChain() }) {+export async function runCopilotTurn({ agent, history, network, emit = () => {}, isActive = () => true, surfaceNote = '', chain = providerChain(), onRound = () => {} }) {if (!chain.length) {throw Object.assign(new Error('No LLM provider configured. Set GROQ_API_KEY, OPENROUTER_API_KEY, or NVIDIA_API_KEY (or GOOGLE_CLOUD_PROJECT for the Vertex credits anchor).'), { code: 'llm_unavailable' });}@@ -295,6 +296,11 @@ export async function runCopilotTurn({ agent, history, network, emit = () => {},const citations = [];const toolCalls = [];let finalText = '';+ let served = null; // the rung that answered the latest round+ const noteServed = (provider, usage) => {+ served = { provider: provider.name, model: provider.model, catalogModel: provider.catalogModel || null, keySource: provider.keySource || null, usage: usage || null };+ onRound(served);+ };const active = () => isActive();// Read-only tools are pure within a turn, the wallet/intel/quote a round sees@@ -436,6 +442,7 @@ export async function runCopilotTurn({ agent, history, network, emit = () => {},tools: COPILOT_TOOLS,onContent: (t) => { emitted = true; finalText += t; send('chunk', { text: t }); },});+ noteServed(provider, roundOut.usage);break;} catch (e) {lastErr = e;@@ -504,10 +511,10 @@ export async function runCopilotTurn({ agent, history, network, emit = () => {},tools: [],onContent: (t) => { finalText += t; send('chunk', { text: t }); },});- if (out) break;+ if (out) { noteServed(provider, out.usage); break; }} catch { /* try next provider */ }}}- return { reply: finalText.trim(), proposals, citations, toolCalls };+ return { reply: finalText.trim(), proposals, citations, toolCalls, served };}diff --git a/api/_lib/gateway/conversation.js b/api/_lib/gateway/conversation.jsindex 74609693b..48078f0e8 100644--- a/api/_lib/gateway/conversation.js+++ b/api/_lib/gateway/conversation.js@@ -13,6 +13,7 @@// (./voice.js).import { runCopilotTurn } from '../copilot-engine.js';+import { resolveAgentBrain } from '../agent-brain.js';import { appendThreadMessage, threadHistoryForModel } from '../agent-thread.js';import { resolveChatAgent, listAccountAgents } from './agents.js';import { createPreview, setPreviewMessageRef, PREVIEW_TTL_MINUTES } from './store.js';@@ -131,9 +132,11 @@ export async function converse({ gw, event, link, text }) {const status = statusLine(gw, event.chatId);let turn;try {+ const brain = await resolveAgentBrain({ agent, purpose: 'run', lenient: true });turn = await runCopilotTurn({agent,history,+ chain: brain.chain,network: 'mainnet',surfaceNote: surfaceNote(event.platform, { buttons: hasButtons(gw) }),emit: (name, data) => { if (name === 'tool_start') status.working(data.name); },diff --git a/api/_lib/strategy-loop/tick.js b/api/_lib/strategy-loop/tick.jsindex cbcc190d1..d979d7272 100644--- a/api/_lib/strategy-loop/tick.js+++ b/api/_lib/strategy-loop/tick.js@@ -22,7 +22,7 @@// in worker memory between steps.import { sql } from '../db.js';-import { providerChainFor } from '../llm-tool-chain.js';+import { resolveAgentBrain } from '../agent-brain.js';import { createAgentLoop, initialLoopState, loopFinished, finalAnswer } from '../agent-loop.js';import { computeContext } from '../memory-store.js';import { insertNotification } from '../notify.js';@@ -502,7 +502,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 resolveAgentBrain({ agent, purpose: 'run', lenient: true })).chain;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 });@@ -591,7 +591,9 @@ export async function runAgentTick({ agentId, workerId, cfg, log, signal = null,const rows = [];for (const [i, event] of pending.entries()) {const row = eventRow(event);- if (event.kind === 'model_call') {+ if (event.kind === 'model_call' && event.keySource === 'owner') {+ row.cost_usd = 0;+ } else if (event.kind === 'model_call') {const charge = await chargeInference({userId: agent.user_id,agentId,diff --git a/api/agents/copilot.js b/api/agents/copilot.jsindex d6893a7c5..2ce79252e 100644--- a/api/agents/copilot.js+++ b/api/agents/copilot.js@@ -44,7 +44,8 @@ import { limits } from '../_lib/rate-limit.js';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 { ModelChoiceError } from '../_lib/agent-model.js';+import { resolveAgentBrain, brainBadge } from '../_lib/agent-brain.js';import { meterFreeModel, FreeTierExhaustedError, freeTierErrorBody, retryAfterSeconds } from '../_lib/free-tier.js';import { recordEvent } from '../_lib/usage.js';import { costMicroUsd } from '../_lib/llm-pricing.js';@@ -87,9 +88,10 @@ export default async function handler(req, res, id) {return error(res, 422, 'no_message', 'send at least one user message');}+ const override = typeof body?.model === 'string' && body.model.trim() ? body.model.trim().slice(0, 80) : null;let choice;try {- choice = copilotModel(body?.model, row.meta);+ choice = await resolveAgentBrain({ agent: row, requested: override, purpose: 'run', lenient: true });} catch (e) {if (e instanceof ModelChoiceError) return error(res, e.status, e.code, e.message);throw e;@@ -102,7 +104,7 @@ 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 { chain } = choice;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.@@ -131,7 +133,7 @@ export default async function handler(req, res, id) {chain,isActive: () => active,onRound: (served) => {- send('model', { model: choice.model, source: choice.source, served: served.catalogModel || served.model, lane: served.provider });+ send('model', { model: choice.model, source: choice.source, served: served.catalogModel || served.model, lane: served.provider, ...brainBadge(choice, served) });meterRound({ userId: auth.userId, agentId: id, served });},// tool_start is for surfaces that paint a live status line (the chat@@ -163,25 +165,6 @@ async function sendThread(req, res, { agentId, userId }) {}, { 'cache-control': 'no-store' });}-/**- * The model one copilot message runs on. An explicit override must call tools- * (the copilot is a tool loop); an agent default without tools is skipped for- * the platform chain rather than blocking the owner's chat. Exported for tests.- * @param {unknown} requested body.model- * @param {object|null} meta agent meta- */-export function copilotModel(requested, meta) {- const override = typeof requested === 'string' && requested.trim() ? requested.trim().slice(0, 80) : null;- try {- return resolveMessageModel({ requested: override, agentMeta: meta, purpose: 'run' });- } catch (e) {- if (!override && e instanceof ModelChoiceError && e.code === 'model_lacks_tools') {- return { model: null, source: 'platform', tools: true };- }- throw e;- }-}-// Every model round is recorded against the owner, priced at the lane that// served it (free lanes cost 0), the same ledger /brain and the runs write.function meterRound({ userId, agentId, served }) {diff --git a/src/agent-copilot.js b/src/agent-copilot.jsindex c745bca07..9cee143a2 100644--- a/src/agent-copilot.js+++ b/src/agent-copilot.js@@ -53,6 +53,8 @@ const STYLE = `.awh-cop-bubble.is-empty { color: var(--ink-dim,#888); }.awh-cop-name { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); padding: 0 4px; }.awh-cop-via { display: inline-block; margin-left: 6px; padding: 0 6px; border-radius: 999px; border: 1px solid var(--line,rgba(255,255,255,.14)); font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); vertical-align: 1px; }+.awh-cop-brain { display: inline-block; margin-left: 6px; padding: 0 6px; border-radius: 999px; border: 1px solid var(--line,rgba(255,255,255,.14)); font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); vertical-align: 1px; }+.awh-cop-brain.is-failover { border-color: var(--warning,#fbbf24); color: var(--warning,#fbbf24); }.awh-cop-msg.is-user .awh-cop-via { margin: 0 4px 2px 0; align-self: flex-end; }.awh-cop-tools { display: flex; flex-direction: column; gap: 4px; }@@ -405,11 +407,25 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO${i === lastAgentIndex() ? `<button class="awh-cop-msg-act" type="button" data-msgact="regen" title="Regenerate">↻ Retry</button>` : ''}</div>` : '';return `<div class="awh-cop-msg is-agent">- <div class="awh-cop-name">${esc(agentName)}${viaTag(m)}</div>+ <div class="awh-cop-name">${esc(agentName)}${viaTag(m)}${brainTag(m)}</div>${activity}${body}${props}${actions}</div>`;}+ // Which brain answered, from the server's own response metadata: the lane and+ // model that served the last round, whose key paid, and whether the agent's+ // chosen brain was skipped for a fallback rung.+ function brainTag(m) {+ const b = m.brain;+ if (!b || !b.served) return '';+ const keyNote = b.keySource === 'owner' ? ' · your key' : b.keySource === 'server' ? ' · platform key' : '';+ const label = b.failover && b.chosen ? `${b.served} (fallback for ${b.chosen})` : `${b.served}${keyNote}`;+ const title = b.failover+ ? `${b.chosen} was unavailable, so ${b.served} answered on ${b.lane}.`+ : `Answered by ${b.served} on ${b.lane}${keyNote}.`;+ return `<span class="awh-cop-brain${b.failover ? ' is-failover' : ''}" data-brain="${esc(b.served)}" data-brain-lane="${esc(b.lane || '')}" title="${esc(title)}">${esc(label)}</span>`;+ }+function viaTag(m) {const label = m.channel && CHANNEL_LABEL[m.channel];return label ? `<span class="awh-cop-via" title="Sent in a paired ${esc(label)} chat">via ${esc(label)}</span>` : '';@@ -872,6 +888,8 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO} else if (event === 'proposal') {agentMsg.proposals.push(normalizeProposal(payload));render();+ } else if (event === 'model') {+ if (payload.served) { agentMsg.brain = payload; render(); }} else if (event === 'chunk') {agentMsg.content += payload.text || '';render();diff --git a/tests/agent-brain.test.js b/tests/agent-brain.test.jsnew file mode 100644index 000000000..b6dcedcc5--- /dev/null+++ b/tests/agent-brain.test.js@@ -0,0 +1,163 @@+// One brain for every agent-turn surface: an agent set to Grok keeps Grok across+// the profile copilot, the chat gateway and scheduled runs, led by the owner's+// saved xAI key, then the server key, then the default chain, and the answer+// names the rung that served it.+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const sqlMock = vi.fn(async () => []);+vi.mock('../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));+const loadKeysMock = vi.fn(async () => ({}));+vi.mock('../api/_lib/provider-keys.js', () => ({ loadUserProviderKeys: (...a) => loadKeysMock(...a) }));++const runCopilotTurnMock = vi.fn(async () => ({ reply: 'hi', proposals: [], toolCalls: [], citations: [], served: null }));+vi.mock('../api/_lib/copilot-engine.js', async (orig) => ({ ...(await orig()), runCopilotTurn: (...a) => runCopilotTurnMock(...a) }));+vi.mock('../api/_lib/agent-thread.js', () => ({+ appendThreadMessage: vi.fn(async () => {}),+ threadHistoryForModel: vi.fn(async () => []),+}));+vi.mock('../api/_lib/gateway/agents.js', () => ({+ resolveChatAgent: vi.fn(async () => AGENT),+ listAccountAgents: vi.fn(async () => []),+}));+vi.mock('../api/_lib/gateway/store.js', () => ({ createPreview: vi.fn(), setPreviewMessageRef: vi.fn(), PREVIEW_TTL_MINUTES: 10 }));+vi.mock('../api/_lib/gateway/voice.js', () => ({ maybeSpeakReply: vi.fn(async () => {}) }));++const { resolveAgentBrain, brainChain, brainBadge, isGrokModel } = await import('../api/_lib/agent-brain.js');+const { runCopilotTurn: realRunCopilotTurn } = await vi.importActual('../api/_lib/copilot-engine.js');+const { converse } = await import('../api/_lib/gateway/conversation.js');+const { chainFor } = await import('../api/_lib/agents-v1/runs.js');++const AGENT = { id: 'a1', user_id: 'u1', name: 'Gina', persona_prompt: 'p', meta: { runtime: { model: 'grok-4.3' } } };+const KEYS = ['GROK_API_KEY', 'XAI_API_KEY', 'OPENROUTER_API_KEY', 'GROQ_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'CEREBRAS_API_KEY'];+const saved = {};++beforeEach(() => {+ for (const k of KEYS) { saved[k] = process.env[k]; delete process.env[k]; }+ process.env.GROQ_API_KEY = 'groq-test';+ sqlMock.mockReset().mockResolvedValue([{ provider_keys: { grok: 'enc' } }]);+ loadKeysMock.mockReset().mockResolvedValue({});+ runCopilotTurnMock.mockClear();+});+afterEach(() => {+ for (const k of KEYS) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; }+});++const lanes = (chain) => chain.map((r) => `${r.name}:${r.keySource}`);++describe('resolveAgentBrain', () => {+ it('puts the owner key first, then the server key, then the default chain, for a Grok agent', async () => {+ process.env.GROK_API_KEY = 'xai-server';+ loadKeysMock.mockResolvedValue({ grok: 'xai-owner' });+ const brain = await resolveAgentBrain({ agent: AGENT, purpose: 'run', lenient: true });+ expect(brain.model).toBe('grok-4.3');+ expect(brain.source).toBe('agent');+ expect(lanes(brain.chain).slice(0, 3)).toEqual(['grok:owner', 'grok:server', 'groq:platform']);+ expect(brain.chain[0].key).toBe('xai-owner');+ expect(brain.chain[1].key).toBe('xai-server');+ });++ it('falls to the server key when the owner saved none', async () => {+ process.env.GROK_API_KEY = 'xai-server';+ const brain = await resolveAgentBrain({ agent: AGENT, purpose: 'run', lenient: true });+ expect(lanes(brain.chain).slice(0, 2)).toEqual(['grok:server', 'groq:platform']);+ });++ it('answers on the default chain when no xAI key exists anywhere', async () => {+ const brain = await resolveAgentBrain({ agent: AGENT, purpose: 'run', lenient: true });+ expect(brain.model).toBe('grok-4.3');+ expect(lanes(brain.chain)).toEqual(['groq:platform']);+ });++ it('never uses the owner key for a signed-out caller', async () => {+ loadKeysMock.mockResolvedValue({ grok: 'xai-owner' });+ const brain = await resolveAgentBrain({ agent: AGENT, signedIn: false });+ expect(brain.chain.some((r) => r.keySource === 'owner')).toBe(false);+ });++ it('leaves a non-Grok agent on its own chain without reading the key', async () => {+ const brain = await resolveAgentBrain({ agent: { ...AGENT, meta: {} } });+ expect(brain.model).toBeNull();+ expect(sqlMock).not.toHaveBeenCalled();+ });+});++describe('brainBadge', () => {+ it('reports the chosen brain serving, with the key that paid', () => {+ const chain = brainChain('grok-4.3', { ownerKey: 'xai-owner' }).chain;+ expect(brainBadge({ model: 'grok-4.3' }, chain[0])).toMatchObject({ served: 'grok-4.3', lane: 'grok', keySource: 'owner', failover: false });+ });+ it('flags a failover rung', () => {+ const rung = { name: 'groq', model: 'qwen/qwen3.8-27b', keySource: 'platform' };+ expect(brainBadge({ model: 'grok-4.3' }, rung)).toMatchObject({ served: 'qwen/qwen3.8-27b', lane: 'groq', failover: true });+ });+ it('isGrokModel only matches xAI catalog ids', () => {+ expect(isGrokModel('grok-4.3')).toBe(true);+ expect(isGrokModel('claude-haiku-4-5-20251001')).toBe(false);+ expect(isGrokModel(null)).toBe(false);+ });+});++describe('profile copilot engine: fails over and reports the serving rung', () => {+ it('skips a dead Grok rung and names the fallback that answered', async () => {+ const sse = (text) => new Response(+ `data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\ndata: [DONE]\n\n`,+ { status: 200, headers: { 'content-type': 'text/event-stream' } },+ );+ const urls = [];+ const fetchMock = vi.spyOn(globalThis, 'fetch').mockImplementation(async (url) => {+ urls.push(String(url));+ return String(url).includes('api.x.ai') ? new Response('{"error":"down"}', { status: 503 }) : sse('hello');+ });+ process.env.GROK_API_KEY = 'xai-server';+ loadKeysMock.mockResolvedValue({ grok: 'xai-owner' });+ const brain = await resolveAgentBrain({ agent: AGENT, purpose: 'run', lenient: true });+ const rounds = [];+ const turn = await realRunCopilotTurn({+ agent: AGENT, history: [{ role: 'user', content: 'hi' }], network: 'mainnet',+ chain: brain.chain, onRound: (s) => rounds.push(s),+ });+ fetchMock.mockRestore();+ expect(urls.filter((u) => u.includes('api.x.ai')).length).toBe(2); // owner then server+ expect(turn.reply).toBe('hello');+ expect(turn.served).toMatchObject({ provider: 'groq', keySource: 'platform' });+ expect(rounds).toHaveLength(1);+ expect(brainBadge(brain, turn.served).failover).toBe(true);+ });++ it('reports the Grok owner rung when xAI answers', async () => {+ const body = `data: ${JSON.stringify({ choices: [{ delta: { content: 'grok here' } }] })}\n\ndata: [DONE]\n\n`;+ const fetchMock = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => new Response(body, { status: 200 }));+ loadKeysMock.mockResolvedValue({ grok: 'xai-owner' });+ const brain = await resolveAgentBrain({ agent: AGENT, purpose: 'run', lenient: true });+ const turn = await realRunCopilotTurn({ agent: AGENT, history: [{ role: 'user', content: 'hi' }], network: 'mainnet', chain: brain.chain });+ const auth = fetchMock.mock.calls[0][1].headers.authorization;+ fetchMock.mockRestore();+ expect(auth).toBe('Bearer xai-owner');+ expect(brainBadge(brain, turn.served)).toMatchObject({ served: 'grok-4.3', lane: 'grok', keySource: 'owner', failover: false });+ });+});++describe('chat gateway', () => {+ it('runs the turn on the agent brain chain', async () => {+ process.env.GROK_API_KEY = 'xai-server';+ const gw = { platform: 'telegram', canEdit: true, sendText: vi.fn(async () => 'm1'), editMessage: vi.fn(), typing: vi.fn() };+ await converse({ gw, event: { chatId: 'c1', platform: 'telegram' }, link: { id: 'l1', user_id: 'u1' }, text: 'hello' });+ const call = runCopilotTurnMock.mock.calls[0][0];+ expect(lanes(call.chain).slice(0, 2)).toEqual(['grok:server', 'groq:platform']);+ });+});++describe('scheduled runs', () => {+ it('uses the agent brain when the run names no model, and keeps the owner key rung on a free-only run', async () => {+ process.env.GROK_API_KEY = 'xai-server';+ loadKeysMock.mockResolvedValue({ grok: 'xai-owner' });+ sqlMock.mockImplementation(async (strings) => (String(strings[0]).includes('FROM users')+ ? [{ provider_keys: { grok: 'enc' } }]+ : [{ id: 'a1', user_id: 'u1', meta: AGENT.meta }]));+ const chain = await chainFor({ agent_id: 'a1', user_id: 'u1', model: null, budget_credits_usd: 0 });+ expect(lanes(chain)[0]).toBe('grok:owner');+ expect(chain.some((r) => r.keySource === 'server')).toBe(false); // server Grok is paid, a free-only run drops it+ const funded = await chainFor({ agent_id: 'a1', user_id: 'u1', model: null, budget_credits_usd: 5 });+ expect(lanes(funded).slice(0, 3)).toEqual(['grok:owner', 'grok:server', 'groq:platform']);+ });+});