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: add tests and improvements for agent memory, skills, and communication
nirholas1019a71c90a7
diff --git a/chat/src/AgentPicker.svelte b/chat/src/AgentPicker.svelteindex f57afd6c6..e5a5e0dac 100644--- a/chat/src/AgentPicker.svelte+++ b/chat/src/AgentPicker.svelte@@ -1,6 +1,6 @@<script>import { createEventDispatcher } from 'svelte';- import { localAgentId } from './stores.js';+ import { localAgentId, activeAgent } from './stores.js';const dispatch = createEventDispatcher();@@ -27,13 +27,28 @@debounceTimer = setTimeout(() => search(query), 300);}- function pick(agent) {- localAgentId.set(agent.id);- dispatch('pick', agent);+ async function pick(agent) {+ loading = true;+ try {+ const res = await fetch(`/api/marketplace/agents/${agent.id}`);+ if (res.ok) {+ const json = await res.json();+ const detail = json.data?.agent ?? agent;+ localAgentId.set(detail.id);+ activeAgent.set(detail);+ dispatch('pick', detail);+ }+ } catch {+ localAgentId.set(agent.id);+ activeAgent.set(agent);+ dispatch('pick', agent);+ }+ loading = false;}function clear() {localAgentId.set('');+ activeAgent.set(null);dispatch('pick', null);}diff --git a/chat/src/App.svelte b/chat/src/App.svelteindex e0c489bdd..82e5c5f3a 100644--- a/chat/src/App.svelte+++ b/chat/src/App.svelte@@ -22,7 +22,7 @@} from './providers.js';import ModelSelector from './ModelSelector.svelte';import CompanyLogo from './CompanyLogo.svelte';- import { controller, remoteServer, config, params, toolSchema, syncServer, brandConfig, ttsEnabled, localAgentId, talkingHeadEnabled, route, mode, websiteCategory } from './stores.js';+ import { controller, remoteServer, config, params, toolSchema, syncServer, brandConfig, ttsEnabled, localAgentId, activeAgent, talkingHeadEnabled, route, mode, websiteCategory } from './stores.js';import AuthPage from './manus/pages/AuthPage.svelte';import Pricing from './manus/pages/Pricing.svelte';import MarketingPage from './manus/pages/MarketingPage.svelte';@@ -60,7 +60,7 @@feUsers,feX,} from './feather.js';- import { defaultToolSchema, agentToolSchema, pumpToolSchema } from './tools.js';+ import { defaultToolSchema, agentToolSchema, pumpToolSchema, curatedToolPacks } from './tools.js';import { debounce, readFileAsDataURL } from './util.js';import { flash } from './actions';import Message from './Message.svelte';@@ -277,11 +277,15 @@for (const convo of deletedConversations) {delete convosMap[convo.id];}- // TODO: Delete messages.- // for (const message of deletedMessages) {- // const conversationId = con- // convosMap- // }+ for (const deletedMsg of deletedMessages) {+ for (const convoId of Object.keys(convosMap)) {+ const idx = convosMap[convoId].messages.findIndex((m) => m.id === deletedMsg.id);+ if (idx !== -1) {+ convosMap[convoId].messages.splice(idx, 1);+ break;+ }+ }+ }convos = convosMap;await syncPush({@@ -739,20 +743,11 @@handleAbort();};- // TODO: Consensus- // if (convo.models.length === 1) {- complete(convo, onupdate, onabort);- // } else {- // completeConsensus(- // convo,- // (chunk) => {- // convo.messages[i].content += chunk.choices[0].delta.content;- // saveMessage(convo.messages[i]);- // handleAbort();- // },- // () => {}- // );- // }+ if (convo.models.length > 1) {+ completeConsensus(convo, onupdate, onabort);+ } else {+ complete(convo, onupdate, onabort);+ }}function startThinkingTimer(messageIndex) {@@ -831,6 +826,7 @@convo = convoData;saveConversation(convo);+ if ($activeAgent) applyAgentToConvo($activeAgent);historyOpen = false;if (innerWidth > 880) {@@ -838,6 +834,29 @@}}+ function applyAgentToConvo(agent) {+ if (!db) return;+ if (agent.system_prompt && convo.messages.length === 0) {+ const sysMsg = { id: uuidv4(), role: 'system', content: agent.system_prompt };+ convo.messages = [sysMsg];+ saveMessage(sysMsg);+ }+ const nonSystem = convo.messages.filter(m => m.role !== 'system');+ if (agent.greeting && nonSystem.length === 0) {+ const greetMsg = { id: uuidv4(), role: 'assistant', content: agent.greeting, generated: true };+ convo.messages = [...convo.messages, greetMsg];+ saveMessage(greetMsg);+ }+ saveConversation(convo);+ }++ function clearAgentFromConvo() {+ convo.messages = convo.messages.filter(m => m.role !== 'system' && !m.generated);+ saveConversation(convo);+ }++ $: if ($activeAgent) applyAgentToConvo($activeAgent);+// Split history at this point:function saveVersion(message, i) {if (!convo.versions) {@@ -989,6 +1008,8 @@}}+ let installToastMsg = '';+let choiceHandler;async function makeChoice() {return new Promise((resolve) => {@@ -1100,6 +1121,23 @@}}+ const urlParams = new URLSearchParams(window.location.search);+ const installId = urlParams.get('install');+ if (installId) {+ const pack = curatedToolPacks.find(p => p.id === installId);+ if (pack) {+ const alreadyInstalled = $toolSchema.some(g => g.name === pack.name);+ if (!alreadyInstalled) {+ $toolSchema = [...$toolSchema, { name: pack.name, schema: pack.schema }];+ installToastMsg = `Tool pack '${pack.name}' installed.`;+ setTimeout(() => { installToastMsg = ''; }, 3000);+ }+ }+ const url = new URL(window.location.href);+ url.searchParams.delete('install');+ window.history.replaceState({}, '', url.toString());+ }+initializePWAStyles();try {@@ -1655,11 +1693,17 @@</Modal>{/if}+{#if installToastMsg}+ <div transition:fade={{ duration: 200 }} class="fixed bottom-16 left-1/2 z-[200] -translate-x-1/2 rounded-lg border border-green-200 bg-green-50 px-4 py-2 text-sm text-green-800 shadow-md">+ {installToastMsg}+ </div>+{/if}+{#if true}<div class="fixed bottom-4 right-4 z-50 flex flex-col items-end gap-2">{#if agentPickerOpen}<div class="mb-1 w-72 rounded-xl border border-gray-200 bg-white p-3 shadow-xl">- <AgentPicker on:pick={() => (agentPickerOpen = false)} />+ <AgentPicker on:pick={(e) => { agentPickerOpen = false; if (!e.detail) clearAgentFromConvo(); }} /></div>{/if}diff --git a/chat/src/KnobsSidebar.svelte b/chat/src/KnobsSidebar.svelteindex 268f536a2..9f9207a58 100644--- a/chat/src/KnobsSidebar.svelte+++ b/chat/src/KnobsSidebar.svelte@@ -42,7 +42,7 @@<label class="mb-4 flex flex-col text-[10px] uppercase tracking-wide"><div class="mb-2 ml-[3px] flex items-baseline">- <span>Messages context limit</span>+ <span>Message history limit (0 = unlimited)</span></div><inputtype="number"@@ -52,34 +52,36 @@/></label>- <!-- FIXME: -->- <!-- {#if convo.local}+ <label class="mb-4 flex flex-col text-[10px] uppercase tracking-wide">+ <div class="mb-2 ml-[3px] flex items-baseline">+ <span>Reasoning Effort</span>+ <span class="ml-auto">{$params.reasoningEffort['low-medium-high']}</span>+ </div><select- class="{autodetectedFormat- ? 'border-green-300/80 bg-green-50/75'- : 'border-red-300 bg-red-50/75'} rounded-lg text-sm"- value={convo.tmpl}- on:change={(event) => {- convo.tmpl = event.target.value;- }}+ bind:value={$params.reasoningEffort['low-medium-high']}+ class="rounded-lg border border-slate-300 px-2 py-1.5 text-xs text-slate-800 transition-colors focus:border-slate-400 focus:outline-none">- <option value={null} disabled>Select a prompt format</option>- {#each promptFormats as fmt}- <option value={fmt}>{fmt}</option>- {/each}+ <option value="low">Low</option>+ <option value="medium">Medium</option>+ <option value="high">High</option></select>- {/if} -->+ </label>- <!-- <select- class="w-full rounded-lg border-slate-300 text-sm"- value={conversationTemplate}- on:change={async (event) => {- loadConversationTemplate(event.target.value);- }}- >- <option value={null} disabled>Load from template</option>- {#each Object.keys(conversationTemplates) as name}- <option value={name}>{name}</option>- {/each}- </select> -->+ <label class="mb-4 flex flex-col text-[10px] uppercase tracking-wide">+ <div class="mb-2 ml-[3px] flex items-baseline">+ <span>Thinking Tokens</span>+ <span class="ml-auto">{$params.reasoningEffort['range'] === 0 ? 'off' : $params.reasoningEffort['range']}</span>+ </div>+ <input+ type="range"+ min={0}+ max={64000}+ step={1000}+ bind:value={$params.reasoningEffort['range']}+ class="appearance-none overflow-hidden rounded-full border border-slate-300+ [&::-webkit-slider-runnable-track]:h-2.5 [&::-webkit-slider-runnable-track]:rounded-full [&::-webkit-slider-runnable-track]:bg-slate-100+ [&::-webkit-slider-thumb]:h-2.5 [&::-webkit-slider-thumb]:w-2.5 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full+ [&::-webkit-slider-thumb]:bg-slate-700 [&::-webkit-slider-thumb]:shadow-[-407px_0_0_404px_theme('colors.slate.200')]"+ />+ </label></aside>diff --git a/chat/src/ModelSelector.svelte b/chat/src/ModelSelector.svelteindex a47ecb5d3..fece364f1 100644--- a/chat/src/ModelSelector.svelte+++ b/chat/src/ModelSelector.svelte@@ -75,6 +75,9 @@{#if convo.models[0].modality === 'text->image'}<Icon icon={feImage} class="mt-px h-3 w-3 text-slate-800" />{/if}+ {#if convo.models.length > 1}+ <span class="rounded bg-indigo-100 px-1 py-0.5 text-[10px] font-medium text-indigo-700">Consensus</span>+ {/if}</div><Iconicon={feChevronDown}@@ -123,16 +126,15 @@<Icon icon={feImage} class="mt-px h-3 w-3 text-slate-800" />{/if}- <!-- TODO: Consensus-->- <!-- <Checkbox-->- <!-- checked={convo.models?.find((m) => m.id === model.id)}-->- <!-- on:change={() => {}}-->- <!-- on:click={(event) => {-->- <!-- event.stopPropagation();-->- <!-- dispatch('changeMulti', model);-->- <!-- }}-->- <!-- class="ml-auto"-->- <!-- />-->+ <Checkbox+ checked={!!convo.models?.find((m) => m.id === model.id)}+ on:change={() => {}}+ on:click={(event) => {+ event.stopPropagation();+ dispatch('changeMulti', model);+ }}+ class="ml-auto"+ /></button></li>{:else}diff --git a/chat/src/SettingsModal.svelte b/chat/src/SettingsModal.svelteindex 4bf40357e..9d1c79059 100644--- a/chat/src/SettingsModal.svelte+++ b/chat/src/SettingsModal.svelte@@ -198,18 +198,17 @@Brand</button></li>- <!-- TODO: Consensus-->- <!-- <li>-->- <!-- <button-->- <!-- class="{activeTab === 'consensus'-->- <!-- ? 'bg-gray-100/70'-->- <!-- : ' hover:bg-gray-100/70'} flex w-full items-center gap-x-2.5 rounded-lg px-4 py-2.5 text-left text-[13px] font-medium text-slate-700 transition-colors"-->- <!-- on:click={() => (activeTab = 'consensus')}-->- <!-- >-->- <!-- <Icon icon={feUsers} class="h-3 w-3 text-slate-700" />-->- <!-- Consensus mode-->- <!-- </button>-->- <!-- </li>-->+ <li>+ <button+ class="{activeTab === 'consensus'+ ? 'bg-gray-100/70'+ : ' hover:bg-gray-100/70'} flex w-full items-center gap-x-2.5 rounded-lg px-4 py-2.5 text-left text-[13px] font-medium text-slate-700 transition-colors"+ on:click={() => (activeTab = 'consensus')}+ >+ <Icon icon={feUsers} class="h-3 w-3 text-slate-700" />+ Consensus mode+ </button>+ </li></ul></nav></div>@@ -592,18 +591,16 @@>{brandSaving ? 'Saving…' : 'Save branding'}</button>{/if}</div>- <!-- TODO: Consensus-->- <!--{:else if activeTab === 'consensus'}-->- <!-- <div class="mt-1 flex flex-col">-->- <!-- <span class="mb-3 ml-[3px] flex items-center text-[10px] uppercase tracking-wide">-->- <!-- Consensus summary model-->- <!-- <Tooltip class="ml-2">-->- <!-- Model that summarizes outputs from the different models to gather consensus-->- <!-- </Tooltip>-->- <!-- </span>-->-- <!-- <ModelSelector />-->- <!-- </div>-->+ {:else if activeTab === 'consensus'}+ <div class="mt-1 flex flex-col">+ <span class="mb-3 ml-[3px] flex items-center text-[10px] uppercase tracking-wide">+ Consensus summary model+ <Tooltip class="ml-2">+ Model that summarizes outputs from the different models to gather consensus+ </Tooltip>+ </span>+ <p class="text-[13px] text-slate-600">Select multiple models in the model picker to enable consensus mode. Responses will be summarized by <span class="font-medium">claude-3.5-sonnet</span> via OpenRouter.</p>+ </div>{/if}</div></div>diff --git a/chat/src/ToolDropdown.svelte b/chat/src/ToolDropdown.svelteindex 7f6a5c667..8a652aeb1 100644--- a/chat/src/ToolDropdown.svelte+++ b/chat/src/ToolDropdown.svelte@@ -5,6 +5,7 @@import Checkbox from './Checkbox.svelte';import Icon from './Icon.svelte';import { feChevronDown } from './feather.js';+ import ToolPackModal from './ToolPackModal.svelte';export let open = false;export let convo;@@ -12,6 +13,20 @@let collapsed = {};let innerWidth;+ let query = '';++ $: filteredSchema = query.trim()+ ? $toolSchema+ .map((group) => {+ const q = query.toLowerCase();+ const groupMatch = group.name.toLowerCase().includes(q);+ const tools = groupMatch+ ? group.schema+ : group.schema.filter((t) => t.function.name.toLowerCase().includes(q));+ return tools.length ? { ...group, schema: tools } : null;+ })+ .filter(Boolean)+ : $toolSchema;function setTools(newTools) {convo.tools = convo.tools.concat(newTools);@@ -27,6 +42,8 @@convo.tools = [];saveConversation(convo);}++ let packModalOpen = false;</script><svelte:window@@ -61,16 +78,19 @@Unselect all</button></div>-<!-- <input-->-<!-- type="text"-->-<!-- value=""-->-<!-- placeholder="Search for tools"-->-<!-- class="w-full rounded-lg border border-slate-300 px-3 py-2 text-xs text-slate-800 transition-colors placeholder:text-gray-500 focus:border-slate-400 focus:outline-none"-->-<!-- on:input={() => {}}-->-<!-- />-->+ <input+ type="text"+ bind:value={query}+ placeholder="Search for tools"+ autofocus+ class="w-full rounded-lg border border-slate-300 px-3 py-2 text-[10px] text-slate-800 transition-colors placeholder:text-gray-500 focus:border-slate-400 focus:outline-none"+ /></div><ul class="max-h-[300px] overflow-y-auto pb-1.5 scrollbar-ultraslim">- {#each $toolSchema as group}+ {#if filteredSchema.length === 0 && query}+ <li class="px-4 py-3 text-xs text-gray-500">No tools found</li>+ {/if}+ {#each filteredSchema as group}<div class="relative w-full"><!-- svelte-ignore a11y-label-has-associated-control --><label@@ -131,6 +151,16 @@{/if}{/each}</ul>+ <div class="border-t border-slate-100 px-3 py-2">+ <button+ class="w-full rounded-lg border border-slate-200 py-1.5 text-[11px] text-slate-500 transition-colors hover:bg-gray-50 hover:text-slate-700"+ on:click={() => (packModalOpen = true)}+ >+ Browse tool packs+ </button>+ </div></div></div>{/if}++<ToolPackModal bind:open={packModalOpen} />diff --git a/chat/src/ToolPackModal.svelte b/chat/src/ToolPackModal.sveltenew file mode 100644index 000000000..bcc166d37--- /dev/null+++ b/chat/src/ToolPackModal.svelte@@ -0,0 +1,54 @@+<script>+ import Modal from './Modal.svelte';+ import { toolSchema } from './stores.js';+ import { curatedToolPacks } from './tools.js';++ export let open = false;++ function isInstalled(pack) {+ return $toolSchema.some((g) => g.name === pack.name);+ }++ function install(pack) {+ $toolSchema = [...$toolSchema, { name: pack.name, schema: pack.schema }];+ }++ function remove(pack) {+ $toolSchema = $toolSchema.filter((g) => g.name !== pack.name);+ }+</script>++<Modal bind:open>+ <div class="flex flex-col gap-y-4">+ <h2 class="text-base font-semibold text-slate-800">Tool packs</h2>+ <ul class="flex flex-col gap-y-3">+ {#each curatedToolPacks as pack}+ <li class="flex items-start justify-between gap-x-4 rounded-lg border border-slate-200 px-4 py-3">+ <div class="min-w-0">+ <p class="text-[13px] font-medium text-slate-800">{pack.name}</p>+ <p class="mt-0.5 text-[12px] text-slate-500">{pack.description}</p>+ <p class="mt-1 text-[11px] text-slate-400">+ {pack.schema.length}+ {pack.schema.length === 1 ? 'tool' : 'tools'}+ </p>+ </div>+ {#if isInstalled(pack)}+ <button+ class="shrink-0 rounded-lg border border-slate-200 px-3 py-1.5 text-[12px] text-slate-500 transition-colors hover:border-red-200 hover:bg-red-50 hover:text-red-600"+ on:click={() => remove(pack)}+ >+ Remove+ </button>+ {:else}+ <button+ class="shrink-0 rounded-lg border border-slate-200 bg-slate-50 px-3 py-1.5 text-[12px] font-medium text-slate-700 transition-colors hover:bg-slate-100"+ on:click={() => install(pack)}+ >+ Install+ </button>+ {/if}+ </li>+ {/each}+ </ul>+ </div>+</Modal>diff --git a/chat/src/WalletConnect.svelte b/chat/src/WalletConnect.sveltenew file mode 100644index 000000000..a2ee1c69a--- /dev/null+++ b/chat/src/WalletConnect.svelte@@ -0,0 +1,81 @@+<script>+ import { currentUser, loadCurrentUser } from './stores.js';+ import { signInWithEVM, signInWithSolana, signOut } from './walletAuth.js';++ let loading = null; // 'evm' | 'sol' | null+ let error = '';++ async function connectEVM() {+ error = '';+ loading = 'evm';+ try {+ await signInWithEVM();+ await loadCurrentUser();+ } catch (e) {+ error = e.message || 'EVM sign-in failed.';+ } finally {+ loading = null;+ }+ }++ async function connectSolana() {+ error = '';+ loading = 'sol';+ try {+ await signInWithSolana();+ await loadCurrentUser();+ } catch (e) {+ error = e.message || 'Solana sign-in failed.';+ } finally {+ loading = null;+ }+ }++ async function handleSignOut() {+ await signOut();+ currentUser.set(null);+ }++ function shortAddr(addr) {+ if (!addr) return '';+ return addr.slice(0, 6) + '…' + addr.slice(-4);+ }+</script>++{#if $currentUser}+ <!-- signed-in chip -->+ <span class="flex items-center gap-2 text-sm text-ink">+ <span class="font-medium" title={$currentUser.wallet_address}>+ {$currentUser.wallet_address ? shortAddr($currentUser.wallet_address) : ($currentUser.display_name || 'Account')}+ </span>+ <span class="opacity-30">·</span>+ <button+ class="text-sm text-ink-soft underline hover:text-ink"+ on:click={handleSignOut}+ >Sign out</button>+ </span>+{:else}+ <div class="flex flex-col items-end gap-1">+ <div class="flex items-center gap-2">+ <!-- EVM button -->+ <button+ disabled={loading !== null}+ on:click={connectEVM}+ class="h-9 rounded-full bg-black px-4 text-sm font-medium text-white transition-colors hover:bg-[#333] disabled:opacity-50"+ >+ {loading === 'evm' ? 'Connecting…' : 'Connect EVM'}+ </button>+ <!-- Solana button -->+ <button+ disabled={loading !== null}+ on:click={connectSolana}+ class="h-9 rounded-full border border-rule bg-white px-4 text-sm font-medium text-ink transition-colors hover:bg-paper disabled:opacity-50"+ >+ {loading === 'sol' ? 'Connecting…' : 'Connect Solana'}+ </button>+ </div>+ {#if error}+ <p class="text-xs text-red-500">{error}</p>+ {/if}+ </div>+{/if}diff --git a/chat/src/stores.js b/chat/src/stores.jsindex 37052d492..6c4657923 100644--- a/chat/src/stores.js+++ b/chat/src/stores.js@@ -8,7 +8,7 @@ export const brandConfig = writable({logo_url: null,accent_color: '#6366f1',tagline: 'Chat with any AI model',- default_model: 'google/gemini-2.0-flash-exp:free',+ default_model: 'openai/gpt-oss-120b:free',agent_id: null,system_prompt: '',});@@ -63,6 +63,7 @@ export const toolSchema = persisted('toolSchemaGroups', []);export const ttsEnabled = persisted('ttsEnabled', false);export const localAgentId = persisted('localAgentId', '');+export const activeAgent = persisted('activeAgentDetail', null);export const talkingHeadEnabled = persisted('talkingHeadEnabled', false);export const route = writable(@@ -84,3 +85,18 @@ export const composerFill = writable(null);export const flowSecondary = persisted('flowSecondary', {});export const appPlatforms = writable(new Set(['macOS']));export const designModel = writable('gpt-image-2');++export const currentUser = writable(null);++export async function loadCurrentUser() {+ try {+ const res = await fetch('/api/auth/me', { credentials: 'include' });+ if (!res.ok) { currentUser.set(null); return null; }+ const { user } = await res.json();+ currentUser.set(user ?? null);+ return user ?? null;+ } catch {+ currentUser.set(null);+ return null;+ }+}diff --git a/chat/src/tools.js b/chat/src/tools.jsindex ee348a29c..979de1578 100644--- a/chat/src/tools.js+++ b/chat/src/tools.js@@ -1,3 +1,130 @@+export const curatedToolPacks = [+ {+ id: 'tradingview',+ name: 'TradingView Charts',+ description: 'Display interactive TradingView price charts for any symbol.',+ schema: [+ {+ clientDefinition: {+ id: 'tradingview-chart-001',+ name: 'TradingViewChart',+ description: 'Displays an interactive TradingView chart for a given symbol.',+ arguments: [+ { name: 'symbol', type: 'string', description: 'Trading symbol e.g. BINANCE:BTCUSDT, NASDAQ:AAPL' },+ { name: 'interval', type: 'string', description: 'Chart interval: 1, 5, 15, 30, 60, D, W, M' },+ { name: 'theme', type: 'string', description: 'light or dark' },+ ],+ body: `const symbol = args.symbol || 'BINANCE:BTCUSDT';+const interval = args.interval || 'D';+const theme = args.theme || 'light';+const html = \`<!DOCTYPE html>+<html>+<head><style>html,body{margin:0;padding:0;height:100%;overflow:hidden}</style></head>+<body>+<div id="tv_chart" style="width:100%;height:100vh"></div>+<script src="https://s3.tradingview.com/tv.js"><\\/script>+<script>+new TradingView.widget({+ container_id:"tv_chart",+ symbol:\${JSON.stringify(symbol)},+ interval:\${JSON.stringify(interval)},+ theme:\${JSON.stringify(theme)},+ style:"1",+ width:"100%",+ height:"100%",+ toolbar_bg:"#f1f3f6",+ hide_side_toolbar:false,+ allow_symbol_change:true+});+<\\/script>+</body></html>\`;+return { contentType: 'text/html', content: html };`,+ },+ type: 'function',+ function: {+ name: 'TradingViewChart',+ description: 'Display an interactive TradingView chart. Use for any request to show a price chart, candlestick chart, or market data visualization.',+ parameters: {+ type: 'object',+ properties: {+ symbol: { type: 'string', description: 'Trading symbol e.g. BINANCE:BTCUSDT, NASDAQ:AAPL, FX:EURUSD' },+ interval: { type: 'string', enum: ['1', '5', '15', '30', '60', 'D', 'W', 'M'], description: 'Chart interval' },+ theme: { type: 'string', enum: ['light', 'dark'], description: 'Chart theme' },+ },+ required: ['symbol'],+ },+ },+ },+ ],+ },+ {+ id: 'web-search',+ name: 'Web Search',+ description: 'Search the web via DuckDuckGo and return a summary and top results.',+ schema: [+ {+ clientDefinition: {+ id: 'pack-websearch-001',+ name: 'WebSearch',+ description: 'Search the web via DuckDuckGo.',+ arguments: [{ name: 'query', type: 'string', description: 'Search query' }],+ body: `const res = await fetch('https://api.duckduckgo.com/?q=' + encodeURIComponent(args.query) + '&format=json&no_html=1');+const d = await res.json();+const topics = (d.RelatedTopics || []).slice(0, 3).map(t => t.Text).filter(Boolean);+return JSON.stringify({ abstract: d.AbstractText || '', topics });`,+ },+ type: 'function',+ function: {+ name: 'WebSearch',+ description: 'Search the web via DuckDuckGo and return an abstract and top related topics.',+ parameters: {+ type: 'object',+ properties: { query: { type: 'string', description: 'Search query' } },+ required: ['query'],+ },+ },+ },+ ],+ },+ {+ id: 'date-time',+ name: 'Date & Time',+ description: 'Get the current time and timezone.',+ schema: [+ {+ clientDefinition: {+ id: 'pack-datetime-001',+ name: 'GetCurrentTime',+ description: 'Returns the current date and time as an ISO string.',+ arguments: [],+ body: 'return new Date().toISOString();',+ },+ type: 'function',+ function: {+ name: 'GetCurrentTime',+ description: 'Returns the current date and time as an ISO 8601 string.',+ parameters: { type: 'object', properties: {} },+ },+ },+ {+ clientDefinition: {+ id: 'pack-datetime-002',+ name: 'GetTimezone',+ description: "Returns the user's current timezone.",+ arguments: [],+ body: "return Intl.DateTimeFormat().resolvedOptions().timeZone;",+ },+ type: 'function',+ function: {+ name: 'GetTimezone',+ description: "Returns the user's current IANA timezone string.",+ parameters: { type: 'object', properties: {} },+ },+ },+ ],+ },+];+export const defaultToolSchema = [{name: 'Client-side',diff --git a/chat/src/walletAuth.js b/chat/src/walletAuth.jsnew file mode 100644index 000000000..5ffe5bdc7--- /dev/null+++ b/chat/src/walletAuth.js@@ -0,0 +1,139 @@+const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';++function toBase58(bytes) {+ let n = BigInt('0x' + Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join(''));+ let result = '';+ const base = BigInt(58);+ while (n > 0n) {+ result = BASE58_ALPHABET[Number(n % base)] + result;+ n /= base;+ }+ for (const byte of bytes) {+ if (byte !== 0) break;+ result = '1' + result;+ }+ return result;+}++/**+ * Returns the current user if a valid session exists, otherwise null.+ * @returns {Promise<object|null>}+ */+export async function getCurrentUser() {+ const res = await fetch('/api/auth/me', { credentials: 'include' });+ if (res.status === 401) return null;+ if (!res.ok) throw new Error(`Failed to fetch current user: ${res.status}`);+ const { user } = await res.json();+ return user;+}++/**+ * Destroys the session cookie.+ * @returns {Promise<void>}+ */+export async function signOut() {+ try {+ await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });+ } catch (_) {}+}++/**+ * Sign in with an EVM wallet via EIP-4361 (SIWE).+ * Requires window.ethereum (MetaMask, injected wallet).+ * @returns {Promise<{user: object, wallet: object}>}+ * @throws {Error} if no wallet, user rejects, or server rejects+ */+export async function signInWithEVM() {+ if (!window.ethereum) throw new Error('No EVM wallet found. Install MetaMask or a compatible wallet.');++ const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });+ const address = accounts[0];+ const chainIdHex = await window.ethereum.request({ method: 'eth_chainId' });+ const chainId = parseInt(chainIdHex, 16);++ const nonceRes = await fetch('/api/auth/siwe/nonce', { credentials: 'include' });+ if (!nonceRes.ok) throw new Error(`Failed to get SIWE nonce: ${nonceRes.status}`);+ const { nonce, csrf, issuedAt } = await nonceRes.json();++ const host = window.location.host;+ const origin = window.location.origin;+ const message = [+ `${host} wants you to sign in with your Ethereum account:`,+ address,+ '',+ 'Sign in to three.ws.',+ '',+ `URI: ${origin}`,+ 'Version: 1',+ `Chain ID: ${chainId}`,+ `Nonce: ${nonce}`,+ `Issued At: ${issuedAt}`,+ ].join('\n');++ const signature = await window.ethereum.request({+ method: 'personal_sign',+ params: [message, address],+ });++ const verifyRes = await fetch('/api/auth/siwe/verify', {+ method: 'POST',+ credentials: 'include',+ headers: { 'Content-Type': 'application/json', 'x-csrf-token': csrf },+ body: JSON.stringify({ message, signature }),+ });+ if (!verifyRes.ok) {+ const text = await verifyRes.text().catch(() => verifyRes.status.toString());+ throw new Error(`SIWE verification failed: ${text}`);+ }+ const { user } = await verifyRes.json();+ return { user, wallet: { type: 'evm', address, chainId } };+}++/**+ * Sign in with a Solana wallet via SIWS (CAIP-122).+ * Requires window.solana (Phantom or compatible).+ * @returns {Promise<{user: object, wallet: object}>}+ * @throws {Error} if no wallet, user rejects, or server rejects+ */+export async function signInWithSolana() {+ if (!window.solana) throw new Error('No Solana wallet found. Install Phantom or a compatible wallet.');++ await window.solana.connect();+ const address = window.solana.publicKey.toString();++ const nonceRes = await fetch('/api/auth/siws/nonce', { credentials: 'include' });+ if (!nonceRes.ok) throw new Error(`Failed to get SIWS nonce: ${nonceRes.status}`);+ const { nonce, csrf, issuedAt } = await nonceRes.json();++ const host = window.location.host;+ const origin = window.location.origin;+ const message = [+ `${host} wants you to sign in with your Solana account:`,+ address,+ '',+ 'Sign in to three.ws.',+ '',+ `URI: ${origin}`,+ 'Version: 1',+ 'Chain ID: mainnet',+ `Nonce: ${nonce}`,+ `Issued At: ${issuedAt}`,+ ].join('\n');++ const bytes = new TextEncoder().encode(message);+ const { signature: sigBytes } = await window.solana.signMessage(bytes);+ const signature = toBase58(sigBytes);++ const verifyRes = await fetch('/api/auth/siws/verify', {+ method: 'POST',+ credentials: 'include',+ headers: { 'Content-Type': 'application/json', 'x-csrf-token': csrf },+ body: JSON.stringify({ message, signature }),+ });+ if (!verifyRes.ok) {+ const text = await verifyRes.text().catch(() => verifyRes.status.toString());+ throw new Error(`SIWS verification failed: ${text}`);+ }+ const { user } = await verifyRes.json();+ return { user, wallet: { type: 'solana', address } };+}diff --git a/experiments/eips-ercs b/experiments/eips-ercsdeleted file mode 160000index 99b08e135..000000000--- a/experiments/eips-ercs+++ /dev/null@@ -1 +0,0 @@-Subproject commit 99b08e1358c20221af17b6474001e43dcd7dbfd0diff --git a/marketplace.html b/marketplace.htmlindex 69355c6a7..12bd7357d 100644--- a/marketplace.html+++ b/marketplace.html@@ -38,6 +38,7 @@<nav class="market-nav"><a href="/" data-nav="home"><span class="ico">⌂</span> Home</a><a href="/marketplace" data-nav="agent" class="active"><span class="ico">▣</span> Agent</a>+ <a href="/marketplace?tab=tools" data-nav="tools"><span class="ico">⚙</span> Tools</a><a href="/features" data-nav="skills"><span class="ico">≡</span> Skills</a><a href="/dashboard" data-nav="model"><span class="ico">◉</span> Model</a></nav>@@ -148,6 +149,53 @@</aside></div></section>++ <!-- Tools tab -->+ <section class="market-tools" id="market-tools" hidden>+ <header class="market-topbar">+ <h2 class="market-tools-title">Tool Packs</h2>+ </header>+ <div class="market-tools-grid">+ <div class="tool-pack-card">+ <div class="head">+ <div class="avatar">◈</div>+ <div style="min-width:0;flex:1">+ <div class="title">TradingView Charts</div>+ <div class="author">1 tool</div>+ </div>+ </div>+ <div class="desc">Live candlestick charts for any crypto or stock symbol</div>+ <!-- TODO: wire up install handler in Svelte chat app -->+ <a class="tool-install-btn" href="/chat?install=tradingview">Add to chat</a>+ </div>++ <div class="tool-pack-card">+ <div class="head">+ <div class="avatar">⊕</div>+ <div style="min-width:0;flex:1">+ <div class="title">Web Search</div>+ <div class="author">1 tool</div>+ </div>+ </div>+ <div class="desc">Search the web and return top results inline</div>+ <!-- TODO: wire up install handler in Svelte chat app -->+ <a class="tool-install-btn" href="/chat?install=web-search">Add to chat</a>+ </div>++ <div class="tool-pack-card">+ <div class="head">+ <div class="avatar">◷</div>+ <div style="min-width:0;flex:1">+ <div class="title">Date & Time</div>+ <div class="author">2 tools</div>+ </div>+ </div>+ <div class="desc">Get current time and timezone in any conversation</div>+ <!-- TODO: wire up install handler in Svelte chat app -->+ <a class="tool-install-btn" href="/chat?install=datetime">Add to chat</a>+ </div>+ </div>+ </section></main><script type="module" src="/src/marketplace.js"></script>diff --git a/prompts/chat-improvements/01-agent-system-prompt.md b/prompts/chat-improvements/01-agent-system-prompt.mdnew file mode 100644index 000000000..53e54a2d9--- /dev/null+++ b/prompts/chat-improvements/01-agent-system-prompt.md@@ -0,0 +1,121 @@+# Task: Wire agent system_prompt and greeting into chat++## Context++This is the `chat/` Svelte app at `/workspaces/3D-Agent/chat/src/`. It's a multi-provider LLM chat UI.++Users can pick an agent from a marketplace picker (`chat/src/AgentPicker.svelte`). When picked, the agent's ID is stored in `localAgentId` (a persisted Svelte store in `chat/src/stores.js`). This drives the 3D avatar widget — but **nothing else**. The agent's `system_prompt`, `greeting`, and `capabilities` fields that live in the database are never fetched or applied to the conversation. The agent has a personality in the DB, but the chat ignores it entirely.++## What the API returns++`GET /api/marketplace/agents/:id` returns:+```json+{+ "data": {+ "agent": {+ "id": "...",+ "name": "...",+ "system_prompt": "You are ...",+ "greeting": "Hi! I'm ...",+ "capabilities": {},+ "thumbnail_url": "..."+ }+ }+}+```++This is confirmed in `api/marketplace/[action].js` — `toDetail()` at the bottom of that file includes `system_prompt`, `greeting`, and `capabilities`.++## What needs to change++### 1. `chat/src/AgentPicker.svelte`++The `pick(agent)` function (line 30) only calls `localAgentId.set(agent.id)`. It has the full agent object from the list endpoint, but the list endpoint returns minimal fields (name, thumbnail).++Change `pick()` to fetch the full agent detail before dispatching:++```js+async function pick(agent) {+ loading = true;+ try {+ const res = await fetch(`/api/marketplace/agents/${agent.id}`);+ if (res.ok) {+ const json = await res.json();+ const detail = json.data?.agent ?? agent;+ localAgentId.set(detail.id);+ dispatch('pick', detail);+ }+ } catch {+ localAgentId.set(agent.id);+ dispatch('pick', agent);+ }+ loading = false;+}+```++Also export a store for the active agent detail. Add to `chat/src/stores.js`:+```js+export const activeAgent = persisted('activeAgentDetail', null);+```++And in `AgentPicker.svelte`, import and set it:+```js+import { localAgentId, activeAgent } from './stores.js';+// in pick():+activeAgent.set(detail);+// in clear():+activeAgent.set(null);+```++### 2. `chat/src/App.svelte`++Import `activeAgent` from stores. Then add a reactive block that applies the agent to the current conversation when `activeAgent` changes:++```js+$: if ($activeAgent) {+ applyAgentToConvo($activeAgent);+}++function applyAgentToConvo(agent) {+ // Inject system prompt as first message if not already present+ if (agent.system_prompt && convo.messages.length === 0) {+ const sysMsg = { id: uuidv4(), role: 'system', content: agent.system_prompt };+ convo.messages = [sysMsg];+ saveMessage(sysMsg);+ saveConversation(convo);+ }+ // Add greeting as first assistant message if no messages yet (or only system)+ const nonSystem = convo.messages.filter(m => m.role !== 'system');+ if (agent.greeting && nonSystem.length === 0) {+ const greetMsg = {+ id: uuidv4(),+ role: 'assistant',+ content: agent.greeting,+ generated: true,+ };+ convo.messages = [...convo.messages, greetMsg];+ saveMessage(greetMsg);+ saveConversation(convo);+ }+}+```++When `clear()` is called in AgentPicker (removes the agent), remove the system message from the current convo if it was agent-injected. You can detect this by checking `convo.messages[0]?.role === 'system'` and whether it matches the cleared agent's `system_prompt`.++### 3. New conversation++When a new conversation is created (around line 818 in `App.svelte`), if `$activeAgent` is set, apply it to the fresh convo immediately after creating it.++## Success criteria++1. Pick an agent from the picker → the chat immediately shows the agent's greeting as an assistant message+2. The system prompt is in the conversation (visible if you add a system message block, or confirmed via network tab showing it sent)+3. Clearing the agent → system message and greeting are removed from a fresh convo+4. An existing convo with messages is not modified when an agent is picked (don't clobber in-progress convos)++## House rules++- Edit existing files only, do not create new ones (except adding the store export to stores.js)+- Match existing code style (tabs, Svelte reactive syntax)+- Run `node --check chat/src/App.svelte` won't work for Svelte — instead do `cd chat && npx vite build` to verify no build errors+- Report: what shipped, what was skipped, what broke, unrelated bugs noticeddiff --git a/prompts/chat-improvements/02-tool-search.md b/prompts/chat-improvements/02-tool-search.mdnew file mode 100644index 000000000..392a4febe--- /dev/null+++ b/prompts/chat-improvements/02-tool-search.md@@ -0,0 +1,76 @@+# Task: Implement tool search in ToolDropdown++## Context++This is the `chat/` Svelte app at `/workspaces/3D-Agent/chat/src/`. The tool picker is in `chat/src/ToolDropdown.svelte`.++There is a commented-out search input at lines 64–70 of `ToolDropdown.svelte`:++```svelte+<!-- <input-->+<!-- type="text"-->+<!-- value=""-->+<!-- placeholder="Search for tools"-->+<!-- class="w-full rounded-lg border border-slate-300 px-3 py-2 text-[10px] text-slate-800 transition-colors placeholder:text-gray-500 focus:border-slate-400 focus:outline-none"-->+<!-- on:input={() => {}}-->+<!-- />-->+```++The `$toolSchema` store (from `chat/src/stores.js`) is an array of groups, each with `{ name: string, schema: Array<{ function: { name: string } }> }`. Currently all groups and tools are always shown.++## What needs to change++### `chat/src/ToolDropdown.svelte`++1. **Uncomment the search input** and wire it up properly.++2. **Add a `query` variable** in the script block (it likely already has one or similar — check before adding).++3. **Filter the displayed groups/tools** based on the query. The filter should:+ - Be case-insensitive+ - Match against both the group name and individual tool names (`schema[i].function.name`)+ - Show a group if the group name matches OR if any tool inside it matches+ - When a group partially matches (only some tools match), only show the matching tools in that group's list+ - Show all tools when query is empty++4. **Bind the input** to the query variable.++The filtered schema should be a derived value, not mutating `$toolSchema`. Use a local `$: filteredSchema = ...` reactive declaration.++Example shape:+```js+let query = '';+$: filteredSchema = query.trim()+ ? $toolSchema+ .map(group => {+ const q = query.toLowerCase();+ const groupMatch = group.name.toLowerCase().includes(q);+ const tools = groupMatch+ ? group.schema+ : group.schema.filter(t => t.function.name.toLowerCase().includes(q));+ return tools.length ? { ...group, schema: tools } : null;+ })+ .filter(Boolean)+ : $toolSchema;+```++Then replace `{#each $toolSchema as group}` with `{#each filteredSchema as group}`.++5. The search input should have `autofocus` so it's focused when the dropdown opens.++6. Show a "No tools found" message (similar to the existing empty state style) when `filteredSchema.length === 0` and `query` is non-empty.++## Success criteria++1. Opening the tool dropdown shows a functional search input at the top+2. Typing "trading" shows only the TradingViewChart tool+3. Typing "client" shows the full Client-side group+4. Clearing the search shows all groups again+5. `cd chat && npx vite build` passes with no errors++## House rules++- Edit `chat/src/ToolDropdown.svelte` only+- Match existing code style (tabs, Svelte syntax, Tailwind classes matching adjacent elements)+- Do not add a new dependency+- Report: what shipped, what was skipped, what broke, unrelated bugs noticeddiff --git a/prompts/chat-improvements/03-consensus-mode.md b/prompts/chat-improvements/03-consensus-mode.mdnew file mode 100644index 000000000..92741fbcc--- /dev/null+++ b/prompts/chat-improvements/03-consensus-mode.md@@ -0,0 +1,81 @@+# Task: Wire up Consensus mode++## Context++This is the `chat/` Svelte app at `/workspaces/3D-Agent/chat/src/`. A multi-model consensus feature was started but never completed. The backend function `completeConsensus` is fully implemented in `chat/src/convo.js` (line 152). The UI toggle and call site are all commented out. This task wires it all together.++## What exists++### `chat/src/convo.js` — `completeConsensus` (line 152)++Fully implemented. It:+1. Queries all models in `convo.models` in parallel (non-streaming)+2. Sends all results to `anthropic/claude-3.5-sonnet` via OpenRouter to produce a consensus summary+3. Calls `onupdate` with the summary chunk++It's imported in `App.svelte` at line 5 but never called.++### `chat/src/App.svelte` — commented-out call site (lines 742–755)++```js+// TODO: Consensus+// if (convo.models.length === 1) {+complete(convo, onupdate, onabort);+// } else {+// completeConsensus(convo, ...)+// }+```++### `chat/src/SettingsModal.svelte` — commented-out tab (lines 201–212 and 595–606)++A "Consensus mode" settings tab is commented out. It was going to show a `ModelSelector` for choosing the summary model.++### `chat/src/ModelSelector.svelte` — commented-out checkbox (lines 126–135)++A checkbox next to each model for multi-select is commented out.++## What needs to change++### 1. `chat/src/App.svelte`++Uncomment and fix the call site (lines 742–755). When `convo.models.length > 1`, use `completeConsensus` instead of `complete`. The commented code has a bug — it passes a raw chunk to `onupdate` without the full delta shape. Fix it to match how `onupdate` works for the normal `complete` path (look at how `onupdate` processes chunks in the surrounding code — it expects `chunk.choices[0].delta.content`).++The fix should be:+```js+if (convo.models.length > 1) {+ completeConsensus(convo, onupdate, onabort);+} else {+ complete(convo, onupdate, onabort);+}+```++### 2. `chat/src/ModelSelector.svelte`++Uncomment the checkbox block (lines 126–135). The checkbox needs to:+- Be checked when `convo.models` contains this model+- On change, dispatch a `changeMulti` event with the model (the commented code already does this)++Look at how the `changeMulti` event is handled in `App.svelte` (search for `changeMulti`) and confirm it's wired. If it's not, add a handler that adds/removes the model from `convo.models`.++### 3. `chat/src/SettingsModal.svelte`++Uncomment the "Consensus mode" nav tab (lines 201–212) and its tab content (lines 595–606). The tab content just shows a `ModelSelector` — that's fine as-is.++### 4. Visual indicator++When `convo.models.length > 1`, the input area or the model selector should visually indicate "Consensus mode". A small badge or label next to the model display is enough — keep it minimal.++## Success criteria++1. Selecting multiple models in ModelSelector enables consensus mode+2. Sending a message with 2+ models queries all of them and produces a single summarized response+3. Single-model convos work exactly as before+4. The Settings modal shows the Consensus tab+5. `cd chat && npx vite build` passes with no errors++## House rules++- Edit existing files only: `App.svelte`, `ModelSelector.svelte`, `SettingsModal.svelte`, `convo.js`+- Do not change the `completeConsensus` implementation in `convo.js` unless there's a clear bug+- Match existing code style+- Report: what shipped, what was skipped, what broke, unrelated bugs noticeddiff --git a/prompts/chat-improvements/04-message-deletion-sync.md b/prompts/chat-improvements/04-message-deletion-sync.mdnew file mode 100644index 000000000..4e1f99c05--- /dev/null+++ b/prompts/chat-improvements/04-message-deletion-sync.md@@ -0,0 +1,64 @@+# Task: Complete message deletion in sync++## Context++This is the `chat/` Svelte app at `/workspaces/3D-Agent/chat/src/`. There is a sync system (`chat/src/sync.js`) that pushes/pulls conversations and messages. Message deletion is partially wired — the sync pull handler receives `deletedMessages` from the server but doesn't apply them.++## The gap++In `chat/src/App.svelte` around line 280:++```js+// TODO: Delete messages.+// for (const message of deletedMessages) {+// const conversationId = con+// delete convosMap+// }+```++The deleted messages arrive from sync but are dropped on the floor. `deletedMessages` is already destructured from the sync pull result — the code just needs to find which conversation each deleted message belongs to and remove it.++## What needs to change++### `chat/src/App.svelte`++Replace the TODO comment block with working deletion logic. The `convosMap` is a `{ [convoId]: convo }` object. Each convo has a `messages` array of message objects with an `id` field.++The deleted messages from sync are message objects (or at minimum have an `id`). You need to:+1. Iterate `deletedMessages`+2. For each, find the convo that contains a message with that id+3. Remove the message from that convo's messages array++```js+for (const deletedMsg of deletedMessages) {+ for (const convoId of Object.keys(convosMap)) {+ const idx = convosMap[convoId].messages.findIndex(m => m.id === deletedMsg.id);+ if (idx !== -1) {+ convosMap[convoId].messages.splice(idx, 1);+ break;+ }+ }+}+```++Read the surrounding code carefully before changing anything — confirm the exact variable names (`deletedMessages`, `convosMap`) by checking the destructuring above the TODO comment and the loop that handles `deletedConversations` just above it (that pattern is the model to follow).++### `chat/src/sync.js`++Check whether `deleteSingleItem` for a message type is implemented. Search for `deleteSingleItem` in `sync.js` and `App.svelte`. If it's exported from `sync.js` and callable for message items, no changes needed there. If it only handles conversations, extend it to handle messages using the same pattern.++Also check: when a user deletes a message locally (look for any delete/trash button on messages in `Message.svelte` or `App.svelte`), is `deleteSingleItem` called? If a delete button exists but doesn't call `deleteSingleItem`, wire it up.++## Success criteria++1. `deletedMessages` from sync pull are removed from `convosMap` (and thus from the rendered conversation)+2. Local message deletion (if the UI exists) calls `deleteSingleItem` so it propagates via sync+3. No regression on normal message flow+4. `cd chat && npx vite build` passes++## House rules++- Read `chat/src/sync.js` and the full sync pull block in `App.svelte` before making changes+- Follow the existing pattern for `deletedConversations` — message deletion should mirror it+- Do not redesign the sync protocol+- Report: what shipped, what was skipped, what broke, unrelated bugs noticeddiff --git a/prompts/chat-improvements/05-tradingview-tool-fix.md b/prompts/chat-improvements/05-tradingview-tool-fix.mdnew file mode 100644index 000000000..c0cd1ce4b--- /dev/null+++ b/prompts/chat-improvements/05-tradingview-tool-fix.md@@ -0,0 +1,62 @@+# Task: Verify and fix the TradingViewChart client tool++## Context++A `TradingViewChart` tool was added to `chat/src/tools.js` in the `defaultToolSchema` array (it's the first entry in the `Client-side` group). It renders a TradingView widget inside an iframe using `contentType: 'text/html'`.++The tool `body` is a template literal that builds HTML and returns `{ contentType: 'text/html', content: html }`. The body is stored as a **string** in `clientDefinition.body` and later `eval()`'d client-side when the tool is called.++## The problem to verify++The tool body contains escaped `<\/script>` tags (backslash-escaped closing script tags inside a template literal). This is necessary to avoid breaking the outer JS string, but the escaping needs to be correct for the actual eval context.++The body string in `tools.js` currently looks like:+```js+body: `const symbol = args.symbol || 'BINANCE:BTCUSDT';+...+<script src="https://s3.tradingview.com/tv.js"><\\/script>+...+<\\/script>+...`+```++When this string is stored and then `eval()`'d, the `<\\/script>` in the source becomes `<\/script>` at runtime, which in an `srcdoc` iframe renders correctly as `</script>`. **Verify this chain is correct.**++## How client tools are executed++Find where `clientDefinition.body` is eval'd. Search `chat/src/` for `eval` or `new Function` or `clientDefinition`. The execution likely happens in `App.svelte` or a dedicated tool runner. Read that code to understand:+1. How `args` is passed in+2. Whether it's `eval()` or `new Function('args', body)(args)`+3. Whether async/await is supported (the `Choice` tool uses `await choose(...)`)++## What to check and fix++1. **Read the tool executor** — find where body strings are run and confirm the call signature matches what the TradingViewChart body expects (`args.symbol`, `args.interval`, `args.theme`).++2. **Verify the escape chain** — trace what the body string looks like at each stage:+ - As written in `tools.js` (raw source)+ - After JS parses the template literal (what's in memory)+ - After `eval()` runs it (what gets returned)+ - What `srcdoc` receives++3. **Fix if broken** — if the `<\/script>` escaping is wrong, correct it. The goal is for the `srcdoc` iframe to receive valid HTML with proper `</script>` tags.++4. **Verify the return shape** — the executor likely checks `toolresponse.content.contentType`. Confirm the body returns `{ contentType: 'text/html', content: html }` in the shape the executor and `Toolcall.svelte` expect.++ In `Toolcall.svelte` (line 30–52), when `toolresponse.content.contentType === 'text/html'`, it sets `displayType = 'webpage'` and renders `displayedContent` via `srcdoc`. The `displayedContent` is set from `toolresponse.content.content` when a `content` field is present (line 39). Confirm our tool returns exactly this.++5. **Test the full path** — if you can run the dev server (`cd chat && npm run dev`), open the chat, enable the TradingViewChart tool, and ask the model to show a BTC chart. Confirm the iframe renders. If you can't run the dev server, add a note about what to manually test.++## Success criteria++1. The escape chain for `</script>` tags is correct — no double-escaping or under-escaping+2. The return shape `{ contentType: 'text/html', content: html }` is confirmed to match what `Toolcall.svelte` expects+3. `cd chat && npx vite build` passes+4. If runnable: enabling the tool and asking for a chart produces a rendered TradingView widget++## House rules++- Primary file to edit: `chat/src/tools.js`+- Read `chat/src/Toolcall.svelte` and the tool executor before making changes+- Do not change `Toolcall.svelte` unless there is a clear bug in how it handles the `text/html` content type+- Report: what was verified correct, what was fixed, what was skipped, unrelated bugs noticeddiff --git a/prompts/chat-improvements/06-tool-pack-marketplace.md b/prompts/chat-improvements/06-tool-pack-marketplace.mdnew file mode 100644index 000000000..27c008044--- /dev/null+++ b/prompts/chat-improvements/06-tool-pack-marketplace.md@@ -0,0 +1,72 @@+# Task: Add tool pack install to the ToolDropdown++## Context++This is the `chat/` Svelte app at `/workspaces/3D-Agent/chat/src/`. Tools are displayed in groups in `chat/src/ToolDropdown.svelte`. The `toolSchema` store (persisted to localStorage in `chat/src/stores.js`) holds an array of `{ name, schema }` groups.++Currently, tool groups are hardcoded in `chat/src/tools.js` (`defaultToolSchema`, `agentToolSchema`, `pumpToolSchema`) and loaded into the store at startup in `App.svelte`. There is no way for users to install additional tool packs.++There is an existing marketplace at `/api/marketplace/` for agents. The goal here is to add a **"Browse packs"** button at the bottom of the ToolDropdown that opens a small modal listing installable tool packs, each of which can be added to `toolSchema`.++## What to build++### 1. Define curated tool packs++In `chat/src/tools.js`, add an exported array `curatedToolPacks`. Each pack has:+- `id` — unique string+- `name` — display name+- `description` — one line+- `schema` — same shape as a group's `schema` array (array of tool objects with `clientDefinition` + `function`)++Start with these two packs (in addition to the already-existing TradingViewChart which is in the default schema):++**Pack: "Web Search"** — a single tool `WebSearch` that fetches `https://api.duckduckgo.com/?q={query}&format=json&no_html=1` and returns the `AbstractText` and top 3 `RelatedTopics[].Text`. Body uses `fetch`.++**Pack: "Date & Time"** — two tools: `GetCurrentTime` (returns `new Date().toISOString()`) and `GetTimezone` (returns `Intl.DateTimeFormat().resolvedOptions().timeZone`).++### 2. `chat/src/ToolDropdown.svelte`++At the bottom of the dropdown (after the `</ul>`), add a "Browse packs" button:++```svelte+<div class="border-t border-slate-100 px-3 py-2">+ <button+ class="w-full rounded-lg border border-slate-200 py-1.5 text-[11px] text-slate-500 transition-colors hover:bg-gray-50 hover:text-slate-700"+ on:click={() => (packModalOpen = true)}+ >+ Browse tool packs+ </button>+</div>+```++### 3. Pack install modal++Create `chat/src/ToolPackModal.svelte`. It's a simple modal (use the existing `Modal.svelte` component) that:+- Lists each pack from `curatedToolPacks`+- Shows name, description, tool count+- Shows an "Install" button if not installed, "Remove" if installed (check by matching `group.name` against pack `name` in `$toolSchema`)+- Install: appends the pack as a new group to `$toolSchema`+- Remove: filters it out of `$toolSchema`++Use the existing `Modal.svelte` — import and wrap with `<Modal bind:open={packModalOpen}>`.++Check how `Modal.svelte` is used in `SettingsModal.svelte` for the correct usage pattern.++### 4. Wire into `ToolDropdown.svelte`++Import `ToolPackModal` and add `<ToolPackModal bind:open={packModalOpen} />` to the dropdown template. Add `let packModalOpen = false` to the script.++## Success criteria++1. A "Browse tool packs" button appears at the bottom of the tool dropdown+2. Clicking it opens a modal listing the curated packs+3. Installing a pack adds it as a group to the tool dropdown and persists across refresh+4. Removing a pack removes it from the dropdown+5. `cd chat && npx vite build` passes++## House rules++- Add to `chat/src/tools.js` and create `chat/src/ToolPackModal.svelte`; edit `chat/src/ToolDropdown.svelte`+- Do not create a backend API — packs are curated client-side for now+- Match existing Tailwind class style from `ToolDropdown.svelte` and `SettingsModal.svelte`+- Report: what shipped, what was skipped, what broke, unrelated bugs noticeddiff --git a/prompts/chat-improvements/07-knobs-sidebar-audit.md b/prompts/chat-improvements/07-knobs-sidebar-audit.mdnew file mode 100644index 000000000..66e0c9174--- /dev/null+++ b/prompts/chat-improvements/07-knobs-sidebar-audit.md@@ -0,0 +1,64 @@+# Task: Audit and fix KnobsSidebar++## Context++This is the `chat/` Svelte app at `/workspaces/3D-Agent/chat/src/`. `chat/src/KnobsSidebar.svelte` is a settings sidebar that controls `params` (temperature, max tokens, etc). Line 2 of that file has `<!-- FIXME: -->` with no description — something is broken or incomplete and was flagged but never documented.++## What to do++### 1. Read the file fully++Read `chat/src/KnobsSidebar.svelte` in its entirety. Note:+- What controls are present+- What `params` fields they bind to+- Whether any input is visually broken, incorrectly bounded, or missing a label++### 2. Read the `params` store definition++In `chat/src/stores.js`, `params` is a persisted store with these defaults:+```js+{+ temperature: 0.3,+ maxTokens: 0,+ messagesContextLimit: 0,+ reasoningEffort: {+ 'low-medium-high': 'high',+ range: 64000,+ }+}+```++Cross-check: are all these fields represented in the sidebar? Are any sidebar controls binding to fields that don't exist in `params`?++### 3. Read how the sidebar is used in `App.svelte`++Search for `KnobsSidebar` in `App.svelte` to see how `knobsOpen` is toggled and whether any props are passed. Confirm there are no prop mismatches.++### 4. Check `reasoningEffort` controls++`params.reasoningEffort` has two modes: `'low-medium-high'` (string enum) and `range` (number). The sidebar may have controls for these. Verify:+- The range slider (if present) binds to `$params.reasoningEffort.range` not `$params.reasoningEffort`+- The low/medium/high selector (if present) binds to `$params.reasoningEffort['low-medium-high']`++Nested store paths in Svelte need care — `bind:value={$params.reasoningEffort.range}` works for reading but may not reactively write back. If a control is not persisting its value, fix the binding to use an intermediate variable or a setter.++### 5. Fix the FIXME++Based on your findings, fix whatever is broken. Remove the `<!-- FIXME: -->` comment once fixed (or replace it with a specific comment if something genuinely can't be fixed yet).++### 6. Add `messagesContextLimit` if missing++If the sidebar doesn't have a control for `messagesContextLimit`, add one — a number input labeled "Message history limit" with `min=0`, bound to `$params.messagesContextLimit`. A value of `0` means unlimited (note this in the label as "0 = unlimited"). Match the style of the existing max tokens input.++## Success criteria++1. All `params` fields have working, correctly-bound controls in the sidebar+2. The `<!-- FIXME: -->` comment is resolved — either fixed or replaced with a specific explanation+3. Changing a value in the sidebar persists after page refresh (because `params` is a persisted store)+4. `cd chat && npx vite build` passes++## House rules++- Edit `chat/src/KnobsSidebar.svelte` only (plus `stores.js` if there's a genuine store bug)+- Match existing label and input style in the sidebar+- Report: what the FIXME turned out to be, what was fixed, what was skipped, unrelated bugs noticeddiff --git a/prompts/chat-improvements/08-agent-marketplace-page.md b/prompts/chat-improvements/08-agent-marketplace-page.mdnew file mode 100644index 000000000..ebcabfe5f--- /dev/null+++ b/prompts/chat-improvements/08-agent-marketplace-page.md@@ -0,0 +1,71 @@+# Task: Add Tools tab to the agent marketplace page++## Context++The project has an agent marketplace page at `/workspaces/3D-Agent/marketplace.html` with a sidebar nav. The nav currently has: Home, Agent, Skills, Model. "Skills" links to `/features` and "Model" links to `/dashboard` — these are placeholders. The marketplace page is a vanilla HTML/JS/CSS page (not Svelte).++The goal is to add a **Tools** tab to the marketplace sidebar that lists curated tool packs users can install into the chat. This page is a discovery surface — it links to the chat with a query param that auto-installs the pack.++## What to build++### 1. Add a Tools tab to the marketplace sidebar++In `marketplace.html`, the sidebar nav looks like:+```html+<a href="/" data-nav="home">…Home</a>+<a href="/marketplace" data-nav="agent" class="active">…Agent</a>+<a href="/features" data-nav="skills">…Skills</a>+<a href="/dashboard" data-nav="model">…Model</a>+```++Add a new entry:+```html+<a href="/marketplace?tab=tools" data-nav="tools">…Tools</a>+```++Use a wrench or plugin icon consistent with the existing icon style in the sidebar.++### 2. Create a marketplace CSS file or extend the existing one++Find the existing `marketplace.css` (referenced in `marketplace.html`). Add styles for the tools grid if needed, or reuse agent card styles.++### 3. Add tool pack cards to the page content++When `?tab=tools` is in the URL (or the Tools nav item is active), show a grid of tool pack cards. Each card shows:+- Pack name+- Description+- Number of tools+- An "Add to chat" button that links to `/chat#tools?install=PACK_ID` (or similar — the exact install mechanism can be a TODO note, since the client-side install logic lives in the Svelte app)++The tool packs to display are the same ones defined in `chat/src/tools.js` (`curatedToolPacks` — see prompt `06-tool-pack-marketplace.md`). Since this is a static HTML page, hardcode the pack definitions here too (they're small).++Start with these packs:+- **TradingView Charts** — `id: tradingview`, description: "Live candlestick charts for any crypto or stock symbol", tools: 1+- **Web Search** — `id: web-search`, description: "Search the web and return top results inline", tools: 1+- **Date & Time** — `id: datetime`, description: "Get current time and timezone in any conversation", tools: 2++### 4. Tab switching++The marketplace page uses `data-nav` attributes and likely has JS to handle tab state. Read the existing JS in `marketplace.html` (or a linked script) to understand how the agent tab is activated, then apply the same pattern for the tools tab.++If the page uses URL params to determine the active tab, handle `?tab=tools` at page load to activate the tools view.++### 5. Active state++When on the tools tab, the Tools nav item should have `class="active"` and the agent content should be hidden (follow the existing show/hide pattern).++## Success criteria++1. `/marketplace?tab=tools` shows the tools tab with pack cards+2. The Tools sidebar item is highlighted when on the tools tab+3. Each pack card shows name, description, tool count, and an "Add to chat" button+4. The Agent tab still works correctly with no regression+5. `node --check` passes on any JS files touched (or no JS files touched)++## House rules++- Edit `marketplace.html` and `marketplace.css` (or whatever CSS file styles the marketplace)+- Do not create a backend API — this is a static discovery page+- Match the visual style of the existing agent cards+- The "Add to chat" button can link to `/chat` with a query param — a TODO comment for the Svelte install side is acceptable+- Report: what shipped, what was skipped, what broke, unrelated bugs noticeddiff --git a/prompts/chat-improvements/09-auto-install-tool-pack.md b/prompts/chat-improvements/09-auto-install-tool-pack.mdnew file mode 100644index 000000000..db9ad5a0b--- /dev/null+++ b/prompts/chat-improvements/09-auto-install-tool-pack.md@@ -0,0 +1,59 @@+# Task: Auto-install tool pack from URL param on chat load++## Context++This is the `chat/` Svelte app at `/workspaces/3D-Agent/chat/src/`. The marketplace page (at `/marketplace?tab=tools`) links to `/chat` with a query param like `?install=tradingview` to trigger installing a tool pack. This task wires up the Svelte side to detect that param and install the pack automatically.++This task depends on tool packs being defined in `chat/src/tools.js` as `curatedToolPacks` (added in prompt `06-tool-pack-marketplace.md`). If that array doesn't exist yet, create a minimal version with just the TradingViewChart pack for now.++## What to build++### `chat/src/App.svelte`++On mount, check `window.location.search` for an `?install=` param. If present, find the matching pack from `curatedToolPacks` by `id`, and install it if not already in `$toolSchema`.++Add this to the `onMount` block (or near the existing URL/hash handling):++```js+const urlParams = new URLSearchParams(window.location.search);+const installId = urlParams.get('install');+if (installId) {+ const pack = curatedToolPacks.find(p => p.id === installId);+ if (pack) {+ const alreadyInstalled = $toolSchema.some(g => g.name === pack.name);+ if (!alreadyInstalled) {+ $toolSchema = [...$toolSchema, { name: pack.name, schema: pack.schema }];+ }+ }+ // Remove the param from URL without reload+ const url = new URL(window.location.href);+ url.searchParams.delete('install');+ window.history.replaceState({}, '', url.toString());+}+```++### Import++Import `curatedToolPacks` in `App.svelte`:+```js+import { defaultToolSchema, agentToolSchema, pumpToolSchema, curatedToolPacks } from './tools.js';+```++### User feedback++After auto-installing, show a brief toast or flash message: "Tool pack '[name]' installed." Use whatever notification mechanism already exists in the app — search for `flash` or toast usage in `App.svelte`. There's an `actions.js` with a `flash` action — use that if it's already in use.++## Success criteria++1. Navigating to `/chat?install=tradingview` automatically installs the TradingViewChart tool pack+2. The `?install=` param is removed from the URL after install (no page reload)+3. Already-installed packs are not duplicated+4. Unknown `install` values are silently ignored+5. `cd chat && npx vite build` passes++## House rules++- Edit `chat/src/App.svelte` and `chat/src/tools.js` only+- Do not add a new dependency+- Match existing code style+- Report: what shipped, what was skipped, what broke, unrelated bugs noticeddiff --git a/prompts/chat-improvements/README.md b/prompts/chat-improvements/README.mdnew file mode 100644index 000000000..740d8df81--- /dev/null+++ b/prompts/chat-improvements/README.md@@ -0,0 +1,40 @@+# Chat Improvements — Dispatch Index++Eight independent tasks. Each can be run in a fresh chat with no knowledge of the others.++Run them in any order — none depends on another except where noted.++---++## Tasks++| File | Task | Effort | Notes |+|------|------|--------|-------|+| [01-agent-system-prompt.md](./01-agent-system-prompt.md) | Wire agent system_prompt + greeting into chat | ~2h | Highest impact — agents currently have no personality in chat |+| [02-tool-search.md](./02-tool-search.md) | Implement tool search in ToolDropdown | ~30m | Uncomment + wire the existing commented-out search input |+| [03-consensus-mode.md](./03-consensus-mode.md) | Wire up multi-model Consensus mode | ~2h | Backend exists, all UI is commented out — just needs unwiring |+| [04-message-deletion-sync.md](./04-message-deletion-sync.md) | Complete message deletion in sync | ~1h | `deletedMessages` from sync is received but ignored |+| [05-tradingview-tool-fix.md](./05-tradingview-tool-fix.md) | Verify + fix TradingViewChart tool | ~1h | Verify escape chain and return shape are correct |+| [06-tool-pack-marketplace.md](./06-tool-pack-marketplace.md) | Add tool pack install UI to ToolDropdown | ~3h | Browse + install curated tool packs from a modal |+| [07-knobs-sidebar-audit.md](./07-knobs-sidebar-audit.md) | Audit and fix KnobsSidebar FIXME | ~1h | Unknown FIXME on line 2 — investigate and resolve |+| [08-agent-marketplace-page.md](./08-agent-marketplace-page.md) | Add Tools tab to marketplace page | ~2h | Vanilla HTML/JS — adds tool pack discovery to /marketplace |+| [09-auto-install-tool-pack.md](./09-auto-install-tool-pack.md) | Auto-install tool pack from URL param | ~30m | Reads `?install=PACK_ID` on chat load and installs the pack |++---++## Dependency note++Task **09** references `curatedToolPacks` from `tools.js` (added in task **06**). If running 09 before 06, check whether `curatedToolPacks` already exists at the top of `chat/src/tools.js`. If not, add a minimal version as described in the prompt.++Task **08** (marketplace page) and task **09** (auto-install) form a pair — 08 is the discovery surface, 09 is the install side. They can still be run independently.++---++## House rules (apply to all tasks)++- One deliverable per task, one PR per task+- No scope creep — note unrelated bugs but don't fix them+- Prefer editing existing files to creating new ones+- Match existing code style (tabs, Svelte reactive syntax, Tailwind classes)+- Verify with `cd chat && npx vite build` after any Svelte changes+- End each session with a reporting block: what shipped, what was skipped, what broke, unrelated bugs noticeddiff --git a/prompts/chat-wallet-auth/01-wallet-auth-utility.md b/prompts/chat-wallet-auth/01-wallet-auth-utility.mdnew file mode 100644index 000000000..c3841b30a--- /dev/null+++ b/prompts/chat-wallet-auth/01-wallet-auth-utility.md@@ -0,0 +1,152 @@+# Task: Create walletAuth.js utility module in the chat app++## Goal+Create `/workspaces/3D-Agent/chat/src/walletAuth.js` — a self-contained ES module that+implements EVM (SIWE) and Solana (SIWS) sign-in flows for the chat app, plus+`getCurrentUser()` and `signOut()`. This module only uses browser `fetch`; it has+zero npm dependencies and does not import anything from outside `chat/src/`.++---++## Context++The chat app lives at `/workspaces/3D-Agent/chat/` (Svelte + Vite, no wallet libs).+It shares the same domain as the main site (`three.ws`), so the `__Host-sid` session+cookie set by the backend auth endpoints is automatically available to the chat app.++The backend already has fully working endpoints:++| Endpoint | Method | Purpose |+|---|---|---|+| `/api/auth/me` | GET | Returns `{ user }` if session valid, 401 otherwise |+| `/api/auth/logout` | POST | Destroys the session cookie |+| `/api/auth/siwe/nonce` | GET | Returns `{ nonce, csrf, issuedAt, expiresAt }`, sets `__Host-csrf-siwe` cookie |+| `/api/auth/siwe/verify` | POST | Verifies EIP-4361 message+sig, creates session |+| `/api/auth/siws/nonce` | GET | Returns `{ nonce, csrf, issuedAt, expiresAt }`, sets `__Host-csrf-siws` cookie |+| `/api/auth/siws/verify` | POST | Verifies SIWS message+sig, creates session |++All fetch calls must include `credentials: 'include'` so cookies are sent.++### EVM (SIWE) flow+1. `GET /api/auth/siwe/nonce` → `{ nonce, csrf }`+2. Build EIP-4361 message (plain text, see format below)+3. Call `window.ethereum.request({ method: 'personal_sign', params: [message, address] })`+4. `POST /api/auth/siwe/verify` with `{ message, signature }` and header `x-csrf-token: csrf`++EIP-4361 message format:+```+{host} wants you to sign in with your Ethereum account:+{address}++Sign in to three.ws.++URI: {origin}+Version: 1+Chain ID: {chainId}+Nonce: {nonce}+Issued At: {issuedAt}+```++Getting the EVM address and chainId:+```js+const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });+const address = accounts[0];+const chainIdHex = await window.ethereum.request({ method: 'eth_chainId' });+const chainId = parseInt(chainIdHex, 16);+```++### Solana (SIWS) flow+1. `GET /api/auth/siws/nonce` → `{ nonce, csrf }`+2. Build SIWS message (CAIP-122 / SIP-0 format, see below)+3. Encode message as UTF-8 bytes, sign with `window.solana.signMessage(bytes)`+4. Base58-encode the 64-byte signature (implement a minimal base58 encoder inline)+5. `POST /api/auth/siws/verify` with `{ message, signature }` and header `x-csrf-token: csrf`++SIWS message format:+```+{host} wants you to sign in with your Solana account:+{address}++Sign in to three.ws.++URI: {origin}+Version: 1+Chain ID: mainnet+Nonce: {nonce}+Issued At: {issuedAt}+```++Getting Solana address:+```js+await window.solana.connect();+const address = window.solana.publicKey.toString();+```++---++## What to implement++```js+// chat/src/walletAuth.js++/**+ * Returns the current user if a valid session exists, otherwise null.+ * @returns {Promise<object|null>}+ */+export async function getCurrentUser() { ... }++/**+ * Destroys the session cookie.+ * @returns {Promise<void>}+ */+export async function signOut() { ... }++/**+ * Sign in with an EVM wallet via EIP-4361 (SIWE).+ * Requires window.ethereum (MetaMask, injected wallet).+ * @returns {Promise<{user: object, wallet: object}>}+ * @throws {Error} if no wallet, user rejects, or server rejects+ */+export async function signInWithEVM() { ... }++/**+ * Sign in with a Solana wallet via SIWS (CAIP-122).+ * Requires window.solana (Phantom or compatible).+ * @returns {Promise<{user: object, wallet: object}>}+ * @throws {Error} if no wallet, user rejects, or server rejects+ */+export async function signInWithSolana() { ... }+```++### Base58 for Solana signatures+The backend accepts base58-encoded signatures. Implement a minimal inline encoder:++```js+const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';+function toBase58(bytes) {+ // BigInt-based encoding+ let n = BigInt('0x' + Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join(''));+ let result = '';+ const base = BigInt(58);+ while (n > 0n) {+ result = BASE58_ALPHABET[Number(n % base)] + result;+ n /= base;+ }+ for (const byte of bytes) {+ if (byte !== 0) break;+ result = '1' + result;+ }+ return result;+}+```++---++## Success criteria+- File exists at `chat/src/walletAuth.js`+- All four functions are exported+- No imports from outside `chat/src/`+- No npm packages imported (pure browser fetch + window.ethereum/window.solana)+- `getCurrentUser()` returns null (not throws) on 401+- `signOut()` is fire-and-forget (swallows errors)+- Both sign-in functions throw descriptive Errors on failurediff --git a/prompts/chat-wallet-auth/02-current-user-store.md b/prompts/chat-wallet-auth/02-current-user-store.mdnew file mode 100644index 000000000..699a764e5--- /dev/null+++ b/prompts/chat-wallet-auth/02-current-user-store.md@@ -0,0 +1,76 @@+# Task: Add currentUser Svelte store to chat/src/stores.js++## Goal+Add a `currentUser` Svelte writable store and a `loadCurrentUser()` function to+`/workspaces/3D-Agent/chat/src/stores.js`. The store holds the authenticated user+object (or `null` when signed out) and is used by nav and auth UI components across+the chat app.++---++## Context++`/workspaces/3D-Agent/chat/src/stores.js` already contains all Svelte stores for the+chat app (API keys, config, route, etc.). It uses `writable` and `persisted` from+`./localstorage.js`.++The chat app and the main site share the same domain (`three.ws`), so the+`__Host-sid` session cookie set by backend sign-in is available here automatically.++The backend endpoint to check session state:+- `GET /api/auth/me` with `credentials: 'include'`+- Returns `{ user: { id, email, display_name, plan, avatar_url, ... } }` on success+- Returns 401 when not signed in++---++## What to add to stores.js++### 1. Import addition+Add `get` to the existing `svelte/store` import if not already there (it already is —+`stores.js` line 1: `import { writable, get } from 'svelte/store';`).++### 2. New store+```js+// Authenticated user — null when signed out, user object when signed in.+// Populated by loadCurrentUser(); do not persist (always re-check on mount).+export const currentUser = writable(null);+```++### 3. New function+```js+/**+ * Fetch the current session user from /api/auth/me and update the store.+ * Silently sets null on any error or 401.+ * @returns {Promise<object|null>}+ */+export async function loadCurrentUser() {+ try {+ const res = await fetch('/api/auth/me', { credentials: 'include' });+ if (!res.ok) { currentUser.set(null); return null; }+ const { user } = await res.json();+ currentUser.set(user ?? null);+ return user ?? null;+ } catch {+ currentUser.set(null);+ return null;+ }+}+```++---++## What NOT to change+- Do not modify any existing store definitions+- Do not add persistence (`persisted`) to `currentUser` — it must always be+ re-fetched from the server (session could have expired)+- Do not call `loadCurrentUser()` inside `stores.js` itself — callers (`App.svelte`,+ `TopNav.svelte`, etc.) will call it in their `onMount`++---++## Success criteria+- `currentUser` is exported from `stores.js` as a writable store with initial value `null`+- `loadCurrentUser` is exported from `stores.js`+- Calling `loadCurrentUser()` sets the store to the user object on 200, or `null` on any error+- No existing store or export is changed or removeddiff --git a/prompts/chat-wallet-auth/03-wallet-connect-component.md b/prompts/chat-wallet-auth/03-wallet-connect-component.mdnew file mode 100644index 000000000..e4e6a8540--- /dev/null+++ b/prompts/chat-wallet-auth/03-wallet-connect-component.md@@ -0,0 +1,146 @@+# Task: Create WalletConnect.svelte component++## Goal+Create `/workspaces/3D-Agent/chat/src/WalletConnect.svelte` — a self-contained Svelte+component that lets users sign in with an EVM wallet (MetaMask / injected) or a+Solana wallet (Phantom), and shows their address + a sign-out button when authenticated.++---++## Context++### Existing files this component uses+- `chat/src/walletAuth.js` — exports `getCurrentUser`, `signOut`, `signInWithEVM`,+ `signInWithSolana` (created in task 01)+- `chat/src/stores.js` — exports `currentUser` (writable store, null when signed out)+ and `loadCurrentUser` (async function that refreshes the store from `/api/auth/me`)++### Tailwind+The chat app uses Tailwind CSS v3. Match the existing button styles already in+`TopNav.svelte`:+- Primary button: `h-9 rounded-full bg-black px-4 text-sm font-medium text-white hover:bg-[#333]`+- Secondary button: `h-9 rounded-full border border-rule bg-white px-4 text-sm font-medium text-ink hover:bg-paper`+- Rule/border color variable: `border-rule`+- Text color: `text-ink`, muted: `text-ink-soft`++---++## Component behavior++### When `$currentUser` is null (signed out)+Show two buttons side by side:+1. **Connect EVM** — clicking it calls `signInWithEVM()`, shows loading state, then+ calls `loadCurrentUser()` on success. On error shows a small inline error message.+2. **Connect Solana** — same but calls `signInWithSolana()`.++While loading, disable both buttons and show "Connecting…" text on the active one.++### When `$currentUser` is set (signed in)+Show a chip:+- Left: shortened wallet address or `display_name` if no wallet address.+ Short address format: first 6 chars + `…` + last 4 chars.+ Use `currentUser.wallet_address` if present, else `currentUser.display_name`.+- Right: "Sign out" button. Clicking it calls `signOut()` then sets `currentUser` to+ null via `currentUser.set(null)`.++### Error display+Show errors inline below the buttons (not an alert/modal). Clear the error when the+user clicks either button again.++---++## Implementation++```svelte+<script>+ import { currentUser, loadCurrentUser } from './stores.js';+ import { signInWithEVM, signInWithSolana, signOut } from './walletAuth.js';++ let loading = null; // 'evm' | 'sol' | null+ let error = '';++ async function connectEVM() {+ error = '';+ loading = 'evm';+ try {+ await signInWithEVM();+ await loadCurrentUser();+ } catch (e) {+ error = e.message || 'EVM sign-in failed.';+ } finally {+ loading = null;+ }+ }++ async function connectSolana() {+ error = '';+ loading = 'sol';+ try {+ await signInWithSolana();+ await loadCurrentUser();+ } catch (e) {+ error = e.message || 'Solana sign-in failed.';+ } finally {+ loading = null;+ }+ }++ async function handleSignOut() {+ await signOut();+ currentUser.set(null);+ }++ function shortAddr(addr) {+ if (!addr) return '';+ return addr.slice(0, 6) + '…' + addr.slice(-4);+ }+</script>++{#if $currentUser}+ <!-- signed-in chip -->+ <span class="flex items-center gap-2 text-sm text-ink">+ <span class="font-medium" title={$currentUser.wallet_address}>+ {$currentUser.wallet_address ? shortAddr($currentUser.wallet_address) : ($currentUser.display_name || 'Account')}+ </span>+ <span class="opacity-30">·</span>+ <button+ class="text-sm text-ink-soft underline hover:text-ink"+ on:click={handleSignOut}+ >Sign out</button>+ </span>+{:else}+ <div class="flex flex-col items-end gap-1">+ <div class="flex items-center gap-2">+ <!-- EVM button -->+ <button+ disabled={loading !== null}+ on:click={connectEVM}+ class="h-9 rounded-full bg-black px-4 text-sm font-medium text-white transition-colors hover:bg-[#333] disabled:opacity-50"+ >+ {loading === 'evm' ? 'Connecting…' : 'Connect EVM'}+ </button>+ <!-- Solana button -->+ <button+ disabled={loading !== null}+ on:click={connectSolana}+ class="h-9 rounded-full border border-rule bg-white px-4 text-sm font-medium text-ink transition-colors hover:bg-paper disabled:opacity-50"+ >+ {loading === 'sol' ? 'Connecting…' : 'Connect Solana'}+ </button>+ </div>+ {#if error}+ <p class="text-xs text-red-500">{error}</p>+ {/if}+ </div>+{/if}+```++---++## Success criteria+- File exists at `chat/src/WalletConnect.svelte`+- Signed-out state shows EVM + Solana connect buttons+- Signed-in state shows shortened address (or display_name) + Sign out+- Loading state disables both buttons and relabels the active one+- Errors display inline without crashing the app+- No external npm packages (only imports from `./stores.js` and `./walletAuth.js`)diff --git a/prompts/chat-wallet-auth/04-wire-topnav.md b/prompts/chat-wallet-auth/04-wire-topnav.mdnew file mode 100644index 000000000..0b46fcb7a--- /dev/null+++ b/prompts/chat-wallet-auth/04-wire-topnav.md@@ -0,0 +1,122 @@+# Task: Wire WalletConnect into TopNav and initialize session on app mount++## Goal+1. Replace the static "Sign in" / "Sign up" buttons in `chat/src/manus/TopNav.svelte`+ with the `WalletConnect` component (which handles both states: signed-in and signed-out).+2. Call `loadCurrentUser()` in `chat/src/App.svelte`'s `onMount` so the auth store is+ populated when the app boots.++---++## Context++### TopNav.svelte — current "Sign in / Sign up" buttons+File: `/workspaces/3D-Agent/chat/src/manus/TopNav.svelte`++The right side of the desktop nav (around line 154–165) currently renders:+```svelte+<!-- RIGHT: auth buttons + hamburger -->+<div class="flex items-center gap-2">+ <div class="hidden items-center gap-2 md:flex">+ <button+ class="h-9 rounded-full bg-black px-4 text-sm font-medium text-white transition-colors hover:bg-[#333]"+ on:click={() => route.set('signin')}+ >Sign in</button>+ <button+ class="h-9 rounded-full border border-rule bg-white px-4 text-sm font-medium text-ink transition-colors hover:bg-paper"+ on:click={() => route.set('signup')}+ >Sign up</button>+ </div>+ <!-- hamburger button (mobile) -->+ ...+</div>+```++The mobile sheet (around line 183–195) has separate Sign in / Sign up buttons too.++### WalletConnect component+File: `/workspaces/3D-Agent/chat/src/WalletConnect.svelte`+- Reads from the `currentUser` store (null = signed out)+- Shows "Connect EVM" + "Connect Solana" when signed out+- Shows address chip + Sign out when signed in++### App.svelte — onMount+File: `/workspaces/3D-Agent/chat/src/App.svelte`++`onMount` already exists at line ~1043. `loadCurrentUser` needs to be called there+so the `currentUser` store is populated before any navigation renders.++---++## Changes required++### 1. `TopNav.svelte`++**Desktop nav — replace the two static auth buttons:**+```svelte+<!-- BEFORE -->+<div class="hidden items-center gap-2 md:flex">+ <button ... on:click={() => route.set('signin')}>Sign in</button>+ <button ... on:click={() => route.set('signup')}>Sign up</button>+</div>++<!-- AFTER -->+<div class="hidden items-center gap-2 md:flex">+ <WalletConnect />+</div>+```++**Mobile sheet — replace the two static auth buttons in the `<div class="flex gap-2 px-6 py-4">` block:**+```svelte+<!-- BEFORE -->+<div class="flex gap-2 px-6 py-4">+ <button class="h-9 flex-1 rounded-full bg-black ..." on:click={() => { route.set('signin'); mobileOpen = false; }}>Sign in</button>+ <button class="h-9 flex-1 rounded-full border ..." on:click={() => { route.set('signup'); mobileOpen = false; }}>Sign up</button>+</div>++<!-- AFTER -->+<div class="flex gap-2 px-6 py-4">+ <WalletConnect />+</div>+```++**Add import at the top of the `<script>` block:**+```js+import WalletConnect from '../WalletConnect.svelte';+```++### 2. `App.svelte`++**Add import** at the top of the `<script>` block alongside existing store imports:+```js+import { loadCurrentUser } from './stores.js';+```++**Call inside `onMount`**, early — before the brand config fetch is a good spot (around line 1047):+```js+onMount(async () => {+ syncRouteFromHash();+ window.addEventListener('hashchange', syncRouteFromHash);++ // Populate auth state from session cookie+ await loadCurrentUser();++ // ... rest of existing onMount ...+```++---++## What NOT to change+- Do not remove the hamburger button from the mobile layout+- Do not touch any other part of TopNav (nav links, dropdowns, logo)+- Do not modify any existing onMount logic in App.svelte beyond adding the import+ and the `await loadCurrentUser()` call++---++## Success criteria+- TopNav desktop nav shows `WalletConnect` instead of the two static auth buttons+- TopNav mobile sheet shows `WalletConnect` instead of the two static auth buttons+- On app load, `loadCurrentUser()` is called in `onMount` so `currentUser` is set+ before the nav renders+- The app compiles without errors (`npm run build` in `chat/`)diff --git a/prompts/chat-wallet-auth/05-wire-auth-page.md b/prompts/chat-wallet-auth/05-wire-auth-page.mdnew file mode 100644index 000000000..8c441d8c8--- /dev/null+++ b/prompts/chat-wallet-auth/05-wire-auth-page.md@@ -0,0 +1,148 @@+# Task: Add wallet sign-in buttons to AuthPage.svelte++## Goal+Update `/workspaces/3D-Agent/chat/src/manus/pages/AuthPage.svelte` to include+real EVM and Solana wallet sign-in options. Currently the page is a stub that+`console.log`s and routes to `'chat'` without calling any auth backend.++---++## Context++### Current AuthPage.svelte+File: `/workspaces/3D-Agent/chat/src/manus/pages/AuthPage.svelte`++The component currently:+- Accepts `export let kind = 'signin'` prop (`'signin'` | `'signup'`)+- Has a `submit()` function that just `console.log`s and sets `route` to `'chat'`+- Renders Google + GitHub social buttons (non-functional stubs)+- Renders an email/password form++The layout has a card with social buttons at the top, an `or` divider, then the form.++### What needs to be added+Replace the existing non-functional Google + GitHub stub buttons with working+EVM and Solana wallet buttons. Keep the email/password form below them — it can+remain a stub for now (do not need to implement email/password auth here).++### Available utilities+- `chat/src/walletAuth.js` (see task 01) — exports `signInWithEVM`, `signInWithSolana`+- `chat/src/stores.js` — exports `currentUser`, `loadCurrentUser`++### After successful wallet sign-in+1. Call `await loadCurrentUser()` to populate the store+2. Call `route.set('chat')` to navigate to the chat view++---++## Changes required++### Replace the `<script>` block++```svelte+<script>+ import { route } from '../../stores.js';+ import { loadCurrentUser } from '../../stores.js';+ import { signInWithEVM, signInWithSolana } from '../../walletAuth.js';++ export let kind = 'signin'; // 'signin' | 'signup'++ let email = '';+ let password = '';+ let name = '';+ let loading = null; // 'evm' | 'sol' | null+ let error = '';++ async function connectEVM() {+ error = '';+ loading = 'evm';+ try {+ await signInWithEVM();+ await loadCurrentUser();+ route.set('chat');+ } catch (e) {+ error = e.message || 'EVM sign-in failed.';+ } finally {+ loading = null;+ }+ }++ async function connectSolana() {+ error = '';+ loading = 'sol';+ try {+ await signInWithSolana();+ await loadCurrentUser();+ route.set('chat');+ } catch (e) {+ error = e.message || 'Solana sign-in failed.';+ } finally {+ loading = null;+ }+ }++ function submit() {+ // Email/password auth not yet implemented+ route.set('chat');+ }+</script>+```++### Replace the social buttons section++Replace the existing Google + GitHub buttons block:+```svelte+<!-- BEFORE -->+<div class="mt-6 space-y-3">+ <button class="bg-white border border-[#E5E3DC] ...">+ <span ... /> Continue with Google+ </button>+ <button class="bg-white border border-[#E5E3DC] ...">+ <span ... /> Continue with GitHub+ </button>+</div>+```++With EVM + Solana wallet buttons:+```svelte+<!-- AFTER -->+<div class="mt-6 space-y-3">+ <button+ disabled={loading !== null}+ on:click={connectEVM}+ class="bg-black text-white rounded-xl h-11 w-full flex items-center justify-center gap-2 hover:bg-[#333] text-sm font-medium disabled:opacity-50 transition-colors"+ >+ {loading === 'evm' ? 'Connecting…' : 'Connect EVM Wallet'}+ </button>+ <button+ disabled={loading !== null}+ on:click={connectSolana}+ class="bg-white border border-[#E5E3DC] text-[#1A1A1A] rounded-xl h-11 w-full flex items-center justify-center gap-2 hover:bg-[#F5F4EF] text-sm font-medium disabled:opacity-50 transition-colors"+ >+ {loading === 'sol' ? 'Connecting…' : 'Connect Solana Wallet'}+ </button>+ {#if error}+ <p class="text-xs text-red-500 text-center">{error}</p>+ {/if}+</div>+```++---++## What NOT to change+- Keep the email/password form exactly as-is (it can remain a stub)+- Keep the "or" divider between wallet buttons and email form+- Keep the "Don't have an account? Sign up" / "Already have an account? Sign in"+ toggle at the bottom+- Keep the card layout and all existing styles++---++## Success criteria+- AuthPage shows "Connect EVM Wallet" and "Connect Solana Wallet" buttons+- Clicking either calls the appropriate sign-in function+- On success: `loadCurrentUser()` is called, then `route.set('chat')`+- On error: error message appears below the buttons+- Both buttons are disabled while loading+- The email/password form still renders below the divider+- No Svelte compile errorsdiff --git a/prompts/tasks/agent-3d-emotion-detection.md b/prompts/tasks/agent-3d-emotion-detection.mdnew file mode 100644index 000000000..7d0678480--- /dev/null+++ b/prompts/tasks/agent-3d-emotion-detection.md@@ -0,0 +1,89 @@+# Task: Improve emotion detection for the 3D avatar++## Context++`/workspaces/3D-Agent/chat/src/App.svelte` has a `detectEmotion()` function used to trigger expressions on the `agent-3d` floating avatar after each assistant message:++```js+function detectEmotion(text) {+ const t = text.toLowerCase();+ if (/\b(sorry|unfortunately|error|failed|can't|cannot|problem|issue|wrong)\b/.test(t)) return 'concern';+ if (/\b(great|excellent|perfect|congrats|amazing|wonderful|fantastic|awesome)\b/.test(t)) return 'celebration';+ if (/\b(interesting|fascinating|curious|wonder|actually|surprisingly)\b/.test(t)) return 'curiosity';+ if (/\b(understand|feel|must be|difficult|hard|tough|challenging)\b/.test(t)) return 'empathy';+ if (/\b(let me|one moment|working on|processing|calculating)\b/.test(t)) return 'patience';+ return null;+}+```++This is a simple keyword match. It fires on individual words out of context ("I can't wait to help you" → 'concern') and misses most emotional content.++## What to improve++### 1. Match on message-level sentiment, not word presence++The current regex fires if any matching word appears anywhere. Replace with a scoring approach that weighs multiple signals before returning an emotion:++```js+function detectEmotion(text) {+ const t = text.toLowerCase();+ const scores = {+ concern: 0,+ celebration: 0,+ curiosity: 0,+ empathy: 0,+ patience: 0,+ };++ // Negative/problem signals+ if (/\b(error|failed|can't|cannot|unable to|unfortunately|issue|problem|broken|doesn't work)\b/.test(t)) scores.concern += 2;+ if (/\b(sorry|apologize|my mistake|incorrect)\b/.test(t)) scores.concern += 1;++ // Positive/celebration signals+ if (/\b(great|excellent|perfect|congrats|congratulations|amazing|wonderful|fantastic|awesome|well done)\b/.test(t)) scores.celebration += 2;+ if (/\b(success|worked|solved|fixed|done|completed)\b/.test(t)) scores.celebration += 1;++ // Curiosity signals+ if (/\b(interesting|fascinating|curious|wonder|surprising|actually|notably|worth knowing)\b/.test(t)) scores.curiosity += 2;+ if (/\?/.test(text)) scores.curiosity += 1;++ // Empathy signals+ if (/\b(understand|i see|that makes sense|must be|difficult|hard|tough|challenging|frustrating)\b/.test(t)) scores.empathy += 2;+ if (/\b(feel|sounds like|i hear you)\b/.test(t)) scores.empathy += 1;++ // Patience/thinking signals+ if (/\b(let me|one moment|working on|processing|calculating|give me a|just a)\b/.test(t)) scores.patience += 2;++ // Counteract: "can't wait" should not be 'concern'+ if (/\bcan't wait\b/.test(t)) scores.concern -= 2;+ if (/\bno problem\b/.test(t)) scores.concern -= 2;++ const top = Object.entries(scores).sort((a, b) => b[1] - a[1])[0];+ return top[1] >= 2 ? top[0] : null;+}+```++### 2. Apply to TalkingHead too++`speakLastMessage()` in `App.svelte` calls `detectEmotion()` for `agent-3d` but not for TalkingHead. After calling `talkingHead.speak()`, also call `talkingHead.setMood()` if an emotion is detected:++```js+} else if ($talkingHeadEnabled && agentVisible) {+ if (talkingHeadReady) {+ const mood = detectEmotion(last.content);+ if (mood) talkingHead.setMood(mood);+ talkingHead.speak({ text: last.content, mood: mood || 'neutral' });+ } else {+ pendingSpeak = last.content;+ }+}+```++## Files to edit+- `/workspaces/3D-Agent/chat/src/App.svelte` — replace `detectEmotion()`, update TalkingHead speak call++## Verification+- Send a message like "I apologize, I was unable to complete that task" → avatar should show concern+- Send "You solved it! That's fantastic!" → avatar should show celebration+- Send "I can't wait to help you with this!" → should NOT show concern (the counteract rule)+- Send a neutral message → no emotion triggered (returns null, no `expressEmotion` call)diff --git a/prompts/tasks/agent-3d-ready-gate.md b/prompts/tasks/agent-3d-ready-gate.mdnew file mode 100644index 000000000..22e0f72ac--- /dev/null+++ b/prompts/tasks/agent-3d-ready-gate.md@@ -0,0 +1,100 @@+# Task: Gate speakLastMessage on agent-3d element readiness++## Context++`/workspaces/3D-Agent/chat/src/App.svelte` calls `agentEl.speak(text)` on the `<agent-3d>` custom element to trigger lipsync. However, `agentEl` is set via `bind:this` as soon as the DOM element is created — but the `agent-3d` web component loads its 3D scene asynchronously. Calling `.speak()` before the scene is ready is a no-op.++The same problem was already fixed for `TalkingHead` in this codebase (see `talkingHeadReady` flag and `onTalkingHeadReady()` function). The `agent-3d` element needs the same treatment.++## What to fix++### 1. Check what events agent-3d dispatches++The `agent-3d` custom element is loaded from `/agent-3d/latest/agent-3d.js`. Check what events it fires when ready:++```bash+grep -r "dispatchEvent\|CustomEvent\|ready\|loaded" /workspaces/3D-Agent/node_modules 2>/dev/null | grep -i "agent-3d" | head -20+```++Or check the source/docs of the agent-3d element to find the ready event name. Common patterns: `'ready'`, `'load'`, `'agent-ready'`.++If no ready event is documented, use a polling approach as fallback.++### 2. Add an agentReady flag++In `App.svelte`, alongside the existing `talkingHeadReady`:++```js+let agentReady = false;+let agentPendingSpeak = null;+```++### 3. Listen for the ready event on the agent-3d element++After the element is bound (when `agentEl` becomes non-null), attach a one-time event listener:++```js+$: if (agentEl && !agentReady) {+ agentEl.addEventListener('ready', () => {+ agentReady = true;+ if (agentPendingSpeak) {+ agentEl.speak(agentPendingSpeak);+ agentPendingSpeak = null;+ }+ }, { once: true });+}+```++If the event name is different from `'ready'`, adjust accordingly.++**Fallback if no ready event exists:** poll until `agentEl.speak` behaves (check if a `isReady` or `loaded` property exists on the element):++```js+$: if (agentEl && !agentReady) {+ const poll = setInterval(() => {+ if (agentEl?.isReady || typeof agentEl?.speak === 'function') {+ agentReady = true;+ clearInterval(poll);+ if (agentPendingSpeak) {+ agentEl.speak(agentPendingSpeak);+ agentPendingSpeak = null;+ }+ }+ }, 200);+}+```++### 4. Update speakLastMessage to queue if not ready++```js+if (agentEl && effectiveAgentId) {+ if (agentReady) {+ agentEl.speak(last.content);+ const emotion = detectEmotion(last.content);+ if (emotion) setTimeout(() => agentEl?.expressEmotion(emotion), 600);+ } else {+ agentPendingSpeak = last.content;+ }+}+```++### 5. Reset on agent change++When `effectiveAgentId` changes (user picks a different agent), reset the ready flag:++```js+$: if (effectiveAgentId) {+ agentReady = false;+ agentPendingSpeak = null;+}+```++## Files to edit+- `/workspaces/3D-Agent/chat/src/App.svelte`++## Verification+- Open the chat with an agent configured+- Send a message immediately after page load (before the 3D scene finishes loading)+- The speak call should be queued and fire once the avatar is ready — not silently dropped+- If you send another message while a previous speak is pending, only the latest is queued (overwrite `agentPendingSpeak`)+- After the first successful speak, subsequent messages speak immediatelydiff --git a/prompts/tasks/agent-idle-animations.md b/prompts/tasks/agent-idle-animations.mdnew file mode 100644index 000000000..721abd503--- /dev/null+++ b/prompts/tasks/agent-idle-animations.md@@ -0,0 +1,126 @@+# Task: Add idle animation system to keep agents alive when not speaking++## Context++The project is three.ws — a platform for 3D AI agents.++The repo is at `/workspaces/3D-Agent`.++**What exists:**++- `src/agent-avatar.js` — The Empathy Layer. Drives emotion blends and morph targets per-frame. Has a `_tickEmotion()` method hooked into the viewer's `_afterAnimateHooks`. At the bottom of the file there is `BEGIN:IDLE_LOOP_IMPORT` / `END:IDLE_LOOP_IMPORT` markers — this suggests an `IdleAnimation` module was planned.++- `src/idle-animation.js` — **Check if this file exists.** The import `import { IdleAnimation } from './idle-animation.js'` is in `agent-avatar.js`. If the file doesn't exist, it's a broken import.++- `src/runtime/scene.js` — `SceneController` with `playClipByName(name, opts)`. Can trigger named animation clips on the avatar.++- `src/runtime/animation-slots.js` — Animation slot resolution (`resolveSlot`, `DEFAULT_ANIMATION_MAP`). Maps logical names to actual clip names.++- `src/agent-protocol.js` — Event bus. Protocol events include `gesture`, `speak`, `think`, `skill-done`.++**The problem:** When an agent is not speaking or performing a skill, it stands completely still — frozen like a statue. This looks unnatural and breaks immersion. A living agent should breathe, shift weight, glance around, blink, or make small movements.++**The goal:** Implement the `IdleAnimation` system that keeps the agent visually alive during idle periods, and pauses gracefully when the agent starts speaking or performing a gesture.++---++## Design++### IdleAnimation class++Create or complete `src/idle-animation.js`:++```js+export class IdleAnimation {+ constructor({ scene, protocol, avatar }) {+ this._scene = scene; // SceneController+ this._protocol = protocol; // AgentProtocol bus+ this._avatar = avatar; // AgentAvatar reference+ this._active = false;+ this._currentIdle = null;+ this._idleTimer = null;++ // Listen for events that interrupt idle+ protocol.on('speak', () => this._pause());+ protocol.on('gesture', () => this._pause());+ protocol.on('skill-done', () => this._scheduleResume());+ protocol.on('speak-end', () => this._scheduleResume());+ }++ start() {+ this._active = true;+ this._scheduleNext();+ }++ stop() {+ this._active = false;+ clearTimeout(this._idleTimer);+ }+}+```++### Idle behaviors++Cycle through a set of idle behaviors at random intervals (8–15 seconds between each):++1. **Breathing** — Subtle chest/shoulder rise-and-fall. If the avatar has a `breathing` clip, play it on loop. Otherwise, drive `spine.position.y` with a sine wave (amplitude 0.002, frequency 0.3Hz) using the `_afterAnimateHooks` system.++2. **Weight shift** — Play a `idle` or `idle_shift` animation clip if available (from `DEFAULT_ANIMATION_MAP`). Fall back to a subtle hip sway via bone transform.++3. **Head look-around** — Emit `look-at { target: 'camera' }` then after 3s `look-at { target: 'model' }`. Uses existing look-at logic in `agent-avatar.js`.++4. **Blink** — Drive `eyeBlinkLeft` and `eyeBlinkRight` morph targets: quick ramp to 1.0 over 80ms, hold 40ms, ramp back to 0 over 80ms. Repeat 1–2 times. Schedule every 3–6 seconds independently of other idles.++5. **Subtle emotion drift** — If curiosity < 0.1 and the agent has been idle for > 30s, emit `emote { trigger: 'curiosity', weight: 0.15 }`. This gives a slight "looking around, interested" expression.++### Clip availability detection++Not all avatars have the same animation clips. Before trying to play a clip, check if it exists:++```js+_hasClip(name) {+ return this._scene.viewer?.mixer?._actions?.some(+ a => a._clip.name.toLowerCase().includes(name.toLowerCase())+ );+}+```++If a clip doesn't exist, fall back to the morph-target-only approach.++### Interruption and resume++- `_pause()`: Cancel the current idle timer, stop any playing idle clip (with a fast 0.3s fade-out).+- `_scheduleResume()`: After a 2s delay (let the speech/gesture finish), call `_scheduleNext()`.++---++## Files to create/edit++**Create (if doesn't exist):**+- `src/idle-animation.js` — `IdleAnimation` class++**Edit:**+- `src/agent-avatar.js` — instantiate `IdleAnimation` and call `start()` after the avatar is initialized. The `BEGIN:IDLE_LOOP_IMPORT` / `END:IDLE_LOOP_IMPORT` markers show where this should happen.++**Do not touch:**+- `src/agent-protocol.js` event vocabulary+- `src/runtime/scene.js` SceneController+- `src/viewer.js`++---++## Acceptance criteria++1. Load any GLB avatar in the viewer with an agent attached. Wait 10 seconds — the avatar makes at least one subtle idle movement (blink, look-around, or head sway).+2. Send a message to the agent. The idle animation pauses while the agent responds.+3. After the agent finishes responding, idle animations resume within 3 seconds.+4. If the avatar has no animation clips (a static GLB), the idle system runs without errors — morphs and bone transforms only.+5. `npx vite build` passes. `node --check src/idle-animation.js` passes.++## Constraints++- ESM only. Tabs, 4-wide. Match existing style in `src/`.+- No new npm dependencies — use Three.js APIs already available.+- Idle animations must not fight with the emotion blend system in `agent-avatar.js`. Idle drives bones/clips; emotion drives morph targets. They operate on different systems and don't conflict.+- `IdleAnimation` must clean up all timers and event listeners in `stop()` to prevent memory leaks when the element is unmounted.+- Blink rate: 1 blink every 3–6 seconds (humans blink ~15x/min — don't make it creepy by blinking too fast).diff --git a/prompts/tasks/agent-memory-backend-sync.md b/prompts/tasks/agent-memory-backend-sync.mdnew file mode 100644index 000000000..d4c1444ff--- /dev/null+++ b/prompts/tasks/agent-memory-backend-sync.md@@ -0,0 +1,197 @@+# Task: Wire AgentMemory backend sync to the API++## Context++The project is three.ws — a platform for 3D AI agents.++The repo is at `/workspaces/3D-Agent`.++**What exists:**++- `src/agent-memory.js` — In-browser memory store for agents. Stores to `localStorage` immediately. Has a `backendSync` option that defaults to `false`. When `backendSync = true`, the constructor calls `this._scheduleSync()` but the sync implementation is incomplete — it calls a backend endpoint that may not exist.++ Look at `_scheduleSync()` and `_flushToBackend()` (or similar methods) in the file to understand what's currently there vs. what's missing.++- `api/agents/[id]/` — Agent CRUD API. There is likely a `/memories` endpoint structure, but check if `api/agents/[id]/memories.js` (or similar) actually exists and handles read/write.++- `api/_lib/schema.sql` — Has an `agent_memories` table:+ ```sql+ -- agent_memories: id, agent_id, type, content, tags, salience, expires_at, created_at+ ```++- `src/runtime/index.js` — The LLM brain loop. Creates `AgentMemory` (likely with `backendSync: false` currently) and uses `memory.query()` to inject context before LLM calls.++- `src/agent-identity.js` — Records events to the backend (uses `POST /api/agent-actions`). The memory sync should follow a similar pattern.++**The problem:** Agent memories are lost on page refresh because `localStorage` is unreliable and `backendSync` is disabled. The `agent_memories` DB table exists but nothing writes to it from the frontend.++**The goal:** Complete the `AgentMemory` backend sync so that:+1. When a memory is added (`memory.add()`), it's synced to `/api/agents/:id/memories`+2. On initialization, existing memories are hydrated from the backend+3. On page refresh, memories persist across sessions++---++## Backend: memory CRUD endpoint++Check if `api/agents/[id]/memories.js` exists. If not, create it.++**`GET /api/agents/:id/memories`**++Returns all non-expired memories for the agent:+```js+const rows = await sql`+ SELECT id, type, content, tags, salience, expires_at, created_at+ FROM agent_memories+ WHERE agent_id = ${agentId}+ AND (expires_at IS NULL OR expires_at > now())+ ORDER BY created_at DESC+ LIMIT 200+`;+return json(res, 200, { data: rows });+```++Auth: session or bearer. Agent must belong to the authenticated user.++**`POST /api/agents/:id/memories`**++Saves one memory entry:+```+Body: { type, content, tags?, salience?, expiresAt? }+```++```js+const row = await sql`+ INSERT INTO agent_memories (id, agent_id, type, content, tags, salience, expires_at)+ VALUES (gen_random_uuid(), ${agentId}, ${type}, ${content}, ${tags}, ${salience}, ${expiresAt})+ RETURNING id+`;+return json(res, 201, { id: row[0].id });+```++Rate limit: max 100 writes per minute per agent.++**`DELETE /api/agents/:id/memories/:memoryId`**++Soft delete or hard delete — check how the rest of the API handles deletions.++---++## Changes to src/agent-memory.js++### constructor++When `backendSync = true` and an `agentId` is provided, hydrate from backend on startup:++```js+constructor(agentId, { backendSync = false } = {}) {+ this.agentId = agentId;+ this.backendSync = backendSync;+ this._entries = [];+ this._hydrate(); // from localStorage, as before++ if (backendSync && agentId) {+ this._hydrateFromBackend(); // async, fire-and-forget+ }+}++async _hydrateFromBackend() {+ try {+ const res = await fetch(`/api/agents/${this.agentId}/memories`, {+ credentials: 'include',+ });+ if (!res.ok) return;+ const { data } = await res.json();+ for (const row of data) {+ // Only add if not already in _entries (avoid duplicates with localStorage)+ if (!this._entries.find(e => e.id === row.id)) {+ this._entries.push({+ id: row.id,+ type: row.type,+ content: row.content,+ tags: row.tags || [],+ context: {},+ salience: row.salience || 0.5,+ createdAt: new Date(row.created_at).getTime(),+ expiresAt: row.expires_at ? new Date(row.expires_at).getTime() : null,+ });+ }+ }+ } catch {+ // Backend unavailable — localStorage data is the fallback+ }+}+```++### _scheduleSync (update or implement)++Currently either a no-op or incomplete. Complete it to POST new entries:++```js+_scheduleSync(entry) {+ this._persist(); // localStorage, as before++ if (!this.backendSync || !this.agentId) return;++ // Fire-and-forget — don't block add()+ fetch(`/api/agents/${this.agentId}/memories`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ type: entry.type,+ content: entry.content,+ tags: entry.tags,+ salience: entry.salience,+ expiresAt: entry.expiresAt,+ }),+ credentials: 'include',+ }).catch(() => {}); // silently ignore — localStorage is the source of truth+}+```++### Enabling sync in the runtime++In `src/runtime/index.js`, when creating `AgentMemory`, pass `backendSync: true` if the agent is authenticated:++```js+const memory = new AgentMemory(agentId, {+ backendSync: !!sessionUser, // only sync if authenticated+});+```++How to know if authenticated: check if `element.js` passes session context to the runtime, or call `GET /api/auth/me` once at runtime init.++---++## Files to create/edit++**Create (if doesn't exist):**+- `api/agents/[id]/memories.js`++**Edit:**+- `src/agent-memory.js` — complete `_hydrateFromBackend()` and `_scheduleSync()`+- `src/runtime/index.js` — enable `backendSync: true` for authenticated agents++**Do not touch:**+- `src/memory/index.js` (the file-based memory variant — separate concern)+- `agent_memories` table schema — it already exists++---++## Acceptance criteria++1. Boot the element with an authenticated session. Add a memory via the agent's `remember` skill. Refresh the page — the memory is still there (loaded from backend).+2. Without authentication (`backendSync: false`), memories still work from localStorage — no regression.+3. `GET /api/agents/:id/memories` returns the stored memories as JSON.+4. `POST /api/agents/:id/memories` returns `{ id: "..." }`.+5. An unauthenticated request to the memories endpoint returns `401`.+6. Memory hydration failure (backend down) does not crash the agent — localStorage memories still load.+7. `npx vite build` passes. `node --check api/agents/[id]/memories.js` passes.++## Constraints++- Backend sync is fire-and-forget — never block `add()` on a network round-trip.+- localStorage remains the source of truth for reads. Backend is the persistence layer.+- ESM only in `src/`. API endpoints use `wrap(...)` pattern from `api/CLAUDE.md`.+- Max 200 memories returned from `GET` endpoint (already in the query above).+- No new npm dependencies.diff --git a/prompts/tasks/agent-protocol-rate-limit.md b/prompts/tasks/agent-protocol-rate-limit.mdnew file mode 100644index 000000000..dfc7a97ff--- /dev/null+++ b/prompts/tasks/agent-protocol-rate-limit.md@@ -0,0 +1,139 @@+# Task: Add rate limiting to agent-protocol.js to prevent runaway skill loops++## Context++The project is three.ws — a platform for 3D AI agents.++The repo is at `/workspaces/3D-Agent`.++**What exists:**++- `src/agent-protocol.js` — The event bus for the agent runtime. Everything communicates via `protocol.emit()` / `protocol.on()`. All events (speak, think, gesture, emote, perform-skill, skill-done, etc.) flow through this bus.++- `src/runtime/index.js` — The LLM brain loop. Has `MAX_TOOL_ITERATIONS = 8` to prevent infinite tool loops. But this limit is per-conversation-turn — it doesn't prevent a skill from emitting protocol events that trigger other skills in a cascade.++- `src/CLAUDE.md` explicitly notes: **"No rate limit on `protocol.emit()`. A runaway skill loop will cascade."**++**The problem:** If a skill emits `perform-skill` which triggers another skill that emits `perform-skill` again (or if an error in the emotion layer causes rapid re-emission), the protocol bus can cascade into an infinite event loop. This freezes the browser tab and makes the agent unresponsive.++**The goal:** Add a lightweight rate limiter to `AgentProtocol.emit()` that:+1. Counts events per type over a sliding window (e.g. 100ms)+2. If any event type exceeds a threshold (e.g. 50 events/100ms), stops emitting that event type and fires a `protocol-error` event instead+3. Automatically resets after a cooldown period (e.g. 1 second)++---++## Design++### Rate limiter approach++Use a token bucket or simple counter-per-window per event type:++```js+// In AgentProtocol class+constructor() {+ this._handlers = new Map();+ this._counters = new Map(); // eventType → { count, windowStart }+ this._throttled = new Set(); // event types currently rate-limited++ // Limits: max emits per 100ms per event type+ this._limits = {+ 'perform-skill': 10, // skills shouldn't cascade > 10/100ms+ 'emote': 20, // emotion events are high-frequency but bounded+ 'speak': 5, // speaking should be rare+ '*': 100, // global catch-all+ };+ this._windowMs = 100;+ this._cooldownMs = 1000;+}+```++In `emit(type, payload)`:+```js+emit(type, payload) {+ if (this._isThrottled(type)) {+ console.warn(`[agent-protocol] rate-limited: ${type} — too many events`);+ return; // drop the event+ }++ this._recordEmit(type);+ // ... existing dispatch logic ...+}++_isThrottled(type) {+ if (this._throttled.has(type)) return true;+ const counter = this._counters.get(type) || { count: 0, windowStart: Date.now() };+ const now = Date.now();++ if (now - counter.windowStart > this._windowMs) {+ // Reset window+ counter.count = 1;+ counter.windowStart = now;+ this._counters.set(type, counter);+ return false;+ }++ counter.count++;+ const limit = this._limits[type] ?? this._limits['*'];++ if (counter.count > limit) {+ this._throttle(type);+ return true;+ }+ return false;+}++_throttle(type) {+ this._throttled.add(type);+ // Emit a protocol-error so the UI can show something+ // Use a flag to prevent this from itself being rate-limited+ if (type !== 'protocol-error') {+ this._dispatchDirect('protocol-error', {+ code: 'rate_limited',+ eventType: type,+ message: `Event type "${type}" rate-limited — too many emissions in ${this._windowMs}ms`,+ });+ }+ setTimeout(() => {+ this._throttled.delete(type);+ this._counters.delete(type);+ }, this._cooldownMs);+}+```++### Debug mode++Add a `debug` option to the constructor: when `true`, log every emit with a timestamp instead of rate-limiting. Useful for development.++---++## Files to edit++**Edit:**+- `src/agent-protocol.js` — add the rate limiter as described++**Do not touch:**+- Any caller of `protocol.emit()` — the rate limit is transparent to callers+- `src/runtime/index.js` — the `MAX_TOOL_ITERATIONS` limit stays in place as a separate guard++---++## Acceptance criteria++1. Normal agent operation (user sends a message, agent responds, skills fire once) — no events are rate-limited. All 10+ normal events/conversation pass through unthrottled.+2. Simulate a runaway loop: in the browser console, run:+ ```js+ for (let i = 0; i < 200; i++) window.VIEWER.agent_protocol.emit('perform-skill', { skill: 'test' });+ ```+ After 10 events in 100ms, the remaining events are dropped and a `protocol-error` event is fired.+3. After 1 second, `protocol.emit('perform-skill', ...)` works again (cooldown expired).+4. The `protocol-error` event can be subscribed to: `protocol.on('protocol-error', (e) => console.log(e))`.+5. `npx vite build` passes. `node --check src/agent-protocol.js` passes.++## Constraints++- The rate limiter must not add perceptible latency to normal emit() calls — use `Date.now()` (not `performance.now()`) for simplicity.+- No new npm dependencies.+- ESM only. Tabs, 4-wide. Match existing style in `src/agent-protocol.js`.+- The `'*'` global limit is the backstop — per-type limits override it for known types.+- `debug` mode should be settable at runtime: `protocol.debug = true`.diff --git a/prompts/tasks/avatar-fallback-cdn.md b/prompts/tasks/avatar-fallback-cdn.mdnew file mode 100644index 000000000..e5576d87f--- /dev/null+++ b/prompts/tasks/avatar-fallback-cdn.md@@ -0,0 +1,124 @@+# Task: Add fallback and retry for avatar CDN loading failures++## Context++`/workspaces/3D-Agent/chat/src/TalkingHead.svelte` loads the TalkingHead library from a single CDN:++```js+const mod = await import(+ 'https://cdn.jsdelivr.net/gh/met4citizen/[email protected]/modules/talkinghead.mjs'+);+```++If jsDelivr is slow or down, the avatar silently fails to load. The `loadError` state is set, but the only feedback is a small red text inside the avatar container which is easy to miss.++Similarly, the default avatar GLB URL is fetched from `models.readyplayer.me`. If that CDN is slow, `head.showAvatar()` hangs indefinitely with no timeout.++## What to fix++### 1. Add a timeout to the CDN import++Wrap the dynamic import in a race against a timeout:++```js+const importWithTimeout = (url, ms) => Promise.race([+ import(/* @vite-ignore */ url),+ new Promise((_, reject) =>+ setTimeout(() => reject(new Error('CDN load timed out')), ms)+ )+]);++const mod = await importWithTimeout(+ 'https://cdn.jsdelivr.net/gh/met4citizen/[email protected]/modules/talkinghead.mjs',+ 15000+);+```++### 2. Retry once on failure++```js+let mod;+try {+ mod = await importWithTimeout('https://cdn.jsdelivr.net/gh/met4citizen/[email protected]/modules/talkinghead.mjs', 15000);+} catch {+ // Wait 2s and retry once+ await new Promise(r => setTimeout(r, 2000));+ mod = await importWithTimeout('https://cdn.jsdelivr.net/gh/met4citizen/[email protected]/modules/talkinghead.mjs', 15000);+}+```++### 3. Improve the error state UI++Currently the error is a small red text. Make it more visible and actionable:++```svelte+{#if loadError}+ <div class="error">+ <p>Avatar failed to load</p>+ <p class="detail">{loadError}</p>+ <button on:click={retry}>Retry</button>+ </div>+{/if}+```++Add a `retry()` function that resets `loadError = null` and re-runs `onMount` logic. The simplest implementation: set a reactive `retryCount` variable that `onMount` watches to re-trigger:++```js+let retryCount = 0;+let loadError = null;++async function retry() {+ loadError = null;+ retryCount++;+}++onMount(async () => {+ // existing load logic, but triggered reactively+});+```++Actually, since `onMount` only runs once, extract the load logic into a separate `loadAvatar()` async function and call it from `onMount` and from `retry()`.++### 4. Add a timeout to showAvatar++After creating the `TalkingHead` instance, wrap `showAvatar()` in a timeout:++```js+await Promise.race([+ head.showAvatar({ url: avatarUrl, body: avatarBody, avatarMood: 'neutral', lipsyncLang: 'en' }),+ new Promise((_, reject) => setTimeout(() => reject(new Error('Avatar model load timed out')), 20000))+]);+```++### 5. Update the error styles++```css+.error {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 8px;+ padding: 16px;+}+.error p { color: #f88; font-size: 12px; text-align: center; }+.error .detail { color: #aaa; font-size: 11px; }+.error button {+ background: #333;+ color: #fff;+ border: none;+ border-radius: 6px;+ padding: 4px 12px;+ font-size: 12px;+ cursor: pointer;+}+```++## Files to edit+- `/workspaces/3D-Agent/chat/src/TalkingHead.svelte`++## Verification+- Temporarily change the CDN URL to a bad URL and open the chat+- After ~15 seconds, the error state should show with a Retry button+- Clicking Retry should attempt to reload+- With a valid URL, the avatar loads normally (the timeout doesn't interfere)+- Restoring the correct URL and clicking Retry should successfully load the avatardiff --git a/prompts/tasks/character-studio-ethers-migration.md b/prompts/tasks/character-studio-ethers-migration.mdnew file mode 100644index 000000000..85c61710f--- /dev/null+++ b/prompts/tasks/character-studio-ethers-migration.md@@ -0,0 +1,66 @@+# Task: Migrate character-studio from ethers.js v5 to v6++## Context++`/workspaces/3D-Agent/character-studio/package.json` depends on `ethers@^5.7` which reached end-of-life. ethers v6 has breaking API changes. The character-studio appears to be a Three.js-based avatar editor that optionally uses wallet/blockchain features.++## What to do++### 1. Audit actual ethers usage first++```bash+grep -rn "ethers\|provider\|signer\|Contract\|BigNumber\|utils\." /workspaces/3D-Agent/character-studio/src --include="*.js" --include="*.ts" --include="*.jsx" --include="*.tsx" | grep -v node_modules | grep -v ".test."+```++List every ethers v5 API call found. Common breaking changes in v6:+- `ethers.utils.parseEther` → `ethers.parseEther`+- `ethers.utils.formatEther` → `ethers.formatEther`+- `ethers.BigNumber.from` → `BigInt(...)` or `ethers.toBigInt`+- `provider.getGasPrice()` → `provider.getFeeData()`+- `new ethers.providers.Web3Provider` → `new ethers.BrowserProvider`+- `new ethers.providers.JsonRpcProvider` → `new ethers.JsonRpcProvider`+- Contract: `contract.functions.method()` → `contract.method()`++### 2. Update package.json++In `/workspaces/3D-Agent/character-studio/package.json`, change:+```json+"ethers": "^5.7"+```+to:+```json+"ethers": "^6.0"+```++### 3. Apply the API migrations++For each usage found in step 1, apply the corresponding v6 pattern from the list above.++Full migration guide: https://docs.ethers.org/v6/migrating/++### 4. Install and verify++```bash+cd /workspaces/3D-Agent/character-studio+npm install+npm run build+```++Fix any TypeScript or import errors that arise.++### 5. Check @web3-react version++`@web3-react` v6 is also outdated. If it's in package.json, check if it's actually used:+```bash+grep -rn "web3-react\|useWeb3React" /workspaces/3D-Agent/character-studio/src+```+If it's unused, remove it from package.json. If it's used, it may need upgrading to v8 separately — note it in a comment but don't do it in this task.++## Files to edit+- `/workspaces/3D-Agent/character-studio/package.json`+- Any `.js/.ts/.jsx/.tsx` files in `/workspaces/3D-Agent/character-studio/src/` that use ethers++## Verification+- `cd /workspaces/3D-Agent/character-studio && npm run build` completes with no errors+- `grep -r "ethers@5\|from 'ethers/v5'" /workspaces/3D-Agent/character-studio/src` returns nothing+- All existing functionality (avatar loading, any wallet connect) still worksdiff --git a/prompts/tasks/chat-agent-protocol-bridge.md b/prompts/tasks/chat-agent-protocol-bridge.mdnew file mode 100644index 000000000..ee86b96c9--- /dev/null+++ b/prompts/tasks/chat-agent-protocol-bridge.md@@ -0,0 +1,108 @@+# Task: Bridge the standalone chat app to the agent runtime protocol bus++## Context++The project is three.ws — a platform for 3D AI agents.++The repo is at `/workspaces/3D-Agent`.++**Two separate apps exist:**++1. **`chat/`** — A full-featured standalone Svelte 4 chat UI. Multi-provider LLM chat (Anthropic, OpenAI, Ollama, etc.), tool calling, image generation. Independent of the 3D agent system. Entry: `chat/src/App.svelte`.++2. **`src/` (the main app)** — The 3D agent runtime. Has `agent-protocol.js` (event bus), `agent-avatar.js` (emotions + morph targets), `runtime/index.js` (LLM brain), and the `<agent-3d>` web component.++**The chat app already has a TalkingHead component** (`chat/src/TalkingHead.svelte`) — a 3D avatar that speaks using the TalkingHead library. But it's wired to the chat's own LLM responses, not to the `agent-protocol.js` event bus from `src/`.++**The problem:** When a user is on a three.ws agent page and using the embedded chat panel (`AgentPanel` from the SDK or `agent-home.js` in the runtime), the chat messages don't flow through the agent protocol bus. So the 3D avatar doesn't react to what's being said — no emotional response, no lipsync trigger, no gesture.++**The goal:** When a message is sent or received in the embedded chat panel, emit the corresponding events on the agent protocol bus so the avatar reacts in real time.++---++## Scope++This task is specifically about the **embedded chat panel** in `src/agent-home.js` (the UI that appears inside the `<agent-3d>` element), NOT about the standalone `chat/` app.++The standalone `chat/` app is a separate product — don't wire it to the protocol bus. That would be a much larger integration.++---++## What the embedded chat already does++Check `src/agent-home.js` (or `src/components/` if the chat UI is there) to understand:+- How user messages are displayed+- How agent responses are displayed+- Whether it calls `protocol.emit('speak', ...)` when the agent responds++The LLM runtime in `src/runtime/index.js` already emits `speak` events on the protocol bus when the agent generates a response. But the chat panel may display responses without waiting for the protocol event, or it may be bypassed in certain flows.++---++## What to audit and fix++### 1. User message → avatar reaction++When the user sends a message in the embedded chat, the avatar should look at the user (emit `look-at { target: 'user' }`) and show curiosity (emit `emote { trigger: 'curiosity', weight: 0.6 }`):++```js+// In the message-send handler of agent-home.js+protocol.emit('look-at', { target: 'user' });+protocol.emit('emote', { trigger: 'curiosity', weight: 0.6 });+```++### 2. Agent response → speak event++When the LLM returns a response, `runtime/index.js` should already emit `speak { text, sentiment }`. Verify this is happening. If it's not, add it.++### 3. Thinking indicator → patience emotion++When the LLM is processing (streaming hasn't started yet), emit:+```js+protocol.emit('think', { thought: 'processing your message...' });+protocol.emit('emote', { trigger: 'patience', weight: 0.5 });+```++### 4. Error → concern emotion++If the LLM call fails:+```js+protocol.emit('emote', { trigger: 'concern', weight: 0.8 });+```++### 5. Chat scroll / typing indicator visibility++These are UI concerns only — no protocol events needed.++---++## Files to audit and edit++1. Read `src/agent-home.js` (or wherever the embedded chat panel lives) in full.+2. Read `src/runtime/index.js` to see what protocol events it emits during the LLM loop.+3. Read `src/agent-protocol.js` to understand the event vocabulary.++Then add the missing `protocol.emit()` calls in the appropriate places.++**Do not touch:**+- `chat/src/App.svelte` or any file in `chat/` — the standalone chat is separate+- `src/agent-avatar.js` — it already handles all the emote/speak/look-at events correctly+- The LLM provider logic in `src/runtime/providers.js`++---++## Acceptance criteria++1. Send a message in the embedded chat panel. The avatar immediately turns to face the camera / user (look-at event fires).+2. While the LLM is streaming a response, the avatar shows a patience/thinking expression.+3. When the agent's response appears, the avatar shows emotion appropriate to the sentiment of the reply (celebration for positive, concern for negative).+4. If the LLM errors out, the avatar shows concern.+5. All of this works without breaking the text display in the chat panel.+6. `npx vite build` passes.++## Constraints++- Only emit events that are defined in the protocol vocabulary (see `src/CLAUDE.md` protocol bus table for the full list).+- Don't add direct method calls to `agent-avatar.js` — use the protocol bus only.+- Keep changes surgical — only add `protocol.emit()` calls, don't refactor the chat panel UI.+- If a `protocol` reference isn't available in `agent-home.js`, check how other modules get it (likely via constructor injection or module-level singleton).diff --git a/prompts/tasks/chat-export.md b/prompts/tasks/chat-export.mdnew file mode 100644index 000000000..f1ae1adfc--- /dev/null+++ b/prompts/tasks/chat-export.md@@ -0,0 +1,84 @@+# Task: Add conversation export (Markdown and JSON)++## Context++`/workspaces/3D-Agent/chat/src/App.svelte` stores conversations in IndexedDB. Users have no way to export or back up their conversations. This task adds an Export button to the conversation options menu that downloads the current conversation as Markdown or JSON.++## What to build++### 1. Add export functions++In `App.svelte` script, add:++```js+function exportConvoAsMarkdown() {+ const lines = [];+ for (const msg of convo.messages) {+ if (msg.role === 'system') continue;+ const role = msg.role === 'user' ? '**You**' : '**Assistant**';+ lines.push(`${role}\n\n${msg.content || ''}\n\n---\n`);+ }+ downloadFile(lines.join('\n'), `conversation-${convo.id.slice(0, 8)}.md`, 'text/markdown');+}++function exportConvoAsJSON() {+ const data = {+ id: convo.id,+ time: convo.time,+ models: convo.models,+ messages: convo.messages.filter(m => m.role !== 'system' || !m.customInstructions).map(m => ({+ role: m.role,+ content: m.content,+ model: m.model,+ time: m.time,+ })),+ };+ downloadFile(JSON.stringify(data, null, 2), `conversation-${convo.id.slice(0, 8)}.json`, 'application/json');+}++function downloadFile(content, filename, type) {+ const blob = new Blob([content], { type });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ a.click();+ URL.revokeObjectURL(url);+}+```++### 2. Find the conversation options menu++Search `App.svelte` for `MoreDropdown` or an existing dropdown/menu on conversations. If there's already a "..." menu per conversation, add Export options there.++If no such menu exists, add a simple dropdown near the top of the current conversation view. Look for where the model name or conversation header is rendered.++Add two buttons to the menu:+```svelte+<button on:click={exportConvoAsMarkdown} class="...">+ Export as Markdown+</button>+<button on:click={exportConvoAsJSON} class="...">+ Export as JSON+</button>+```++Match the existing button styling in whatever dropdown you find.++### 3. Handle edge cases++- If `convo.messages` is empty, show a disabled state or skip (no point exporting empty chat)+- Skip messages where `content` is null/empty (tool call-only messages)+- For Markdown export, if a message has `toolcalls`, append a note: `*[used tool: toolname]*`++## Files to edit+- `/workspaces/3D-Agent/chat/src/App.svelte`+- Possibly `/workspaces/3D-Agent/chat/src/manus/MoreDropdown.svelte` if that's where the menu lives++## Verification+- Open a conversation with several messages+- Click the export button/menu item for Markdown+- A `.md` file should download with all messages formatted cleanly+- Open the file — it should be readable and correctly formatted+- Export as JSON — the `.json` file should parse cleanly with `JSON.parse()`+- Exporting an empty conversation should either be disabled or produce a file with just metadatadiff --git a/prompts/tasks/chat-message-search.md b/prompts/tasks/chat-message-search.mdnew file mode 100644index 000000000..802b8bc58--- /dev/null+++ b/prompts/tasks/chat-message-search.md@@ -0,0 +1,88 @@+# Task: Add conversation search to the chat history sidebar++## Context++`/workspaces/3D-Agent/chat/src/App.svelte` has a history sidebar that shows past conversations grouped by date (today, yesterday, this week, etc.). There is no way to search across conversation history.++The conversations are stored in the `convos` object (a map of id → convo) loaded from IndexedDB. Each `convo.messages` is an array of message objects with `role` and `content` fields.++## What to build++### 1. Add a search input to the history sidebar++Find where the history sidebar renders in `App.svelte` (search for `historyBuckets` — that's where conversations are listed). Add a search input above the conversation list:++```svelte+<script>+ let searchQuery = '';+ $: filteredConvos = searchQuery.trim()+ ? Object.values(convos).filter(c =>+ c.messages.some(m =>+ typeof m.content === 'string' &&+ m.content.toLowerCase().includes(searchQuery.toLowerCase())+ ) ||+ (c.title || '').toLowerCase().includes(searchQuery.toLowerCase())+ )+ : null; // null = show normal historyBuckets+</script>++<input+ type="search"+ placeholder="Search conversations..."+ bind:value={searchQuery}+ class="mx-2 my-2 w-[calc(100%-16px)] rounded-md border border-slate-200 bg-white px-3 py-1.5 text-sm outline-none focus:border-indigo-400"+/>+```++### 2. Show flat search results when searching++When `filteredConvos` is non-null (user is typing), render a flat list instead of `historyBuckets`:++```svelte+{#if filteredConvos}+ {#if filteredConvos.length === 0}+ <p class="px-3 py-4 text-center text-sm text-slate-400">No conversations found</p>+ {:else}+ {#each filteredConvos.sort((a, b) => b.time - a.time) as c}+ <!-- render same conversation item as the normal list -->+ {/each}+ {/if}+{:else}+ <!-- existing historyBuckets rendering -->+{/if}+```++Find the existing conversation item rendering (the `<button>` or `<a>` that loads a conversation on click) and reuse the same component/markup for search results.++### 3. Clear search when a conversation is selected++When the user clicks a conversation from search results, clear `searchQuery = ''` so the sidebar returns to normal view.++### 4. Highlight the matching snippet (optional but nice)++For each search result, show a short excerpt of the matching message content under the title:++```svelte+{@const matchingMsg = c.messages.find(m =>+ typeof m.content === 'string' &&+ m.content.toLowerCase().includes(searchQuery.toLowerCase())+)}+{#if matchingMsg}+ <p class="truncate text-xs text-slate-400">+ ...{matchingMsg.content.slice(+ Math.max(0, matchingMsg.content.toLowerCase().indexOf(searchQuery.toLowerCase()) - 20),+ matchingMsg.content.toLowerCase().indexOf(searchQuery.toLowerCase()) + 60+ )}...+ </p>+{/if}+```++## Files to edit+- `/workspaces/3D-Agent/chat/src/App.svelte` — add search state, input, and conditional rendering++## Verification+- Open the chat with several past conversations+- Type a word that appears in an old message — matching conversations appear+- Clicking a result loads that conversation and clears the search+- Typing a word with no matches shows "No conversations found"+- Clearing the search input restores the normal date-bucketed viewdiff --git a/prompts/tasks/conversation-title-generation.md b/prompts/tasks/conversation-title-generation.mdnew file mode 100644index 000000000..683d0d2d5--- /dev/null+++ b/prompts/tasks/conversation-title-generation.md@@ -0,0 +1,114 @@+# Task: Auto-generate conversation titles using the LLM++## Context++`/workspaces/3D-Agent/chat/src/App.svelte` stores conversations in `convos`. Conversations have a `time` field and a `messages` array but no `title` field — the history sidebar shows them by date only, making it impossible to distinguish between conversations at a glance.++The chat already has a working LLM call pipeline via `complete()` in `convo.js` and a `fetch`-based API setup.++## What to build++### 1. Add a `generateTitle()` function in App.svelte++After an assistant message is received (when `generating` goes from `true` to `false`), if the conversation has no title yet and has at least 2 messages (one user, one assistant), call the active model to generate a short title.++```js+async function generateTitle() {+ if (convo.title) return; // already titled+ const msgs = convo.messages.filter(m => m.role === 'user' || m.role === 'assistant');+ if (msgs.length < 2) return;++ // Use the first user message + first assistant response as context+ const context = msgs.slice(0, 4).map(m => `${m.role}: ${m.content?.slice(0, 300)}`).join('\n');+ const model = convo.models[0];+ if (!model?.id) return;++ try {+ const provider = providers.find(p => p.name === model.provider);+ if (!provider) return;++ const response = await fetch(`${provider.url}${provider.completionUrl}`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ ...(model.provider === 'Anthropic'+ ? { 'x-api-key': provider.apiKeyFn(), 'anthropic-version': '2023-06-01' }+ : { Authorization: `Bearer ${provider.apiKeyFn()}` }),+ },+ body: JSON.stringify({+ model: model.id,+ stream: false,+ max_tokens: 20,+ messages: [+ { role: 'user', content: `Summarize this conversation in 4-6 words as a title. No quotes, no punctuation.\n\n${context}` }+ ],+ }),+ });+ if (!response.ok) return;+ const data = await response.json();+ const title = data?.choices?.[0]?.message?.content?.trim()+ || data?.content?.[0]?.text?.trim(); // Anthropic shape+ if (title) {+ convo.title = title;+ saveConversation(convo);+ convos = { ...convos, [convo.id]: convo };+ }+ } catch {+ // Non-critical, fail silently+ }+}+```++### 2. Trigger it when generation completes++Find where `generating = false` is set after a successful completion. After that line, call:+```js+generateTitle();+```++There may be multiple places where `generating = false` is set — only call it after a successful response (not on abort/error).++### 3. Show the title in the history sidebar++In the history sidebar conversation list, show `convo.title` if it exists, otherwise fall back to the current display (date or first message excerpt):++```svelte+<span class="truncate text-sm font-medium text-slate-700">+ {convo.title || convo.messages.find(m => m.role === 'user')?.content?.slice(0, 50) || 'New conversation'}+</span>+```++Find the exact location in the sidebar rendering loop and update it.++### 4. Allow renaming++Add a double-click handler on the conversation title in the sidebar to make it editable inline:++```svelte+{#if editingTitleId === c.id}+ <input+ class="w-full text-sm font-medium text-slate-700 outline-none"+ bind:value={c.title}+ on:blur={() => { saveConversation(c); convos = {...convos}; editingTitleId = null; }}+ on:keydown={(e) => e.key === 'Enter' && e.target.blur()}+ autofocus+ />+{:else}+ <span class="truncate text-sm font-medium" on:dblclick={() => editingTitleId = c.id}>+ {c.title || 'New conversation'}+ </span>+{/if}+```++Add `let editingTitleId = null` to the script.++## Files to edit+- `/workspaces/3D-Agent/chat/src/App.svelte`++## Verification+- Start a new conversation and send a message, wait for the response+- The conversation in the sidebar should get a short title within a second or two after the response completes+- The title should be 4-6 words describing what was discussed+- Double-clicking a title in the sidebar should let you edit it inline+- Edited titles persist after page reload+- Old conversations with no title still show a fallback (first message text or "New conversation")diff --git a/prompts/tasks/convo-error-handling.md b/prompts/tasks/convo-error-handling.mdnew file mode 100644index 000000000..b44c000db--- /dev/null+++ b/prompts/tasks/convo-error-handling.md@@ -0,0 +1,86 @@+# Task: Add error handling to convo.js API boundaries++## Context++`/workspaces/3D-Agent/chat/src/convo.js` is the core file that calls LLM provider APIs (OpenAI-compatible, Anthropic, etc.) and handles streaming responses.++Currently fetch calls do not check `response.ok`, JSON parses can throw silently, and provider-level error responses (e.g. `{"error": {"message": "..."}}`) are treated as valid data. This causes silent failures and cryptic UI states.++## What to fix++### 1. Check `response.ok` after every fetch (~line 143)++Currently:+```js+const response = await completions(get(controller).signal);+if (stream) {+ streamResponse(model.provider, response.body, onupdate, onabort);+} else {+ const responseBody = await response.json();+ onupdate(responseBody);+}+```++Should be:+```js+const response = await completions(get(controller).signal);+if (!response.ok) {+ let msg = `API error ${response.status}`;+ try { const e = await response.json(); msg = e?.error?.message || e?.message || msg; } catch {}+ throw new Error(msg);+}+if (stream) {+ streamResponse(model.provider, response.body, onupdate, onabort);+} else {+ const responseBody = await response.json();+ onupdate(responseBody);+}+```++### 2. Wrap `response.json()` calls in try-catch (~line 200 in `completeConsensus`)++Currently:+```js+const result = await response.json();+return { model: model.id, response: result.choices[0].message.content };+```++Should be:+```js+let result;+try { result = await response.json(); } catch {+ throw new Error(`Invalid JSON from ${model.id}`);+}+if (!result?.choices?.[0]?.message?.content) {+ throw new Error(`Unexpected response shape from ${model.id}`);+}+return { model: model.id, response: result.choices[0].message.content };+```++### 3. In `complete()` (~line 50-150), wrap the entire function body in try-catch and call `onabort` on error++Currently errors thrown inside `complete()` propagate uncaught. The caller in `App.svelte` does not always have a try-catch.++Wrap the body:+```js+export async function complete(convo, onupdate, onabort) {+ try {+ // ... existing body ...+ } catch (err) {+ if (err.name === 'AbortError') return;+ onabort?.(err.message || String(err));+ }+}+```++### 4. Check `response.ok` for image generation fetch (~line 559)++Find the image generation `fetch(...)` call and add the same `response.ok` check pattern.++## Files to edit+- `/workspaces/3D-Agent/chat/src/convo.js`++## Verification+- In the running chat app, set an invalid API key and send a message — the UI should show an error message rather than silently hanging or crashing.+- In browser devtools, network tab should show the failed request; the chat UI should display the API error message text.+- Valid requests should still work normally.diff --git a/prompts/tasks/delete-eips-ercs-experiment.md b/prompts/tasks/delete-eips-ercs-experiment.mdnew file mode 100644index 000000000..f9e0e97c4--- /dev/null+++ b/prompts/tasks/delete-eips-ercs-experiment.md@@ -0,0 +1,32 @@+# Task: Remove accidentally-cloned experiments/eips-ercs directory++## Context++`/workspaces/3D-Agent/experiments/eips-ercs` is an accidentally-cloned external repository that was committed into this project. It's unrelated to the 3D avatar / AI chat purpose of this project and adds significant bloat.++Check `/workspaces/3D-Agent/experiments/` — there should be a README or note indicating `eips-ercs` was an accidental clone.++## What to do++1. Verify the directory is not referenced anywhere:+```bash+grep -r "eips-ercs" /workspaces/3D-Agent --include="*.js" --include="*.ts" --include="*.svelte" --include="*.go" --include="*.json" | grep -v "node_modules" | grep -v ".git"+```++If no results, proceed.++2. Delete the directory:+```bash+rm -rf /workspaces/3D-Agent/experiments/eips-ercs+```++3. Stage the deletion and commit:+```bash+git add -A+git commit -m "remove accidentally-cloned eips-ercs experiment"+```++## Verification+- `ls /workspaces/3D-Agent/experiments/` should not show `eips-ercs`+- `git status` should be clean after the commit+- No build or import errors after deletiondiff --git a/prompts/tasks/delete-messages-sync.md b/prompts/tasks/delete-messages-sync.mdnew file mode 100644index 000000000..7fad8b129--- /dev/null+++ b/prompts/tasks/delete-messages-sync.md@@ -0,0 +1,67 @@+# Task: Fix deleted messages not syncing in the sync pull flow++## Context++`/workspaces/3D-Agent/chat/src/App.svelte` has a sync system that pulls conversations and messages from a remote server. Around line 280 there is an incomplete TODO:++```js+// TODO: Delete messages.+// for (const message of deletedMessages) {+// const conversationId = con+// convosMap+// }+```++This is inside a function that processes sync results. When another device deletes a message, that deletion is never applied locally — the message stays visible forever on the receiving device.++The `deleteMessage` function at ~line 365 already works correctly for local deletes (removes from IndexedDB and optionally syncs to server). The gap is only in the pull direction: when `syncPull` returns deleted messages, they aren't removed from `convos`.++## What to fix++### 1. Understand the data shape++Look at what `syncPull` returns. In `App.svelte` around line 245-285, the pull result destructures something like:+```js+const { newConversations, deletedConversations, newMessages, deletedMessages } = await syncPull(...)+```++Find the exact variable names by reading the sync pull code at `/workspaces/3D-Agent/chat/src/sync.js`.++### 2. Complete the TODO++Replace the commented-out block with working code. The goal: for each deleted message ID in `deletedMessages`, find which conversation in `convosMap` contains it and remove it.++Pattern to implement:+```js+for (const deletedMsg of deletedMessages) {+ for (const convo of Object.values(convosMap)) {+ const idx = convo.messages.findIndex(m =>+ (typeof m === 'string' ? m : m.id) === deletedMsg.id+ );+ if (idx !== -1) {+ convo.messages.splice(idx, 1);+ break;+ }+ }+}+```++After splicing, trigger reactivity by reassigning: `convos = convosMap`.++### 3. Verify the shape of deletedMessages items++Before implementing, read `/workspaces/3D-Agent/chat/src/sync.js` to confirm:+- What shape objects in `deletedMessages` have (do they have `.id` or are they raw ID strings?)+- Whether the array is named `deletedMessages` or something else in the destructuring++Adjust the implementation to match.++## Files to edit+- `/workspaces/3D-Agent/chat/src/App.svelte` — replace the TODO comment block (~line 280)++## Verification+- Set up two browser tabs with the same sync token and password in Settings+- Send a message in tab 1, confirm it appears in tab 2 after sync+- Delete the message in tab 1+- Trigger a sync pull in tab 2 — the message should disappear+- No console errors should appeardiff --git a/prompts/tasks/go-server-content-type-headers.md b/prompts/tasks/go-server-content-type-headers.mdnew file mode 100644index 000000000..5c8ae5d08--- /dev/null+++ b/prompts/tasks/go-server-content-type-headers.md@@ -0,0 +1,91 @@+# Task: Add Content-Type headers and improve error responses in the Go tool server++## Context++`/workspaces/3D-Agent/chat/server/main.go` has two JSON-returning handlers (`ToolSchema` and `InvokeTool`) that do not set `Content-Type: application/json`. This causes some clients to misparse responses and can break fetch-based JSON parsers.++The `InvokeTool` handler also has an error response inconsistency: sometimes it uses `http.Error()` (plain text) and sometimes `json.NewEncoder(w).Encode(map...)` (JSON), so clients can't reliably detect errors.++Current handler (simplified):+```go+func (tr *ToolHandler) InvokeTool(w http.ResponseWriter, r *http.Request) {+ // ...decode...+ if err := json.NewDecoder(...).Decode(&call); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest) // plain text+ return+ }+ // ...invoke...+ if err != nil {+ json.NewEncoder(w).Encode(map[string]any{"error": err.Error()}) // JSON+ return+ }+ json.NewEncoder(w).Encode(out)+}+```++## What to fix++### 1. Set Content-Type on all JSON responses++Add a helper at the top of `main.go`:+```go+func writeJSON(w http.ResponseWriter, status int, v any) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ json.NewEncoder(w).Encode(v)+}+```++### 2. Update ToolSchema to use writeJSON++```go+func (tr *ToolHandler) ToolSchema(w http.ResponseWriter, r *http.Request) {+ // ... build encodedGroups ...+ writeJSON(w, http.StatusOK, encodedGroups)+}+```++### 3. Update InvokeTool to use consistent JSON errors++Replace all `http.Error(...)` calls with `writeJSON(w, status, map[string]any{"error": msg})`:++```go+func (tr *ToolHandler) InvokeTool(w http.ResponseWriter, r *http.Request) {+ var call struct { ... }+ if err := json.NewDecoder(io.TeeReader(r.Body, os.Stdout)).Decode(&call); err != nil {+ writeJSON(w, http.StatusBadRequest, map[string]any{"error": err.Error()})+ return+ }++ for _, group := range tr.Groups {+ out, err := group.Repo.Invoke(nil, call.Name, call.Args)+ if err != nil {+ if strings.HasPrefix(err.Error(), "tool not found") {+ continue+ }+ writeJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})+ return+ }+ writeJSON(w, http.StatusOK, out)+ return+ }++ writeJSON(w, http.StatusNotFound, map[string]any{"error": "tool not found: " + call.Name})+}+```++Note the last case: the original code falls through to a bare `http.Error` if no group handled the tool. Replace that with a proper JSON 404.++### 4. Update ListDirectory and ReadFile handlers similarly++Check `/workspaces/3D-Agent/chat/server/files.go` — if those handlers return JSON, apply the same `writeJSON` helper.++## Files to edit+- `/workspaces/3D-Agent/chat/server/main.go`+- `/workspaces/3D-Agent/chat/server/files.go` (if it returns JSON)++## Verification+- `cd /workspaces/3D-Agent/chat/server && go build .` — must compile+- `curl -i http://localhost:8081/tool_schema` — response headers must include `Content-Type: application/json`+- `curl -i -X POST http://localhost:8081/tool -d 'bad json'` — must return JSON `{"error":"..."}` not plain text, with status 400+- `curl -i -X POST http://localhost:8081/tool -H 'Content-Type: application/json' -d '{"name":"nonexistent","arguments":{}}'` — must return JSON `{"error":"tool not found: nonexistent"}` with status 404diff --git a/prompts/tasks/indexeddb-save-notifications.md b/prompts/tasks/indexeddb-save-notifications.mdnew file mode 100644index 000000000..edb67d37f--- /dev/null+++ b/prompts/tasks/indexeddb-save-notifications.md@@ -0,0 +1,91 @@+# Task: Surface IndexedDB save failures to the user++## Context++`/workspaces/3D-Agent/chat/src/App.svelte` stores all conversations and messages in IndexedDB. When a transaction fails (disk full, browser storage quota exceeded, private browsing restrictions), the error is silently logged to the console:++```js+// ~line 163+transaction.onerror = () => {+ console.error('Message save failed', transaction.error);+};++// ~line 337+transaction.onerror = () => {+ console.error('Conversation save failed', transaction.error);+};++// ~line 378+transaction.onerror = () => {+ console.error('Message delete failed', transaction.error);+};+```++Users lose data with no indication anything went wrong.++## What to build++### 1. Add a toast/notification store++In `/workspaces/3D-Agent/chat/src/stores.js`, add:+```js+export const notifications = writable([]);++export function notify(message, type = 'error') {+ const id = Math.random().toString(36).slice(2);+ notifications.update(n => [...n, { id, message, type }]);+ setTimeout(() => notifications.update(n => n.filter(x => x.id !== id)), 5000);+}+```++### 2. Replace console.error calls with notify()++In `App.svelte`, import `notify` from `./stores.js` and replace all three `console.error` calls in IndexedDB `onerror` handlers with:+```js+transaction.onerror = () => {+ notify('Failed to save — your changes may be lost. Check browser storage settings.');+};+```++Keep a `console.error` alongside for debugging:+```js+transaction.onerror = () => {+ console.error('Message save failed', transaction.error);+ notify('Failed to save — your changes may be lost.');+};+```++### 3. Add a Notifications component++Create `/workspaces/3D-Agent/chat/src/Notifications.svelte`:+```svelte+<script>+ import { notifications } from './stores.js';+</script>++{#if $notifications.length > 0}+ <div class="fixed bottom-16 left-1/2 z-[200] flex -translate-x-1/2 flex-col gap-2">+ {#each $notifications as n (n.id)}+ <div class="rounded-lg px-4 py-2 text-sm text-white shadow-lg+ {n.type === 'error' ? 'bg-red-600' : 'bg-slate-800'}">+ {n.message}+ </div>+ {/each}+ </div>+{/if}+```++### 4. Mount it in App.svelte++Import and add `<Notifications />` just before the closing `</main>` tag in `App.svelte`.++## Files to edit+- `/workspaces/3D-Agent/chat/src/stores.js` — add `notifications` store and `notify()`+- `/workspaces/3D-Agent/chat/src/App.svelte` — import `notify`, update three `onerror` handlers, mount `<Notifications />`+- `/workspaces/3D-Agent/chat/src/Notifications.svelte` — create new file++## Verification+- Open the chat in a browser+- In devtools console, run: `indexedDB.open('threews-chat').onerror = () => {}`+- A real way to test: open the app in Firefox private browsing (IndexedDB is restricted) — a red toast should appear at the bottom when trying to save a message+- Normal operation should show no toastsdiff --git a/prompts/tasks/kol-wallet-pnl-live-data.md b/prompts/tasks/kol-wallet-pnl-live-data.mdnew file mode 100644index 000000000..478afb9b6--- /dev/null+++ b/prompts/tasks/kol-wallet-pnl-live-data.md@@ -0,0 +1,133 @@+# Task: Replace the KOL wallet P&L stub with live on-chain data++## Context++The project is three.ws — a platform for 3D AI agents with Pump.fun/Solana trading capabilities.++The repo is at `/workspaces/3D-Agent`.++**What exists:**++- `src/kol/wallets.js` — Key Opinion Leader (KOL) wallet tracking. At line 2, there is a comment:+ ```js+ // TODO: replace stub with dynamic source (on-chain P&L indexer, Dune, Birdeye)+ ```+ This means the KOL wallet data is currently hardcoded or returns mock data.++- `api/` — Backend API. Check if there's an existing wallet analytics endpoint.++- The project already uses Pump.fun APIs (`api/pump-fun-mcp.js`) and Solana Web3 (`@solana/web3.js`). Birdeye is a Solana wallet/token analytics API that provides P&L data.++**The goal:** Replace the stub in `src/kol/wallets.js` with live data from Birdeye's wallet P&L API.++---++## Before starting++Read `src/kol/wallets.js` in full to understand:+- What data structure it currently returns+- How it's consumed by the KOL leaderboard or agent skill (check who imports it)+- What "P&L" fields are needed (realized P&L, unrealized P&L, win rate, etc.)++Also read any existing KOL-related files:+- Any KOL skills in `src/skills/`+- `prompts/repo-integrations/13-wallet-pnl-skill.md` — this prompt may have already designed the integration+- `prompts/repo-integrations/11-kol-quest-smart-money-widget.md` — related widget++---++## Birdeye API++Birdeye provides a Solana wallet analytics API. Key endpoint:++```+GET https://public-api.birdeye.so/v1/wallet/portfolio+Headers: X-API-KEY: {BIRDEYE_API_KEY}+Params: wallet={walletAddress}&chain=solana+```++Returns portfolio with token holdings, prices, and P&L data.++For wallet trading history / realized P&L:+```+GET https://public-api.birdeye.so/v1/wallet/tx_list+Params: wallet={walletAddress}&chain=solana&tx_type=swap+```++---++## Architecture++### Backend endpoint++Create `api/kol/wallets.js` (or `api/kol/[wallet].js`) that proxies Birdeye:++```+GET /api/kol/wallets?addresses=addr1,addr2,...+```++- Takes a comma-separated list of wallet addresses+- Fetches portfolio + P&L from Birdeye for each+- Returns normalized P&L data+- Server-side only (Birdeye API key never sent to browser)+- Cache results for 60 seconds (use Upstash Redis if available, or in-memory `Map` with TTL)++Auth: can be public (read-only leaderboard data) or require session — match whatever the existing KOL UI expects.++### Frontend++Update `src/kol/wallets.js` to:+1. Remove the stub/hardcoded data+2. Fetch from `/api/kol/wallets?addresses=...`+3. Return the live P&L data in the same shape the callers expect++The data shape (confirm against actual current shape in the file):+```js+{+ address: '...',+ displayName: '...', // from existing config or ENS/SNS+ realizedPnl: 1234.56, // USD+ unrealizedPnl: 789.01,+ winRate: 0.73, // 0-1+ totalTrades: 142,+ topToken: { symbol: 'BONK', pnl: 500.00 },+}+```++---++## Files to create/edit++**Create:**+- `api/kol/wallets.js` — Birdeye proxy endpoint++**Edit:**+- `src/kol/wallets.js` — replace stub with fetch to backend++**Do not touch:**+- Any KOL UI components — the data shape must match what they already expect+- `api/pump-fun-mcp.js`++---++## Environment variables++- `BIRDEYE_API_KEY` — required. Add to `.env.example` if one exists.++---++## Acceptance criteria++1. With a real Solana wallet address that has trading history, `GET /api/kol/wallets?addresses=<addr>` returns non-zero P&L data.+2. The KOL leaderboard/widget shows live data instead of stubs.+3. The endpoint returns cached data on the second call within 60s (check response time or add a cache-hit header).+4. Without `BIRDEYE_API_KEY`, the endpoint returns `503` with `{ error: 'birdeye_not_configured' }`.+5. `npx vite build` passes. `node --check api/kol/wallets.js` passes.++## Constraints++- `BIRDEYE_API_KEY` must never be sent to the browser.+- Cache responses: Birdeye rate-limits free-tier keys to 100 req/min.+- If Birdeye returns an error for a specific wallet, return partial data for the other wallets rather than failing the whole request.+- No new npm dependencies — use `fetch` for the Birdeye API call.+- Match the existing data shape consumed by callers of `src/kol/wallets.js` exactly.diff --git a/prompts/tasks/livekit-voice-agent-runtime.md b/prompts/tasks/livekit-voice-agent-runtime.mdnew file mode 100644index 000000000..bd09610cd--- /dev/null+++ b/prompts/tasks/livekit-voice-agent-runtime.md@@ -0,0 +1,160 @@+# Task: Wire LiveKit realtime voice into the agent runtime++## Context++The project is three.ws — a platform for 3D AI agents.++The repo is at `/workspaces/3D-Agent`.++**What exists today:**++- `experiments/livekit-voice/` — An upstream clone of `livekit-examples/agent-starter-react`. A production-grade realtime voice agent built on LiveKit. Has a React frontend + a Python/Node agent server. It handles VAD (voice activity detection), STT (Whisper), LLM (GPT-4), and TTS in a continuous pipeline. We're interested in the LiveKit client SDK pattern, not running the experiment's server.++- `src/runtime/speech.js` — Current STT: `BrowserSTT` (uses `window.SpeechRecognition`). Current TTS: `BrowserTTS` or `ElevenLabsTTS`. Both are one-shot — the user clicks "listen", the agent speaks, then stops.++- `src/runtime/index.js` — The LLM brain loop. Calls `speech.speak(text)` and `speech.listen()` separately. No continuous conversation.++- `src/agent-protocol.js` — Event bus. Relevant events: `speak { text, sentiment }`, `listen-start {}`, `listen-end { text }`.++- `src/element.js` — The `<agent-3d>` web component. Has `voice` attribute (undocumented). The runtime is initialized here.++**The problem:** Voice interaction today is click-to-talk, one turn at a time. There's no continuous voice conversation where the user and agent take turns naturally. LiveKit enables low-latency bidirectional audio with server-side VAD and agent-side TTS — but nothing wires it to this project's agent runtime.++**The goal:** Add a `LiveKitVoice` class to `src/runtime/speech.js` that connects to a LiveKit room, streams microphone audio to a LiveKit agent server, and plays back agent TTS audio — integrating with the existing protocol bus (emit `speak` when agent talks, `listen-start`/`listen-end` when user talks).++---++## Architecture++### LiveKit room model++LiveKit uses a room abstraction. The 3D agent page joins a room as a "participant". A server-side LiveKit agent joins the same room and handles the voice pipeline. The agent server emits data messages to signal when it's speaking and what text it said, so the frontend can:+1. Drive avatar animations when agent speaks+2. Show transcripts++### What this task builds++A `LiveKitVoice` class in `src/runtime/speech.js`:++```js+export class LiveKitVoice {+ constructor({ serverUrl, token, protocol }) { ... }+ async connect() { ... } // join the room, set up tracks+ async disconnect() { ... } // leave cleanly+ get connected() { ... }+}+```++- `serverUrl`: LiveKit server WebSocket URL (e.g. `wss://...livekit.cloud`)+- `token`: room access token (JWT) — fetched from the backend (see below)+- `protocol`: the agent protocol event bus (`AgentProtocol` instance)++When the LiveKit agent server sends text (via data channel), `LiveKitVoice` emits `speak { text, sentiment: 0 }` on the protocol bus so `agent-avatar.js` can react to it.++When the microphone track is active (user speaking), it emits `listen-start {}`. When VAD detects end-of-speech, it emits `listen-end { text }` (text from transcript, if provided by server).++### Token endpoint++Add `api/agents/[id]/livekit-token.js`:++```+GET /api/agents/:id/livekit-token+```++Returns `{ token: string, serverUrl: string }`. Uses the LiveKit server SDK to generate a room access token for the agent room (room name: `agent-${agentId}`). Requires authentication (session or bearer).++Environment variables needed:+- `LIVEKIT_API_KEY`+- `LIVEKIT_API_SECRET`+- `LIVEKIT_SERVER_URL`++### Frontend integration++In `src/element.js`, when the `voice="livekit"` attribute is set:+1. Fetch `GET /api/agents/:id/livekit-token` for the token+2. Instantiate `LiveKitVoice({ serverUrl, token, protocol })`+3. Call `voice.connect()`+4. On element disconnect/destroy, call `voice.disconnect()`++---++## Files to create/edit++**Create:**+- `api/agents/[id]/livekit-token.js` — token endpoint. Use `livekit-server-sdk` (check if it's a project dep; if not, use `@livekit/agents` or generate the JWT manually using `jose` which IS a project dep — see LiveKit JWT format below).+- `src/runtime/livekit-voice.js` — `LiveKitVoice` class. Import `LivekitClient` from `livekit-client` npm package.++**Edit:**+- `src/runtime/speech.js` — export `LiveKitVoice` from `livekit-voice.js` via re-export for clean import surface. Add `createVoice(config)` factory that returns a `LiveKitVoice` when `config.provider === 'livekit'`.+- `src/element.js` — handle `voice="livekit"` attribute. Fetch token, connect, disconnect on cleanup.++**Do not touch:**+- `BrowserTTS`, `BrowserSTT`, `ElevenLabsTTS` — these remain as alternatives+- `src/agent-avatar.js` — it already reacts to `speak` events on the protocol bus++---++## LiveKit JWT format (if generating without server SDK)++```js+// Using `jose` (already a dep) to sign a LiveKit access token+import { SignJWT } from 'jose';+const secret = new TextEncoder().encode(process.env.LIVEKIT_API_SECRET);+const token = await new SignJWT({+ video: { roomJoin: true, room: roomName, canPublish: true, canSubscribe: true },+ sub: `user-${userId}`,+ iss: process.env.LIVEKIT_API_KEY,+ nbf: Math.floor(Date.now() / 1000),+ exp: Math.floor(Date.now() / 1000) + 3600,+}).setProtectedHeader({ alg: 'HS256' }).sign(secret);+```++---++## LiveKit client pattern (reference from experiment)++```js+import { Room, RoomEvent, Track } from 'livekit-client';++const room = new Room();+await room.connect(serverUrl, token);++// Publish microphone+await room.localParticipant.setMicrophoneEnabled(true);++// Listen for agent audio+room.on(RoomEvent.TrackSubscribed, (track, pub, participant) => {+ if (track.kind === Track.Kind.Audio) {+ const el = track.attach(); // returns <audio> element+ document.body.appendChild(el);+ }+});++// Listen for data messages from agent+room.on(RoomEvent.DataReceived, (data, participant) => {+ const msg = JSON.parse(new TextDecoder().decode(data));+ if (msg.type === 'transcript') {+ protocol.emit('speak', { text: msg.text, sentiment: 0 });+ }+});+```++---++## Acceptance criteria++1. Set `voice="livekit"` on `<agent-3d agent-id="...">`. The element fetches a token and connects to LiveKit.+2. Speak into the microphone — the LiveKit agent hears it and responds. The response audio plays through the browser.+3. When the agent responds, `agent-avatar.js` reacts to the `speak` event (emotion + lipsync if task `talkinghead-lipsync-agent-runtime.md` is also complete).+4. Removing the element (or navigating away) cleanly disconnects the room — no dangling audio tracks or event listeners.+5. Without `LIVEKIT_*` env vars set, the token endpoint returns a clear `503` with `{ error: 'livekit_not_configured' }` — it does not crash.+6. Without `voice="livekit"`, existing `BrowserSTT`/`BrowserTTS` behavior is unchanged.+7. `npx vite build` passes. `node --check src/runtime/livekit-voice.js` passes.++## Constraints++- `livekit-client` is the official npm package for the browser SDK. Check if it's already a project dependency (`package.json`). If not, add it. This is the one new dependency this task may introduce.+- `livekit-server-sdk` may be used on the backend if already present; otherwise generate the JWT with `jose`.+- ESM only. Tabs, 4-wide. Match existing style.+- `LiveKitVoice` must not import `agent-avatar.js` or anything from the emotion layer — use the protocol bus only.+- All audio cleanup (tracks, subscriptions, room) must happen in `disconnect()` to prevent memory leaks.diff --git a/prompts/tasks/lobehub-spec-resolution.md b/prompts/tasks/lobehub-spec-resolution.mdnew file mode 100644index 000000000..51a036d1b--- /dev/null+++ b/prompts/tasks/lobehub-spec-resolution.md@@ -0,0 +1,136 @@+# Task: Resolve LobeHub integration spec unknowns before running integration tasks++## Context++The project is three.ws — a platform for 3D AI agents.++The repo is at `/workspaces/3D-Agent`.++The `prompts/lobehub-embed/` directory contains 8 tasks (00–08) for integrating three.ws agents into LobeHub (a popular open-source chat UI). Before any of those tasks can be run, several spec unknowns need to be resolved.++**Read `prompts/lobehub-embed/AUDIT.md` in full** — it documents all 6 categories of drift between the tasks as written and the current codebase. This task is to fix those spec issues.++The key unknowns from the audit:++1. **"The user's LobeHub fork" is undefined** — every task references it but never says what it is. We need to establish: repo URL, branch, version pin, local path.++2. **Task numbering collision in 06/07/08** — internal headers say "Task 01", "Task 03", "Task 04" but filenames are 06, 07, 08. Needs renumbering or explicit sub-stack labeling.++3. **6 `TODO(lobehub-spec)` comments** — in tasks 01–05, there are inline comments like `TODO(lobehub-spec): confirm the plugin manifest URL format` that were left for resolution. These need concrete answers before implementation.++4. **Stale repo path** — tasks say `/workspaces/3D` but the actual path is `/workspaces/3D-Agent`. Low impact (agents use their own working path) but should be corrected in the audit notes.++5. **Missing fast-path task** — `00-fork-sidebar-fastpath.md` was added to address the lack of a sidebar shortcut, but it hasn't been integrated into the README ordering.++6. **Uneven sub-stack ordering** — Tasks 06/07/08 are a "host SDK sub-stack" that depends on tasks 01–05 being complete first, but this is not documented.++---++## What to do++### Step 1: Establish the LobeHub fork++Check if there's a LobeHub fork linked anywhere in the project:+- `package.json` / `chat/package.json` — any `lobe-chat` dep or fork URL?+- `.gitmodules` — any LobeHub submodule?+- `prompts/lobehub-embed/README.md` — any fork URL mentioned?+- Git remote: `git remote -v` — any LobeHub remote?++If no fork is found, document the fact clearly in `prompts/lobehub-embed/FORK.md`:+```md+# LobeHub Fork++Status: NOT YET SET UP++Before running any lobehub-embed tasks, complete these steps:++1. Fork https://github.com/lobehub/lobe-chat+2. Note the fork URL here+3. Clone locally: `git clone <fork-url> ../lobe-chat-fork`+4. Note the local path here+5. Note the LobeHub version (check package.json in the fork): vX.Y.Z++Once done, fill in:+- Fork URL:+- Local path:+- Branch:+- LobeHub version:+```++### Step 2: Resolve the 6 TODO(lobehub-spec) comments++Read tasks 01–05 and find every `TODO(lobehub-spec):` comment. For each one, research the answer:++- Check LobeHub's plugin documentation: https://lobehub.com/docs/usage/plugins/development+- Check LobeHub's GitHub: https://github.com/lobehub/lobe-chat (plugin system, manifest format, iframe handshake protocol)+- Look at existing LobeHub plugins for reference implementations++For each resolved TODO, update the task file in-place — replace the `TODO(lobehub-spec):` comment with the actual answer.++Expected TODOs to resolve (verify by reading the files):+- Plugin manifest URL format and schema+- The iframe `postMessage` handshake protocol (what messages, in what order, with what payloads)+- The plugin auth handoff mechanism (how LobeHub passes user auth to the plugin iframe)+- The plugin message renderer format (how custom message types appear in the chat timeline)+- Any LobeHub version pinning requirements++### Step 3: Fix task numbering in 06/07/08++Update internal headers in:+- `prompts/lobehub-embed/06-host-sdk-package.md` — change `# Task 01` to `# Task 06 — @3dagent/embed host SDK package`+- `prompts/lobehub-embed/07-message-renderer.md` — change `# Task 03` to `# Task 07 — In-chat message renderer`+- `prompts/lobehub-embed/08-mention-autocomplete.md` — change `# Task 04` to `# Task 08 — @ autocomplete for agents`++Also update internal "Depends on task 03" references in 08 to "Depends on task 07."++### Step 4: Update the README++Update `prompts/lobehub-embed/README.md` to:+- Add task 00 to the ordered list+- Mark tasks 06/07/08 as "Host SDK sub-stack" with a note they depend on 01–05+- Add a "Prerequisites" section pointing to `FORK.md`++---++## Files to create/edit++**Create:**+- `prompts/lobehub-embed/FORK.md` — fork setup instructions + status++**Edit:**+- `prompts/lobehub-embed/01-plugin-manifest.md` — resolve TODO(lobehub-spec) comments+- `prompts/lobehub-embed/02-iframe-handshake.md` — resolve TODO(lobehub-spec) comments+- `prompts/lobehub-embed/03-host-auth-handoff.md` — resolve TODO(lobehub-spec) comments+- `prompts/lobehub-embed/04-action-passthrough.md` — resolve TODO(lobehub-spec) comments+- `prompts/lobehub-embed/05-plugin-submission.md` — resolve TODO(lobehub-spec) comments+- `prompts/lobehub-embed/06-host-sdk-package.md` — fix internal header+- `prompts/lobehub-embed/07-message-renderer.md` — fix internal header+- `prompts/lobehub-embed/08-mention-autocomplete.md` — fix internal header + dependency ref+- `prompts/lobehub-embed/README.md` — add task 00, sub-stack labels, prerequisites++**Do not touch:**+- `prompts/lobehub-embed/00-fork-sidebar-fastpath.md` — already correct+- Any implementation code++---++## Acceptance criteria++1. Every `TODO(lobehub-spec):` comment in tasks 01–05 is replaced with a concrete answer or marked `UNRESOLVABLE: <reason>` if the answer genuinely cannot be determined without the fork.+2. Tasks 06, 07, 08 have correct internal header numbers matching their filenames.+3. `prompts/lobehub-embed/FORK.md` exists and gives clear setup instructions.+4. `prompts/lobehub-embed/README.md` includes task 00 and marks the 06/07/08 sub-stack.+5. Running any lobehub-embed task after this should not hit a `TODO(lobehub-spec)` blocker.++## Research resources++- LobeHub plugin development docs: https://lobehub.com/docs/usage/plugins/development+- LobeHub plugin schema: https://github.com/lobehub/lobe-chat-plugins+- LobeHub source (plugin system): https://github.com/lobehub/lobe-chat/tree/main/src/services/plugin+- Existing community plugins: https://github.com/lobehub/lobe-chat-plugins/tree/main/plugins++## Constraints++- Do not start implementing any lobehub-embed feature. This task is research + documentation only.+- If a TODO requires testing against the actual LobeHub fork and the fork isn't set up, mark it `BLOCKED: requires fork setup` rather than guessing.+- Keep task file edits surgical — only replace the TODO comment and immediately surrounding context, don't rewrite the tasks.diff --git a/prompts/tasks/mcp-endpoint-auth-hardening.md b/prompts/tasks/mcp-endpoint-auth-hardening.mdnew file mode 100644index 000000000..3451d0e91--- /dev/null+++ b/prompts/tasks/mcp-endpoint-auth-hardening.md@@ -0,0 +1,122 @@+# Task: Harden authentication on the MCP endpoint++## Context++The project is three.ws — a platform for 3D AI agents.++The repo is at `/workspaces/3D-Agent`.++**What exists:**++- `api/mcp.js` — ~40KB file. The MCP (Model Context Protocol) 2025-06-18 endpoint over HTTP. Exposed at `/api/mcp`. Tools: `list_my_avatars`, `get_avatar`, `search_public_avatars`, `render_avatar`, `delete_avatar`, `validate_model`, `inspect_model`, `optimize_model`. Has per-tool rate limits.++**Read `api/mcp.js` in full before starting.** The file is large and complex — understand what it does before making any changes.++**The concern:** MCP endpoints are a common attack vector because:+1. They're designed to be called by AI agents (automated, not human)+2. They operate on behalf of users (accessing their avatars, potentially deleting data)+3. Rate limits need to be tight enough to prevent enumeration and abuse++**Potential issues to look for in the current implementation:**+- Does `delete_avatar` require explicit confirmation or just a single call?+- Are rate limits enforced per authenticated user, or just per IP?+- Does the endpoint validate that the requested avatar belongs to the authenticated user before operating on it?+- Is there a maximum on the `search_public_avatars` result set to prevent bulk enumeration?+- Are error messages informative enough to be useful but not so verbose they leak internals?++---++## What to audit++Read `api/mcp.js` and check for these specific issues:++### 1. Ownership checks on destructive operations++Every tool that modifies or deletes a specific avatar must verify ownership:+```js+// For tools that take an avatar ID:+const avatar = await sql`SELECT owner_id FROM avatars WHERE id = ${avatarId}`;+if (!avatar[0] || avatar[0].owner_id !== userId) {+ return toolError('not_found', 'Avatar not found');+}+```++If this check is missing for `delete_avatar` or `render_avatar` (which could be expensive), add it.++### 2. Per-user rate limits, not just per-IP++MCP clients send an `Authorization: Bearer <api_key>` header. Rate limits should be based on the API key / user ID, not the IP address — otherwise all requests from a shared cloud provider IP share the same bucket.++Check if `limits.authIp` is used (mixes auth+IP) or if there's a separate `limits.authUser`. If limits are IP-only, add a user-level rate limit for authenticated requests.++### 3. delete_avatar guard++Destructive operations should require a confirmation parameter or at minimum log an audit trail:++```js+// In the delete_avatar tool handler:+if (!args.confirm) {+ return toolError('confirmation_required',+ 'Set confirm: true to permanently delete this avatar');+}+// Log the deletion+await sql`INSERT INTO audit_log (user_id, action, resource_id, created_at)+ VALUES (${userId}, 'delete_avatar', ${args.avatarId}, now())`;+```++### 4. Search enumeration limit++`search_public_avatars` should cap results and prevent cursor-based full enumeration by anonymous callers. If unauthenticated, limit to 10 results with no pagination.++### 5. Error message hygiene++MCP tool errors should not expose internal error messages (SQL errors, stack traces). All errors should go through a sanitizer:++```js+function toolError(code, message) {+ return { error: code, error_description: message };+ // Never return e.message from a caught exception directly+}+```++---++## What to fix++After reading the file, fix the specific issues you find. Typical fixes:+- Add ownership checks where missing+- Add `confirm: true` guard to `delete_avatar`+- Add audit log insert for destructive operations (check if `audit_log` table exists in schema; if not, just add a comment noting it's needed)+- Tighten search pagination for unauthenticated callers+- Sanitize error messages++---++## Files to edit++**Edit:**+- `api/mcp.js` — targeted hardening fixes++**Do not touch:**+- The MCP protocol framing (request/response format)+- Any tool that doesn't have a security issue+- Rate limit configuration for non-destructive read tools++---++## Acceptance criteria++1. `DELETE_AVATAR` with no `confirm` parameter returns an error asking for confirmation.+2. Requesting another user's avatar via any tool returns `not_found` (not `forbidden` — don't leak the existence of other users' avatars).+3. Rate limits are enforced per user (not just per IP) for authenticated requests.+4. `search_public_avatars` without authentication returns at most 10 results.+5. No SQL error messages appear in MCP tool responses.+6. `npx vite build` passes. `node --check api/mcp.js` passes.+7. Existing MCP tool functionality is unaffected for legitimate authenticated use.++## Constraints++- Surgical changes only — this is a security hardening pass, not a refactor.+- Don't change the tool names, input schemas, or output shapes — MCP clients depend on these.+- Don't add new tools in this task.+- Follow the API pattern in `api/CLAUDE.md` for any new DB queries.diff --git a/prompts/tasks/memory-encrypted-ipfs.md b/prompts/tasks/memory-encrypted-ipfs.mdnew file mode 100644index 000000000..d0bd738f0--- /dev/null+++ b/prompts/tasks/memory-encrypted-ipfs.md@@ -0,0 +1,201 @@+# Task: Complete the encrypted-IPFS memory mode in src/memory/index.js++## Context++The project is three.ws — a platform for 3D AI agents.++The repo is at `/workspaces/3D-Agent`.++`src/memory/index.js` implements a file-based memory system for agents — human-readable `.md` files with YAML frontmatter, an auto-generated `MEMORY.md` index, and an append-only timeline. It supports four storage modes: `local`, `ipfs`, `encrypted-ipfs`, and `none`.++**Current state of the modes:**++- `local` — fully implemented: stores to `localStorage`, files are plain text+- `none` — fully implemented: noop+- `ipfs` — partially implemented: fetches memory files from an IPFS/Arweave gateway on load+- `encrypted-ipfs` — **stub only**: the `Memory.load()` method routes to `_loadIPFS()` for both `ipfs` and `encrypted-ipfs`, but the encrypted path does nothing different — it just loads plaintext files from IPFS same as the regular IPFS mode++The spec for `encrypted-ipfs` mode:+- Memory files are encrypted before being pinned to IPFS+- Only the agent's private key (or a derived key from the agent's wallet) can decrypt them+- This is the mode used for agents with on-chain identity (ERC-8004) who want private memory++**The goal:** Implement the `encrypted-ipfs` mode end-to-end:+1. Encrypt memory files before IPFS upload using AES-256-GCM with a key derived from the agent's wallet signature+2. Decrypt on load+3. Pin encrypted files to IPFS via the backend `/api/agents/:id/memory/pin` endpoint (to be created)++---++## Cryptography design++### Key derivation++The encryption key is derived deterministically from the agent's wallet:+```+key material = ECDH_sign(wallet, "three.ws:memory:v1:" + agentId)+```++In practice, using `ethers.js` Wallet (already a project dep):+```js+const signature = await signer.signMessage(`three.ws:memory:v1:${agentId}`);+// signature is 65 bytes (132 hex chars)+// Use first 32 bytes as AES key material+const keyBytes = ethers.getBytes(signature).slice(0, 32);+const cryptoKey = await crypto.subtle.importKey(+ 'raw', keyBytes, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']+);+```++This key is deterministic: the same wallet + agentId always produces the same key. No key storage needed — re-derive on load.++### Encryption of a single file++```js+async function encryptFile(cryptoKey, plaintext) {+ const iv = crypto.getRandomValues(new Uint8Array(12));+ const encoded = new TextEncoder().encode(plaintext);+ const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, cryptoKey, encoded);+ // Pack: [12 bytes iv][ciphertext]+ const out = new Uint8Array(12 + ciphertext.byteLength);+ out.set(iv, 0);+ out.set(new Uint8Array(ciphertext), 12);+ return out; // Uint8Array+}++async function decryptFile(cryptoKey, packed) {+ const iv = packed.slice(0, 12);+ const ciphertext = packed.slice(12);+ const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, cryptoKey, ciphertext);+ return new TextDecoder().decode(plain);+}+```++On IPFS, store the encrypted bytes as-is (binary). The CID then references a binary blob, not a text file.++---++## Backend endpoint++**Create `api/agents/[id]/memory/pin.js`:**++```+POST /api/agents/:id/memory/pin+Body: { filename: string, data: string } (data is base64url-encoded encrypted bytes)+Returns: { cid: string }+```++This endpoint:+1. Authenticates the request (session or bearer, agent ownership check)+2. Decodes the base64url data+3. Pins to IPFS/Arweave via the existing `src/ipfs.js` gateway pattern — use the Cloudflare R2 + Pinata or Web3.Storage integration already in the project (check `api/_lib/r2.js` and any existing IPFS pinning code in `api/`)+4. Returns the CID++Also **create `api/agents/[id]/memory/[cid].js`:**++```+GET /api/agents/:id/memory/:cid+Returns: binary (encrypted bytes) with Content-Type: application/octet-stream+```++Fetches the encrypted blob from IPFS/R2 and streams it back. Requires agent ownership to prevent enumeration.++---++## Changes to src/memory/index.js++### Memory class constructor++Add `cryptoKey` field:+```js+constructor({ mode, namespace, index, files, timeline, cryptoKey } = {}) {+ ...+ this.cryptoKey = cryptoKey || null;+}+```++### Memory._loadIPFS (update)++```js+static async _loadIPFS({ mode, namespace, manifestURI, fetchFn, deriveKey }) {+ // For encrypted-ipfs: call deriveKey() to get the CryptoKey+ const cryptoKey = mode === 'encrypted-ipfs' ? await deriveKey() : null;++ const base = manifestURI.replace(/manifest\.json$/, '');+ const idxRes = await fetchFn(`${base}memory/MEMORY.md`);+ // ... existing fetch logic ...++ // For encrypted-ipfs: decrypt each file after fetching+ if (mode === 'encrypted-ipfs' && cryptoKey) {+ for (const [filename, content] of files) {+ // content is base64url-encoded encrypted bytes (from IPFS)+ const encrypted = base64urlDecode(content);+ const plain = await decryptFile(cryptoKey, encrypted);+ files.set(filename, plain);+ }+ }++ return new Memory({ mode, namespace, index: ..., files: ..., timeline: ..., cryptoKey });+}+```++### Memory.save (update)++When `mode === 'encrypted-ipfs'`:+1. For each dirty file, encrypt it using `this.cryptoKey`+2. POST the encrypted bytes (base64url) to `/api/agents/${namespace}/memory/pin`+3. Get back a CID+4. Update the `MEMORY.md` index with `ipfs://<cid>` links instead of relative paths++### Memory.load static method (update)++Pass `deriveKey` function through when `mode === 'encrypted-ipfs'`:+```js+static async load({ mode, namespace, manifestURI, fetchFn, deriveKey }) {+ if (mode === 'encrypted-ipfs') {+ if (!deriveKey) throw new Error('encrypted-ipfs mode requires a deriveKey function');+ return Memory._loadIPFS({ mode, namespace, manifestURI, fetchFn, deriveKey });+ }+ // ...+}+```++### Caller update++`src/manifest.js` or wherever `Memory.load()` is called — pass a `deriveKey` function when mode is `encrypted-ipfs`. The `deriveKey` function calls `signer.signMessage(...)` as described above. The signer comes from the agent's wallet (already wired in `src/erc8004/agent-registry.js`).++---++## Files to create/edit++**Create:**+- `api/agents/[id]/memory/pin.js`+- `api/agents/[id]/memory/[cid].js`++**Edit:**+- `src/memory/index.js` — implement encrypt/decrypt in `_loadIPFS`, update `save()` for encrypted-ipfs++**Do not touch:**+- `local` mode behavior+- `ipfs` mode behavior (plaintext IPFS — unchanged)+- `src/agent-memory.js` (the in-memory store — separate)++---++## Acceptance criteria++1. Create a `Memory` instance with `mode: 'encrypted-ipfs'`, add some entries, call `save()`. The IPFS-pinned files are binary (not readable as text). The `MEMORY.md` index contains `ipfs://Qm...` CIDs.+2. Create a new `Memory` instance loading from the same manifest — all entries are recovered correctly.+3. Loading with a wrong key (different wallet signature) produces a `DOMException: The operation failed for an operation-specific reason` — not a crash.+4. `ipfs` mode (plaintext) is completely unaffected.+5. `local` mode is completely unaffected.+6. `POST /api/agents/:id/memory/pin` returns a CID. `GET /api/agents/:id/memory/:cid` returns the encrypted bytes.+7. `npx vite build` passes. `node --check src/memory/index.js` passes.++## Constraints++- ESM only. Tabs, 4-wide.+- Use `crypto.subtle` (Web Crypto API) — no third-party crypto library.+- `ethers` is already a project dep — use it for wallet signing. Don't add a new dep.+- The `deriveKey` function is provided by the caller — `memory/index.js` has no direct dependency on `ethers` or wallet code.+- API endpoints follow the pattern in `api/CLAUDE.md` exactly.diff --git a/prompts/tasks/memory-semantic-embeddings.md b/prompts/tasks/memory-semantic-embeddings.mdnew file mode 100644index 000000000..03eec0532--- /dev/null+++ b/prompts/tasks/memory-semantic-embeddings.md@@ -0,0 +1,136 @@+# Task: Replace substring search in AgentMemory with semantic embeddings++## Context++The project is three.ws — a platform for 3D AI agents.++The repo is at `/workspaces/3D-Agent`.++`src/agent-memory.js` is the in-browser memory store for agent state. Its `query()` method currently does a plain substring match:++```js+// src/agent-memory.js — current query logic (around line 80-100)+query({ type, tags, limit = 50, since = 0 } = {}) {+ const now = Date.now();+ let results = this._entries.filter((m) => {+ if (m.expiresAt && m.expiresAt < now) return false;+ if (since && m.createdAt < since) return false;+ if (type && m.type !== type) return false;+ if (tags?.length) return tags.some((t) => m.tags.includes(t));+ return true;+ });+ return results+ .sort((a, b) => b.salience - a.salience || b.createdAt - a.createdAt)+ .slice(0, limit);+}+```++The CLAUDE.md for this module notes: *"`memory.recall()` is substring search. No embeddings yet."*++There is no `recall()` method yet — it's a placeholder concept. The LLM runtime at `src/runtime/index.js` calls `memory.query(opts)` when it needs to inject context before the LLM call.++**The problem:** An agent that remembers "the user prefers dark mode" won't surface that memory when the user asks about "theme" or "appearance" — because there's no "dark mode" substring match. Semantic search would catch the intent.++**The goal:** Add a `recall(queryText, opts)` method to `AgentMemory` that does semantic similarity search using Anthropic's embeddings API, falling back to the existing `query()` if embeddings are unavailable or not yet stored.++---++## Architecture++### Embedding storage++Each `MemoryEntry` gets an optional `embedding` field — a `Float32Array` or plain `number[]` of 1024 floats (Anthropic `voyage-3-lite` model produces 1024-dim vectors). Embeddings are generated lazily: when a memory is added and an embed function is available, embed it immediately. For existing memories without embeddings, fall back to substring search.++### Embedding function++The agent runtime already proxies API calls through the backend. Add a thin endpoint `GET /api/agents/:id/embed?text=...` (or `POST` with body) that calls Anthropic's embedding endpoint and returns the vector. The `AgentMemory` constructor accepts an optional `embedFn: async (text) => number[]` — this keeps the memory module decoupled from the specific API client.++### Cosine similarity++```js+function cosineSim(a, b) {+ let dot = 0, na = 0, nb = 0;+ for (let i = 0; i < a.length; i++) { dot += a[i]*b[i]; na += a[i]*a[i]; nb += b[i]*b[i]; }+ return dot / (Math.sqrt(na) * Math.sqrt(nb));+}+```++### recall() method++```js+async recall(queryText, { type, limit = 10, minScore = 0.75 } = {}) {+ // 1. If no embedFn, fall back to query() substring match+ // 2. Embed queryText+ // 3. Filter to entries that have embeddings (skip ones without)+ // 4. Score each entry's embedding against queryText embedding via cosineSim+ // 5. Also include entries without embeddings that pass the old substring filter+ // 6. Sort by score descending, return top `limit`+}+```++---++## Files to create/edit++**Create:**+- `api/agents/[id]/embed.js` — thin Vercel endpoint. `GET ?text=...` or `POST { text }`. Calls Anthropic embeddings API. Returns `{ embedding: number[] }`. Use the `wrap`, `error`, `json` helpers from `api/_lib/http.js`. Auth: session or bearer. Rate limit: use `limits.authIp`.++ Anthropic embedding call:+ ```js+ import Anthropic from '@anthropic-ai/sdk';+ const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });+ const response = await client.embeddings.create({+ model: 'voyage-3-lite',+ input: [text],+ input_type: 'query',+ });+ return response.embeddings[0].embedding;+ ```++**Edit:**+- `src/agent-memory.js`:+ - `constructor`: accept `{ embedFn }` in opts+ - `add()`: after storing, if `embedFn` available, call it async and store result in `mem.embedding` (fire-and-forget, don't block `add()`)+ - Add `async recall(queryText, opts)` method+ - Export the `cosineSim` helper (for testing)++- `src/runtime/index.js`: pass `embedFn` to `AgentMemory` constructor. The embed function should call `fetch('/api/agents/${agentId}/embed', { method:'POST', body: JSON.stringify({text}), headers: {'content-type':'application/json'}, credentials:'include' })` and return the embedding array.++**Do not touch:**+- Existing `query()` method behavior — `recall()` is additive+- `src/memory/index.js` (the file-based memory variant — separate concern)+- Any viewer or avatar files++---++## Endpoint shape++`POST /api/agents/:id/embed`++Request body: `{ text: string }`++Response `200`: `{ embedding: number[] }` (1024 floats)++Error cases:+- 400 if `text` is empty or > 8192 chars+- 401 if not authenticated+- 429 if rate limited++---++## Acceptance criteria++1. Call `memory.add({ type: 'user', content: 'prefers dark mode', tags: [] })` — the entry gets an embedding attached.+2. Call `await memory.recall('what theme does the user like?')` — the "dark mode" entry comes back in the top results even though no substring matches.+3. Call `memory.query({ type: 'user' })` — still works unchanged (no regression).+4. If `embedFn` is not provided (default), `recall()` falls back to the existing substring-based `query()` and returns a resolved promise.+5. `POST /api/agents/:id/embed` returns a 1024-element array for a sample text.+6. `npx vite build` passes. `node --check src/agent-memory.js` passes.++## Constraints++- ESM only. Tabs, 4-wide. Match existing style in `src/`.+- The Anthropic SDK is already a project dependency — don't add it again.+- Embedding generation is fire-and-forget on `add()` — never block the caller.+- `recall()` must work even if some entries have no embeddings (skip scoring them, include via substring fallback instead).+- API endpoint follows the pattern in `api/CLAUDE.md` exactly — use `wrap`, `cors`, `method`, `error`, `json` helpers.diff --git a/prompts/tasks/privy-auth-element-flow.md b/prompts/tasks/privy-auth-element-flow.mdnew file mode 100644index 000000000..d9973651c--- /dev/null+++ b/prompts/tasks/privy-auth-element-flow.md@@ -0,0 +1,189 @@+# Task: Complete the Privy OAuth auth flow in element.js++## Context++The project is three.ws — a platform for 3D AI agents.++The repo is at `/workspaces/3D-Agent`.++**What exists:**++- `src/element.js` — The `<agent-3d>` custom element. On boot it:+ 1. Loads the agent manifest+ 2. Initializes the viewer (Three.js WebGL)+ 3. Starts the agent runtime (LLM brain)++ It has an `auth` attribute (values: `"none"` | `"privy"` | `"siwe"`). When `auth="privy"` is set, there is a comment in the code indicating Privy should handle auth, but the flow is not implemented — it just skips auth.++- `src/erc8004/privy.js` — Privy integration hooks. Has functions for initializing the Privy client, handling the redirect callback, and getting the authenticated user. But these are not called from `element.js`.++- `api/auth/[action].js` — Backend auth. Handles `login` (email+password), `logout`, `me`. Has `createSession()` which writes `__Host-sid` cookie.++- `api/auth/privy-callback.js` — Likely exists or needs creation. Privy OAuth callback handler that exchanges a Privy JWT for a session cookie.++- `api/_lib/auth.js` — `createSession()`, `getSessionUser()`, `sessionCookie()`. The session model is solid.++**The problem:** `auth="privy"` on `<agent-3d>` does nothing. Privy is a Web3 auth platform that supports email, SMS, social (Google/Twitter/Discord), and wallet sign-in. The hooks exist (`src/erc8004/privy.js`) but aren't wired to the element's boot flow or the backend session.++**The goal:** When `auth="privy"` is set on the element:+1. On boot, check if there's an existing session (`GET /api/auth/me`)+2. If not authenticated, show a Privy login modal+3. After Privy login succeeds, exchange the Privy JWT for a backend session cookie (via `POST /api/auth/privy-callback`)+4. Proceed with normal element boot (manifest load, viewer, runtime)+5. On sign-out, destroy the session++This is distinct from the SIWE wallet auth task (`wallet-auth/` prompts) — Privy handles its own wallet auth internally. This task is specifically about using Privy as the auth provider for the `<agent-3d>` element.++---++## Privy integration pattern++Privy provides a JS SDK (`@privy-io/js-sdk-core` or `@privy-io/react-auth`). Since this project is vanilla JS (not React), use `@privy-io/js-sdk-core`.++Check `package.json` — if `@privy-io/js-sdk-core` or similar is already a dependency, use it. If not, add it.++```js+import { PrivyClient } from '@privy-io/js-sdk-core';++const privy = new PrivyClient(PRIVY_APP_ID, {+ // config options+});++// Login flow+const { user } = await privy.login();+// user.id is the Privy DID+// user.wallet?.address is the connected wallet (if any)++// Get JWT for backend verification+const token = await privy.getAccessToken();+// POST this token to /api/auth/privy-callback+```++`PRIVY_APP_ID` comes from `VITE_PRIVY_APP_ID` env var.++---++## Backend: privy-callback endpoint++**Create or update `api/auth/privy-callback.js`:**++```+POST /api/auth/privy-callback+Body: { token: string } — Privy JWT (access token)+```++Verifies the Privy JWT using Privy's public JWKS endpoint, then:+1. Extracts the Privy user ID (`sub` claim) and optionally wallet address+2. Upserts a user record in the `users` table (create if first login, or find by privy_id)+3. Creates a session cookie via `createSession()`+4. Returns `{ user: { id, email, displayName } }`++Privy JWKS verification:+```js+import { createRemoteJWKSet, jwtVerify } from 'jose';+const JWKS = createRemoteJWKSet(new URL('https://auth.privy.io/api/v1/apps/{appId}/jwks.json'));+const { payload } = await jwtVerify(token, JWKS, { issuer: 'privy.io' });+// payload.sub = Privy user ID+```++The `users` table needs a `privy_id` column if it doesn't have one. Check `api/_lib/schema.sql`. If missing:+```sql+ALTER TABLE users ADD COLUMN IF NOT EXISTS privy_id text UNIQUE;+CREATE UNIQUE INDEX IF NOT EXISTS users_privy_id_unique ON users (privy_id) WHERE privy_id IS NOT NULL;+```++Add this migration to `api/_lib/schema.sql` AND create `specs/schema/NNN-privy-auth.sql` (use the next available number).++---++## Changes to element.js++In the element's `connectedCallback()` or `_boot()` method, add an auth gate before the manifest/viewer init:++```js+async _boot() {+ const authMode = this.getAttribute('auth') || 'none';++ if (authMode === 'privy') {+ const authed = await this._ensurePrivyAuth();+ if (!authed) return; // login modal shown, boot will resume after redirect+ }++ // ... existing boot: load manifest, init viewer, start runtime ...+}++async _ensurePrivyAuth() {+ // 1. Check existing session+ const me = await fetch('/api/auth/me', { credentials: 'include' });+ if (me.ok) return true; // already authed++ // 2. Init Privy and trigger login+ const { initPrivy, loginWithPrivy, exchangePrivyToken } = await import('./erc8004/privy.js');+ const appId = import.meta.env.VITE_PRIVY_APP_ID;+ if (!appId) {+ console.warn('[agent-3d] VITE_PRIVY_APP_ID not set — skipping Privy auth');+ return true; // degrade gracefully+ }++ const token = await loginWithPrivy(appId); // shows Privy modal, returns JWT+ if (!token) return false;++ // 3. Exchange for backend session+ const res = await fetch('/api/auth/privy-callback', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ token }),+ credentials: 'include',+ });++ return res.ok;+}+```++---++## Changes to src/erc8004/privy.js++Implement or complete `loginWithPrivy(appId)`:+- Initializes Privy SDK with `appId`+- Shows the login modal+- Returns the Privy access token JWT on success+- Returns null if the user cancels++---++## Files to create/edit++**Create:**+- `api/auth/privy-callback.js`+- `specs/schema/NNN-privy-auth.sql` (next available migration number)++**Edit:**+- `api/_lib/schema.sql` — add `privy_id` column to `users`+- `src/element.js` — add `_ensurePrivyAuth()`, call it in `_boot()` when `auth="privy"`+- `src/erc8004/privy.js` — implement `loginWithPrivy(appId)` returning a JWT or null++**Do not touch:**+- SIWE auth endpoints (`/api/auth/siwe/`)+- Email/password auth+- Session cookie format (`__Host-sid`)++---++## Acceptance criteria++1. Set `<agent-3d auth="privy" agent-id="...">` on a page. On load, the Privy login modal appears.+2. Log in with an email or Google account. The modal closes. The element boots normally (viewer loads, agent starts).+3. Refresh the page — still logged in (session cookie persists).+4. `GET /api/auth/me` returns the user record.+5. `<agent-3d auth="none">` — Privy is not loaded, no modal, element boots immediately.+6. `VITE_PRIVY_APP_ID` unset — element logs a warning and boots without auth (degrades gracefully).+7. `npx vite build` passes. `node --check api/auth/privy-callback.js` passes.++## Constraints++- ESM only in `src/`. API endpoints use CommonJS-style `export default wrap(...)` pattern from `api/CLAUDE.md`.+- Use `jose` for JWT verification (already a dep). Do not add `jsonwebtoken`.+- The Privy SDK (`@privy-io/js-sdk-core`) may be added as a new dep if not present.+- `src/element.js` must not break when `auth` attribute is absent or set to `"none"` or `"siwe"`.+- Don't hardcode the Privy app ID anywhere — always read from `VITE_PRIVY_APP_ID`.diff --git a/prompts/tasks/pump-swap-inner-ix.md b/prompts/tasks/pump-swap-inner-ix.mdnew file mode 100644index 000000000..2a5b03e2e--- /dev/null+++ b/prompts/tasks/pump-swap-inner-ix.md@@ -0,0 +1,147 @@+# Task: Implement the skipped pump-swap inner instruction in the cron job++## Context++The project is three.ws — a platform for 3D AI agents with Pump.fun token trading capabilities.++The repo is at `/workspaces/3D-Agent`.++**What exists:**++- `api/cron/[name].js` — A Vercel cron endpoint that handles periodic lifecycle jobs. One job is `pump-swap` which executes pending DCA (dollar-cost averaging) swap orders for agent tokens on Pump.fun/Raydium.++- Around the swap inner instruction build in `api/cron/[name].js`, there is a comment:+ ```js+ // Phase 3.1: Skipping for safety — pump-swap inner ix build not yet implemented+ // TODO: build the actual swap instruction here+ ```+ The job currently logs the pending orders but does not execute any swaps.++- `api/pump-fun-mcp.js` (~23KB) — Has token creation, portfolio tracking, and other Pump.fun operations. Likely has utility functions for building Pump.fun transactions that the cron job should reuse.++- `src/solana/` — Solana utilities including vanity key grinding, SNS resolution, etc.++- `solana-agent-sdk/` — Solana agent SDK with actions for token transfers and swaps. Contains the underlying swap logic.++- `api/agents/[id]/solana/` — Agent Solana wallet endpoints.++**The problem:** The `pump-swap` cron job reads pending DCA orders from the database but doesn't execute them. When a user sets up a DCA strategy for their agent token (e.g. "buy $10 of my token every day"), nothing happens because the swap instruction builder was "skipped for safety."++**The goal:** Implement the swap instruction builder in the cron job so that pending Pump.fun swap orders are actually executed.++---++## Before starting++1. **Read `api/cron/[name].js` in full** to understand the current job structure — what orders it reads, what state it tracks, what it skips.+2. **Read `api/pump-fun-mcp.js` in full** to find existing swap utilities.+3. **Read `solana-agent-sdk/`** for the swap action implementation.+4. **Read `api/agents/[id]/solana/`** to understand how agent wallets are accessed.++The comment location in `api/cron/[name].js` is the primary source of truth. This prompt describes the expected approach but may not match the actual code — always read the source first.++---++## Expected swap flow on Pump.fun/Raydium++A Pump.fun token swap (buy or sell) requires:++1. **Fetch pool state** — Get the bonding curve address for the token mint. For graduated tokens (on Raydium), use the Raydium AMM pool.+ ```js+ // Pump.fun bonding curve address derivation+ const [bondingCurve] = PublicKey.findProgramAddressSync(+ [Buffer.from('bonding-curve'), mint.toBuffer()],+ PUMP_PROGRAM_ID+ );+ ```++2. **Get associated token accounts** — For the buyer and the bonding curve.+ ```js+ const buyerATA = getAssociatedTokenAddressSync(mint, buyer.publicKey);+ const bondingCurveATA = getAssociatedTokenAddressSync(mint, bondingCurve, true);+ ```++3. **Build the buy instruction** — Pump.fun buy discriminator is `0x66063d1201daebea` (8-byte discriminator for `buy` in Anchor IDL). Parameters: `{ amount: u64, maxSolCost: u64 }`.+ ```js+ const data = Buffer.alloc(24);+ data.writeBigUInt64LE(BigInt('0x66063d1201daebea'), 0); // discriminator+ data.writeBigUInt64LE(BigInt(tokenAmount), 8); // amount+ data.writeBigUInt64LE(BigInt(maxSolCost), 16); // max sol cost (slippage)+ ```++4. **Compute slippage** — Apply the configured slippage percentage to the quoted price. Default: 2%.++5. **Assemble and send transaction** — Use priority fees from `ComputeBudgetProgram.setComputeUnitPrice`.++6. **Record result** — Update the swap order status in the DB (success/failed + tx signature).++---++## Database schema++Check the existing schema in `api/_lib/schema.sql` for a `swap_orders` or `dca_orders` or similar table. The cron job reads from it — look at the SQL queries in the cron handler to understand the table name and columns.++After the swap, update the order:+```sql+UPDATE <orders_table>+SET status = $1,+ tx_signature = $2,+ executed_at = now(),+ error = $3+WHERE id = $4+```++---++## Error handling++Swaps can fail for several reasons:+- Insufficient SOL balance+- Slippage exceeded (bonding curve price moved)+- Network error / timeout+- Token graduated to Raydium but cron still tries bonding curve++Handle each case:+- Insufficient balance: mark order `status = 'failed'`, `error = 'insufficient_balance'`+- Slippage: retry up to 2 times with 1% wider slippage, then fail+- Network timeout: mark `status = 'pending'` again (will retry next cron cycle)+- Graduated: detect by checking if bonding curve is complete, route to Raydium instead++Do NOT silently swallow errors. Log each failure with order ID + error for debugging.++---++## Files to edit++**Edit:**+- `api/cron/[name].js` — Implement the swap instruction builder where the "skipping for safety" comment is. Import utilities from `api/pump-fun-mcp.js` or `solana-agent-sdk/` rather than duplicating swap logic.++**Do not create new files** unless the refactoring genuinely requires extracting a shared utility.++---++## Safety checklist (do these before the task is done)++- [ ] The cron job has a per-order try/catch — one failed swap must not abort all others+- [ ] Maximum SOL spend per cron run is capped (read the existing cap from config/env, or add `MAX_SOL_PER_CRON_RUN = 0.1` if none exists)+- [ ] Idempotency: if the cron runs twice in quick succession (duplicate trigger), orders should not be double-executed. Use a DB lock or an `executing` status flag.+- [ ] The swap sends from the **agent's** Solana wallet, not a shared server wallet. Verify the wallet loading code.+- [ ] No private keys are logged.++---++## Acceptance criteria++1. Create a test DCA order in the DB (manually or via the existing API). Run the cron job. The swap executes and the order is marked `status = 'executed'` with a `tx_signature`.+2. A swap with insufficient balance marks the order `failed` — does not crash the cron job.+3. A slippage error retries twice, then marks failed.+4. Running the cron job twice simultaneously does not double-execute any order.+5. `node --check api/cron/[name].js` passes.+6. No existing cron jobs (other than `pump-swap`) are affected.++## Constraints++- Use `@solana/web3.js` — already a project dependency.+- Do not introduce `@coral-xyz/anchor` as a new dependency unless it's already present. Use manual discriminators/instruction encoding instead.+- The swap logic must use the agent's own Solana wallet (loaded from the DB or env). Never use a hardcoded private key.+- Keep the existing "Phase 3.1" comment in place (update it to "implemented" after completion) so git history shows intent.diff --git a/prompts/tasks/remove-consensus-dead-code.md b/prompts/tasks/remove-consensus-dead-code.mdnew file mode 100644index 000000000..8148644da--- /dev/null+++ b/prompts/tasks/remove-consensus-dead-code.md@@ -0,0 +1,47 @@+# Task: Remove completeConsensus dead code++## Context++`/workspaces/3D-Agent/chat/src/convo.js` exports a `completeConsensus()` function (~line 152) that was an experimental multi-model consensus feature. It is commented out everywhere it was called in `App.svelte` and is not reachable from any UI. It's ~100 lines of dead code that references OpenRouter specifically and would need significant work to actually function correctly.++There are also related TODO comments in `ModelSelector.svelte` and `SettingsModal.svelte` marking consensus UI as disabled.++## What to remove++### 1. Delete `completeConsensus` from convo.js++In `/workspaces/3D-Agent/chat/src/convo.js`, delete the entire `completeConsensus` export function. It starts at:+```js+export async function completeConsensus(convo, onupdate, onabort) {+```+and ends after the final closing `}` of that function (~line 250).++### 2. Remove the unused import in App.svelte++In `/workspaces/3D-Agent/chat/src/App.svelte`, find:+```js+import { complete, completeConsensus, generateImage } from './convo.js';+```+Remove `completeConsensus` from the import:+```js+import { complete, generateImage } from './convo.js';+```++### 3. Remove the commented-out TODO blocks++In `App.svelte` around line 742, delete the commented-out consensus block (the `// TODO: Consensus` comment and any surrounding commented code).++In `/workspaces/3D-Agent/chat/src/ModelSelector.svelte` around line 126, delete the `<!--TODO: Consensus-->` comment.++In `/workspaces/3D-Agent/chat/src/SettingsModal.svelte` around lines 201 and 595, delete the `<!--TODO: Consensus-->` comments.++## Files to edit+- `/workspaces/3D-Agent/chat/src/convo.js` — delete `completeConsensus` function+- `/workspaces/3D-Agent/chat/src/App.svelte` — remove import, remove commented TODO block+- `/workspaces/3D-Agent/chat/src/ModelSelector.svelte` — remove TODO comment+- `/workspaces/3D-Agent/chat/src/SettingsModal.svelte` — remove TODO comments (2 locations)++## Verification+- `cd /workspaces/3D-Agent/chat && npm run build` should complete with no errors+- `grep -r "completeConsensus\|TODO.*Consensus" /workspaces/3D-Agent/chat/src` should return no results+- The chat UI should work identically — no consensus feature ever appeared in the UIdiff --git a/prompts/tasks/sdk-typescript-declarations.md b/prompts/tasks/sdk-typescript-declarations.mdnew file mode 100644index 000000000..de5cb5495--- /dev/null+++ b/prompts/tasks/sdk-typescript-declarations.md@@ -0,0 +1,323 @@+# Task: Add TypeScript declaration files to @nirholas/agent-kit SDK++## Context++The project is three.ws — a platform for 3D AI agents.++The repo is at `/workspaces/3D-Agent`.++The SDK is at `sdk/` and published as `@nirholas/agent-kit`. It is pure JavaScript (JSDoc-only, no TypeScript source). Consumers who use TypeScript or have `"checkJs": true` get no autocomplete or type safety.++**Current SDK structure:**+```+sdk/+ src/+ index.js — main export, AgentKit class+ panel.js — AgentPanel UI component+ manifests.js — generate .well-known JSON files+ permissions.js — PermissionsClient (ERC-7710 delegations)+ solana.js — signInWithSolana(), registerSolanaAgent(), Solana Pay+ solana-attestations.js — attestFeedback(), attestValidation()+ erc8004/+ abi.js — REGISTRY_DEPLOYMENTS, contract ABIs+ registry.js — connectWallet(), registerAgent(), pinToIPFS(), buildRegistrationJSON()+ package.json+```++The SDK's `package.json` likely has no `types` field. There are no `.d.ts` files.++**The goal:** Write hand-authored `.d.ts` declaration files for the entire public API surface of the SDK. These should be accurate enough for autocomplete and type-checking without being so strict they generate spurious errors in downstream TS projects.++---++## Files to create++Create `sdk/types/` directory with one `.d.ts` per source module, plus an `index.d.ts` root:++```+sdk/types/+ index.d.ts+ panel.d.ts+ manifests.d.ts+ permissions.d.ts+ solana.d.ts+ solana-attestations.d.ts+ erc8004/+ abi.d.ts+ registry.d.ts+```++---++## Declarations to write++Read each source file carefully before writing its declaration. Here is the expected shape — verify against actual source:++### `sdk/types/index.d.ts`++```ts+export { AgentKit } from './AgentKit';+export type { AgentKitOptions } from './AgentKit';++export declare class AgentKit {+ constructor(options: AgentKitOptions);+ connect(): Promise<void>;+ disconnect(): void;+ readonly panel: import('./panel').AgentPanel;+}++export interface AgentKitOptions {+ agentId: string;+ serverUrl?: string;+ /** EVM chain ID to use for ERC-8004 registration */+ chainId?: number;+ /** Element to mount the chat panel into */+ container?: HTMLElement | string;+}+```++### `sdk/types/panel.d.ts`++```ts+export declare class AgentPanel {+ constructor(opts: AgentPanelOptions);+ mount(container: HTMLElement): void;+ unmount(): void;+ open(): void;+ close(): void;+ toggle(): void;+ on(event: AgentPanelEvent, handler: (data: unknown) => void): void;+ off(event: AgentPanelEvent, handler: (data: unknown) => void): void;+}++export interface AgentPanelOptions {+ agentId: string;+ serverUrl?: string;+ theme?: 'light' | 'dark' | 'auto';+ position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';+}++export type AgentPanelEvent = 'message' | 'open' | 'close' | 'error';+```++### `sdk/types/manifests.d.ts`++```ts+export interface AgentManifest {+ name: string;+ description?: string;+ modelUri?: string;+ skills?: string[];+ author?: string;+ chainId?: number;+ agentId?: number;+}++export declare function generateAgentRegistration(manifest: AgentManifest): AgentRegistrationJSON;+export declare function generateAgentCard(manifest: AgentManifest): AgentCardJSON;+export declare function generateAiPlugin(manifest: AgentManifest): AiPluginJSON;++export interface AgentRegistrationJSON { [key: string]: unknown }+export interface AgentCardJSON { [key: string]: unknown }+export interface AiPluginJSON { [key: string]: unknown }+```++### `sdk/types/permissions.d.ts`++```ts+export declare class PermissionsClient {+ constructor(opts: PermissionsClientOptions);+ requestPermission(params: PermissionRequest): Promise<PermissionGrant>;+ revokePermission(grantId: string): Promise<void>;+ listPermissions(): Promise<PermissionGrant[]>;+}++export interface PermissionsClientOptions {+ chainId: number;+ provider?: unknown; // EIP-1193 provider+}++export interface PermissionRequest {+ type: string;+ data: Record<string, unknown>;+ expiry?: number;+}++export interface PermissionGrant {+ id: string;+ type: string;+ data: Record<string, unknown>;+ grantedAt: number;+ expiresAt?: number;+}+```++### `sdk/types/solana.d.ts`++```ts+export declare function signInWithSolana(opts: SolanaSignInOptions): Promise<SolanaSignInResult>;+export declare function registerSolanaAgent(opts: SolanaAgentRegistrationOptions): Promise<string>;+export declare function solanaPay(opts: SolanaPayOptions): Promise<SolanaPayResult>;++export interface SolanaSignInOptions {+ walletAdapter: unknown; // @solana/wallet-adapter-base WalletAdapter+ domain?: string;+ statement?: string;+}++export interface SolanaSignInResult {+ address: string;+ signature: string;+ message: string;+}++export interface SolanaAgentRegistrationOptions {+ agentId: string;+ walletAdapter: unknown;+ metadataUri?: string;+}++export interface SolanaPayOptions {+ recipient: string;+ amount: number;+ label?: string;+ message?: string;+ reference?: string;+}++export interface SolanaPayResult {+ signature: string;+ confirmed: boolean;+}+```++### `sdk/types/solana-attestations.d.ts`++```ts+export declare function attestFeedback(opts: AttestFeedbackOptions): Promise<AttestationResult>;+export declare function attestValidation(opts: AttestValidationOptions): Promise<AttestationResult>;++export interface AttestFeedbackOptions {+ agentId: string;+ score: number; // -100 to 100+ comment?: string;+ walletAdapter: unknown;+}++export interface AttestValidationOptions {+ agentId: string;+ passed: boolean;+ proofHash: string;+ proofUri?: string;+ kind: string;+ walletAdapter: unknown;+}++export interface AttestationResult {+ signature: string;+ txHash?: string;+}+```++### `sdk/types/erc8004/abi.d.ts`++```ts+export declare const REGISTRY_DEPLOYMENTS: Record<number, {+ identityRegistry?: string;+ reputationRegistry?: string;+ validationRegistry?: string;+}>;++export declare const IDENTITY_REGISTRY_ABI: readonly unknown[];+export declare const REPUTATION_REGISTRY_ABI: readonly unknown[];+export declare const VALIDATION_REGISTRY_ABI: readonly unknown[];+```++### `sdk/types/erc8004/registry.d.ts`++```ts+export declare function connectWallet(): Promise<WalletConnection>;+export declare function registerAgent(opts: RegisterAgentOptions): Promise<RegisterAgentResult>;+export declare function pinToIPFS(data: unknown): Promise<string>;+export declare function buildRegistrationJSON(opts: RegistrationJSONOptions): AgentRegistrationData;++export interface WalletConnection {+ address: string;+ chainId: number;+ provider: unknown;+ signer: unknown;+}++export interface RegisterAgentOptions {+ agentUri: string;+ chainId?: number;+ metadata?: Array<{ key: string; value: string }>;+ walletConnection?: WalletConnection;+}++export interface RegisterAgentResult {+ agentId: number;+ txHash: string;+ chainId: number;+}++export interface RegistrationJSONOptions {+ name: string;+ description?: string;+ modelUri?: string;+ chainId?: number;+}++export interface AgentRegistrationData {+ name: string;+ description?: string;+ model_uri?: string;+ [key: string]: unknown;+}+```++---++## package.json update++Add to `sdk/package.json`:+```json+{+ "types": "types/index.d.ts",+ "exports": {+ ".": {+ "types": "./types/index.d.ts",+ "import": "./src/index.js"+ }+ }+}+```++---++## Important++**Read each source file before writing its declaration.** The shapes above are based on a code review but may not be 100% accurate. The source is authoritative — declarations must match what actually exists. If a function has additional parameters, include them. If a class has methods not listed above, add them.++If the source uses JSDoc `@typedef` blocks, extract those types into the declaration file.++---++## Acceptance criteria++1. `cd sdk && npx tsc --noEmit --allowJs false --declaration --checkJs false --strict types/index.d.ts` — no errors (or `tsc --noEmit` on a sample consumer).+2. Create a test file `sdk/types/test.ts`:+ ```ts+ import { AgentKit } from '../src/index.js';+ const kit = new AgentKit({ agentId: 'test-123' });+ ```+ `npx tsc --noEmit sdk/types/test.ts` passes (after setting up minimal tsconfig).+3. `sdk/package.json` has `"types": "types/index.d.ts"`.+4. No new JS files added — declarations only.+5. `npx vite build` at repo root still passes.++## Constraints++- Do not convert any `.js` source to TypeScript — declarations only.+- Don't introduce `any` where a real shape is known. Use `unknown` for genuinely opaque values (e.g. wallet adapters).+- Keep declarations minimal — match what the source actually exports, nothing more.diff --git a/prompts/tasks/talkinghead-avatar-url-setting.md b/prompts/tasks/talkinghead-avatar-url-setting.mdnew file mode 100644index 000000000..9c76fc064--- /dev/null+++ b/prompts/tasks/talkinghead-avatar-url-setting.md@@ -0,0 +1,91 @@+# Task: Make the TalkingHead avatar URL configurable via Settings++## Context++`/workspaces/3D-Agent/chat/src/TalkingHead.svelte` has a hardcoded default Ready Player Me avatar URL:++```js+export let avatarUrl =+ 'https://models.readyplayer.me/64bfa15f0e72c63d7c3934a6.glb?morphTargets=ARKit,Oculus+Visemes,...';+```++This is someone else's avatar model. Users should be able to paste their own Ready Player Me GLB URL.++`TalkingHead` is mounted in `/workspaces/3D-Agent/chat/src/App.svelte`:+```svelte+<TalkingHead bind:this={talkingHead} on:ready={onTalkingHeadReady} />+```++## What to build++### 1. Add a persisted store for the avatar URL++In `/workspaces/3D-Agent/chat/src/stores.js`, add:+```js+export const talkingHeadAvatarUrl = persisted('talkingHeadAvatarUrl', '');+```++### 2. Pass the URL to TalkingHead in App.svelte++In `App.svelte`, import the new store:+```js+import { ..., talkingHeadAvatarUrl } from './stores.js';+```++Pass it to TalkingHead (use the default when empty):+```svelte+<TalkingHead+ bind:this={talkingHead}+ on:ready={onTalkingHeadReady}+ avatarUrl={$talkingHeadAvatarUrl || undefined}+/>+```++(`undefined` causes TalkingHead to use its own default prop value)++### 3. Add an input field in SettingsModal++In `/workspaces/3D-Agent/chat/src/SettingsModal.svelte`, find the section for voice/avatar settings (search for `ttsEnabled` or `speaker`).++Add a text input for the avatar URL:+```svelte+<script>+ import { talkingHeadAvatarUrl } from './stores.js';+</script>++<div class="flex flex-col gap-1">+ <label class="text-sm font-medium text-slate-700">3D Avatar URL (Ready Player Me .glb)</label>+ <input+ type="url"+ placeholder="https://models.readyplayer.me/your-avatar.glb?morphTargets=ARKit,Oculus+Visemes,..."+ bind:value={$talkingHeadAvatarUrl}+ class="rounded-md border border-slate-200 px-3 py-1.5 text-sm outline-none focus:border-indigo-400"+ />+ <p class="text-xs text-slate-400">+ Get your URL from <a href="https://readyplayer.me" target="_blank" class="underline">readyplayer.me</a>.+ Must include <code>morphTargets=ARKit,Oculus+Visemes</code> query param for lipsync.+ </p>+</div>+```++### 4. Reload TalkingHead when URL changes++In `App.svelte`, when `talkingHeadAvatarUrl` changes, reset the ready flag so `speakLastMessage` doesn't try to speak before the new avatar loads:++```js+$: if ($talkingHeadAvatarUrl) {+ talkingHeadReady = false;+ pendingSpeak = null;+}+```++## Files to edit+- `/workspaces/3D-Agent/chat/src/stores.js`+- `/workspaces/3D-Agent/chat/src/App.svelte`+- `/workspaces/3D-Agent/chat/src/SettingsModal.svelte`++## Verification+- Open Settings, paste a Ready Player Me GLB URL with the required morphTargets params+- Close Settings — the floating avatar should reload with the new model+- The URL should persist after page reload+- Leaving the field empty should use the default avatardiff --git a/prompts/tasks/talkinghead-lipsync-agent-runtime.md b/prompts/tasks/talkinghead-lipsync-agent-runtime.mdnew file mode 100644index 000000000..f1437d167--- /dev/null+++ b/prompts/tasks/talkinghead-lipsync-agent-runtime.md@@ -0,0 +1,148 @@+# Task: Wire TalkingHead viseme lipsync into the agent runtime speak event++## Context++The project is three.ws — a platform for creating 3D AI agents with WebGL avatars, emotional presence, and an LLM brain.++The repo is at `/workspaces/3D-Agent`.++**What exists today:**++- `src/runtime/speech.js` — TTS providers: `BrowserTTS`, `ElevenLabsTTS`, `createTTS()`. When the runtime calls `speak(text)`, these fire audio but have no concept of mouth/jaw animation.+- `src/agent-avatar.js` — The Empathy Layer. Drives morph targets per-frame (`mouthSmile`, `mouthFrown`, etc.). Handles emotion blends but has **no lipsync** — the mouth does not move in sync with speech audio.+- `experiments/talking-head/` — An upstream clone of `met4citizen/TalkingHead`. Its `modules/talkinghead.mjs` implements full viseme lipsync: phoneme tables, viseme morph weights, and an animation loop that drives mouth shapes in sync with audio. The relevant exported API is `TalkingHead.speakText(text, avatar, callbacks)` which drives visemes from text + audio concurrently.+- `src/agent-protocol.js` — The event bus. The `speak` event shape is `{ text, sentiment }`.+- `src/runtime/index.js` — The LLM brain loop. It calls `speech.speak(text)` directly. Max tool iterations: 8.+- `src/runtime/scene.js` — `SceneController` wraps the Viewer. Has `setExpression(name, weight)`, `playClipByName(name, opts)`, and direct access to `this.viewer`.++**The problem:** When the agent speaks, audio plays but the avatar's mouth is completely static. The morph targets for mouth shapes (`mouthOpen`, `mouthSmile`, `jawOpen`, `viseme_*` for ARKit-style avatars) exist on the mesh but nothing drives them during speech.++**The goal:** During any `speak` event, drive jaw/mouth morph targets in sync with the speech audio so the avatar visibly lip-syncs.++---++## Scope++**In scope:**+- A `LipsyncDriver` module at `src/runtime/lipsync.js` that:+ - Accepts a reference to the Three.js scene (to find morph targets)+ - Accepts a `text` string+ - Drives jaw/mouth morph targets while audio plays+ - Uses a simple energy-based approach (phoneme-to-viseme lookup from the TalkingHead experiment as a reference) — not a full neural lipsync+ - Cleans up (resets all mouth morphs to 0) when speech ends or is cancelled+- Wiring `LipsyncDriver` into `src/runtime/speech.js` as an optional add-on — if lipsync is enabled, it runs alongside `speak()`. If no suitable morph targets are found, it noops silently.+- Integration with `BrowserTTS` and `ElevenLabsTTS` via the `onStart`/`onEnd` callbacks both already support.++**Out of scope:**+- Full neural lipsync (Rhubarb, wav2vec, etc.)+- Importing the `experiments/talking-head/` module directly (it has its own three.js instance and render loop — don't entangle it)+- Any changes to `agent-avatar.js` emotion logic+- TTS provider changes beyond hooking `onStart`/`onEnd`++---++## Reference: viseme morph targets++Ready Player Me avatars (the most common avatar type in this project) use ARKit-style morph targets. The relevant ones for lipsync:++```+viseme_aa — "ah" sound (father)+viseme_CH — "ch/sh" (church, she)+viseme_DD — "d/t/n/l" (dog, top)+viseme_E — "eh" (bed)+viseme_FF — "f/v" (farm, very)+viseme_I — "ee" (see)+viseme_kk — "k/g" (cat, go)+viseme_nn — "n/ng" (now, sing)+viseme_O — "oh" (go, hope)+viseme_PP — "b/m/p" (back, map)+viseme_RR — "r" (red)+viseme_sil — silence+viseme_SS — "s/z" (see, zoo)+viseme_TH — "th" (the, think)+viseme_U — "oo" (you, new)+```++Fallback for non-ARKit avatars: `jawOpen`, `mouthOpen`.++---++## Approach++**Text-to-phoneme heuristic (no audio analysis required):**++Map character runs to approximate phoneme buckets. This is intentionally rough — the goal is plausible mouth movement, not perfect accuracy:++```js+const CHAR_TO_VISEME = {+ a: 'viseme_aa', e: 'viseme_E', i: 'viseme_I', o: 'viseme_O', u: 'viseme_U',+ b: 'viseme_PP', m: 'viseme_PP', p: 'viseme_PP',+ f: 'viseme_FF', v: 'viseme_FF',+ d: 'viseme_DD', t: 'viseme_DD', n: 'viseme_DD', l: 'viseme_DD',+ k: 'viseme_kk', g: 'viseme_kk',+ s: 'viseme_SS', z: 'viseme_SS',+ r: 'viseme_RR',+ 'th': 'viseme_TH',+ 'ch': 'viseme_CH', 'sh': 'viseme_CH',+};+```++Tokenize `text` into a sequence of `{ viseme, durationMs }` pairs by splitting on whitespace + estimating ~80ms per phoneme. Then drive them as a timed sequence using `setTimeout` while audio plays.++**Morph target resolution:** Walk `scene.traverse()` once to find all meshes with `morphTargetDictionary`. Build a lookup table `{ visemeName → [{ mesh, index }] }`. Reuse it for the lifetime of the driver.++**Integration point in `speech.js`:**++```js+// BrowserTTS.speak() — modified+async speak(text, { onStart, onEnd, scene } = {}) {+ // ... existing code ...+ utter.onstart = () => {+ this._speaking = true;+ if (scene) this._lipsync = startLipsync(text, scene);+ onStart?.();+ };+ utter.onend = () => {+ this._speaking = false;+ this._lipsync?.stop();+ onEnd?.();+ resolve();+ };+}+```++Pass `scene` from `SceneController` when calling `speech.speak()` in `runtime/index.js`.++---++## Files to create/edit++**Create:**+- `src/runtime/lipsync.js` — `startLipsync(text, scene)` → returns `{ stop() }`. All logic here.++**Edit:**+- `src/runtime/speech.js` — pass `scene` through to lipsync in `BrowserTTS.speak()` and `ElevenLabsTTS.speak()`. Don't break the existing API — `scene` is optional.+- `src/runtime/index.js` — pass `scene` from `SceneController` when calling `speech.speak()`.++**Do not touch:**+- `src/agent-avatar.js` — don't change emotion blend logic+- `experiments/talking-head/` — read for reference only, don't import+- Any viewer files++---++## Acceptance criteria++1. Load any Ready Player Me GLB in the viewer. Start the agent. Have it speak a sentence.+2. The avatar's mouth visibly moves during speech — not just the smile/frown from emotion, but distinct phoneme-shaped movements.+3. When speech ends, all mouth morphs return to 0 within 200ms.+4. If the scene has no ARKit morph targets (e.g. a Mixamo character without visemes), the code noops — no errors, no broken morphs.+5. `npx vite build` passes with no new warnings.+6. `node --check src/runtime/lipsync.js` passes.++## Constraints++- ESM only. Tabs, 4-wide. Match existing style in `src/runtime/`.+- No new npm dependencies — use the Three.js `Object3D.traverse` and `Mesh.morphTargetDictionary` APIs already available.+- Don't import anything from `experiments/`.+- The lipsync must stop and reset if `speech.cancel()` is called mid-utterance.diff --git a/prompts/tasks/tool-call-error-boundaries.md b/prompts/tasks/tool-call-error-boundaries.mdnew file mode 100644index 000000000..97e0ced68--- /dev/null+++ b/prompts/tasks/tool-call-error-boundaries.md@@ -0,0 +1,62 @@+# Task: Add error boundaries around tool call invocation in App.svelte++## Context++`/workspaces/3D-Agent/chat/src/App.svelte` has a tool call pipeline where the LLM returns a tool call, the frontend invokes it against a server endpoint, and the result is fed back into the conversation. This multi-step async flow has no error handling.++If the tool server is down, returns invalid JSON, or a tool throws — the pipeline silently breaks, the conversation gets stuck, and the user sees a spinner forever.++## What to fix++### 1. Find the tool invocation code++Search for the `fetch('/tool'` or similar call in `App.svelte`. It likely looks like:++```js+const toolResponse = await fetch(`${$remoteServer.address}/tool`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: toolcall.name, arguments: toolcall.args })+});+const result = await toolResponse.json();+```++Find the exact location by searching for `toolcall` and `fetch` near each other in App.svelte.++### 2. Wrap with try-catch and surface errors++Replace the bare fetch+json pattern with:+```js+let toolResult;+try {+ const toolResponse = await fetch(`${$remoteServer.address}/tool`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: toolcall.name, arguments: toolcall.args })+ });+ if (!toolResponse.ok) {+ throw new Error(`Tool server returned ${toolResponse.status}`);+ }+ toolResult = await toolResponse.json();+} catch (err) {+ toolResult = { error: err.message || 'Tool invocation failed' };+}+```++Feeding an error object back into the conversation is correct — it lets the LLM see that the tool failed and respond accordingly, rather than hanging.++### 3. Check the tool result shape++The Go server at `/workspaces/3D-Agent/chat/server/main.go` returns `{"error": "..."}` for failures. Make sure the code that reads `toolResult` and adds it to `convo.messages` handles the `error` field gracefully (doesn't crash trying to read `toolResult.output` when only `toolResult.error` exists).++Look for where the tool response is appended to messages and ensure it works whether the result is a success object or `{ error: string }`.++## Files to edit+- `/workspaces/3D-Agent/chat/src/App.svelte` — wrap tool fetch in try-catch++## Verification+- In Settings, set the remote server address to `http://localhost:9999` (nothing running there)+- Enable a tool and ask the LLM to use it+- The conversation should continue with an error message from the tool rather than hanging+- The LLM should receive the error and be able to explain what went wrong+- No unhandled promise rejections in the browser consolediff --git a/prompts/tasks/tts-endpoint.md b/prompts/tasks/tts-endpoint.mdnew file mode 100644index 000000000..3b1af0054--- /dev/null+++ b/prompts/tasks/tts-endpoint.md@@ -0,0 +1,63 @@+# Task: Implement /api/tts/google endpoint in the Go chat server++## Context++The chat app at `/workspaces/3D-Agent/chat` has a 3D talking avatar powered by the `TalkingHead` library (met4citizen/TalkingHead). It is mounted in `/workspaces/3D-Agent/chat/src/App.svelte` and defined in `/workspaces/3D-Agent/chat/src/TalkingHead.svelte`.++`TalkingHead.svelte` line 21 hardcodes:+```js+export let ttsEndpoint = '/api/tts/google';+```++The Go server at `/workspaces/3D-Agent/chat/server/main.go` has no `/api/tts/google` route. The avatar can load visually but cannot speak because this endpoint doesn't exist — `speakText()` calls it internally.++## What to build++Add a `POST /api/tts/google` handler to `/workspaces/3D-Agent/chat/server/main.go` that proxies to the Google Cloud Text-to-Speech REST API.++### Request format (sent by TalkingHead library)+```json+{+ "input": { "text": "Hello world" },+ "voice": { "languageCode": "en-US", "ssmlGender": "FEMALE" },+ "audioConfig": { "audioEncoding": "MP3" }+}+```++### Response format (expected by TalkingHead)+Raw MP3 audio bytes with `Content-Type: audio/mpeg`.++The TalkingHead library sends this exact request shape to the endpoint and expects raw audio back. See upstream source: https://github.com/met4citizen/TalkingHead++### Implementation steps++1. Add a `GOOGLE_TTS_API_KEY` env var — read it with `os.Getenv("GOOGLE_TTS_API_KEY")` in `main.go`.++2. Register the route in `main()`:+```go+r.Post("/api/tts/google", TTSHandler)+```++3. Implement `TTSHandler`:+ - Read the request body (it's the JSON payload above)+ - Forward it via POST to `https://texttospeech.googleapis.com/v1/text:synthesize?key=<GOOGLE_TTS_API_KEY>`+ - The Google API returns `{ "audioContent": "<base64-encoded-mp3>" }`+ - Base64-decode `audioContent`+ - Write the raw bytes back with `Content-Type: audio/mpeg`++4. If `GOOGLE_TTS_API_KEY` is empty, return HTTP 503 with a JSON error: `{"error": "TTS not configured"}`.++### Go imports needed+```go+"encoding/base64"+```+(the rest like `encoding/json`, `net/http`, `io`, `os` are already imported)++## Files to edit+- `/workspaces/3D-Agent/chat/server/main.go` — add route + handler++## Verification+- Start the server: `cd /workspaces/3D-Agent/chat/server && go run .`+- `curl -X POST http://localhost:8081/api/tts/google -H 'Content-Type: application/json' -d '{"input":{"text":"hello"},"voice":{"languageCode":"en-US","ssmlGender":"FEMALE"},"audioConfig":{"audioEncoding":"MP3"}}' --output test.mp3`+- `file test.mp3` should report MPEG audio+- Without the env var set, curl should return `{"error": "TTS not configured"}`diff --git a/prompts/tasks/validation-registry-mainnet-deploy.md b/prompts/tasks/validation-registry-mainnet-deploy.mdnew file mode 100644index 000000000..8e4937f0b--- /dev/null+++ b/prompts/tasks/validation-registry-mainnet-deploy.md@@ -0,0 +1,141 @@+# Task: Deploy ValidationRegistry to all mainnet EVM chains++## Context++The project is three.ws — a platform for 3D AI agents with on-chain identity via ERC-8004.++The repo is at `/workspaces/3D-Agent`.++**What exists:**++- `contracts/src/ValidationRegistry.sol` — Solidity 0.8.24. Allow-listed validators attest off-chain proofs for agents. Functions: `recordValidation(agentId, passed, proofHash, proofURI, kind)` (validator-only), `getValidation()`, `getLatestByKind()`, `getValidationRange()`, `addValidator()`, `removeValidator()`, `transferOwnership()`.++- `contracts/DEPLOYMENTS.md` — Deployment status:+ - IdentityRegistry: **deployed** on all 15 mainnet chains and 7 testnet chains+ - ReputationRegistry: **deployed** on all 15 mainnet chains and 7 testnet chains+ - ValidationRegistry: **deployed on testnet only** (`0x8004Cb1BF31DAf7788923b405b754f57acEB4272`). **NOT on mainnet.**++- `contracts/script/` — Foundry deploy scripts. IdentityRegistry and ReputationRegistry were deployed via CREATE2 (same address on every chain). ValidationRegistry needs the same treatment.++- `src/erc8004/abi.js` — `REGISTRY_DEPLOYMENTS` maps chainId → addresses. ValidationRegistry mainnet entry is absent/null. `VALIDATION_REGISTRY_DEPLOYMENTS` is a separate export (check the file for current state).++- `sdk/src/erc8004/abi.js` — Same ABI and deployment map, mirrored in the SDK package. Both must be updated.++**Mainnet chains (15 total):**++| Chain | ChainId |+|-------|---------|+| Ethereum | 1 |+| Optimism | 10 |+| BNB Smart Chain | 56 |+| Gnosis | 100 |+| Polygon | 137 |+| Fantom | 250 |+| zkSync Era | 324 |+| Moonbeam | 1284 |+| Mantle | 5000 |+| Base | 8453 |+| Arbitrum One | 42161 |+| Celo | 42220 |+| Avalanche C-Chain | 43114 |+| Linea | 59144 |+| Scroll | 534352 |++**The goal:** Deploy ValidationRegistry to all 15 mainnet chains using the same CREATE2 salt as the testnet deployment, so it gets the same address (`0x8004Cb1BF31DAf7788923b405b754f57acEB4272`) on every chain. Then update the deployment records in `contracts/DEPLOYMENTS.md`, `src/erc8004/abi.js`, and `sdk/src/erc8004/abi.js`.++---++## Important constraints++**Read `contracts/CLAUDE.md` before making ANY changes.** Key rules:+- ABI shape, storage layout, deployed address, deploy script changes all require user approval first.+- These contracts are immutable once deployed. No mistakes.+- The ValidationRegistry ABI and bytecode must NOT be changed — deploy the exact same contract as testnet.++**This task is write/planning only — do NOT execute `forge script` or any on-chain transaction without explicit user confirmation.** The deliverable is a verified deploy plan + updated source files (once addresses are known).++---++## Steps++### 1. Verify the CREATE2 salt and factory++Check `contracts/script/` for the deploy script that was used for IdentityRegistry and ReputationRegistry. Find:+- The CREATE2 factory address used (standard `0x4e59b44847b379578588920cA78FbF26c0B4956C` or custom)+- The salt value+- The init code hash++Confirm that applying the same factory + salt to ValidationRegistry bytecode would produce `0x8004Cb1BF31DAf7788923b405b754f57acEB4272`. Verify by computing:+```+address = keccak256(0xff ++ factory ++ salt ++ keccak256(initcode))[12:]+```++### 2. Write/update the Foundry deploy script++If a `DeployValidationRegistry.s.sol` script doesn't exist, create it mirroring the pattern from the IdentityRegistry/ReputationRegistry deploy scripts. It must:+- Use the same CREATE2 factory and salt+- Verify the resulting address matches `0x8004Cb1BF31DAf7788923b405b754f57acEB4272` and revert if not+- Accept a private key from `DEPLOYER_PRIVATE_KEY` env var+- Be runnable per-chain via `--rpc-url`++### 3. Dry-run command list++Produce the exact `forge script` command for each of the 15 chains. Format:+```bash+# Ethereum (chainId 1)+forge script contracts/script/DeployValidationRegistry.s.sol \+ --rpc-url $ETH_RPC_URL \+ --broadcast \+ --verify \+ --etherscan-api-key $ETHERSCAN_API_KEY+```++Do not run these — write them to a file `contracts/script/deploy-validation-registry.sh` for the user to execute.++### 4. Update records (fill in after deployment)++After the user runs the deploy script and confirms the addresses, update:++**`contracts/DEPLOYMENTS.md`** — Add `ValidationRegistry` mainnet row with:+- Address: `0x8004Cb1BF31DAf7788923b405b754f57acEB4272` (same as testnet if CREATE2 worked)+- One tx hash per chain (fill in when known — use `TODO: fill after deployment` placeholder)++**`src/erc8004/abi.js`** — In `REGISTRY_DEPLOYMENTS`, for every mainnet chainId, add the `validationRegistry` field:+```js+1: {+ identityRegistry: '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432',+ reputationRegistry: '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63',+ validationRegistry: '0x8004Cb1BF31DAf7788923b405b754f57acEB4272', // ← add this+},+```++**`sdk/src/erc8004/abi.js`** — Same update, mirrored.++### 5. Post-deployment verification++For each chain, verify the contract is live:+```bash+cast call --rpc-url $RPC 0x8004Cb1BF31DAf7788923b405b754f57acEB4272 "owner()(address)"+```+Expected: the deployer address (or a multisig if transferred).++---++## Deliverables++1. `contracts/script/DeployValidationRegistry.s.sol` (create or update)+2. `contracts/script/deploy-validation-registry.sh` — the 15-chain deploy command list+3. Updated `contracts/DEPLOYMENTS.md` (with TODO placeholders for tx hashes)+4. Updated `src/erc8004/abi.js` with all 15 mainnet chainIds having `validationRegistry`+5. Updated `sdk/src/erc8004/abi.js` to match++---++## Acceptance criteria++1. `forge build` passes with no new warnings.+2. `node --check src/erc8004/abi.js` passes.+3. `contracts/DEPLOYMENTS.md` has a complete ValidationRegistry section for all 15 mainnet chains.+4. `src/erc8004/abi.js` has `validationRegistry` populated for all mainnet chainIds.+5. `sdk/src/erc8004/abi.js` matches `src/erc8004/abi.js`.+6. The deploy script was NOT executed — it is ready for the user to run manually.diff --git a/prompts/tasks/viewer-double-load-fix.md b/prompts/tasks/viewer-double-load-fix.mdnew file mode 100644index 000000000..e5a7608d7--- /dev/null+++ b/prompts/tasks/viewer-double-load-fix.md@@ -0,0 +1,115 @@+# Task: Fix double model load in the validator++## Context++The project is three.ws — a platform for 3D AI agents.++The repo is at `/workspaces/3D-Agent`.++**What exists:**++- `src/validator.js` — Validates GLB/GLTF models: checks structure, materials, meshes, animations, ERC-8004 compliance. It runs as part of the agent "validate-model" skill.++- `src/viewer.js` — ~1200-line Three.js viewer. Loads and renders GLB files. Uses `GLTFLoader` internally.++- `src/agent-skills.js` — Built-in skills including `validate-model`. When triggered, it calls the validator.++**The problem:** When a model is loaded and then validated, the GLB is fetched and parsed **twice** — once by the viewer to display it, and once by the validator to analyze it. For a 10MB GLB file on a slow connection, this is a painful double-download.++The Three.js `GLTFLoader` has a built-in cache (`THREE.Cache`) that should prevent the second fetch if the URL is the same. But the validator likely creates its own `GLTFLoader` instance or fetches the file independently, bypassing the cache.++**The goal:** Make validation reuse the already-loaded model data from the viewer rather than reloading from the network.++---++## Before starting++Read these files in full to understand the actual code before proposing or making changes:++1. `src/validator.js` — understand how it loads models. Look for `fetch()`, `GLTFLoader`, `FileReader`, or any network call.+2. `src/viewer.js` — understand how the Viewer stores the loaded model. Look for `this.content`, `this._gltf`, or any post-load cached state.+3. `src/agent-skills.js` — see how `validate-model` calls the validator and what data it passes.+4. `src/runtime/tools.js` — see how the `validate` tool is invoked.++The specific fix depends on what the code actually does. This prompt describes two likely scenarios.++---++## Likely fix scenarios++### Scenario A: Validator calls `fetch()` independently++If `validator.js` contains a `fetch(url)` call to load the GLB:++Enable the Three.js cache before the validator runs:+```js+THREE.Cache.enabled = true;+```++The Viewer already loaded the model — if Three.js caching is on, the second load hits the memory cache instead of the network. This is a one-line fix.++Check if `THREE.Cache.enabled` is already set somewhere in `src/viewer.js`. If yes, the bug is elsewhere.++### Scenario B: Validator uses a separate GLTFLoader with no cache++If the validator creates a new `GLTFLoader()` without using `THREE.Cache`:++Pass the already-parsed GLTF object from the Viewer to the Validator instead of a URL:++```js+// In viewer.js, store the parsed GLTF after load+this._loadedGltf = gltf; // the result from GLTFLoader.load()++// In agent-skills.js or runtime/tools.js, pass it to the validator+import { Validator } from './validator.js';+const validator = new Validator();+await validator.validate(viewer._loadedGltf); // pass GLTF object, not URL+```++The validator needs to accept either a URL (fallback) or a pre-loaded GLTF object.++### Scenario C: Validator reads the file from R2/IPFS separately++If the validator fetches the model from a remote URL independently of the viewer:++Use the Viewer's `THREE.Cache` (which caches ArrayBuffers by URL). Or, more robustly: in the validate-model skill handler, extract the ArrayBuffer from the viewer's cache and pass it to the validator as a `Uint8Array`.++---++## What to do++1. Read the files listed above.+2. Identify which scenario applies (or a fourth scenario not listed).+3. Implement the minimal fix.+4. Add a comment explaining the optimization.++---++## Files to edit++Likely candidates (edit only what the fix requires):+- `src/validator.js`+- `src/viewer.js` (if storing cached GLTF state)+- `src/agent-skills.js` or `src/runtime/tools.js` (if changing how validator is called)++**Do not:**+- Refactor the Viewer class+- Change the Validator's public API signature beyond adding an optional parameter+- Touch `src/agent-avatar.js` or emotion logic++---++## Acceptance criteria++1. Load a GLB model in the viewer. Open the Network tab in DevTools. Trigger model validation (via the "validate-model" skill or the validate button in the UI).+2. The GLB file is **not** fetched a second time. Network tab shows zero new requests for the `.glb` URL after the initial load.+3. Validation results are identical to before — the same warnings/errors are reported.+4. `npx vite build` passes with no new warnings.+5. `node --check src/validator.js` passes.++## Constraints++- Surgical change only — touch the minimum number of lines.+- If the fix is a one-liner (`THREE.Cache.enabled = true`), do not refactor surrounding code.+- If passing the GLTF object, keep the URL-based path as a fallback (e.g. when called standalone without a viewer context).+- Do not change the Validator's return type or error format.diff --git a/prompts/tasks/voice-cloning-phase2.md b/prompts/tasks/voice-cloning-phase2.mdnew file mode 100644index 000000000..55184dbd9--- /dev/null+++ b/prompts/tasks/voice-cloning-phase2.md@@ -0,0 +1,170 @@+# Task: Voice cloning for agent personas (Phase 2)++## Context++The project is three.ws — a platform for 3D AI agents.++The repo is at `/workspaces/3D-Agent`.++**Background:**++Phase 2 of the three.ws roadmap is "Agent Personalization + Voice Cloning." The goal is that an agent has a consistent, unique voice — not the generic browser TTS voice, but a cloned voice that matches the agent's persona.++**Current voice stack:**++- `src/runtime/speech.js` — TTS providers:+ - `BrowserTTS` — Web Speech API, generic robot voice+ - `ElevenLabsTTS` — ElevenLabs streaming TTS, high quality but uses a shared/generic voice+ - `createTTS(config)` — factory function++- `src/element.js` — `<agent-3d>` web component. Has a `voice` attribute. Currently the voice provider is set once at element boot from manifest config.++- Agent manifest format (`agent-manifest/0.1`) — has a `voice` field in the manifest spec. Currently unused beyond provider selection.++- `api/agents/[id]/` — Agent CRUD API.++**The goal:** Allow each agent to have a cloned voice stored as part of its identity. The workflow:+1. **Recording:** User records 30–60 seconds of voice audio in the agent editor+2. **Cloning:** Audio is sent to ElevenLabs Voice Cloning API to create a custom voice+3. **Storage:** The resulting ElevenLabs `voice_id` is stored on the agent record+4. **Playback:** When the agent speaks, it uses its cloned voice via `ElevenLabsTTS`++---++## Architecture++### Database++Add `voice_id` and `voice_provider` columns to `agent_identities`:++```sql+ALTER TABLE agent_identities+ ADD COLUMN IF NOT EXISTS voice_provider text DEFAULT 'browser',+ ADD COLUMN IF NOT EXISTS voice_id text,+ ADD COLUMN IF NOT EXISTS voice_cloned_at timestamptz;+```++Add a migration file at `specs/schema/NNN-voice-cloning.sql`.++### Backend endpoints++**`POST /api/agents/:id/voice/clone`**++Accepts a multipart form upload with:+- `audio` — WAV or MP3 file (30–300 seconds, max 10MB)+- `name` — voice name (default: agent's name)+- `description` — optional++Flow:+1. Validate file size/type+2. Upload to ElevenLabs Voice Cloning API:+ ```+ POST https://api.elevenlabs.io/v1/voices/add+ xi-api-key: {ELEVENLABS_API_KEY}+ Content-Type: multipart/form-data+ Body: { name, description, files: [audioBlob] }+ ```+3. Store returned `voice_id` in `agent_identities`+4. Return `{ voice_id, name }`++Requires: agent ownership check. Rate limit: max 3 voice clones per user per day.++**`DELETE /api/agents/:id/voice`**++Removes the cloned voice:+1. Calls ElevenLabs `DELETE /v1/voices/{voice_id}` to free their quota+2. Clears `voice_id` and `voice_provider = 'browser'` on the agent record+3. Returns `204`++**`GET /api/agents/:id/voice`**++Returns `{ voice_provider, voice_id, voice_cloned_at }`. Used by the frontend to show current voice status.++### Frontend: Voice recording UI++Add a "Voice" section to the agent editor (`src/editor/` — check what files exist there). This UI needs:++1. A **Record** button that captures microphone audio via `MediaRecorder`+2. A timer showing recording duration (target: 30–60s, warn if too short)+3. A **Stop & Clone** button that uploads the recording+4. Status: "Cloning..." → "Voice cloned ✓" + a sample playback button+5. A **Remove voice** button (calls `DELETE /api/agents/:id/voice`)++Sample playback: after cloning, call:+```+POST https://api.elevenlabs.io/v1/text-to-speech/{voice_id}/stream+```+with a sample text like `"Hello, I'm your agent. How can I help you today?"` and play the audio.++### Runtime integration++In `src/runtime/index.js` or `src/element.js`, when loading the agent, check if the manifest or agent record has a `voice_id`. If so, initialize `ElevenLabsTTS` with that voice ID:++```js+const tts = createTTS({+ provider: agentData.voice_provider || 'browser',+ voiceId: agentData.voice_id,+ proxyURL: '/api/tts/elevenlabs', // proxy to keep API key server-side+});+```++The TTS proxy endpoint at `POST /api/tts/elevenlabs` should already exist or needs to be created (it forwards to ElevenLabs with server-side key).++### Manifest field++Add `voice` to the agent manifest type:+```json+{+ "voice": {+ "provider": "elevenlabs",+ "voice_id": "abc123xyz"+ }+}+```++The manifest is served from `GET /api/agents/:id/manifest`. Include the voice field in the manifest response.++---++## Files to create/edit++**Create:**+- `api/agents/[id]/voice.js` — handles `GET`, `POST /clone`, `DELETE` (use method routing or separate files per project convention — check `api/agents/[id]/` for existing patterns)+- `specs/schema/NNN-voice-cloning.sql`+- Voice recording component in `src/editor/voice-recorder.js` (or `.jsx` if existing editor components use vhtml JSX)++**Edit:**+- `api/_lib/schema.sql` — add columns to `agent_identities`+- `src/runtime/index.js` or `src/element.js` — initialize TTS with cloned voice if available+- `api/agents/[id]/manifest.js` — include voice field in manifest response++**Do not touch:**+- `src/runtime/speech.js` — `ElevenLabsTTS` already supports arbitrary `voiceId`+- ElevenLabs TTS proxy if it already exists++---++## Environment variables++- `ELEVENLABS_API_KEY` — server-side only, never sent to client+- Already needed by existing ElevenLabs TTS features++---++## Acceptance criteria++1. Record 45 seconds of speech in the agent editor. Click "Clone Voice." The request processes and returns a `voice_id`.+2. Navigate to the agent's page. Have the agent speak. The voice matches the recording (noticeably different from the browser default voice).+3. Click "Remove voice." The agent reverts to browser TTS.+4. `GET /api/agents/:id/manifest` includes `voice.voice_id` when cloned.+5. Uploading a 3-second clip returns `400` with a clear error: `audio_too_short`.+6. Uploading a 50MB file returns `413`.+7. `npx vite build` passes. `node --check api/agents/[id]/voice.js` passes.++## Constraints++- `ELEVENLABS_API_KEY` must never be sent to the browser. All ElevenLabs API calls go through backend proxy endpoints.+- MediaRecorder records as `audio/webm;codecs=opus` in most browsers. ElevenLabs accepts MP3, WAV, M4A, WebM — WebM/Opus works directly.+- ESM in `src/`. API endpoints use `wrap(...)` pattern from `api/CLAUDE.md`.+- No new npm deps for the recording UI — use native `MediaRecorder` Web API.+- Rate limit voice cloning: max 3 per user per day (implement via `limits` helper or a manual counter).diff --git a/prompts/tasks/voice-input-chat.md b/prompts/tasks/voice-input-chat.mdnew file mode 100644index 000000000..de93f2b31--- /dev/null+++ b/prompts/tasks/voice-input-chat.md@@ -0,0 +1,101 @@+# Task: Add voice input (speech-to-text) to the chat composer++## Context++`/workspaces/3D-Agent/chat/src` is a Svelte chat app. The chat already has TTS output (speaking responses aloud) but no voice input — users can only type messages.++The composer/input area is in `/workspaces/3D-Agent/chat/src/manus/Composer.svelte` or within `App.svelte` (search for the textarea where user messages are typed).++The browser has a native `SpeechRecognition` API (Chrome/Edge) that requires no API key. This is the simplest path.++## What to build++### 1. Find the composer textarea++In `App.svelte` or `Composer.svelte`, find the `<textarea>` or `<input>` where the user types their message. Note what variable it's bound to (likely `userInput` or similar).++### 2. Add a microphone button next to the composer++Add a mic button that starts/stops recording:++```svelte+<script>+ let recording = false;+ let recognition = null;++ function toggleVoiceInput(onResult) {+ if (recording) {+ recognition?.stop();+ recording = false;+ return;+ }+ const SR = window.SpeechRecognition || window.webkitSpeechRecognition;+ if (!SR) {+ alert('Speech recognition is not supported in this browser. Try Chrome or Edge.');+ return;+ }+ recognition = new SR();+ recognition.lang = 'en-US';+ recognition.interimResults = false;+ recognition.onresult = (e) => {+ const transcript = e.results[0][0].transcript;+ onResult(transcript);+ };+ recognition.onerror = () => { recording = false; };+ recognition.onend = () => { recording = false; };+ recognition.start();+ recording = true;+ }+</script>++<button+ type="button"+ title={recording ? 'Stop recording' : 'Speak a message'}+ on:click={() => toggleVoiceInput((t) => { userInput = t; })}+ class="flex h-8 w-8 items-center justify-center rounded-full transition+ {recording ? 'bg-red-500 text-white animate-pulse' : 'text-slate-400 hover:text-slate-600'}"+>+ <!-- mic icon SVG or Icon component -->+</button>+```++Replace `userInput` with whatever variable the textarea is bound to. Use the existing `Icon` component with `feMic` if that icon exists in `feather.js`, or inline a simple SVG mic icon.++### 3. Check feather.js for a mic icon++Run: `grep -n "mic\|Mic" /workspaces/3D-Agent/chat/src/feather.js`++If `feMic` exists, import and use it. If not, add a simple inline SVG:+```svelte+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"+ stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/>+ <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>+ <line x1="12" y1="19" x2="12" y2="23"/>+ <line x1="8" y1="23" x2="16" y2="23"/>+</svg>+```++### 4. Auto-submit option++Optionally, after `onResult` sets the transcript, auto-submit if the message is non-empty:+```js+onResult = (t) => {+ userInput = t;+ // Auto-submit:+ if (t.trim()) submitMessage();+}+```++Only add auto-submit if you find a `submitMessage` or equivalent function that's safe to call directly.++## Files to edit+- `/workspaces/3D-Agent/chat/src/manus/Composer.svelte` or `App.svelte` — wherever the composer textarea lives++## Verification+- Open the chat in Chrome or Edge+- Click the mic button — browser should ask for microphone permission+- Speak a sentence — it should appear in the text input+- Click mic again or finish speaking — recording stops (button returns to grey)+- In Firefox or Safari, clicking mic should show a friendly error message (not crash)+- Pulsing red animation visible while recordingdiff --git a/public/chat/index.html b/public/chat/index.htmlindex 1024c0782..4bc6dd1a7 100644--- a/public/chat/index.html+++ b/public/chat/index.html@@ -43,8 +43,8 @@}}</script>- <script type="module" crossorigin src="/chat/assets/index-BCO4lpvp.js"></script>- <link rel="stylesheet" crossorigin href="/chat/assets/index-B3kWrhvO.css">+ <script type="module" crossorigin src="/chat/assets/index-fqASZrpU.js"></script>+ <link rel="stylesheet" crossorigin href="/chat/assets/index-BUeeFXPP.css"></head><body><div id="app"></div>diff --git a/public/marketplace.css b/public/marketplace.cssindex 3c56591be..dcc3c4634 100644--- a/public/marketplace.css+++ b/public/marketplace.css@@ -660,6 +660,93 @@ body.market-page {margin-top: 3px;}+/* ── Tools tab ───────────────────────────────────────────────────────── */++.market-tools {+ display: flex;+ flex-direction: column;+}++.market-tools-title {+ margin: 0;+ font-size: 16px;+ font-weight: 600;+ color: var(--mk-text);+}++.market-tools-grid {+ padding: 18px 24px 80px;+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));+ gap: 16px;+ align-content: start;+}++.tool-pack-card {+ background: var(--mk-panel);+ border: 1px solid var(--mk-border);+ border-radius: var(--mk-radius);+ padding: 16px;+ display: flex;+ flex-direction: column;+ gap: 10px;+}++.tool-pack-card .head {+ display: flex;+ align-items: center;+ gap: 12px;+}++.tool-pack-card .avatar {+ width: 36px;+ height: 36px;+ border-radius: 8px;+ background: var(--mk-panel-2);+ display: grid;+ place-items: center;+ font-size: 18px;+ flex-shrink: 0;+}++.tool-pack-card .title {+ font-weight: 600;+ font-size: 15px;+ margin: 0;+ color: var(--mk-text);+}++.tool-pack-card .author {+ font-size: 12px;+ color: var(--mk-text-3);+ margin-top: 2px;+}++.tool-pack-card .desc {+ font-size: 13px;+ color: var(--mk-text-2);+ line-height: 1.5;+ flex: 1;+}++.tool-install-btn {+ display: inline-block;+ background: var(--mk-accent);+ color: #0a0a0a;+ border: 0;+ padding: 9px 16px;+ border-radius: 10px;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ text-decoration: none;+ text-align: center;+}++.tool-install-btn:hover {+ background: #fff;+}+/* ── Empty / loading ─────────────────────────────────────────────────── */.market-empty {diff --git a/solana-agent-sdk/tasks/add-custom-errors.md b/solana-agent-sdk/tasks/add-custom-errors.mdnew file mode 100644index 000000000..4c0246069--- /dev/null+++ b/solana-agent-sdk/tasks/add-custom-errors.md@@ -0,0 +1,133 @@+# Feature: Custom error classes++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++## What to Build++The SDK currently throws generic `Error` everywhere. Consumers can't programmatically distinguish "user rejected" from "insufficient funds" from "RPC error". Add custom error classes so consumers can write:++```ts+try {+ await agent.swap(...);+} catch (err) {+ if (err instanceof TransactionRejectedError) showRejectedToast();+ if (err instanceof InsufficientFundsError) showFundsError(err.required, err.available);+ if (err instanceof SwapError) showSwapError(err.quote);+}+```++## Implementation++### `src/errors.ts`++Create this file with the following error classes:++```ts+/** Base class for all @three-ws/solana-agent errors */+export class SolanaAgentError extends Error {+ constructor(message: string) {+ super(message);+ this.name = this.constructor.name;+ }+}++/** Thrown when a transaction is rejected by the user (browser wallet) or timed out waiting for approval */+export class TransactionRejectedError extends SolanaAgentError {+ constructor(public readonly reason: string = "User rejected") {+ super(`Transaction rejected: ${reason}`);+ }+}++/** Thrown when a wallet is not connected (WalletAdapterProvider with null publicKey) */+export class WalletNotConnectedError extends SolanaAgentError {+ constructor() {+ super("Wallet is not connected");+ }+}++/** Thrown when a wallet adapter does not support a required operation */+export class WalletCapabilityError extends SolanaAgentError {+ constructor(public readonly capability: string) {+ super(`Wallet does not support: ${capability}`);+ }+}++/** Thrown when a sender has no token account for the given mint */+export class MissingTokenAccountError extends SolanaAgentError {+ constructor(public readonly mint: string, public readonly owner: string) {+ super(`No token account for mint ${mint} owned by ${owner}`);+ }+}++/** Thrown when a Jupiter swap quote or swap request fails */+export class SwapError extends SolanaAgentError {+ constructor(+ message: string,+ public readonly inputMint?: string,+ public readonly outputMint?: string,+ ) {+ super(message);+ }+}++/** Thrown when transaction simulation fails before submission */+export class SimulationError extends SolanaAgentError {+ constructor(public readonly simulationError: unknown) {+ super(`Transaction simulation failed: ${JSON.stringify(simulationError)}`);+ }+}++/** Thrown when a transaction is not confirmed within the timeout period */+export class ConfirmationTimeoutError extends SolanaAgentError {+ constructor(public readonly signature: string, public readonly timeoutMs: number) {+ super(`Transaction ${signature} not confirmed within ${timeoutMs}ms`);+ }+}+```++### Update existing code to use custom errors++Update these locations to throw custom errors instead of generic `Error`:++**`src/wallet/browser-server.ts`:**+- Timeout: `throw new TransactionRejectedError("Timed out waiting for user approval")` (import `TransactionRejectedError`)+- User rejected: `throw new TransactionRejectedError("User rejected")`++**`src/actions/transfer-spl.ts`** (after fix-sender-ata-missing.md is applied, or add it now):+- No sender ATA: `throw new MissingTokenAccountError(mint.toBase58(), wallet.publicKey.toBase58())`++**`src/tx/fees.ts`** (after fix-cu-fallback.md is applied, or add it now):+- Simulation error: `throw new SimulationError(sim.value.err)`++**`src/actions/swap.ts`:**+- Jupiter quote fail: `throw new SwapError(\`Jupiter quote failed: ${await res.text()}\`, inputMint, outputMint)`+- Jupiter swap fail: `throw new SwapError(\`Jupiter swap failed: ${await res.text()}\`, inputMint, outputMint)`++### Export++**`src/index.ts`** — add:+```ts+export {+ SolanaAgentError,+ TransactionRejectedError,+ WalletNotConnectedError,+ WalletCapabilityError,+ MissingTokenAccountError,+ SwapError,+ SimulationError,+ ConfirmationTimeoutError,+} from "./errors.js";+```++## Verification++1. `npm run build` passes with zero errors+2. All error classes are exported from the main package entry point+3. `new TransactionRejectedError() instanceof SolanaAgentError` is `true`+4. `new TransactionRejectedError() instanceof Error` is `true`+5. Error `name` property matches the class name (not "Error")+6. At minimum `browser-server.ts` uses `TransactionRejectedError` instead of generic `Error`diff --git a/solana-agent-sdk/tasks/add-decimal-fetch-onchain.md b/solana-agent-sdk/tasks/add-decimal-fetch-onchain.mdnew file mode 100644index 000000000..3a29f8883--- /dev/null+++ b/solana-agent-sdk/tasks/add-decimal-fetch-onchain.md@@ -0,0 +1,104 @@+# Feature: Fetch token decimals on-chain instead of guessing++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++## The Problem++`src/actions/swap.ts` contains:+```ts+function guessDecimals(mint: string): number {+ const KNOWN: Record<string, number> = {+ [SOL_MINT]: 9,+ "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v": 6, // USDC mainnet+ // ...+ };+ return KNOWN[mint] ?? 9; // defaults to 9 — wrong for most tokens+}+```++Most SPL tokens use 6 decimals, not 9. Using 9 as a fallback makes display values 1,000x too small for any unknown token. The display is only used in `TxMetadata` (shown to the user before they sign), so a wrong decimal count shows misleading amounts like "1,000,000 BONK" instead of "0.001 BONK".++## Fix++### `src/actions/swap.ts`++Replace the synchronous `guessDecimals` with an async function that fetches from chain, with a local cache for the session:++```ts+const decimalsCache = new Map<string, number>();++async function fetchDecimals(connection: Connection, mint: string): Promise<number> {+ if (mint === SOL_MINT) return 9;++ const cached = decimalsCache.get(mint);+ if (cached !== undefined) return cached;++ try {+ const { getMint, TOKEN_PROGRAM_ID } = await import("@solana/spl-token");+ const { PublicKey } = await import("@solana/web3.js");+ const info = await getMint(connection, new PublicKey(mint), "confirmed", TOKEN_PROGRAM_ID);+ decimalsCache.set(mint, info.decimals);+ return info.decimals;+ } catch {+ // Unknown or token-2022 mint — default to 6 (more common than 9 for non-SOL tokens)+ return 6;+ }+}+```++**Important:** `@solana/spl-token` and `@solana/web3.js` are already direct dependencies — do NOT use dynamic `import()`. Import them statically at the top of the file as they already are.++Updated static version:+```ts+const decimalsCache = new Map<string, number>();++async function fetchDecimals(connection: Connection, mint: string): Promise<number> {+ if (mint === SOL_MINT) return 9;+ const cached = decimalsCache.get(mint);+ if (cached !== undefined) return cached;+ try {+ const info = await getMint(connection, new PublicKey(mint), "confirmed", TOKEN_PROGRAM_ID);+ decimalsCache.set(mint, info.decimals);+ return info.decimals;+ } catch {+ return 6;+ }+}+```++`getMint` and `TOKEN_PROGRAM_ID` are already imported from `@solana/spl-token` in the file — confirm they're in scope or add to the existing import.++### Update `jupiterSwap` signature++The function already has `connection: Connection` as a parameter. Change the metadata-building block from:+```ts+const inDecimals = guessDecimals(inputMint);+const outDecimals = guessDecimals(outputMint);+```+to:+```ts+const [inDecimals, outDecimals] = await Promise.all([+ fetchDecimals(connection, inputMint),+ fetchDecimals(connection, outputMint),+]);+```++### Remove `guessDecimals`++Delete the old `guessDecimals` function entirely. Remove the `KNOWN` constants map.++### Keep the well-known fallback for SOL++`SOL_MINT` is already handled explicitly in `fetchDecimals` (returns 9). The other known mints (USDC, USDT, mSOL) will be fetched from chain and cached — their correct values will be retrieved on first use.++## Verification++1. `npm run build` passes with zero errors+2. No `guessDecimals` function exists in the codebase+3. `fetchDecimals` returns 9 for `SOL_MINT` without an RPC call+4. `fetchDecimals` caches results — calling twice for the same mint only makes one RPC call+5. Fallback for unknown/failed mint is 6 (not 9)diff --git a/solana-agent-sdk/tasks/add-memo-support.md b/solana-agent-sdk/tasks/add-memo-support.mdnew file mode 100644index 000000000..b28ec98fe--- /dev/null+++ b/solana-agent-sdk/tasks/add-memo-support.md@@ -0,0 +1,112 @@+# Feature: Memo attachment to transactions++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++## What to Build++The Solana Memo Program (`MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr`) allows attaching arbitrary UTF-8 text to any transaction. This is commonly used for tagging payments, adding notes, or including off-chain identifiers (e.g. invoice IDs, chat message IDs).++## Implementation++### `src/utils/memo.ts`++```ts+import { PublicKey, TransactionInstruction } from "@solana/web3.js";++export const MEMO_PROGRAM_ID = new PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr");++/**+ * Build a Memo program instruction.+ * The memo string will be visible in explorer and indexers.+ * Max recommended length: 566 bytes (Solana transaction size limit).+ */+export function memoInstruction(memo: string, signerPublicKeys: PublicKey[] = []): TransactionInstruction {+ const data = Buffer.from(memo, "utf-8");+ return new TransactionInstruction({+ keys: signerPublicKeys.map((pk) => ({ pubkey: pk, isSigner: true, isWritable: false })),+ programId: MEMO_PROGRAM_ID,+ data,+ });+}+```++### Add `memo` to `BuildAndSendOptions`++`src/tx/build.ts` — add optional `memo` to `BuildAndSendOptions`:++```ts+export interface BuildAndSendOptions {+ priorityFee?: number;+ cuLimit?: number;+ maxRetries?: number;+ meta?: TxMetadata;+ lookupTables?: AddressLookupTableAccount[];+ /**+ * Optional UTF-8 memo string attached to the transaction.+ * Visible in Solana Explorer and on-chain indexers.+ */+ memo?: string;+}+```++In `buildAndSend`, if `opts.memo` is provided, add a memo instruction at the END of the instruction list (memo must be last per convention):++```ts+const allInstructions = opts.memo+ ? [...instructions, memoInstruction(opts.memo, [wallet.publicKey])]+ : instructions;+```++Use `allInstructions` for CU estimation and transaction building.++### Add `memo` parameter to transfer functions++**`src/actions/transfer-sol.ts`** — add `memo?: string` to `TransferSolParams`:+```ts+export interface TransferSolParams {+ to: PublicKey | string;+ amount: number;+ memo?: string;+}+```+Pass through to `buildAndSend` opts:+```ts+return buildAndSend(wallet, connection, [ix], {+ ...opts,+ memo: params.memo ?? opts?.memo,+ meta: ...+});+```++**`src/actions/transfer-spl.ts`** — same, add `memo?: string` to `TransferSplParams`.++### Add `memo` to LLM action schemas++**`src/solana-agent-kit/actions.ts`** — add optional `memo` to `transferSolAction` and `transferSplAction` schemas:+```ts+memo: z.string().max(500).optional().describe("Optional memo string attached to the transaction (visible on-chain)"),+```++Pass it through to the action params in the handler.++### Export++**`src/utils/memo.ts`** — export `memoInstruction` and `MEMO_PROGRAM_ID`.++**`src/index.ts`** — add:+```ts+export { memoInstruction, MEMO_PROGRAM_ID } from "./utils/memo.js";+```++## Verification++1. `npm run build` passes with zero errors+2. `memoInstruction` and `MEMO_PROGRAM_ID` exported from main index+3. `BuildAndSendOptions.memo` is optional (no breaking change)+4. `TransferSolParams.memo` and `TransferSplParams.memo` are optional+5. LLM action schemas have optional `memo` field+6. No new npm dependencies (Memo program is a Solana native program, no SDK needed)diff --git a/solana-agent-sdk/tasks/add-staking-actions.md b/solana-agent-sdk/tasks/add-staking-actions.mdnew file mode 100644index 000000000..b14ac5c97--- /dev/null+++ b/solana-agent-sdk/tasks/add-staking-actions.md@@ -0,0 +1,128 @@+# Feature: SOL staking actions (stake, unstake, get stake)++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++Staking is one of the most common Solana operations. This task adds native SOL staking support via the Solana Stake Program — no third-party protocols.++## What to Build++### `src/actions/stake.ts`++Three functions:++**1. `stakeSOL` — delegate SOL to a validator**+```ts+export interface StakeSolParams {+ /** Amount of SOL to stake (not lamports) */+ amount: number;+ /** Validator vote account address */+ voteAccount: PublicKey | string;+}++export interface StakeSolResult {+ signature: string;+ /** The new stake account address */+ stakeAccount: string;+}++export async function stakeSOL(+ wallet: WalletProvider,+ connection: Connection,+ params: StakeSolParams,+ opts?: BuildAndSendOptions,+): Promise<StakeSolResult>+```++Implementation:+- Generate a new `Keypair` for the stake account (ephemeral — its private key is discarded after creating, since it's owned by the stake program)+- Build instructions: `SystemProgram.createAccount` → `StakeProgram.initialize` → `StakeProgram.delegate`+- Sign the transaction with BOTH the wallet keypair AND the stake account keypair (the stake account needs to sign its creation). Note: `WalletProvider` only signs with one key — use `buildAndSend` but also add the stake account as a partial signer. For the browser wallet case, the stake account keypair can sign locally before sending to the browser.+- Actually: since we need the stake account to sign too, and `buildAndSend` doesn't support extra signers, build the transaction manually here rather than using `buildAndSend`.+- Metadata: `{ label: "Stake X SOL", kind: "custom", amountIn: { amount, symbol: "SOL", uiAmount: X } }`++**2. `unstakeSOL` — deactivate a stake account**+```ts+export interface UnstakeSolParams {+ /** Stake account address to deactivate */+ stakeAccount: PublicKey | string;+}++export async function unstakeSOL(+ wallet: WalletProvider,+ connection: Connection,+ params: UnstakeSolParams,+ opts?: BuildAndSendOptions,+): Promise<string> // returns signature+```++- Builds a `StakeProgram.deactivate` instruction+- Uses `buildAndSend`+- Note: deactivation takes ~1 epoch (2-3 days) before the SOL is withdrawable++**3. `getStakeAccounts` — list all stake accounts**+```ts+export interface StakeAccountInfo {+ address: string;+ lamports: number;+ state: "initialized" | "delegated" | "deactivating" | "inactive";+ voteAccount?: string;+ activationEpoch?: number;+ deactivationEpoch?: number;+}++export async function getStakeAccounts(+ connection: Connection,+ owner: PublicKey,+): Promise<StakeAccountInfo[]>+```++- Uses `connection.getProgramAccounts(StakeProgram.programId, { filters: [{ memcmp: { offset: 44, bytes: owner.toBase58() } }] })`+- Parses the stake account data to extract state and validator info+- Returns array sorted by lamports descending++### Imports++Use from `@solana/web3.js`:+```ts+import { StakeProgram, Authorized, Lockup, LAMPORTS_PER_SOL, ... } from "@solana/web3.js";+```++`StakeProgram` has static methods: `createAccount`, `initialize`, `delegate`, `deactivate`, `withdraw`.++### Export++**`src/actions/index.ts`** — add:+```ts+export { stakeSOL, unstakeSOL, getStakeAccounts } from "./stake.js";+export type { StakeSolParams, StakeSolResult, StakeAccountInfo } from "./stake.js";+```++**`src/agent.ts`** — add three methods:+```ts+stakeSOL(voteAccount: PublicKey | string, amount: number, opts?: BuildAndSendOptions): Promise<StakeSolResult>+unstakeSOL(stakeAccount: PublicKey | string, opts?: BuildAndSendOptions): Promise<string>+getStakeAccounts(): Promise<StakeAccountInfo[]>+```++**`src/index.ts`** — export the new types and functions.++### LLM actions — `src/solana-agent-kit/actions.ts`++Add three actions following the existing pattern (Zod schema, similes, examples, handler):+- `stake_sol` — stakes SOL to a validator+- `unstake_sol` — deactivates a stake account+- `get_stake_accounts` — lists stake accounts++Add them to `allActions`.++## Verification++1. `npm run build` passes with zero errors+2. `stakeSOL`, `unstakeSOL`, `getStakeAccounts` exported from main index+3. `SolanaAgent` has all three methods+4. Three new LLM actions in `allActions` array in `solana-agent-kit/actions.ts`+5. No new npm dependenciesdiff --git a/solana-agent-sdk/tasks/add-tests-actions.md b/solana-agent-sdk/tasks/add-tests-actions.mdnew file mode 100644index 000000000..02ae9f921--- /dev/null+++ b/solana-agent-sdk/tasks/add-tests-actions.md@@ -0,0 +1,102 @@+# Tests: Unit tests for action functions++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Package location: `/workspaces/3D-Agent/solana-agent-sdk/`++The existing `agent-payments-sdk` package uses Jest (`jest.config.ts`, `ts-jest`). This package has no tests yet. Use the same stack.++Install test dependencies:+```bash+cd /workspaces/3D-Agent/solana-agent-sdk+npm install --save-dev jest ts-jest @types/jest+```++Add to `package.json` scripts:+```json+"test": "node --experimental-vm-modules node_modules/.bin/jest"+```++Create `jest.config.ts`:+```ts+import type { Config } from "jest";++const config: Config = {+ preset: "ts-jest/presets/default-esm",+ testEnvironment: "node",+ extensionsToTreatAsEsm: [".ts"],+ moduleNameMapper: {+ "^(\\.{1,2}/.*)\\.js$": "$1",+ },+ transform: {+ "^.+\\.ts$": ["ts-jest", { useESM: true }],+ },+};++export default config;+```++## What to Test++Create `tests/actions/` directory with these test files. All tests must be fully self-contained — mock RPC calls, do not hit mainnet/devnet.++### `tests/actions/transfer-sol.test.ts`++Test `transferSol` from `src/actions/transfer-sol.ts`.++Mock `buildAndSend` to capture what it receives. The tests should verify:++1. **Correct lamport conversion**: `amount: 0.5` → `lamports = 500_000_000`+2. **Correct instruction**: `SystemProgram.transfer` instruction is built with correct `fromPubkey`, `toPubkey`, `lamports`+3. **Metadata is generated**: `opts.meta.label` contains the amount and "SOL"+4. **Metadata kind**: `opts.meta.kind === "transfer"`+5. **String address accepted**: passing `to` as a base58 string works the same as `PublicKey`+6. **Custom meta override**: if `opts.meta` is provided, it's used instead of auto-generated++Use a mock `WalletProvider` with a fixed public key.++### `tests/actions/transfer-spl.test.ts`++Test `transferSpl` from `src/actions/transfer-spl.ts`.++Mock `connection.getAccountInfo`, `connection.getMint` (via `getMint` from spl-token), and `buildAndSend`.++Tests:+1. **Receiver ATA creation**: when `getAccountInfo(receiverAta)` returns null, a `createAssociatedTokenAccountInstruction` is added+2. **No receiver ATA creation**: when receiver ATA exists, no creation instruction+3. **Sender ATA check**: when `getAccountInfo(senderAta)` returns null, throws an error containing "no token account"+4. **TransferChecked instruction**: correct `senderAta`, `mint`, `receiverAta`, `authority`, `amount`, `decimals`+5. **BigInt metadata**: `uiAmount` is correct string — no `Number(bigint)` precision loss++### `tests/actions/swap.test.ts`++Test `jupiterSwap` and `getSwapQuote` from `src/actions/swap.ts`.++Mock `global.fetch` to return controlled Jupiter API responses.++Tests:+1. **Quote fetch**: correct URL is constructed with `inputMint`, `outputMint`, `amount`, `slippageBps`+2. **Default slippage**: when not provided, defaults to 50 bps+3. **Swap request**: correct POST body `{ quoteResponse, userPublicKey, dynamicComputeUnitLimit: true, prioritizationFeeLamports: "auto" }`+4. **Quote error**: when quote API returns non-200, throws `Error` (or `SwapError` if custom errors task is done)+5. **Swap error**: when swap API returns non-200, throws `Error`+6. **Metadata on MetaAwareWallet**: when wallet implements `setNextMeta`, it's called with a swap metadata object including `kind: "swap"`, `amountIn`, `amountOut`+7. **Non-MetaAware wallet**: when wallet doesn't implement `setNextMeta`, no error is thrown++### `tests/actions/ata.test.ts`++Test `getOrCreateAta` from `src/actions/ata.ts`.++Tests:+1. **ATA already exists**: returns `{ ata, signature: undefined }` when `getAccountInfo` returns data+2. **ATA doesn't exist**: builds `createAssociatedTokenAccountInstruction`, calls `buildAndSend`, returns `{ ata, signature: "fakeSig" }`+3. **Default owner**: when `owner` not provided, uses `wallet.publicKey`+4. **Custom owner**: when `owner` is provided, uses that address++## Verification++1. `npm run build` passes with zero errors+2. `npm test` passes with all tests green+3. No test hits an external network (all RPC calls are mocked)+4. Test files are in `tests/` directory, not `src/`diff --git a/solana-agent-sdk/tasks/add-tests-wallet-providers.md b/solana-agent-sdk/tasks/add-tests-wallet-providers.mdnew file mode 100644index 000000000..4f77fd849--- /dev/null+++ b/solana-agent-sdk/tasks/add-tests-wallet-providers.md@@ -0,0 +1,116 @@+# Tests: Unit tests for wallet providers++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Package location: `/workspaces/3D-Agent/solana-agent-sdk/`++If Jest is not yet set up, install it:+```bash+cd /workspaces/3D-Agent/solana-agent-sdk+npm install --save-dev jest ts-jest @types/jest+```++`jest.config.ts` (create if missing):+```ts+import type { Config } from "jest";+const config: Config = {+ preset: "ts-jest/presets/default-esm",+ testEnvironment: "node",+ extensionsToTreatAsEsm: [".ts"],+ moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1" },+ transform: { "^.+\\.ts$": ["ts-jest", { useESM: true }] },+};+export default config;+```++`package.json` scripts: `"test": "node --experimental-vm-modules node_modules/.bin/jest"`++The wallet provider source files are in `src/wallet/`:+- `keypair.ts` — `KeypairWalletProvider`+- `browser-server.ts` — `BrowserWalletProvider`+- `browser-client.ts` — `BrowserWalletClient`++## What to Test++Create `tests/wallet/` directory.++### `tests/wallet/keypair.test.ts`++Test `KeypairWalletProvider`.++Generate a test keypair using `Keypair.generate()` from `@solana/web3.js`.++Tests:+1. **Base58 string constructor**: `new KeypairWalletProvider(bs58EncodedKey)` sets correct `publicKey`+2. **Uint8Array constructor**: `new KeypairWalletProvider(keypair.secretKey)` sets correct `publicKey`+3. **Array constructor**: `new KeypairWalletProvider(Array.from(keypair.secretKey))` sets correct `publicKey`+4. **signTransaction (legacy)**: signs a `Transaction`, result has a signature for the keypair's public key+5. **signTransaction (versioned)**: signs a `VersionedTransaction`, result `signatures` array is non-empty+6. **signAndSendTransaction**: mocks `sendAndConfirmTransaction` to return `"fakeSig"`, verifies it's called with the keypair++For test 6, mock the module:+```ts+jest.mock("@solana/web3.js", () => ({+ ...jest.requireActual("@solana/web3.js"),+ sendAndConfirmTransaction: jest.fn().mockResolvedValue("fakeSig"),+}));+```++### `tests/wallet/browser-server.test.ts`++Test `BrowserWalletProvider`.++Tests:+1. **Constructor defaults**: `sessionId` is a UUID string, `publicKey` is set from options+2. **String publicKey**: constructor accepts base58 string, converts to `PublicKey`+3. **setNextMeta**: calling `setNextMeta(meta)` then `signTransaction` attaches `meta` to the pending tx+4. **signTransaction creates pending entry**: after calling `signTransaction`, `getPending()` has one entry+5. **signTransaction pending has correct fields**: `id`, `transaction` (base64), `versioned`, `createdAt`, `meta`+6. **submitSigned resolves the promise**: calling `submitSigned(id, signedBase64)` resolves the pending `signTransaction` promise+7. **submitRejected rejects the promise**: calling `submitRejected(id)` rejects with an error containing "rejected"+8. **timeout**: if neither `submitSigned` nor `submitRejected` is called within `timeoutMs`, the promise rejects with "timed out"+9. **meta consumed once**: after one `signTransaction` call, `nextMeta` is cleared; a second call has `meta: undefined`++For test 8, use a short `timeoutMs` (e.g. 50ms) and `jest.useFakeTimers()`.++For test 6, build a valid signed transaction:+```ts+const tx = new Transaction();+tx.recentBlockhash = "11111111111111111111111111111111";+tx.feePayer = Keypair.generate().publicKey;+const signed = Buffer.from(tx.serialize({ requireAllSignatures: false })).toString("base64");+```++### `tests/wallet/browser-client.test.ts`++Test `BrowserWalletClient`. This file runs in Node.js but `BrowserWalletClient` uses `EventSource` and browser globals (`fetch`, `atob`, `btoa`). Mock them.++Setup:+```ts+global.fetch = jest.fn();+global.EventSource = jest.fn().mockImplementation((url: string) => ({+ onmessage: null,+ onerror: null,+ close: jest.fn(),+})) as any;+```++Tests:+1. **connect() opens EventSource**: after `client.connect()`, `EventSource` constructor was called with `baseUrl + "/stream"`+2. **disconnect() closes EventSource**: after connect then disconnect, `close()` is called+3. **onmessage triggers signing**: simulate a message event with a pending tx; verify `signer` is called+4. **auto-sign without onApproval**: signer is called immediately when a message arrives (no approval step)+5. **onApproval blocks signing**: when `onApproval` is provided, signer is NOT called until `approve()` is invoked+6. **onApproval reject path**: calling `reject()` in handler calls `fetch` to the `/reject/:id` endpoint, signer is NOT called+7. **onConfirmed fires**: when the sign POST returns `{ ok: true, signature: "abc" }`, `onConfirmed` is called with the pending tx and `"abc"`+8. **reconnect on error**: simulate `onerror`, verify a new `EventSource` is created after `reconnectMs`++Use `jest.useFakeTimers()` for test 8.++## Verification++1. `npm run build` passes+2. `npm test` passes — all tests green+3. No test uses real network connections+4. `tests/wallet/` contains three test filesdiff --git a/solana-agent-sdk/tasks/add-token-balance-methods.md b/solana-agent-sdk/tasks/add-token-balance-methods.mdnew file mode 100644index 000000000..69d1214cf--- /dev/null+++ b/solana-agent-sdk/tasks/add-token-balance-methods.md@@ -0,0 +1,112 @@+# Feature: `getTokenBalance` and `getTokenAccounts` on `SolanaAgent`++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++`src/agent.ts` contains the `SolanaAgent` class. It currently has:+- `getBalance()` — returns SOL balance in lamports+- `transferSol()`, `transferSpl()`, `swap()`, `getOrCreateAta()`++It is missing basic token balance reads.++## What to Build++Add two methods to `SolanaAgent` and two standalone functions to `src/actions/`:++### Standalone functions++**`src/actions/get-token-balance.ts`**++```ts+export interface TokenBalanceResult {+ mint: string;+ amount: string; // raw base units+ decimals: number;+ uiAmount: string; // human readable+ ata: string; // ATA address+}++export async function getTokenBalance(+ connection: Connection,+ owner: PublicKey,+ mint: PublicKey | string,+): Promise<TokenBalanceResult | null>+```++- Derives the ATA for `owner` + `mint`+- Fetches the token account via `connection.getTokenAccountBalance(ata)`+- Returns `null` if the account doesn't exist (not an error)+- Returns `TokenBalanceResult` with all fields populated+- `uiAmount` should use BigInt-safe division (same pattern as `fix-bigint-precision-swap.md` recommends — `whole.frac` string format, no `Number()` on large values)++**`src/actions/get-token-accounts.ts`**++```ts+export interface TokenAccount {+ mint: string;+ ata: string;+ amount: string; // raw base units+ decimals: number;+ uiAmount: string;+}++export async function getTokenAccounts(+ connection: Connection,+ owner: PublicKey,+): Promise<TokenAccount[]>+```++- Uses `connection.getParsedTokenAccountsByOwner(owner, { programId: TOKEN_PROGRAM_ID })`+- Returns all token accounts with non-zero balance+- Filters out zero-balance accounts+- Uses `@solana/spl-token`'s `TOKEN_PROGRAM_ID` for the filter+- `uiAmount` uses BigInt-safe division++### `src/actions/index.ts`++Add exports:+```ts+export { getTokenBalance } from "./get-token-balance.js";+export type { TokenBalanceResult } from "./get-token-balance.js";+export { getTokenAccounts } from "./get-token-accounts.js";+export type { TokenAccount } from "./get-token-accounts.js";+```++### `src/agent.ts`++Add two methods:++```ts+/** Get SPL token balance. Returns null if the wallet has no account for that mint. */+getTokenBalance(mint: PublicKey | string): Promise<TokenBalanceResult | null> {+ return getTokenBalance(this.connection, this.wallet.publicKey, mint);+}++/** List all SPL token accounts with non-zero balance. */+getTokenAccounts(): Promise<TokenAccount[]> {+ return getTokenAccounts(this.connection, this.wallet.publicKey);+}+```++Import the functions at the top of `agent.ts`.++### `src/index.ts`++Add exports for the new types and functions:+```ts+export { getTokenBalance } from "./actions/get-token-balance.js";+export type { TokenBalanceResult } from "./actions/get-token-balance.js";+export { getTokenAccounts } from "./actions/get-token-accounts.js";+export type { TokenAccount } from "./actions/get-token-accounts.js";+```++## Verification++1. `npm run build` passes with zero errors+2. `SolanaAgent` has both `getTokenBalance(mint)` and `getTokenAccounts()` methods+3. Both standalone functions are exported from the main index+4. `getTokenBalance` returns `null` (not an error) when the ATA doesn't exist+5. `uiAmount` fields use BigInt-safe arithmetic — no `Number(bigint)`diff --git a/solana-agent-sdk/tasks/add-token22-support.md b/solana-agent-sdk/tasks/add-token22-support.mdnew file mode 100644index 000000000..cefc91479--- /dev/null+++ b/solana-agent-sdk/tasks/add-token22-support.md@@ -0,0 +1,94 @@+# Feature: Token-2022 program support++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++Token-2022 (also called Token Extensions) is Solana's newer token standard. Many modern tokens (including memecoins and DeFi tokens) use `TOKEN_2022_PROGRAM_ID` instead of the original `TOKEN_PROGRAM_ID`. Currently the SDK hardcodes `TOKEN_PROGRAM_ID` everywhere, causing silent failures for Token-2022 tokens.++## What to Build++### Detect the correct program ID for any mint++Create a utility function that fetches a mint's owner program from chain:++**`src/utils/token-program.ts`**:+```ts+import { Connection, PublicKey } from "@solana/web3.js";+import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token";++const programCache = new Map<string, PublicKey>();++/**+ * Returns the token program ID (TOKEN_PROGRAM_ID or TOKEN_2022_PROGRAM_ID)+ * for a given mint. Result is cached for the lifetime of the process.+ */+export async function getTokenProgramId(+ connection: Connection,+ mint: PublicKey,+): Promise<PublicKey> {+ const key = mint.toBase58();+ const cached = programCache.get(key);+ if (cached) return cached;++ const info = await connection.getAccountInfo(mint);+ if (!info) throw new Error(`Mint account not found: ${key}`);++ // TOKEN_2022 program is the owner of Token-2022 mints+ const programId = info.owner.equals(TOKEN_2022_PROGRAM_ID)+ ? TOKEN_2022_PROGRAM_ID+ : TOKEN_PROGRAM_ID;++ programCache.set(key, programId);+ return programId;+}+```++### Update `transferSpl`++`src/actions/transfer-spl.ts` currently hardcodes `TOKEN_PROGRAM_ID` in 4 places. Update it to detect the program:++1. After deriving `mint` as `PublicKey`, call `getTokenProgramId(connection, mint)` to get the correct program+2. Replace all hardcoded `TOKEN_PROGRAM_ID` references with the fetched `tokenProgram`+3. Pass `tokenProgram` to `getMint`, `getAssociatedTokenAddressSync`, `createAssociatedTokenAccountInstruction`, and `createTransferCheckedInstruction`++```ts+const mint = typeof params.mint === "string" ? new PublicKey(params.mint) : params.mint;+const to = typeof params.to === "string" ? new PublicKey(params.to) : params.to;++const tokenProgram = await getTokenProgramId(connection, mint);++const mintInfo = await getMint(connection, mint, "confirmed", tokenProgram);+const senderAta = getAssociatedTokenAddressSync(mint, wallet.publicKey, false, tokenProgram, ASSOCIATED_TOKEN_PROGRAM_ID);+const receiverAta = getAssociatedTokenAddressSync(mint, to, false, tokenProgram, ASSOCIATED_TOKEN_PROGRAM_ID);+// ... rest of function uses tokenProgram instead of TOKEN_PROGRAM_ID+```++### Update `getOrCreateAta`++`src/actions/ata.ts` similarly hardcodes `TOKEN_PROGRAM_ID`. Update using the same pattern:++1. Add `connection: Connection` — it's already a parameter+2. After resolving `mint` as `PublicKey`, call `getTokenProgramId(connection, mint)`+3. Replace hardcoded `TOKEN_PROGRAM_ID` with fetched value++### Do NOT update `x402-exact/client.ts` and `x402-exact/facilitator.ts`++The x402 exact scheme uses TransferChecked specifically for established payment tokens (USDC etc.) which are original SPL tokens. Keep those as-is to avoid scope creep.++### Export the utility++**`src/index.ts`** — add:+```ts+export { getTokenProgramId } from "./utils/token-program.js";+```++## Verification++1. `npm run build` passes with zero errors+2. `getTokenProgramId` is exported from the main index+3. `transferSpl` and `getOrCreateAta` use `getTokenProgramId` — no hardcoded `TOKEN_PROGRAM_ID`+4. The program cache means calling with the same mint multiple times only hits RPC once+5. `TOKEN_2022_PROGRAM_ID` is imported from `@solana/spl-token` (it's already a dep — no new deps needed)diff --git a/solana-agent-sdk/tasks/add-versioned-tx-buildandsend.md b/solana-agent-sdk/tasks/add-versioned-tx-buildandsend.mdnew file mode 100644index 000000000..ecec74007--- /dev/null+++ b/solana-agent-sdk/tasks/add-versioned-tx-buildandsend.md@@ -0,0 +1,132 @@+# Feature: VersionedTransaction support in `buildAndSend`++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++## The Problem++`src/tx/build.ts` only builds legacy `Transaction` objects:+```ts+const tx = new Transaction();+tx.recentBlockhash = blockhash;+tx.feePayer = wallet.publicKey;+tx.add(...budgetIxs, ...instructions);+```++Solana's current best practice is to use `VersionedTransaction` with Address Lookup Tables (ALTs). Jupiter swaps already return `VersionedTransaction` and handle this internally. But any SDK consumer building more complex transactions (multi-hop routes, compressed NFTs, DeFi protocols with ALTs) needs versioned tx support in `buildAndSend`.++## Fix++### `src/tx/build.ts`++Add `AddressLookupTableAccount` support to `BuildAndSendOptions`:++```ts+import {+ Transaction,+ VersionedTransaction,+ TransactionMessage,+ type AddressLookupTableAccount,+ type Connection,+ type TransactionInstruction,+} from "@solana/web3.js";++export interface BuildAndSendOptions {+ priorityFee?: number;+ cuLimit?: number;+ maxRetries?: number;+ meta?: TxMetadata;+ /**+ * Address Lookup Tables to include. When provided, builds a VersionedTransaction+ * (v0 message) instead of a legacy Transaction. Required for transactions that+ * reference more than 32 accounts.+ */+ lookupTables?: AddressLookupTableAccount[];+}+```++In `buildAndSend`, branch on whether `lookupTables` is provided:++```ts+for (let attempt = 0; attempt < maxRetries; attempt++) {+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();++ let tx: Transaction | VersionedTransaction;++ if (opts.lookupTables && opts.lookupTables.length > 0) {+ // Build versioned (v0) transaction+ const msg = new TransactionMessage({+ payerKey: wallet.publicKey,+ recentBlockhash: blockhash,+ instructions: [...budgetIxs, ...instructions],+ }).compileToV0Message(opts.lookupTables);+ tx = new VersionedTransaction(msg);+ } else {+ // Build legacy transaction (default, backward compatible)+ const legacyTx = new Transaction();+ legacyTx.recentBlockhash = blockhash;+ legacyTx.lastValidBlockHeight = lastValidBlockHeight;+ legacyTx.feePayer = wallet.publicKey;+ legacyTx.add(...budgetIxs, ...instructions);+ tx = legacyTx;+ }++ try {+ return await wallet.signAndSendTransaction(tx, connection);+ } catch (err) {+ // ... retry logic unchanged+ }+}+```++### Update `estimateComputeUnits` in `src/tx/fees.ts`++It already uses `VersionedTransaction` for simulation (which is correct — v0 message works for simulation regardless of whether the final tx is legacy). No change needed.++### Export `AddressLookupTableAccount` type++It's a re-export from `@solana/web3.js` — consumers already have access. No additional export needed.++### Convenience helper++Add to `src/tx/build.ts`:++```ts+/**+ * Fetch Address Lookup Table accounts by their addresses.+ * Pass the result to buildAndSend's `lookupTables` option.+ */+export async function fetchLookupTables(+ connection: Connection,+ addresses: string[],+): Promise<AddressLookupTableAccount[]> {+ const { AddressLookupTableProgram, PublicKey } = await import("@solana/web3.js");+ const accounts = await Promise.all(+ addresses.map(async (addr) => {+ const res = await connection.getAddressLookupTable(new PublicKey(addr));+ if (!res.value) throw new Error(`Lookup table not found: ${addr}`);+ return res.value;+ }),+ );+ return accounts;+}+```++Use static imports (not dynamic `import()`):+```ts+import { ..., AddressLookupTableAccount } from "@solana/web3.js";+```++Export `fetchLookupTables` from `src/tx/index.ts` and `src/index.ts`.++## Verification++1. `npm run build` passes with zero errors+2. `buildAndSend` with no `lookupTables` still builds a legacy `Transaction` (backward compatible)+3. `buildAndSend` with `lookupTables: []` (empty array) also uses legacy Transaction+4. `buildAndSend` with a non-empty `lookupTables` array builds a `VersionedTransaction`+5. `fetchLookupTables` is exported from the main index+6. `AddressLookupTableAccount` type from `@solana/web3.js` is accepted (no new deps)diff --git a/solana-agent-sdk/tasks/add-wallet-adapter-provider.md b/solana-agent-sdk/tasks/add-wallet-adapter-provider.mdnew file mode 100644index 000000000..7cba41bd1--- /dev/null+++ b/solana-agent-sdk/tasks/add-wallet-adapter-provider.md@@ -0,0 +1,97 @@+# Feature: WalletAdapterProvider — bridge from @solana/wallet-adapter++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++Package location: `/workspaces/3D-Agent/solana-agent-sdk/`+Package name: `@three-ws/solana-agent`++The `WalletProvider` interface (in `src/wallet/types.ts`) is:+```ts+export interface WalletProvider {+ readonly publicKey: PublicKey;+ signTransaction<T extends Transaction | VersionedTransaction>(tx: T): Promise<T>;+ signAndSendTransaction(tx: Transaction | VersionedTransaction, connection: Connection): Promise<string>;+}+```++## What to Build++Create `src/wallet/wallet-adapter.ts` — a `WalletAdapterProvider` class that wraps any `@solana/wallet-adapter-base` wallet adapter and makes it compatible with `WalletProvider`.++`@solana/wallet-adapter-base` is the standard wallet adapter interface used by Phantom, Solflare, Backpack, and every other Solana wallet in React/browser apps. Its relevant interface is:++```ts+// From @solana/wallet-adapter-base (do NOT install this package — use structural typing)+interface WalletAdapter {+ publicKey: PublicKey | null;+ signTransaction?<T extends Transaction | VersionedTransaction>(tx: T): Promise<T>;+ signAllTransactions?<T extends Transaction | VersionedTransaction>(txs: T[]): Promise<T[]>;+ sendTransaction(tx: Transaction | VersionedTransaction, connection: Connection, options?: SendTransactionOptions): Promise<string>;+ connected: boolean;+}+```++## Requirements++### `src/wallet/wallet-adapter.ts`++Use structural typing — do NOT add `@solana/wallet-adapter-base` as a dependency. Define a minimal `WalletAdapterLike` interface locally:++```ts+export interface WalletAdapterLike {+ publicKey: PublicKey | null;+ connected: boolean;+ signTransaction?<T extends Transaction | VersionedTransaction>(tx: T): Promise<T>;+ sendTransaction(tx: Transaction | VersionedTransaction, connection: Connection): Promise<string>;+}+```++The `WalletAdapterProvider` class:+- Constructor takes a `WalletAdapterLike`+- `get publicKey()` — throws `Error("Wallet not connected")` if `adapter.publicKey` is null+- `signTransaction(tx)` — delegates to `adapter.signTransaction(tx)`. Throws `Error("Wallet does not support signTransaction")` if the adapter doesn't implement it+- `signAndSendTransaction(tx, connection)` — delegates to `adapter.sendTransaction(tx, connection)`. Does NOT implement separate sign + send — uses the adapter's native `sendTransaction` which handles both internally (required for hardware wallets)++Also implement `MetaAwareWallet` — add `setNextMeta(meta: TxMetadata)` that stores metadata but since adapter wallets don't have a pending queue, just store it for reading (e.g. so a parent component can display it before calling the action). Keep it simple — store in an instance variable, expose `getNextMeta(): TxMetadata | null`.++### Export++Add to `src/wallet/index.ts`:+```ts+export { WalletAdapterProvider } from "./wallet-adapter.js";+export type { WalletAdapterLike } from "./wallet-adapter.js";+```++Add to `src/index.ts`:+```ts+export { WalletAdapterProvider } from "./wallet/wallet-adapter.js";+export type { WalletAdapterLike } from "./wallet/wallet-adapter.js";+```++### Usage example (for documentation — do not create a file, just make this work):+```ts+// In a React component with useWallet() from @solana/wallet-adapter-react:+const { wallet, sendTransaction, signTransaction, publicKey, connected } = useWallet();++const provider = new WalletAdapterProvider({+ publicKey,+ connected,+ signTransaction,+ sendTransaction,+});++const agent = new SolanaAgent({ wallet: provider, connection });+await agent.transferSol("9Wz...", 0.1);+```++## Verification++1. `npm run build` passes with zero errors+2. `WalletAdapterProvider` is exported from both `@three-ws/solana-agent` and `@three-ws/solana-agent/wallet`+3. `WalletAdapterProvider` satisfies the `WalletProvider` interface (TypeScript structural check)+4. `WalletAdapterProvider` satisfies the `MetaAwareWallet` interface+5. No new npm dependencies added to `package.json`diff --git a/solana-agent-sdk/tasks/fix-bigint-precision-swap.md b/solana-agent-sdk/tasks/fix-bigint-precision-swap.mdnew file mode 100644index 000000000..2bc9edea4--- /dev/null+++ b/solana-agent-sdk/tasks/fix-bigint-precision-swap.md@@ -0,0 +1,66 @@+# Fix: BigInt precision loss in swap metadata display++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++## The Bug++`src/actions/swap.ts` converts Jupiter quote amounts to JavaScript `Number` for display:++```ts+// lines 59-60+const inUi = (Number(quote.inAmount) / 10 ** inDecimals).toFixed(4);+const outUi = (Number(quote.outAmount) / 10 ** outDecimals).toFixed(4);+```++`quote.inAmount` and `quote.outAmount` are strings from Jupiter's API. They can represent amounts larger than `Number.MAX_SAFE_INTEGER` (9,007,199,254,740,991). For tokens with low decimals (e.g. USDC at 6 decimals) and large amounts (e.g. $10 million = 10,000,000,000,000 base units), this silently produces wrong display values.++Example: `Number("10000000000000")` = `10000000000000` (ok), but `Number("9007199254740993")` = `9007199254740992` (wrong — off by 1, silently).++This only affects the **display strings in `TxMetadata`** — the actual transaction amounts are passed as strings to Jupiter and are not affected.++## Fix++### `src/actions/swap.ts`++Replace the `Number()` conversion with a BigInt-safe division helper:++```ts+function toUiAmount(amountStr: string, decimals: number): string {+ if (decimals === 0) return amountStr;+ const amount = BigInt(amountStr);+ const divisor = 10n ** BigInt(decimals);+ const whole = amount / divisor;+ const frac = amount % divisor;+ const fracStr = frac.toString().padStart(decimals, "0").replace(/0+$/, "");+ return fracStr ? `${whole}.${fracStr}` : whole.toString();+}+```++Replace lines 59-60 with:+```ts+const inUi = toUiAmount(quote.inAmount, inDecimals);+const outUi = toUiAmount(quote.outAmount, outDecimals);+```++Place the helper function at the bottom of the file alongside `shortMint` and `guessDecimals`.++**Also fix the same issue in `src/actions/transfer-spl.ts` line 58:**+```ts+const uiAmount = (Number(params.amount) / 10 ** mintInfo.decimals).toString();+```+Replace with the same `toUiAmount` helper. Either copy the function into `transfer-spl.ts` or extract it to a shared utility.++**Recommended:** Create `src/utils/format.ts` with the `toUiAmount` function and import it in both files. Export it from the main `src/index.ts` as a named export so consumers can use it too.++## Verification++1. `npm run build` passes with zero errors+2. No `Number(bigint)` or `Number(string_that_could_be_large)` calls in `swap.ts` or `transfer-spl.ts`+3. `toUiAmount("9007199254740993", 6)` returns `"9007199254.740993"` (correct)+4. `toUiAmount("1000000", 6)` returns `"1"` (correct for 1 USDC)+5. `toUiAmount("1500000", 6)` returns `"1.5"` (correct)+6. `toUiAmount("100", 0)` returns `"100"` (handles zero decimals)diff --git a/solana-agent-sdk/tasks/fix-cu-fallback.md b/solana-agent-sdk/tasks/fix-cu-fallback.mdnew file mode 100644index 000000000..f12512965--- /dev/null+++ b/solana-agent-sdk/tasks/fix-cu-fallback.md@@ -0,0 +1,89 @@+# Fix: Compute unit fallback is too high for simple transfers++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++## The Problem++`src/tx/fees.ts` line 35:+```ts+const units = sim.value.unitsConsumed;+if (!units) return 200_000;+return Math.ceil(units * 1.1);+```++When simulation returns 0 or `undefined` for `unitsConsumed`, the fallback is 200,000 CUs. This is roughly 40x too high for a simple SOL transfer (~5,000 CUs) and ~4x too high for a simple SPL transfer (~50,000 CUs). Users pay fees for CUs they don't use.++The `1.1x` multiplier is also applied on top of whatever the simulation returns, which is correct but the fallback itself needs to be smarter.++Additionally, `sim.value.err` is not checked — if simulation fails (e.g. insufficient funds), the function silently returns the fallback instead of throwing.++## Fix++### `src/tx/fees.ts`++**1. Check for simulation errors and throw:**+```ts+if (sim.value.err) {+ throw new Error(`Transaction simulation failed: ${JSON.stringify(sim.value.err)}`);+}+```++**2. Lower the fallback and make it instruction-count-aware:**+```ts+const units = sim.value.unitsConsumed;+if (!units) {+ // Rough heuristic: 10_000 base + 20_000 per instruction (conservative but not wasteful)+ const instructionCount = instructions.length;+ return Math.min(200_000, 10_000 + instructionCount * 20_000);+}+return Math.ceil(units * 1.1);+```++This gives:+- 1 instruction (SOL transfer): 30,000 CU fallback (vs 200,000 before)+- 2 instructions (SPL transfer + ATA create): 50,000 CU fallback+- Still caps at 200,000 for complex txs++**3. Full updated `estimateComputeUnits` function:**+```ts+export async function estimateComputeUnits(+ connection: Connection,+ instructions: TransactionInstruction[],+ payer: PublicKey,+): Promise<number> {+ const { blockhash } = await connection.getLatestBlockhash();+ const msg = new TransactionMessage({+ payerKey: payer,+ recentBlockhash: blockhash,+ instructions,+ }).compileToV0Message();++ const sim = await connection.simulateTransaction(+ new VersionedTransaction(msg),+ { sigVerify: false },+ );++ if (sim.value.err) {+ throw new Error(`Transaction simulation failed: ${JSON.stringify(sim.value.err)}`);+ }++ const units = sim.value.unitsConsumed;+ if (!units) {+ return Math.min(200_000, 10_000 + instructions.length * 20_000);+ }+ return Math.ceil(units * 1.1);+}+```++**Note:** The simulation error throw changes behaviour — previously a failed simulation would silently fall back to 200,000 CUs and the real transaction would also fail. Now it fails fast with a clear error. This is strictly better.++## Verification++1. `npm run build` passes with zero errors+2. `estimateComputeUnits` throws if `sim.value.err` is set+3. Fallback for 1 instruction is ≤ 30,000 (not 200,000)+4. Fallback still caps at 200,000diff --git a/solana-agent-sdk/tasks/fix-duplicate-pendingtx.md b/solana-agent-sdk/tasks/fix-duplicate-pendingtx.mdnew file mode 100644index 000000000..b76fd734d--- /dev/null+++ b/solana-agent-sdk/tasks/fix-duplicate-pendingtx.md@@ -0,0 +1,67 @@+# Fix: Duplicate `PendingTx` interface definition++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++## The Problem++`PendingTx` is defined identically in two files:++**`src/wallet/browser-server.ts` (lines 24-30):**+```ts+export interface PendingTx {+ id: string;+ transaction: string;+ versioned: boolean;+ createdAt: number;+ meta?: TxMetadata;+}+```++**`src/wallet/browser-client.ts` (lines 29-35):**+```ts+export interface PendingTx {+ id: string;+ transaction: string;+ versioned: boolean;+ createdAt: number;+ meta?: TxMetadata;+}+```++These are structurally identical today, but if either is updated (e.g. adding a new field), the other will silently diverge. The browser client already imports `TxMetadata` from `./types.js` — it should import `PendingTx` from `./browser-server.js` instead of re-defining it.++## Fix++### `src/wallet/browser-client.ts`++1. Remove the local `PendingTx` interface definition+2. Import `PendingTx` from `./browser-server.js`:++```ts+import type { PendingTx } from "./browser-server.js";+```++This import already exists for `TxMetadata` from `./types.js`, so the pattern is established.++### `src/wallet/index.ts`++The `PendingTx` type is currently exported from `browser-server.ts` via the index:+```ts+export type { BrowserWalletOptions, PendingTx } from "./browser-server.js";+```+This is already correct — no change needed here.++### Verify no circular imports++`browser-client.ts` imports from `browser-server.ts`. Check that `browser-server.ts` does NOT import from `browser-client.ts`. It should not — `browser-server.ts` only imports from `./types.js` and `@solana/web3.js`.++## Verification++1. `npm run build` passes with zero errors+2. `PendingTx` is defined exactly once — in `src/wallet/browser-server.ts`+3. `src/wallet/browser-client.ts` imports `PendingTx` from `./browser-server.js`+4. No change to the shape or fields of `PendingTx`diff --git a/solana-agent-sdk/tasks/fix-missing-exports.md b/solana-agent-sdk/tasks/fix-missing-exports.mdnew file mode 100644index 000000000..63dda3fec--- /dev/null+++ b/solana-agent-sdk/tasks/fix-missing-exports.md@@ -0,0 +1,44 @@+# Fix: Missing exports from main index++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++## The Problem++`src/tx/index.ts` exports four functions:+```ts+export { buildAndSend } from "./build.js";+export type { BuildAndSendOptions } from "./build.js";+export { estimatePriorityFee, estimateComputeUnits, priorityFeeIx, computeUnitIx } from "./fees.js";+```++But `src/index.ts` (the main package entry) only re-exports two of them:+```ts+export { buildAndSend, estimatePriorityFee, estimateComputeUnits } from "./tx/index.js";+```++`priorityFeeIx` and `computeUnitIx` are missing. These are useful for advanced consumers who want to build custom transactions with manual compute budget control.++## Fix++### `src/index.ts`++Change line 25 from:+```ts+export { buildAndSend, estimatePriorityFee, estimateComputeUnits } from "./tx/index.js";+```+To:+```ts+export { buildAndSend, estimatePriorityFee, estimateComputeUnits, priorityFeeIx, computeUnitIx } from "./tx/index.js";+```++That's the entire change.++## Verification++1. `npm run build` passes with zero errors+2. `priorityFeeIx` and `computeUnitIx` appear in `dist/index.d.ts` after build+3. A consumer can do: `import { priorityFeeIx, computeUnitIx } from "@three-ws/solana-agent"` without errordiff --git a/solana-agent-sdk/tasks/fix-onconfirmed-callback.md b/solana-agent-sdk/tasks/fix-onconfirmed-callback.mdnew file mode 100644index 000000000..271337e65--- /dev/null+++ b/solana-agent-sdk/tasks/fix-onconfirmed-callback.md@@ -0,0 +1,169 @@+# Fix: `onConfirmed` callback never fires++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++## The Bug++`BrowserWalletClient` has an `onConfirmed` callback option that should fire after a transaction is confirmed on-chain with its signature. It never fires.++**Root cause — two-part:**++**Part 1** — `browser-server.ts` sign handler returns `{ ok: true }` with no signature:+```ts+// src/wallet/browser-server.ts ~line 190-193+if (req.method === "POST" && action === "sign" && id) {+ const body = (await req.json()) as { signedTransaction: string };+ this.submitSigned(id, body.signedTransaction);+ return Response.json({ ok: true }); // ← no signature here+}+```++**Part 2** — `browser-client.ts` expects `{ signature }` in that same response:+```ts+// src/wallet/browser-client.ts ~line 159-161+if (res.ok) {+ const { signature } = (await res.json()) as { signature?: string };+ if (signature) this.opts.onConfirmed?.(pending, signature); // never true+}+```++The problem: `submitSigned` resolves the server-side Promise, which triggers `signAndSendTransaction` to broadcast the tx. But by then the HTTP response has already been sent with `{ ok: true }`. The browser never learns the final signature.++## Fix++The sign handler needs to:+1. Wait for the server to broadcast and confirm the transaction+2. Return `{ signature: string }` in the response++This requires the server to know when the tx has been confirmed. The cleanest approach is to make `submitSigned` return a Promise that resolves to the signature after the server-side flow completes.++**Changes needed:**++### `src/wallet/browser-server.ts`++Change `submitSigned` to return `Promise<string>` (the confirmed signature):+```ts+submitSigned(txId: string, signedBase64: string): Promise<string>+```++Add an internal emitter for the confirmed signature. After `signAndSendTransaction` completes on the server side, emit `confirmed:${id}` with the signature.++In `signAndSendTransaction`, after broadcasting and confirming, emit `confirmed:${id}`:+```ts+async signAndSendTransaction(...) {+ const signed = await this.signTransaction(tx); // waits for browser+ const sig = await connection.sendRawTransaction(signed.serialize(), ...);+ await connection.confirmTransaction(sig, "confirmed");+ this.emitter.emit(`confirmed:${sig_from_signTransaction_id}`, sig); // notify waiting sign handler+ return sig;+}+```++The tricky part: `signTransaction` creates the pending entry and returns the signed tx. Once it resolves, `signAndSendTransaction` has the sig. The sign HTTP handler needs to wait for that sig.++**Recommended implementation:**++In `browser-server.ts`, change the sign handler to wait for a `confirmed:${id}` event before responding:++```ts+// In createHandler():+if (req.method === "POST" && action === "sign" && id) {+ const body = (await req.json()) as { signedTransaction: string };++ // Create a Promise that resolves when the server broadcasts + confirms+ const sigPromise = new Promise<string>((resolve, reject) => {+ const timeout = setTimeout(() => reject(new Error("confirmation timeout")), 60_000);+ this.emitter.once(`confirmed:${id}`, (sig: string) => {+ clearTimeout(timeout);+ resolve(sig);+ });+ });++ this.submitSigned(id, body.signedTransaction); // triggers signAndSendTransaction++ try {+ const signature = await sigPromise;+ return Response.json({ ok: true, signature });+ } catch {+ return Response.json({ ok: false, error: "confirmation timeout" }, { status: 408 });+ }+}+```++In `signAndSendTransaction`, after confirming, emit `confirmed:${id}` where `id` is...++Wait — the problem is that after `signTransaction` resolves, you have the signed tx but not the pending `id`. The `id` is internal to the pending entry.++**Better approach**: store a second emitter map from `id → confirmed`. Pass the `id` through the signing flow.++In `signTransaction`, after the Promise resolves (browser has signed), emit `confirmed:${id}` in the `signAndSendTransaction` wrapper.++Change `signAndSendTransaction` to:+```ts+async signAndSendTransaction(tx, connection) {+ // Need the pending id before signTransaction removes it from the map.+ // Reserve an id upfront, store it as nextPendingId, consume in signTransaction.+ const signed = await this.signTransaction(tx);+ const sig = await connection.sendRawTransaction(signed.serialize(), ...);+ await connection.confirmTransaction(sig, "confirmed");+ // Emit confirmed with the id that was used for this tx+ // signTransaction should expose which id was used+ return sig;+}+```++The cleanest fix: add a `lastSignedId` field that `signTransaction` sets before creating the pending entry, so `signAndSendTransaction` can emit the `confirmed:${id}` event with the right id.++Or even simpler: use a `Map<id, (sig: string) => void>` called `confirmListeners`. In the sign handler, register a listener keyed by `id`. After broadcasting, call it.++**Exact implementation to use:**++Add `private readonly confirmListeners = new Map<string, (sig: string) => void>();`++In `signTransaction`, before resolving the signed tx back to `signAndSendTransaction`, do NOT emit yet — just return the id alongside the signed tx (internal only).++Actually the simplest correct solution:++Modify `signTransaction` to internally track the `id` so `signAndSendTransaction` can emit after confirming. Use an instance variable `private lastPendingId: string | null = null` set at the start of `signTransaction` and cleared after use.++Then in `signAndSendTransaction`:+```ts+async signAndSendTransaction(tx, connection) {+ const signed = await this.signTransaction(tx); // sets lastPendingId+ const pendingId = this.lastPendingId; // capture before clearing+ this.lastPendingId = null;+ const sig = await connection.sendRawTransaction(...);+ await connection.confirmTransaction(sig, "confirmed");+ if (pendingId) this.emitter.emit(`confirmed:${pendingId}`, sig);+ return sig;+}+```++In the sign handler, register a listener before calling `submitSigned`:+```ts+const sigPromise = new Promise<string | null>((resolve) => {+ const t = setTimeout(() => resolve(null), 60_000);+ this.emitter.once(`confirmed:${id}`, (sig: string) => {+ clearTimeout(t);+ resolve(sig);+ });+});+this.submitSigned(id, body.signedTransaction);+const signature = await sigPromise;+return Response.json(signature ? { ok: true, signature } : { ok: false });+```++### `src/wallet/browser-client.ts`++No changes needed — it already reads `{ signature }` from the response and calls `onConfirmed` if present. Once the server returns the real signature, the callback will fire correctly.++## Verification++1. `npm run build` passes with zero errors+2. The `onConfirmed` callback in `BrowserWalletClientOptions` is properly typed and reachable+3. `browser-server.ts` sign handler returns `{ ok: true, signature: string }` after confirmation+4. No regression in the `rejected` handler (still returns `{ ok: true }`)diff --git a/solana-agent-sdk/tasks/fix-sender-ata-missing.md b/solana-agent-sdk/tasks/fix-sender-ata-missing.mdnew file mode 100644index 000000000..91e0df1e5--- /dev/null+++ b/solana-agent-sdk/tasks/fix-sender-ata-missing.md@@ -0,0 +1,75 @@+# Fix: `transferSpl` silently fails when sender has no ATA++## Context++`/workspaces/3D-Agent/solana-agent-sdk` is a TypeScript Solana agent SDK (`@three-ws/solana-agent`).+Build command: `cd /workspaces/3D-Agent/solana-agent-sdk && npm run build`+The build must pass with zero errors before this task is complete.++## The Bug++`src/actions/transfer-spl.ts` derives the sender's ATA address but never checks if the account exists on-chain. If the sender doesn't have a token account for that mint, the `TransferChecked` instruction is still added and the entire transaction fails on-chain with a cryptic `AccountNotFound` error from the RPC.++**Current code (lines 38-49):**+```ts+const senderAta = getAssociatedTokenAddressSync(mint, wallet.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);+const receiverAta = getAssociatedTokenAddressSync(mint, to, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);++const receiverInfo = await connection.getAccountInfo(receiverAta);+if (!receiverInfo) {+ // creates receiver ATA ✓+}+// sender ATA never checked ← bug+```++**Also broken (line 58):**+```ts+const uiAmount = (Number(params.amount) / 10 ** mintInfo.decimals).toString();+```+`Number()` on a `bigint` loses precision for amounts > `2^53`. Use BigInt arithmetic instead.++## Fix++### `src/actions/transfer-spl.ts`++**1. Check sender ATA exists and has sufficient balance before building the transaction:**++After deriving both ATAs, fetch both account infos (can do in parallel):+```ts+const [senderInfo, receiverInfo] = await Promise.all([+ connection.getAccountInfo(senderAta),+ connection.getAccountInfo(receiverAta),+]);++if (!senderInfo) {+ throw new Error(+ `Sender has no token account for mint ${mint.toBase58()}. ` ++ `Create an ATA first or ensure the sender holds this token.`+ );+}+```++**2. Fix BigInt precision in uiAmount display (line 58):**++Replace `Number(params.amount)` with BigInt division:+```ts+// Safe for any token amount+const decimals = BigInt(mintInfo.decimals);+const divisor = 10n ** decimals;+const whole = params.amount / divisor;+const frac = params.amount % divisor;+const uiAmount = decimals === 0n+ ? whole.toString()+ : `${whole}.${frac.toString().padStart(Number(decimals), "0").replace(/0+$/, "") || "0"}`;+```++**3. Keep receiver ATA creation logic as-is** — it's correct.++**Note:** Do not add a balance sufficiency check (i.e., don't fetch token balance to compare against `params.amount`). That would add an extra RPC call and create a TOCTOU race. The on-chain error is the appropriate gate for insufficient balance. The sender ATA existence check is sufficient to prevent the confusing `AccountNotFound` error.++## Verification++1. `npm run build` passes with zero errors+2. `transferSpl` throws a clear `Error` with message containing "no token account" when sender has no ATA+3. `uiAmount` uses BigInt arithmetic — no `Number(bigint)` call+4. `receiverInfo` check and ATA creation logic is unchangeddiff --git a/src/marketplace.js b/src/marketplace.jsindex 6d5af65e7..322291459 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -37,6 +37,7 @@ const $ = (id) => document.getElementById(id);const els = {discovery: $('market-discovery'),detail: $('market-detail'),+ tools: $('market-tools'),cats: $('market-cats'),grid: $('market-grid'),search: $('market-search'),@@ -49,7 +50,10 @@ const els = {function readRoute() {const m = location.pathname.match(/^\/marketplace\/agents\/([^/]+)/);- return m ? { view: 'detail', id: m[1] } : { view: 'list' };+ if (m) return { view: 'detail', id: m[1] };+ const tab = new URLSearchParams(location.search).get('tab');+ if (tab === 'tools') return { view: 'tools' };+ return { view: 'list' };}function navTo(path, replace = false) {@@ -429,11 +433,27 @@ function formatDate(iso) {function render() {const r = readRoute();++ document.querySelectorAll('.market-nav a[data-nav]').forEach((a) => {+ const nav = a.dataset.nav;+ const active =+ (nav === 'agent' && (r.view === 'list' || r.view === 'detail')) ||+ (nav === 'tools' && r.view === 'tools');+ a.classList.toggle('active', active);+ });+if (r.view === 'detail') {loadDetail(r.id);+ els.discovery.hidden = true;+ els.tools.hidden = true;+ } else if (r.view === 'tools') {+ els.detail.hidden = true;+ els.discovery.hidden = true;+ els.tools.hidden = false;} else {els.detail.hidden = true;els.discovery.hidden = false;+ els.tools.hidden = true;}}diff --git a/tasks/task-01-test-runtime-tool-loop.md b/tasks/task-01-test-runtime-tool-loop.mdnew file mode 100644index 000000000..50216b982--- /dev/null+++ b/tasks/task-01-test-runtime-tool-loop.md@@ -0,0 +1,49 @@+# Task: Write Tests for the Agent Runtime Tool Loop++## Context++This is the `three.ws` 3D agent platform. The agent runtime lives in `src/runtime/`. It drives all LLM-powered agent behavior: sending messages to Claude, executing tool calls, and emitting protocol events. This core flow has **zero test coverage**.++## Goal++Write a vitest test suite for the agent runtime tool loop. Tests should live at `tests/src/runtime.test.js`.++## Files to Read First++- `src/runtime/index.js` (~236 lines) — the main runtime class and tool loop (`MAX_TOOL_ITERATIONS=8`)+- `src/runtime/tools.js` (~174 lines) — `BUILTIN_TOOLS` definitions (wave, lookAt, play_clip, setExpression, speak, remember)+- `src/runtime/providers.js` (~116 lines) — `AnthropicProvider` and `NullProvider`+- `src/agent-protocol.js` — `AgentProtocol` event bus, `ACTION_TYPES`+- `tests/src/agent-protocol.test.js` — existing test for reference on style/setup++## What to Test++### Tool loop behavior (`src/runtime/index.js`)+1. Sends user message to provider and gets a response+2. When provider returns a tool call, the runtime dispatches `perform-skill` on the protocol and calls the tool handler+3. Tool loop terminates after `MAX_TOOL_ITERATIONS` (8) even if provider keeps returning tool calls+4. When provider returns a text response (no tool call), loop ends and `speak` action is emitted+5. `think` actions are emitted when provider streams thinking steps (if applicable)+6. Error in tool handler emits `skill-error` on protocol and does not crash the loop++### Built-in tools (`src/runtime/tools.js`)+7. `speak` tool emits `speak` action on protocol with correct text/sentiment payload+8. `remember` tool emits `remember` action on protocol with the provided memory entry+9. `lookAt` tool emits `look-at` action with the correct target+10. `setExpression` tool emits `emote` action with trigger and weight++### NullProvider (`src/runtime/providers.js`)+11. `NullProvider.complete()` returns an empty/noop response without calling any API++## Approach++- Use `NullProvider` (or a mock) to avoid real API calls — keep tests fully offline+- Mock `AgentProtocol` or use a real instance and assert emitted events via `protocol.on()`+- Use `vi.fn()` for tool handlers to assert they were called with correct args+- Follow the existing test style in `tests/src/agent-protocol.test.js`++## Success Criteria++- `npm test tests/src/runtime.test.js` passes with all tests green+- No real HTTP calls made during tests+- Each test is isolated (no shared mutable state between tests)diff --git a/tasks/task-02-test-mcp-server.md b/tasks/task-02-test-mcp-server.mdnew file mode 100644index 000000000..0f6f74093--- /dev/null+++ b/tasks/task-02-test-mcp-server.md@@ -0,0 +1,58 @@+# Task: Write Tests for the MCP Server++## Context++This is the `three.ws` 3D agent platform. The MCP server (`api/mcp.js`, 1,201 lines) implements the Model Context Protocol (MCP 2025-06-18) over JSON-RPC 2.0. It exposes 14 tools to external AI systems. It has **zero test coverage** despite being a critical external-facing API.++## Goal++Write a vitest test suite for the MCP server. Tests should live at `tests/api/mcp.test.js`.++## Files to Read First++- `api/mcp.js` — the full MCP server (read this carefully before writing any tests)+- `api/_lib/auth.js` — `authenticateBearer()`, `getSessionUser()`+- `tests/api/llm-anthropic.test.js` — existing API test for reference on style and how to mock Vercel serverless handlers+- `tests/api/agents.test.js` — another reference for request/response mocking patterns++## What to Test++### Protocol layer+1. `POST /api/mcp` with `method: "initialize"` returns protocol version, server info, and tool list+2. `POST /api/mcp` with unknown method returns JSON-RPC error `-32601` (method not found)+3. `POST /api/mcp` with malformed JSON returns JSON-RPC parse error `-32700`+4. `DELETE /api/mcp` returns 200 (stateless session termination no-op)+5. `GET /api/mcp` returns 405 (SSE not yet implemented)++### Authentication+6. `tools/call` without auth token returns 401 or appropriate JSON-RPC error+7. `tools/call` with a valid bearer JWT succeeds for tools that require no scope+8. `tools/call` for `list_my_avatars` (requires `avatars:read` scope) with a token lacking that scope returns a permission error++### Tool: `search_public_avatars`+9. Returns a list of agents when database has results (mock the DB call)+10. Returns empty list when no results found++### Tool: `validate_model`+11. Returns validation results for a valid model URL (mock `safeFetchModel`)+12. Returns SSRF error when URL resolves to a private IP address++### Tool: `render_avatar`+13. Returns HTML snippet containing `<model-viewer>` for a valid GLB URL++### x402 payment flow+14. Unauthenticated request for a paid tool returns 402 with `WWW-Authenticate` header+15. Request with valid `X-PAYMENT` header passes payment check and proceeds to tool++## Approach++- Mock the Neon DB client to avoid real database calls+- Mock `safeFetchModel` for model-related tools+- Use the same request/response mock pattern as `tests/api/agents.test.js`+- Create a helper `makeRpcRequest(method, params, authHeader?)` to reduce boilerplate++## Success Criteria++- `npm test tests/api/mcp.test.js` passes with all tests green+- No real network or database calls+- Auth paths (no token, wrong scope, valid token) all covereddiff --git a/tasks/task-03-test-auth-flow.md b/tasks/task-03-test-auth-flow.mdnew file mode 100644index 000000000..e2adb89c3--- /dev/null+++ b/tasks/task-03-test-auth-flow.md@@ -0,0 +1,58 @@+# Task: Write Tests for the Auth Flow++## Context++This is the `three.ws` 3D agent platform. Authentication is handled by three systems: email/password sessions (`api/auth/[action].js`), SIWE/Ethereum wallet sign-in (`api/auth/siwe/[action].js`), and OAuth 2.1 with PKCE (`api/oauth/[action].js`). The shared auth helpers live in `api/_lib/auth.js` (291 lines). Some partial tests exist but critical paths are uncovered.++## Goal++Write or extend vitest tests for the auth flow. Check what already exists at `tests/api/oauth-authorize.test.js`, `tests/api/oauth-token.test.js`, and `tests/api/siwe.test.js`, then fill gaps. New tests go in the same files or new ones in `tests/api/`.++## Files to Read First++- `api/_lib/auth.js` — all auth helpers: `getSessionUser`, `authenticateBearer`, `mintAccessToken`, `issueRefreshToken`, `rotateRefreshToken`, `createSession`, `csrfTokenFor`, `verifyCsrfToken`, `hashPassword`, `verifyPassword`+- `api/auth/[action].js` — login, logout, register, password reset, email verify+- `api/auth/siwe/[action].js` — SIWE nonce + verify+- `api/oauth/[action].js` — authorize, token, register, revoke, introspect+- `tests/api/oauth-authorize.test.js` — read this first to understand what's already tested+- `tests/api/oauth-token.test.js` — same+- `tests/api/siwe.test.js` — same++## What to Test (fill gaps only — don't duplicate existing coverage)++### Auth helpers (`api/_lib/auth.js`)+1. `mintAccessToken()` produces a JWT with correct `sub`, `scope`, `aud`, `exp` claims+2. `authenticateBearer()` returns the token payload for a valid JWT+3. `authenticateBearer()` throws/rejects for an expired JWT+4. `authenticateBearer()` throws/rejects for a tampered JWT signature+5. `csrfTokenFor()` + `verifyCsrfToken()` round-trip succeeds+6. `verifyCsrfToken()` fails for a mismatched session++### Email/password auth (`api/auth/[action].js`)+7. `POST /api/auth/login` with valid credentials returns session cookie+8. `POST /api/auth/login` with wrong password returns 401+9. `POST /api/auth/register` creates user and returns session cookie+10. `POST /api/auth/logout` clears session cookie++### SIWE (`api/auth/siwe/[action].js`)+11. `GET /api/auth/siwe/nonce` returns a fresh nonce and stores it (mock DB)+12. `POST /api/auth/siwe/verify` with a valid EIP-4361 message + signature creates a session (mock signature verification)+13. `POST /api/auth/siwe/verify` with an already-used nonce returns 401++### OAuth 2.1 (fill gaps in existing tests)+14. `POST /api/oauth/token` with `refresh_token` grant rotates the token and returns a new access token+15. `POST /api/oauth/token` with a revoked refresh token returns 400+16. `POST /api/oauth/introspect` returns `{ active: true }` for a valid token and `{ active: false }` for expired++## Approach++- Mock Neon DB with `vi.mock` or a test DB fixture+- Mock `bcrypt`/`hashPassword` for speed in unit tests+- For SIWE, mock the signature verification function — don't reconstruct real EIP-4361 signatures+- JWT tests can use a test secret; real JWTs are fine to mint in tests++## Success Criteria++- All new/updated test files pass with `npm test`+- No real DB or network calls+- Auth error paths (wrong password, expired token, reused nonce) all covereddiff --git a/tasks/task-04-test-memory-system.md b/tasks/task-04-test-memory-system.mdnew file mode 100644index 000000000..7ea985cc0--- /dev/null+++ b/tasks/task-04-test-memory-system.md@@ -0,0 +1,60 @@+# Task: Write Tests for the Memory System++## Context++This is the `three.ws` 3D agent platform. Agents have a two-layer memory system:++1. **Runtime store** (`src/agent-memory.js`, 260 lines) — in-memory with localStorage sync and async backend sync. Supports 4 entry types (`USER`, `FEEDBACK`, `PROJECT`, `REFERENCE`), salience × recency scoring, expiration, and fire-and-forget sync to the backend API.+2. **Backend API** (`api/agent-memory.js`, 188 lines) — CRUD endpoints storing to `agent_memories` Postgres table.++Both have **zero test coverage**.++## Goal++Write vitest test suites:+- `tests/src/agent-memory.test.js` for the runtime store+- `tests/api/agent-memory.test.js` for the backend API++## Files to Read First++- `src/agent-memory.js` — `AgentMemory` class: `add()`, `query()`, `_scheduleSync()`, localStorage integration, expiration+- `api/agent-memory.js` — GET (list), POST (create), PUT (update), DELETE (soft-delete) handlers+- `tests/src/manifest.test.js` — example of how to test a src/ module+- `tests/api/agents.test.js` — example of how to mock API handler tests++## What to Test++### Runtime store (`src/agent-memory.js`)++1. `add(entry)` stores entry in memory and returns an id+2. `query({ type: 'USER' })` returns only USER-type entries+3. `query({ tags: ['foo'] })` returns only entries with matching tags+4. `query({ limit: 2 })` returns at most 2 results+5. `query({ since: timestamp })` excludes entries older than the timestamp+6. Expired entries (where `expiresAt` is in the past) are excluded from `query()` results+7. Entries are sorted by salience × recency score (higher salience appears first)+8. `add()` schedules a backend sync (assert `_scheduleSync` was called or that fetch was queued)+9. On init, existing entries are loaded from localStorage if present+10. `add()` persists entry to localStorage immediately++### Backend API (`api/agent-memory.js`)++11. `GET /api/agent-memory?agent_id=<id>` returns entries for that agent (mock DB)+12. `GET /api/agent-memory` without auth returns 401+13. `POST /api/agent-memory` creates a new memory entry and returns it with an `id`+14. `POST /api/agent-memory` with missing required fields returns 400+15. `PUT /api/agent-memory?id=<id>` updates the entry content/salience+16. `DELETE /api/agent-memory?id=<id>` soft-deletes (sets `deleted_at`, not a hard row delete)+17. Agent can only read/write their own memories (cross-agent access returns 403)++## Approach++- For runtime tests: mock `localStorage` with `vi.stubGlobal('localStorage', ...)` and mock `fetch` with `vi.stubGlobal('fetch', ...)`+- For API tests: mock the Neon DB client; use the same req/res mock pattern as `tests/api/agents.test.js`+- Use `vi.useFakeTimers()` for testing expiration and scheduling behavior++## Success Criteria++- `npm test tests/src/agent-memory.test.js tests/api/agent-memory.test.js` passes+- No real localStorage, network, or DB calls+- Expiration, scoring, and cross-agent isolation all explicitly covereddiff --git a/tasks/task-05-test-skills-registry.md b/tasks/task-05-test-skills-registry.mdnew file mode 100644index 000000000..4b7268550--- /dev/null+++ b/tasks/task-05-test-skills-registry.md@@ -0,0 +1,55 @@+# Task: Write Tests for the Skills Registry++## Context++This is the `three.ws` 3D agent platform. The skill system (`src/agent-skills.js`, 459 lines) is the plugin layer that lets agents perform actions beyond LLM text generation. External skills are loaded from URLs (IPFS, Arweave, HTTPS), gated by a trust mode (`any`, `owned-only`, `whitelist`), and executed with a rich context object. This file has **zero test coverage**.++## Goal++Write a vitest test suite at `tests/src/agent-skills.test.js`.++## Files to Read First++- `src/agent-skills.js` — `SkillRegistry` class: `install(spec, { bundleBase })`, trust modes, dependency loading, handler execution+- `src/agent-protocol.js` — `AgentProtocol`, `ACTION_TYPES` (skills emit `perform-skill`, `skill-done`, `skill-error`)+- `src/skill-manifest.js` — skill manifest format+- `tests/src/agent-protocol.test.js` — reference for test style++## What to Test++### Installation & trust+1. `install(spec)` in `any` trust mode accepts any skill regardless of origin+2. `install(spec)` in `owned-only` mode rejects a skill whose origin doesn't match the agent owner+3. `install(spec)` in `whitelist` mode rejects skills not in the whitelist+4. `install(spec)` in `whitelist` mode accepts a skill that is on the whitelist+5. Installing a skill with `dependencies` triggers recursive loading of each dependency URL (mock fetch)+6. Installing the same skill name twice does not duplicate it in the registry++### Skill execution+7. Calling an installed skill invokes its `handler` with `(args, ctx)`+8. The `ctx` object passed to the handler contains `speak`, `remember`, `fetch`, and `call`+9. A successful handler result emits `skill-done` on the protocol with `{ skill, result: { success: true } }`+10. A handler that throws emits `skill-error` on the protocol with the error message+11. `ctx.speak(text)` emits a `speak` action on the protocol+12. `ctx.remember(entry)` emits a `remember` action on the protocol++### Skill lookup+13. After installing, the skill is discoverable via the registry (e.g., `registry.get(name)` or equivalent)+14. Requesting an uninstalled skill returns null/undefined (no crash)++### Manifest loading+15. A skill spec loaded from `ipfs://` URL is fetched and normalized correctly (mock fetch + IPFS gateway)+16. A skill spec loaded from `https://` URL is fetched and normalized correctly (mock fetch)++## Approach++- Mock `fetch` with `vi.stubGlobal('fetch', ...)` to return fixture skill manifests+- Use a real `AgentProtocol` instance and assert emitted events+- Keep fixture skill specs minimal: `{ name, description, signature: [], handler: vi.fn() }`+- Trust mode tests need a mock "agent owner" identity — pass it as constructor arg or mock the identity module++## Success Criteria++- `npm test tests/src/agent-skills.test.js` passes+- Trust modes, dependency loading, execution lifecycle, and error handling all covered+- No real network callsdiff --git a/tasks/task-06-mcp-modularization.md b/tasks/task-06-mcp-modularization.mdnew file mode 100644index 000000000..93c4a2a8f--- /dev/null+++ b/tasks/task-06-mcp-modularization.md@@ -0,0 +1,50 @@+# Task: Modularize the MCP Server++## Context++This is the `three.ws` 3D agent platform. The MCP server (`api/mcp.js`) is a single 1,201-line file implementing the Model Context Protocol with 14 tools. All tool logic, auth gating, payment handling, and JSON-RPC dispatch are co-located. This makes it hard to add tools, test individual tools, or reason about the codebase.++## Goal++Split `api/mcp.js` into focused modules **without changing any behavior**. The public interface (`POST /api/mcp`, tool names, response shapes, auth behavior) must remain identical.++## Proposed Structure++```+api/+ mcp.js ← entry point, stays as the Vercel handler (~50 lines)+ _mcp/+ dispatch.js ← JSON-RPC router: initialize, tools/list, tools/call+ auth.js ← bearer/x402 auth gating for tool calls+ tools/+ avatars.js ← list_my_avatars, get_avatar, search_public_avatars, render_avatar, delete_avatar+ models.js ← validate_model, inspect_model, optimize_model+ solana.js ← solana_agent_reputation, solana_agent_attestations, solana_agent_passport+ pumpfun.js ← pumpfun_recent_claims, pumpfun_token_intel, pumpfun_creator_intel, pumpfun_recent_graduations+ catalog.js ← TOOL_CATALOG array assembled from all tool modules+ payments.js ← x402 payment verification + settlement logic+```++## Instructions++1. Read `api/mcp.js` carefully before touching anything.+2. Create the `api/_mcp/` directory and the files above.+3. Move code in small, verifiable steps — one module at a time.+4. After each module extraction, confirm `api/mcp.js` still works by tracing imports.+5. Keep `api/mcp.js` as the Vercel-exported `default` handler; it should just import from `_mcp/` and call `dispatch()`.+6. Do not change any function signatures, tool names, response shapes, or error codes.+7. Do not add new functionality.++## What NOT to Do++- Do not rename tools, change tool descriptions, or alter input/output schemas+- Do not add a new abstraction layer (e.g., a "tool base class") — just move code+- Do not change auth behavior or payment flow+- Do not convert to TypeScript++## Success Criteria++- `api/mcp.js` is ≤ 60 lines after refactor+- Each file in `api/_mcp/` is ≤ 250 lines+- `npm test tests/api/mcp.test.js` passes (if tests exist — run `npm test` to check)+- Manual smoke test: `curl -X POST /api/mcp -d '{"jsonrpc":"2.0","method":"initialize","id":1}'` returns the same response as beforediff --git a/tasks/task-07-erc8004-optimistic-registration.md b/tasks/task-07-erc8004-optimistic-registration.mdnew file mode 100644index 000000000..5c45bcd7f--- /dev/null+++ b/tasks/task-07-erc8004-optimistic-registration.md@@ -0,0 +1,46 @@+# Task: Eliminate the 15-Minute ERC-8004 Registration Delay++## Context++This is the `three.ws` 3D agent platform. When a user registers an agent on-chain via the ERC-8004 contract, the agent doesn't appear in the discovery index until the next cron job run (every 15 minutes). This is a poor UX — the user expects to see their agent immediately after paying gas and confirming the transaction.++The cron job (`api/cron/[name].js`, function `handleErc8004Crawl`) polls the chain for `Registered` events in block ranges and inserts them into the `erc8004_registrations` Postgres table. The frontend registration happens in `src/erc8004/agent-registry.js` via `registerAgent()`.++## Goal++After a successful on-chain registration, immediately write the registration to the `erc8004_registrations` table via an API call — don't wait for the crawler.++## Approach++### Step 1 — Add a backend endpoint++Create `api/erc8004/register-confirm.js` (new file):++- Method: `POST /api/erc8004/register-confirm`+- Auth: session cookie or bearer with `avatars:write` scope+- Body: `{ chainId, txHash, agentId, metadataUri, ownerAddress }`+- Verify the transaction: call the chain's RPC (`eth_getTransactionReceipt`) to confirm the tx was mined and emitted a `Registered` event from the expected contract address+- If confirmed: upsert the row into `erc8004_registrations` (use `ON CONFLICT DO NOTHING` so the crawler never overwrites it)+- Return `{ success: true }` or an error if the tx isn't mined yet++You can find chain RPC URLs and registry contract addresses in `api/_lib/erc8004-chains.js`. The `Registered` event topic hash is `keccak256("Registered(uint256,string,address)")` — you can hardcode this.++### Step 2 — Call the endpoint from the frontend++In `src/erc8004/agent-registry.js`, after the transaction is confirmed (the code already waits for receipt), add a call to `POST /api/erc8004/register-confirm` with the tx details.++### Step 3 — Trigger metadata enrichment immediately++The crawler has a second phase: `erc8004EnrichMetadata()` which fetches `metadata_uri` and populates the agent's name/description/image. After inserting the row in step 1, immediately fetch and upsert the metadata in the same request handler (reuse whatever logic `erc8004EnrichMetadata` uses, or inline a simple version).++## Constraints++- Do not modify the crawler — it should continue to work as a safety net for any registrations that slip through+- The `ON CONFLICT DO NOTHING` upsert in the endpoint means the crawler never causes duplicates+- Keep the endpoint lightweight — if the tx isn't mined yet, return a clear error (don't poll)++## Success Criteria++- After calling `registerAgent()` in the frontend, the agent appears in the discovery index within ~5 seconds (one tx confirmation)+- No duplicate rows when the crawler later processes the same registration+- The `api/erc8004/register-confirm.js` file is ≤ 100 linesdiff --git a/tasks/task-08-voice-chat-integration.md b/tasks/task-08-voice-chat-integration.mdnew file mode 100644index 000000000..6231fb9d2--- /dev/null+++ b/tasks/task-08-voice-chat-integration.md@@ -0,0 +1,55 @@+# Task: Wire Voice Chat into the Main Agent Widget++## Context++This is the `three.ws` 3D agent platform. The main `<agent-3d>` web component (`src/element.js`) currently uses the Web Speech API for voice via `src/runtime/speech.js`. There is a separate, more capable voice system in `agent-voice-chat/` (Express + Socket.io, with Claude/Groq/OpenAI providers, conversation memory, and encryption). The floating widget UI already has a TTS toggle button but it just toggles Web Speech API on/off.++The goal is to upgrade the floating widget's voice button so it opens a proper voice session backed by the `agent-voice-chat` server, with clear visual feedback.++## Files to Read First++- `src/runtime/speech.js` (406 lines) — current Web Speech API wrapper+- `src/element.js` — `<agent-3d>` custom element; find where the TTS button is wired up+- `agent-voice-chat/server.js` — Socket.io server entry point; understand the event protocol+- `agent-voice-chat/room-manager.js` — how voice rooms/sessions are created+- `agent-voice-chat/providers/` — stt.js, tts.js, claude.js; understand the pipeline++## What to Build++### 1. Voice session client (`src/runtime/voice-client.js`, new file)++A thin Socket.io client that:+- Connects to the `agent-voice-chat` server URL (configurable, defaults to same origin + `/voice`)+- `start(agentId, config)` — joins a room for the given agent+- `stop()` — leaves the room, disconnects socket+- Captures microphone audio and sends chunks to the server via `audio:chunk` event+- Receives `agent:speak` events from the server (text + TTS audio) and plays them+- Fires a `voiceStateChange` CustomEvent on the element with `{ state: 'listening' | 'thinking' | 'speaking' | 'idle' }`++Keep it under 150 lines. Do not re-implement TTS/STT — the server handles all of that.++### 2. Wire it into `src/element.js`++In the `<agent-3d>` element:+- When the TTS button is clicked and `agent-voice-chat` server is available: use `VoiceClient` instead of `Speech`+- When `agent-voice-chat` is not configured (no `voice-server` attribute): fall back to the existing Web Speech API behavior (no regression)+- Add `voice-server` attribute to the element: `<agent-3d voice-server="https://..." ...>`+- Show a visual indicator: button ring color changes based on `voiceStateChange` state (`listening` = green, `thinking` = yellow, `speaking` = blue, `idle` = gray)++### 3. Update the floating widget HTML++The TTS button currently has this title: `"TTS off — click to enable voice"`. Update it so when voice is active it reads `"Voice active — click to stop"`. Wire the visual state ring to the button's CSS.++## Constraints++- Do not modify `agent-voice-chat/` server code+- Do not remove or break the existing Web Speech API fallback+- Do not add Socket.io to the main bundle if `voice-server` attribute is absent — lazy-import it+- Keep `voice-client.js` focused: connect, stream audio, receive speech. No UI logic in it.++## Success Criteria++- `<agent-3d voice-server="/voice" ...>` uses the voice chat server for voice+- `<agent-3d ...>` (no attribute) falls back to Web Speech API as before+- Visual states (idle/listening/thinking/speaking) are reflected on the TTS button+- No new bundle size cost when the `voice-server` attribute is absentdiff --git a/tasks/task-09-memory-sync.md b/tasks/task-09-memory-sync.mdnew file mode 100644index 000000000..1114fa3f7--- /dev/null+++ b/tasks/task-09-memory-sync.md@@ -0,0 +1,68 @@+# Task: Multi-Device Memory Sync++## Context++This is the `three.ws` 3D agent platform. Agents have a runtime memory store (`src/agent-memory.js`) that persists to `localStorage` and syncs to a backend API (`api/agent-memory.js`). The sync is one-directional: writes go from the browser to the backend. If a user opens the same agent on a second device or browser, that device has an empty memory — it never pulls from the backend.++## Goal++Make memory sync bidirectional so agents have consistent memory across devices. When an `<agent-3d>` element loads (or becomes active), it should pull the agent's memories from the backend and merge them into the local store.++## Files to Read First++- `src/agent-memory.js` (260 lines) — `AgentMemory` class: `add()`, `query()`, `_scheduleSync()`, localStorage structure+- `api/agent-memory.js` (188 lines) — `GET /api/agent-memory?agent_id=<id>` returns the agent's entries+- `src/element.js` — `<agent-3d>` custom element; find `connectedCallback()` or wherever the memory module is initialized++## What to Build++### Changes to `src/agent-memory.js`++Add a `pull()` method:++```js+async pull(agentId, authToken) {+ // Fetch all non-deleted entries from GET /api/agent-memory?agent_id=<agentId>+ // For each remote entry:+ // - If not in local store: add it (skip _scheduleSync to avoid re-uploading)+ // - If in local store and remote updatedAt > local updatedAt: overwrite local+ // - If in local store and local is newer: keep local (it will sync up on next push)+ // Persist merged state to localStorage+}+```++Conflict resolution: **last-write-wins by `updatedAt` timestamp**. This is simple and correct for the use case (personal agent memory, single user).++Also:+- Ensure every entry has an `updatedAt` field set on `add()` and updated on any modification+- The `_scheduleSync()` push should send `updatedAt` in the request body so the backend stores it++### Changes to `api/agent-memory.js`++- `GET /api/agent-memory` response should include `updated_at` per entry (check if the DB column exists; if not, use `created_at` as fallback)+- `POST /api/agent-memory` should accept and store `updated_at` from the client+- `PUT /api/agent-memory` should update `updated_at`++### Changes to `src/element.js`++In the element's init sequence (after auth is resolved and `agentId` is known), call:++```js+await memory.pull(agentId, authToken)+```++This should happen **before** the first LLM turn, so the agent has its full memory on the first message.++## Constraints++- `pull()` must be idempotent — calling it twice should not duplicate entries+- Do not pull on every message — only on init (when the element connects)+- The pull should be a best-effort background operation: if the network is unavailable, silently skip and use local state+- Do not change the localStorage key structure++## Success Criteria++- Open an agent on Device A, have a conversation (agent remembers the user's name via `remember` tool)+- Open the same agent on Device B — on first load, memory is pulled and the agent knows the user's name+- No duplicate entries after pulling (idempotent)+- Offline devices degrade gracefully (no error thrown, uses cached localStorage)diff --git a/tasks/task-10-agent-to-agent-communication.md b/tasks/task-10-agent-to-agent-communication.mdnew file mode 100644index 000000000..cda2e9261--- /dev/null+++ b/tasks/task-10-agent-to-agent-communication.md@@ -0,0 +1,77 @@+# Task: Agent-to-Agent Communication via Skills++## Context++This is the `three.ws` 3D agent platform. Agents execute skills via `src/agent-skills.js`. Each skill handler receives a context object `ctx` with helpers like `ctx.speak()`, `ctx.remember()`, `ctx.fetch()`. Currently, there is no way for one agent to delegate work to another agent programmatically.++The event bus (`src/agent-protocol.js`) is local to a single `<agent-3d>` element. The backend has agent data via `GET /api/agents/:id`. The MCP server (`api/mcp.js`) already has a `search_public_avatars` tool.++## Goal++Add `ctx.call(agentId, message)` to the skill execution context so skills can send a message to another agent and receive its response. This enables delegation: a user-facing agent can hand off specialized tasks (e.g., a trading agent calling a research agent).++## What to Build++### 1. Backend endpoint: `api/agent-delegate.js` (new file)++`POST /api/agent-delegate`++- Auth: bearer with any valid scope (agent-to-agent calls are authenticated as the calling agent's session)+- Body: `{ fromAgentId, toAgentId, message, context? }`+- Looks up `toAgentId` in the DB, loads its manifest (system prompt, model config)+- Runs a single LLM turn: sends `message` to the target agent's configured Claude model with the target agent's system prompt+- Returns `{ response: string, agentId: toAgentId }`+- Rate limit: 10 delegate calls per agent per minute (use existing `limits` helper)+- Do not recurse: if the delegated turn itself tries to call `agent-delegate`, reject with 400++### 2. Add `ctx.call()` to `src/agent-skills.js`++In the skill context builder (wherever `ctx` is assembled), add:++```js+ctx.call = async (agentId, message) => {+ const res = await fetch('/api/agent-delegate', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...authHeaders },+ body: JSON.stringify({ fromAgentId: currentAgentId, toAgentId: agentId, message })+ })+ if (!res.ok) throw new Error(`Delegate call failed: ${res.status}`)+ const { response } = await res.json()+ return response+}+```++### 3. Add `call_agent` to the MCP tool catalog (`api/mcp.js`)++Add a new MCP tool so external AI systems can also use agent-to-agent delegation:++```json+{+ "name": "call_agent",+ "description": "Send a message to another three.ws agent and get its response. Use this to delegate specialized tasks.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "agent_id": { "type": "string", "description": "The agent's ID" },+ "message": { "type": "string", "description": "The message to send" }+ },+ "required": ["agent_id", "message"]+ }+}+```++Scope required: `avatars:read`. Implementation: call `POST /api/agent-delegate` internally.++## Constraints++- No recursion: the delegate endpoint must check for a `X-Delegate-Depth` header and reject if depth > 0+- The delegated agent uses its own system prompt and model config — not the calling agent's+- Do not stream the delegate response — return it as a complete string+- `api/agent-delegate.js` should be ≤ 80 lines++## Success Criteria++- A skill can call `await ctx.call('agent-id-123', 'What is the market cap of SOL?')` and receive a string response+- The MCP `call_agent` tool works via `POST /api/mcp`+- Recursive delegation (A → B → A) is rejected with a clear error+- Rate limiting is enforced (11th call within a minute returns 429)