Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: enhance Trading Copilot to prevent freezing and improve wallet auditing script
fudjia82aeeab30744
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2fb18145c..e90410927 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The agent economy now watches itself and pages the team** — After weeks of the agent-to-agent economy silently stalling and being diagnosed hours late, the platform now monitors it as a system: every 5 minutes it checks that the per-minute heartbeat is alive, that no engine is failing or stuck on a fixable problem (missing config, an unfundable payment, a full database), and that real on-chain agent activity is still flowing. Any of those pages the ops channel immediately, keeps re-paging hourly until fixed, and announces recovery. The status page's JSON feed also keeps 24 hours of health history so anyone can see exactly when a stall began. `[improvement, infra]`- **The sniper engine now pages us when it goes down — and restarts itself** — The on-chain sniper worker went quiet on July 3 and nothing noticed: the status page showed the engine offline and zero launches scored, but no alert fired. The platform's watchdog now checks the sniper's own heartbeat every 5 minutes and pages the ops channel within 10 minutes of a stall, with hourly re-pages until it recovers. The worker also gained a dead-man switch: if it loses its database for 15 minutes straight it restarts itself instead of running as a zombie that scores nothing. (`/status`) `[fix, infra]`- **Tour Builder — design a walking 3D store guide with zero code** — Building a guided 3D tour for your store used to mean hand-writing a JSON file. Now there's a live, Wix-style playground at /tour-builder: a demo storefront on one side, a point-and-click editor on the other. Pick who guides the tour, click the sections you want it to walk to, type what it should say, and hit Preview to watch the real tour run exactly as your visitors will see it. When it looks right, one click gives you the curriculum file plus the exact snippets to paste into Shopify. The Shopify tutorial is rebuilt around it — a ten-minute no-code path — with a new advanced guide for multi-page tours, exact section targeting, real spoken voices, custom avatars, deep links, and the JavaScript API. (`/tour-builder`) `[feature, docs]`+- **Trading Copilot no longer freezes after reading your wallet** — When you asked the Copilot about your portfolio, it sometimes read your wallet, then read it again, and got stuck on "Analyzing…" with the typing dots spinning forever — you'd see the same "Portfolio: … 6 tokens" line twice and never get an answer. The Copilot now remembers what it just looked up within a single reply, so a repeated lookup is instant instead of a wasted round, and the moment it starts going in circles it stops and answers with what it already knows. As a backstop, the chat now detects a genuinely dead connection and offers a Retry instead of hanging — so it can never leave you staring at a frozen indicator again. `[fix, improvement]`- **Wallet chips on avatar and agent cards no longer overflow their card** — On the Avatars and Agents dashboards, the wallet identity chip — address, ownership, live balance, rarity and the vanity shortcut — was crammed onto a single line and spilled past the edge of narrow cards, bleeding into the card beside it. It now fills the card footer as a tidy rounded block and wraps its badges onto a second line when space is tight, so every card stays clean at any width. The Community and Characters galleries get the same fix. (`/dashboard/avatars`) `[fix]`## 2026-07-04diff --git a/api/agents/copilot.js b/api/agents/copilot.jsindex cc62d50bf..47137d69e 100644--- a/api/agents/copilot.js+++ b/api/agents/copilot.js@@ -415,12 +415,25 @@ export default async function handler(req, res, id) {let active = true;req.on('close', () => { active = false; });const send = (event, data) => { if (active) res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); };+ // Keepalive: a tool-loop round can sit silent for tens of seconds waiting on a+ // slow provider (or a mid-round failover to the next one). Emit an SSE comment+ // every 15s so the client's stall watchdog can stay tight and only fire on a+ // genuinely dead connection, never on a model that's just thinking.+ const heartbeat = setInterval(() => { if (active) res.write(': ping\n\n'); }, 15_000);const messages = [{ role: 'system', content: buildSystemPrompt({ agentName: row.name || 'Agent', persona: row.persona_prompt, network }) }, ...history];const proposals = [];const citations = [];let finalText = '';+ // Read-only tools are pure within a turn — the wallet/intel/quote a round sees+ // won't change between the model's rounds. Memoize by (name, args) so when the+ // model re-issues an identical read (a common small-model tic that otherwise+ // burns a whole tool-loop round and paints a duplicate "Portfolio: …" line in+ // the UI) we serve it from cache: no second RPC, no duplicate `tool` event, and+ // the loop can tell the round made no new progress and cut to a final answer.+ const readCache = new Map();+// One read-only tool execution → returns a compact result for the model + a UI summary.async function execReadTool(name, args) {if (name === 'get_portfolio') {@@ -545,19 +558,43 @@ export default async function handler(req, res, id) {content: roundOut.content || null,tool_calls: roundOut.toolCalls.map((tc) => ({ id: tc.id, type: 'function', function: { name: tc.name, arguments: tc.args || '{}' } })),});+ // A round is only "progress" if at least one call surfaced something new —+ // a fresh read, or a proposal. If every call this round is a repeat of a+ // read the model already ran this turn, it's spinning: feed the cached+ // results back (OpenAI requires a tool result per tool_call) but break out+ // afterward so the finalize step turns what we have into a real answer+ // instead of stalling the owner behind more identical "Analyzing…" rounds.+ let progressed = false;for (const tc of roundOut.toolCalls) {let args = {};try { args = tc.args ? JSON.parse(tc.args) : {}; } catch { args = {}; }const isPropose = tc.name.startsWith('propose_');let outcome;+ let cached = false;try {- outcome = isPropose ? await execProposeTool(tc.name, args) : await execReadTool(tc.name, args);+ if (isPropose) {+ outcome = await execProposeTool(tc.name, args);+ progressed = true;+ } else {+ const key = `${tc.name}:${JSON.stringify(args)}`;+ if (readCache.has(key)) {+ outcome = readCache.get(key);+ cached = true;+ } else {+ outcome = await execReadTool(tc.name, args);+ readCache.set(key, outcome);+ progressed = true;+ }+ }} catch (e) {outcome = { result: { error: e?.message || 'tool_failed' }, summary: `Tool ${tc.name} failed: ${e?.message || 'error'}` };+ progressed = true; // a genuine failure is new information, not a spin}- if (!isPropose) send('tool', { name: tc.name, summary: outcome.summary });+ // Surface read activity once per distinct read — never re-paint a cached repeat.+ if (!isPropose && !cached) send('tool', { name: tc.name, summary: outcome.summary });messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(outcome.result).slice(0, 6000) });}+ if (!progressed) break; // model looped on data it already has — go answer.}// If the loop hit its round cap mid-tool without a natural answer, ask for a@@ -580,6 +617,7 @@ export default async function handler(req, res, id) {} catch (e) {send('error', { code: e?.code || 'copilot_error', message: e?.message || 'The copilot hit an error. Try again.' });} finally {+ clearInterval(heartbeat);if (active) res.end();}}diff --git a/data/changelog.json b/data/changelog.jsonindex 54b67871c..5fb8927b8 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-05",+ "title": "Trading Copilot no longer freezes after reading your wallet",+ "summary": "When you asked the Copilot about your portfolio, it sometimes read your wallet, then read it again, and got stuck on \"Analyzing…\" with the typing dots spinning forever — you'd see the same \"Portfolio: … 6 tokens\" line twice and never get an answer. The Copilot now remembers what it just looked up within a single reply, so a repeated lookup is instant instead of a wasted round, and the moment it starts going in circles it stops and answers with what it already knows. As a backstop, the chat now detects a genuinely dead connection and offers a Retry instead of hanging — so it can never leave you staring at a frozen indicator again.",+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-07-05","title": "Tour Builder — design a walking 3D store guide with zero code",diff --git a/public/changelog.json b/public/changelog.jsonindex 315a3183f..234d4e388 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-05T11:05:22.729Z",+ "generated_at": "2026-07-05T11:42:03.833Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -177,6 +177,17 @@"docs"]},+ {+ "date": "2026-07-05",+ "type": "update",+ "title": "Trading Copilot no longer freezes after reading your wallet",+ "summary": "When you asked the Copilot about your portfolio, it sometimes read your wallet, then read it again, and got stuck on \"Analyzing…\" with the typing dots spinning forever — you'd see the same \"Portfolio: … 6 tokens\" line twice and never get an answer. The Copilot now remembers what it just looked up within a single reply, so a repeated lookup is instant instead of a wasted round, and the moment it starts going in circles it stops and answers with what it already knows. As a backstop, the chat now detects a genuinely dead connection and offers a Retry instead of hanging — so it can never leave you staring at a frozen indicator again.",+ "link": null,+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-07-05","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex ca1802dfa..2256f58e9 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -134,6 +134,14 @@<category>feature</category><description>Building a guided 3D tour for your store used to mean hand-writing a JSON file. Now there's a live, Wix-style playground at /tour-builder: a demo storefront on one side, a point-and-click editor on the other. Pick who guides the tour, click the sections you want it to walk to, type what it should say, and hit Preview to watch the real tour run exactly as your visitors will see it. When it looks right, one click gives you the curriculum file plus the exact snippets to paste into Shopify. The Shopify tutorial is rebuilt around it — a ten-minute no-code path — with a new advanced guide for multi-page tours, exact section targeting, real spoken voices, custom avatars, deep links, and the JavaScript API.</description></item>+ <item>+ <title>Trading Copilot no longer freezes after reading your wallet</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-05:Trading Copilot no longer freezes after reading your wallet</guid>+ <pubDate>Sun, 05 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>When you asked the Copilot about your portfolio, it sometimes read your wallet, then read it again, and got stuck on "Analyzing…" with the typing dots spinning forever — you'd see the same "Portfolio: … 6 tokens" line twice and never get an answer. The Copilot now remembers what it just looked up within a single reply, so a repeated lookup is instant instead of a wasted round, and the moment it starts going in circles it stops and answers with what it already knows. As a backstop, the chat now detects a genuinely dead connection and offers a Retry instead of hanging — so it can never leave you staring at a frozen indicator again.</description>+ </item><item><title>Wallet chips on avatar and agent cards no longer overflow their card</title><link>https://three.ws/dashboard/avatars</link>diff --git a/public/features.json b/public/features.jsonindex 08ea0cbc8..383ed534f 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-05T11:05:22.717Z",+ "generated_at": "2026-07-05T11:42:03.821Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/audit-service-wallets.mjs b/scripts/audit-service-wallets.mjsnew file mode 100644index 000000000..ad2e84778--- /dev/null+++ b/scripts/audit-service-wallets.mjs@@ -0,0 +1,142 @@+#!/usr/bin/env node+// Audit every platform service wallet in ONE pass: derive each wallet's pubkey+// from its secret env var, read its on-chain SOL/USDC, check it against its+// SOL floor, and cross-check the x402 advertised fee-payer/payTo against what+// the secrets actually resolve to. Surfaces the class of misconfig that silently+// 502s paid endpoints (advertised fee-payer pubkey != the secret we co-sign with)+// and the "below SOL floor → engine paused" halts.+//+// USAGE (needs the deploy secrets in the environment):+// vercel env pull .env.audit.local # pull Production env locally+// node --env-file=.env.audit.local scripts/audit-service-wallets.mjs+// Or run in any environment that already has the wallet secrets exported.+//+// Read-only: derives pubkeys and queries RPC. Never logs secret material — only+// derived public keys, balances, and pass/fail verdicts.++import bs58 from 'bs58';+import { Keypair, PublicKey } from '@solana/web3.js';++const RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const ORIGIN = process.env.AUDIT_ORIGIN || 'https://three.ws';++// Mirrors api/_lib/solana-signers.js SIGNER_SPECS (name, secret env, floor). Kept+// inline so the audit runs standalone without importing the app's module graph.+const SIGNERS = [+ { name: 'economy-master', env: 'ECONOMY_MASTER_SECRET_BASE58', minSol: 1.0, purpose: 'tops up every other service wallet' },+ { name: 'pump-cron-relayer', env: 'PUMP_CRON_RELAYER_SECRET_KEY_B64', minSol: 0.1, purpose: 'buyback + distribute-payments gas' },+ { name: 'pump-x402-launcher', env: 'PUMP_X402_LAUNCHER_SECRET_KEY_B64', minSol: 0.1, purpose: 'fronts pump.fun x402 deploy cost' },+ { name: 'coin-launcher-master', env: 'LAUNCHER_MASTER_SECRET_KEY_B64', fb: 'PUMP_X402_LAUNCHER_SECRET_KEY_B64', minSol: 1.0, purpose: 'coin launch authority' },+ { name: 'sns-parent-owner', env: 'THREEWS_SOL_PARENT_SECRET_BASE58', minSol: 0.05, purpose: 'owns threews.sol; mints subdomains' },+ { name: 'coin-treasury', env: 'COIN_TREASURY_SECRET_KEY_B64', minSol: 0.05, purpose: 'lottery/reflection distributions' },+ { name: 'three-buyback', env: 'THREE_BUYBACK_SECRET_KEY_B64', minSol: 0.05, purpose: 'holds USDC revenue; buys $THREE' },+ { name: 'club-treasury', env: 'CLUB_SOLANA_TREASURY_SECRET_KEY_B64', minSol: 0.05, purpose: 'club tip-sweep payouts' },+ { name: 'platform-treasury', env: 'PLATFORM_TREASURY_KEYPAIR', fb: 'TREASURY_KEYPAIR', minSol: 0.05, purpose: 'SPL withdrawal gas' },+ { name: 'marketplace-payer', env: 'MARKETPLACE_PAYER_KEYPAIR', fb: 'PLATFORM_TREASURY_KEYPAIR', minSol: 0.05, purpose: 'gasless checkout fee-payer' },+ { name: 'a2a-payer', env: 'A2A_PAYER_SOLANA_SECRET', fb: 'A2A_PAYER_SOLANA_PRIVATE_KEY', minSol: 0.02, purpose: 'agent-to-agent settlement co-signer' },+ { name: 'x402-ring-sponsor', env: 'X402_FEE_PAYER_SECRET_BASE58', minSol: 0.03, purpose: 'x402 self-facilitator fee-payer (co-signs settles)' },+ { name: 'x402-ring-payer', env: 'X402_SEED_SOLANA_SECRET_BASE58', fb: 'X402_AGENT_SOLANA_SECRET_BASE58', minSol: 0.03, purpose: 'x402 ring payer (self-pay)' },+ { name: 'circulation-treasury', env: 'CIRCULATION_TREASURY_SECRET', minSol: 0.2, purpose: 'seeds the operated agent pool' },+ { name: 'collection-authority', env: 'SOLANA_AGENT_COLLECTION_AUTHORITY_KEY', minSol: 0.02, purpose: 'agent NFT collection authority' },+];++// Address-only vars (public keys advertised in 402 challenges — no secret here).+const ADVERTISED = [+ { name: 'x402 payTo (Solana)', env: 'X402_PAY_TO_SOLANA', fb: 'X402_PAY_TO' },+ { name: 'x402 fee-payer (Solana)', env: 'X402_FEE_PAYER_SOLANA' },+ { name: 'credits deposit wallet', env: 'CREDITS_DEPOSIT_WALLET_SOLANA' },+ { name: 'platform fee wallet', env: 'PUMP_PLATFORM_FEE_WALLET' },+ { name: 'charity audit address', env: 'X402_CHARITY_AUDIT_ADDRESS_SOLANA' },+];++function decodeSecret(raw) {+ if (!raw) return null;+ let s = String(raw).trim().replace(/^["']|["']$/g, '');+ // JSON array of ints+ if (s.startsWith('[')) {+ try { const a = JSON.parse(s); if (Array.isArray(a)) return Keypair.fromSecretKey(Uint8Array.from(a)); } catch {}+ }+ // base58+ try { const b = bs58.decode(s); if (b.length === 64) return Keypair.fromSecretKey(b); } catch {}+ // base64+ try { const b = Buffer.from(s, 'base64'); if (b.length === 64) return Keypair.fromSecretKey(new Uint8Array(b)); } catch {}+ return null;+}++async function rpc(method, params) {+ const r = await fetch(RPC, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) });+ return (await r.json()).result;+}+async function onchain(addr) {+ const bal = await rpc('getBalance', [addr]).catch(() => null);+ const sol = (bal?.value || 0) / 1e9;+ let usdc = 0;+ try { const u = await rpc('getTokenAccountsByOwner', [addr, { mint: USDC }, { encoding: 'jsonParsed' }]); usdc = Number(u?.value?.[0]?.account?.data?.parsed?.info?.tokenAmount?.uiAmountString || 0); } catch {}+ return { sol, usdc };+}+function pub(spec) {+ const raw = process.env[spec.env] || (spec.fb ? process.env[spec.fb] : null);+ if (!raw) return { configured: false };+ const kp = decodeSecret(raw);+ if (!kp) return { configured: true, bad: true };+ return { configured: true, pubkey: kp.publicKey.toBase58() };+}+function addrOf(spec) {+ const raw = process.env[spec.env] || (spec.fb ? process.env[spec.fb] : null);+ if (!raw) return null;+ const v = String(raw).trim().replace(/^["']|["']$/g, '');+ try { new PublicKey(v); return v; } catch { return null; }+}++const flags = [];+console.log(`\nservice-wallet audit · RPC ${RPC} · origin ${ORIGIN}\n${'='.repeat(72)}`);++console.log('\nSECRET-BACKED SIGNERS (derived pubkey ← secret env):');+const sponsorDerived = {};+for (const s of SIGNERS) {+ const p = pub(s);+ if (!p.configured) { console.log(` ⚪ ${s.name.padEnd(22)} UNCONFIGURED (${s.env} not set)`); continue; }+ if (p.bad) { console.log(` ❌ ${s.name.padEnd(22)} SECRET PRESENT BUT UNDECODABLE (${s.env}) — malformed key`); flags.push(`${s.name}: secret malformed`); continue; }+ const oc = await onchain(p.pubkey);+ const low = oc.sol < s.minSol;+ console.log(` ${low ? '⚠️ ' : '✅'} ${s.name.padEnd(22)} ${p.pubkey} SOL=${oc.sol.toFixed(4)}${low ? ` (BELOW floor ${s.minSol})` : ''} USDC=${oc.usdc}`);+ if (low) flags.push(`${s.name}: SOL ${oc.sol.toFixed(4)} below floor ${s.minSol}`);+ if (s.name === 'x402-ring-sponsor') sponsorDerived.pubkey = p.pubkey;+}++console.log('\nADVERTISED ADDRESSES (public keys, no secret):');+const advVals = {};+for (const a of ADVERTISED) {+ const addr = addrOf(a);+ if (!addr) { console.log(` ⚪ ${a.name.padEnd(24)} not set`); continue; }+ advVals[a.name] = addr;+ const oc = await onchain(addr);+ console.log(` ✅ ${a.name.padEnd(24)} ${addr} SOL=${oc.sol.toFixed(4)} USDC=${oc.usdc}`);+}++// Live cross-check: what production actually advertises right now.+console.log('\nLIVE CONSISTENCY CHECKS:');+try {+ const st = await (await fetch(`${ORIGIN}/api/x402-status`)).json();+ const sol = (st.accepts || []).find((x) => String(x.network).startsWith('solana'));+ const advFee = sol?.extra?.feePayer;+ const advPay = sol?.payTo;+ console.log(` live advertised fee-payer: ${advFee}`);+ console.log(` live advertised payTo: ${advPay}`);+ if (sponsorDerived.pubkey) {+ if (advFee === sponsorDerived.pubkey) console.log(` ✅ advertised fee-payer MATCHES the sponsor secret we co-sign with`);+ else { console.log(` ❌ MISMATCH: advertised fee-payer ${advFee} != sponsor secret pubkey ${sponsorDerived.pubkey} → every sponsor-mode settle 502s`); flags.push('fee-payer advertised != sponsor secret → settles 502'); }+ } else {+ console.log(` ⚠️ cannot compare — X402_FEE_PAYER_SECRET_BASE58 not resolvable in this env`);+ }+ // PayAI shared account guard+ if (advFee === '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4') {+ console.log(` ❌ advertised fee-payer is PayAI's PUBLIC shared account — self-hosted facilitator cannot co-sign for it`);+ flags.push("fee-payer is PayAI's public account (2wKupLR9…) — override X402_FEE_PAYER_SOLANA");+ }+} catch (e) { console.log(` (could not fetch ${ORIGIN}/api/x402-status: ${e.message})`); }++console.log(`\n${'='.repeat(72)}`);+if (flags.length) { console.log(`RESULT: ${flags.length} issue(s):`); flags.forEach((f) => console.log(` ✗ ${f}`)); process.exitCode = 1; }+else console.log('RESULT: all checked wallets configured, funded, and consistent.');diff --git a/src/agent-copilot.js b/src/agent-copilot.jsindex a1aaf5b0b..c7d6ae343 100644--- a/src/agent-copilot.js+++ b/src/agent-copilot.js@@ -168,6 +168,8 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isOlet destroyed = false;let detachNet = null;let streaming = false;+ let currentTurn = null; // AbortController for the in-flight SSE turn, if any+ const STREAM_STALL_MS = 45_000; // no SSE bytes for this long ⇒ dead stream (server heartbeats every 15s)let recognition = null;let listening = false;let voiceOut = false;@@ -449,22 +451,32 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO.filter((m) => m.content),};+ const ctrl = new AbortController();+ currentTurn = ctrl;try {const resp = await fetch(`/api/agents/${encodeURIComponent(agentId)}/copilot`, {method: 'POST', credentials: 'include',headers: { 'Content-Type': 'application/json', accept: 'text/event-stream' },body: JSON.stringify(payload),+ signal: ctrl.signal,});if (!resp.ok || !resp.body) {const j = await resp.json().catch(() => ({}));throw new Error(j?.error_description || j?.error?.message || j?.message || `Copilot unavailable (${resp.status})`);}- await consumeSse(resp.body, agentMsg);+ await consumeSse(resp.body, agentMsg, ctrl);} catch (e) {agentMsg.streaming = false;if (!agentMsg.content) agentMsg.error = true;- showError(e?.message || 'The copilot hit an error.', content);+ if (!destroyed) {+ // A watchdog/destroy abort surfaces as an AbortError with no useful+ // message — translate it into a recoverable prompt so the owner is+ // never left staring at a frozen typing indicator.+ const stalled = ctrl.signal.aborted;+ showError(stalled ? 'The copilot stopped responding. Try again.' : (e?.message || 'The copilot hit an error.'), content);+ }} finally {+ if (currentTurn === ctrl) currentTurn = null;streaming = false;agentMsg.streaming = false;setStatus('');@@ -473,29 +485,40 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO}}- async function consumeSse(stream, agentMsg) {+ async function consumeSse(stream, agentMsg, ctrl) {const reader = stream.getReader();const decoder = new TextDecoder();let buf = '';- for (;;) {- const { value, done } = await reader.read();- if (done) break;- if (destroyed) { reader.cancel().catch(() => {}); break; }- buf += decoder.decode(value, { stream: true });- let sep;- while ((sep = buf.indexOf('\n\n')) >= 0) {- const block = buf.slice(0, sep);- buf = buf.slice(sep + 2);- let event = 'message', data = '';- for (const line of block.split('\n')) {- if (line.startsWith('event:')) event = line.slice(6).trim();- else if (line.startsWith('data:')) data += line.slice(5).trim();+ // Stall watchdog: if the stream goes silent past the heartbeat interval, the+ // connection is dead — abort so the turn fails cleanly into a Retry instead+ // of hanging on the typing indicator forever.+ let stall = null;+ const arm = () => { if (stall) clearTimeout(stall); stall = setTimeout(() => ctrl.abort(), STREAM_STALL_MS); };+ try {+ arm();+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ if (destroyed) { reader.cancel().catch(() => {}); break; }+ arm(); // fresh bytes (data or heartbeat) ⇒ stream is alive+ buf += decoder.decode(value, { stream: true });+ let sep;+ while ((sep = buf.indexOf('\n\n')) >= 0) {+ const block = buf.slice(0, sep);+ buf = buf.slice(sep + 2);+ let event = 'message', data = '';+ for (const line of block.split('\n')) {+ if (line.startsWith('event:')) event = line.slice(6).trim();+ else if (line.startsWith('data:')) data += line.slice(5).trim();+ }+ if (!data) continue;+ let payload;+ try { payload = JSON.parse(data); } catch { continue; }+ handleSseEvent(event, payload, agentMsg);}- if (!data) continue;- let payload;- try { payload = JSON.parse(data); } catch { continue; }- handleSseEvent(event, payload, agentMsg);}+ } finally {+ if (stall) clearTimeout(stall);}}@@ -662,6 +685,7 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isOonHide() { stopListening(); stopSpeaking(); },destroy() {destroyed = true;+ currentTurn?.abort();stopListening();stopSpeaking();messages.forEach((m) => (m.proposals || []).forEach((p) => p._safetyPanel?.destroy?.()));diff --git a/src/agent-screen-runcmd.js b/src/agent-screen-runcmd.jsindex afb5b7c07..832d782a5 100644--- a/src/agent-screen-runcmd.js+++ b/src/agent-screen-runcmd.js@@ -35,17 +35,24 @@ const BB_PLACEHOLDERS = [['BROWSERBASE_PROJECT_ID', '<your-bb-project>'],];+// Anthropic key drives Stagehand's page.act()/page.extract() — the difference+// between an agent that only loads pages and one that types, clicks, and reads.+// User-supplied (their own key), so it's an explicit placeholder on every runtime.+const ANTHROPIC_PLACEHOLDER = ['ANTHROPIC_API_KEY', '<your-anthropic-key>'];+function normalizeRuntime(runtime) {return RUNTIMES.includes(runtime) ? runtime : 'local';}// The ordered [key, value] env pairs a runtime needs. AGENT_ID / AGENT_JWT /-// PUSH_URL are required for every runtime; Browserbase adds its two creds.+// PUSH_URL / ANTHROPIC_API_KEY are required for every runtime; Browserbase adds+// its two creds.export function runtimeEnv({ runtime = 'local', agentId = '', agentJwt = '', origin = 'https://three.ws' } = {}) {const env = [['AGENT_ID', agentId],['AGENT_JWT', agentJwt],['PUSH_URL', `${origin}${PUSH_PATH}`],+ ANTHROPIC_PLACEHOLDER,];if (normalizeRuntime(runtime) === 'bb') env.push(...BB_PLACEHOLDERS);return env;diff --git a/tests/agent-screen-runcmd.test.js b/tests/agent-screen-runcmd.test.jsindex 89c17f00e..a60d5b431 100644--- a/tests/agent-screen-runcmd.test.js+++ b/tests/agent-screen-runcmd.test.js@@ -27,11 +27,13 @@ const REAL = {};describe('runtimeEnv', () => {- it('always includes AGENT_ID, AGENT_JWT and the origin-joined PUSH_URL', () => {+ it('always includes AGENT_ID, AGENT_JWT, the origin-joined PUSH_URL and the Anthropic key', () => {const env = Object.fromEntries(runtimeEnv({ runtime: 'local', ...REAL }));expect(env.AGENT_ID).toBe(REAL.agentId);expect(env.AGENT_JWT).toBe(REAL.agentJwt);expect(env.PUSH_URL).toBe(`${REAL.origin}${PUSH_PATH}`);+ // act/extract needs a model key on every runtime, not just bb+ expect(env.ANTHROPIC_API_KEY).toBe('<your-anthropic-key>');});it('adds Browserbase creds only for the bb runtime', () => {@@ -51,7 +53,7 @@ describe('buildRunCommand', () => {it('local runtime inlines the real agentId, key and push url before npm start', () => {const cmd = buildRunCommand({ runtime: 'local', ...REAL });expect(cmd).toBe(- `AGENT_ID=${REAL.agentId} AGENT_JWT=${REAL.agentJwt} PUSH_URL=${REAL.origin}${PUSH_PATH} npm start`,+ `AGENT_ID=${REAL.agentId} AGENT_JWT=${REAL.agentJwt} PUSH_URL=${REAL.origin}${PUSH_PATH} ANTHROPIC_API_KEY=<your-anthropic-key> npm start`,);});@@ -84,9 +86,12 @@ describe('buildRunCommand', () => {}});- it('local and docker carry no angle-bracket placeholders at all', () => {+ it('local and docker carry no angle-bracket placeholder except the Anthropic key', () => {for (const runtime of ['local', 'docker']) {- expect(buildRunCommand({ runtime, ...REAL })).not.toMatch(/<[^>]+>/);+ const cmd = buildRunCommand({ runtime, ...REAL });+ // ANTHROPIC_API_KEY is a genuine user-supplied value on every runtime;+ // once it's removed there must be no other placeholder left to guess.+ expect(cmd.replace('<your-anthropic-key>', '')).not.toMatch(/<[^>]+>/);}});});diff --git a/workers/agent-screen-worker/README.md b/workers/agent-screen-worker/README.mdindex 3fbdfa0d0..6db42181f 100644--- a/workers/agent-screen-worker/README.md+++ b/workers/agent-screen-worker/README.md@@ -41,11 +41,18 @@ No Docker needed. Run as a plain Node process or in any VM:```bashexport BROWSERBASE_API_KEY=...export BROWSERBASE_PROJECT_ID=...+export ANTHROPIC_API_KEY=... # drives page.act()/page.extract() — see belowexport AGENT_ID=...export AGENT_JWT=...npm start```+> **`ANTHROPIC_API_KEY` is what makes the agent *do* things.** Stagehand's+> `page.act()` (type, click, submit) and `page.extract()` (read the page) are+> LLM-driven. Without a key the agent still opens the browser, navigates, and+> screenshots — but every interactive step fails. Set it to see the agent+> actually work a task, not just load pages.+## Environment variables| Variable | Required | Default | Description |@@ -55,6 +62,8 @@ npm start| `PUSH_URL` | no | `https://three.ws/api/agent-screen-push` | Push endpoint override || `BROWSERBASE_API_KEY` | no | — | Browserbase API key (cloud mode) || `BROWSERBASE_PROJECT_ID` | no | — | Required when `BROWSERBASE_API_KEY` is set |+| `ANTHROPIC_API_KEY` | recommended | — | Drives `page.act()`/`page.extract()`. Without it the agent navigates + screenshots but can't type, click, or read pages. |+| `STAGEHAND_MODEL` | no | `anthropic/claude-opus-4-8` | Model for act/extract. Keep the `anthropic/` prefix (routes to Stagehand's Anthropic client). Use `anthropic/claude-haiku-4-5` for cheaper, faster casting at high volume. || `CYCLE_MS` | no | `30000` | Task loop cycle time in ms || `SCREENSHOT_INTERVAL_MS` | no | `5000` | Minimum ms between full screenshots (text-only pushes fill the gap) |diff --git a/workers/agent-screen-worker/config.js b/workers/agent-screen-worker/config.jsindex 70a70b104..2435f9405 100644--- a/workers/agent-screen-worker/config.js+++ b/workers/agent-screen-worker/config.js@@ -11,6 +11,23 @@ export function loadConfig() {throw new Error('BROWSERBASE_PROJECT_ID is required when BROWSERBASE_API_KEY is set');}+ // Stagehand's page.act()/page.extract() are LLM-driven — without a model + key+ // they throw on the first real interaction. The provider-prefixed form+ // ("anthropic/<model>") passes the model string straight to Stagehand's+ // Anthropic client, so it isn't gated by Stagehand's built-in model allowlist+ // and survives model releases. Navigation-only casters don't need it, so this+ // is a loud warning rather than a hard requirement.+ const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY || '';+ const MODEL_NAME = process.env.STAGEHAND_MODEL || 'anthropic/claude-opus-4-8';++ if (!ANTHROPIC_API_KEY) {+ console.warn(+ '[config] ANTHROPIC_API_KEY is not set — the agent can navigate and screenshot, ' ++ 'but page.act()/page.extract() (typing, clicking, reading) will fail. ' ++ 'Set ANTHROPIC_API_KEY to enable full task execution.',+ );+ }+return {AGENT_ID: process.env.AGENT_ID,AGENT_JWT: process.env.AGENT_JWT,@@ -21,6 +38,8 @@ export function loadConfig() {HOME_URL: process.env.HOME_URL || 'https://three.ws',BROWSERBASE_API_KEY,BROWSERBASE_PROJECT_ID,+ ANTHROPIC_API_KEY,+ MODEL_NAME,CYCLE_MS: Number(process.env.CYCLE_MS || 30_000),// Whether to capture a screenshot on every pushFrame call (can be throttled)SCREENSHOT_INTERVAL_MS: Number(process.env.SCREENSHOT_INTERVAL_MS || 5_000),diff --git a/workers/agent-screen-worker/index.js b/workers/agent-screen-worker/index.jsindex bc715857a..3a4a53902 100644--- a/workers/agent-screen-worker/index.js+++ b/workers/agent-screen-worker/index.js@@ -28,9 +28,19 @@ async function main() {env,apiKey: cfg.BROWSERBASE_API_KEY || undefined,projectId: cfg.BROWSERBASE_PROJECT_ID || undefined,+ // LLM that drives page.act()/page.extract(). The provider-prefixed model+ // name routes straight to Stagehand's Anthropic client (not gated by its+ // built-in allowlist); the key is passed explicitly so the worker never+ // depends on process-wide env resolution inside Stagehand.+ modelName: cfg.MODEL_NAME,+ modelClientOptions: cfg.ANTHROPIC_API_KEY+ ? { apiKey: cfg.ANTHROPIC_API_KEY }+ : undefined,verbose: 1,});+ console.log(`[agent-screen-worker] act/extract model: ${cfg.MODEL_NAME}`);+await stagehand.init();const { page, context } = stagehand;