Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Refactor code structure for improved readability and maintainability

nirholas0e42b4a77a0d
diff --git a/.env.example b/.env.example
index 9ade6ef7c..b5ce28879 100644
--- a/.env.example
+++ b/.env.example
@@ -109,6 +109,11 @@ PINATA_JWT=
# (legacy v1 API — upload endpoint: https://api.web3.storage/upload)
WEB3_STORAGE_TOKEN=
+# ── KOL wallet P&L analytics (api/kol/[action].js wallets handler) ─────────
+# Birdeye API key for Solana wallet portfolio + P&L data.
+# Get one at https://birdeye.so — free tier allows ~100 req/min.
+BIRDEYE_API_KEY=
+
# ── Pump.fun live feed integration (api/_lib/pumpfun-mcp.js) ──────────────
# Upstream pumpfun-claims-bot MCP server URL. When set, /api/agents/pumpfun
# and /api/agents/pumpfun-feed are enabled, the cron at /api/cron/pumpfun-signals
diff --git a/api/kol/[action].js b/api/kol/[action].js
index 6735f9579..abcefc667 100644
--- a/api/kol/[action].js
+++ b/api/kol/[action].js
@@ -6,6 +6,89 @@ import { fileURLToPath } from 'node:url';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+// ── wallets (Birdeye P&L proxy) ───────────────────────────────────────────────
+
+const BIRDEYE_BASE = 'https://public-api.birdeye.so';
+const CACHE_TTL_MS = 60_000;
+const MAX_ADDRESSES = 20;
+const _cache = new Map(); // address → { data, ts }
+
+function _getCached(addr) {
+ const entry = _cache.get(addr);
+ if (!entry) return null;
+ if (Date.now() - entry.ts > CACHE_TTL_MS) { _cache.delete(addr); return null; }
+ return entry.data;
+}
+
+function _setCache(addr, data) { _cache.set(addr, { data, ts: Date.now() }); }
+
+async function _fetchBirdeye(addr, apiKey) {
+ const url = `${BIRDEYE_BASE}/v1/wallet/portfolio?wallet=${encodeURIComponent(addr)}&chain=solana`;
+ const ctrl = new AbortController();
+ const t = setTimeout(() => ctrl.abort(), 8000);
+ try {
+ const res = await fetch(url, { headers: { 'X-API-KEY': apiKey }, signal: ctrl.signal });
+ if (!res.ok) throw new Error(`birdeye ${res.status}`);
+ const j = await res.json();
+ if (!j.success) throw new Error('birdeye responded with success=false');
+ return j.data;
+ } finally {
+ clearTimeout(t);
+ }
+}
+
+function _normalizePortfolio(addr, portfolio) {
+ const items = portfolio?.items ?? [];
+ let topToken = null;
+ let maxVal = 0;
+ for (const item of items) {
+ const val = item.valueUsd ?? 0;
+ if (val > maxVal) { maxVal = val; topToken = { symbol: item.symbol ?? '?', pnl: val }; }
+ }
+ return {
+ address: addr,
+ realizedPnl: portfolio?.realizedPnl ?? 0,
+ unrealizedPnl: portfolio?.unrealizedPnl ?? (portfolio?.totalUsd ?? 0),
+ winRate: portfolio?.winRate ?? 0,
+ totalTrades: portfolio?.totalTrades ?? 0,
+ topToken,
+ };
+}
+
+async function handleWallets(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const apiKey = process.env.BIRDEYE_API_KEY;
+ if (!apiKey) return error(res, 503, 'birdeye_not_configured', 'Birdeye API key not configured');
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const addresses = (url.searchParams.get('addresses') ?? '')
+ .split(',').map((s) => s.trim()).filter(Boolean).slice(0, MAX_ADDRESSES);
+ if (addresses.length === 0) return error(res, 400, 'validation_error', 'addresses query param is required');
+
+ const uncached = addresses.filter((a) => _getCached(a) === null);
+ const cacheHit = uncached.length === 0;
+
+ if (uncached.length > 0) {
+ await Promise.allSettled(uncached.map(async (addr) => {
+ try {
+ const portfolio = await _fetchBirdeye(addr, apiKey);
+ _setCache(addr, _normalizePortfolio(addr, portfolio));
+ } catch {
+ _setCache(addr, _normalizePortfolio(addr, null));
+ }
+ }));
+ }
+
+ const data = addresses.map((a) => _getCached(a)).filter(Boolean);
+ res.setHeader('x-cache', cacheHit ? 'HIT' : 'MISS');
+ return json(res, 200, { data });
+}
+
const WALLETS_PATH = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../src/kol/wallets.json');
async function loadWallets() {
@@ -70,6 +153,7 @@ const DISPATCH = {
'import-gmgn': handleImportGmgn,
leaderboard: handleLeaderboard,
trades: handleTrades,
+ wallets: handleWallets,
};
export default wrap(async (req, res) => {
diff --git a/api/mcp.js b/api/mcp.js
index 16181a988..9ebfc44b2 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -447,7 +447,13 @@ const TOOL_CATALOG = [
description: 'Soft-delete an avatar you own. Requires avatars:delete scope.',
inputSchema: {
type: 'object',
- properties: { id: { type: 'string', format: 'uuid' } },
+ properties: {
+ id: { type: 'string', format: 'uuid' },
+ confirm: {
+ type: 'boolean',
+ description: 'Must be true to confirm permanent deletion.',
+ },
+ },
required: ['id'],
additionalProperties: false,
},
@@ -654,11 +660,13 @@ const TOOLS = {
},
search_public_avatars: {
- async handler(args) {
+ async handler(args, auth) {
+ // Unauthenticated callers (x402/anonymous) are capped at 10 to prevent bulk enumeration.
+ const maxLimit = auth.userId ? 50 : 10;
const result = await searchPublicAvatars({
q: args.q,
tag: args.tag,
- limit: args.limit || 12,
+ limit: Math.min(args.limit || 12, maxLimit),
});
return {
content: [
@@ -727,8 +735,20 @@ const TOOLS = {
delete_avatar: {
scope: 'avatars:delete',
async handler(args, auth) {
+ if (!args.confirm) {
+ return {
+ content: [
+ {
+ type: 'text',
+ text: 'Set confirm: true to permanently delete this avatar.',
+ },
+ ],
+ isError: true,
+ };
+ }
const ok = await deleteAvatar({ id: args.id, userId: auth.userId });
if (!ok) throw new Error('avatar not found or not yours');
+ // TODO: audit_log table needed — INSERT (user_id, action='delete_avatar', resource_id, created_at)
return { content: [{ type: 'text', text: `Deleted avatar ${args.id}.` }] };
},
},
diff --git a/chat/server/main.go b/chat/server/main.go
index 7972c11c9..a930b7462 100644
--- a/chat/server/main.go
+++ b/chat/server/main.go
@@ -2,6 +2,7 @@ package main
import (
"context"
+ "encoding/base64"
"encoding/json"
"flag"
"fmt"
@@ -46,6 +47,7 @@ func main() {
r.Get("/list_directory", ListDirectory)
r.Get("/read_file", ReadFile)
+ r.Post("/api/tts/google", TTSHandler)
fmt.Println("Tool server running at http://localhost:8081")
httpServer := &http.Server{Addr: ":8081", Handler: r}
@@ -67,6 +69,46 @@ func main() {
}
}
+func TTSHandler(w http.ResponseWriter, r *http.Request) {
+ apiKey := os.Getenv("GOOGLE_TTS_API_KEY")
+ if apiKey == "" {
+ writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "TTS not configured"})
+ return
+ }
+
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
+ return
+ }
+
+ url := "https://texttospeech.googleapis.com/v1/text:synthesize?key=" + apiKey
+ resp, err := http.Post(url, "application/json", strings.NewReader(string(body)))
+ if err != nil {
+ writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()})
+ return
+ }
+ defer resp.Body.Close()
+
+ var result struct {
+ AudioContent string `json:"audioContent"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()})
+ return
+ }
+
+ audio, err := base64.StdEncoding.DecodeString(result.AudioContent)
+ if err != nil {
+ writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ return
+ }
+
+ w.Header().Set("Content-Type", "audio/mpeg")
+ w.WriteHeader(http.StatusOK)
+ w.Write(audio)
+}
+
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if *password != "" && r.Header.Get("Authorization") != ("Basic "+*password) {
diff --git a/chat/src/App.svelte b/chat/src/App.svelte
index 76062d5d1..ac56a4a86 100644
--- a/chat/src/App.svelte
+++ b/chat/src/App.svelte
@@ -2,7 +2,7 @@
import { v4 as uuidv4 } from 'uuid';
import { onMount, tick } from 'svelte';
import { fade, fly } from 'svelte/transition';
- import { complete, completeConsensus, generateImage } from './convo.js';
+ import { complete, generateImage } from './convo.js';
import KnobsSidebar from './KnobsSidebar.svelte';
import Button from './Button.svelte';
import { marked } from 'marked';
@@ -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, activeAgent, talkingHeadEnabled, route, mode, websiteCategory, loadCurrentUser, notify } from './stores.js';
+ import { controller, remoteServer, config, params, toolSchema, syncServer, brandConfig, ttsEnabled, localAgentId, activeAgent, talkingHeadEnabled, talkingHeadAvatarUrl, route, mode, websiteCategory, loadCurrentUser, notify } from './stores.js';
import Notifications from './Notifications.svelte';
import AuthPage from './manus/pages/AuthPage.svelte';
import Pricing from './manus/pages/Pricing.svelte';
@@ -1379,6 +1379,11 @@
}
}
+ $: if ($talkingHeadAvatarUrl) {
+ talkingHeadReady = false;
+ pendingSpeak = null;
+ }
+
function onTalkingHeadReady() {
talkingHeadReady = true;
if (pendingSpeak) {
@@ -1542,6 +1547,34 @@
>
<Icon icon={feShare} strokeWidth={3} class="m-auto h-4 w-4 text-slate-700" />
</button>
+ <div class="relative">
+ <button
+ class="flex rounded-full p-2 transition-colors hover:bg-gray-100 disabled:opacity-40"
+ on:click={() => (exportOpen = !exportOpen)}
+ disabled={convo.messages.length === 0}
+ title="Export conversation"
+ >
+ <Icon icon={feDownload} strokeWidth={3} class="m-auto h-4 w-4 text-slate-700" />
+ </button>
+ {#if exportOpen}
+ <button
+ class="fixed inset-0 z-20 cursor-default"
+ aria-hidden="true"
+ tabindex="-1"
+ on:click={() => (exportOpen = false)}
+ />
+ <div class="absolute right-0 top-full mt-1 z-30 w-48 rounded-xl border border-[#E5E3DC] bg-white p-1 shadow-pop">
+ <button
+ class="flex h-9 w-full items-center rounded-lg px-3 text-sm font-medium text-[#1A1A1A] hover:bg-[#F5F4EF]"
+ on:click={exportConvoAsMarkdown}
+ >Export as Markdown</button>
+ <button
+ class="flex h-9 w-full items-center rounded-lg px-3 text-sm font-medium text-[#1A1A1A] hover:bg-[#F5F4EF]"
+ on:click={exportConvoAsJSON}
+ >Export as JSON</button>
+ </div>
+ {/if}
+ </div>
<button
data-trigger="knobs"
class="flex rounded-full p-2 transition-colors hover:bg-gray-100"
@@ -1768,6 +1801,34 @@
>
<Icon icon={feShare} strokeWidth={3} class="m-auto h-4 w-4 text-slate-700" />
</button>
+ <div class="relative">
+ <button
+ class="flex rounded-full p-3 transition-colors hover:bg-gray-100 disabled:opacity-40"
+ on:click={() => (exportOpen = !exportOpen)}
+ disabled={convo.messages.length === 0}
+ title="Export conversation"
+ >
+ <Icon icon={feDownload} strokeWidth={3} class="m-auto h-4 w-4 text-slate-700" />
+ </button>
+ {#if exportOpen}
+ <button
+ class="fixed inset-0 z-20 cursor-default"
+ aria-hidden="true"
+ tabindex="-1"
+ on:click={() => (exportOpen = false)}
+ />
+ <div class="absolute right-0 top-full mt-1 z-30 w-48 rounded-xl border border-[#E5E3DC] bg-white p-1 shadow-pop">
+ <button
+ class="flex h-9 w-full items-center rounded-lg px-3 text-sm font-medium text-[#1A1A1A] hover:bg-[#F5F4EF]"
+ on:click={exportConvoAsMarkdown}
+ >Export as Markdown</button>
+ <button
+ class="flex h-9 w-full items-center rounded-lg px-3 text-sm font-medium text-[#1A1A1A] hover:bg-[#F5F4EF]"
+ on:click={exportConvoAsJSON}
+ >Export as JSON</button>
+ </div>
+ {/if}
+ </div>
<button
data-trigger="knobs"
class="flex rounded-full p-3 transition-colors hover:bg-gray-100"
@@ -1978,7 +2039,7 @@
style="width:220px;height:220px;border-radius:16px;overflow:hidden;box-shadow:0 8px 32px rgba(0,0,0,0.18);"
></agent-3d>
{:else if $talkingHeadEnabled && agentVisible}
- <TalkingHead bind:this={talkingHead} on:ready={onTalkingHeadReady} />
+ <TalkingHead bind:this={talkingHead} on:ready={onTalkingHeadReady} avatarUrl={$talkingHeadAvatarUrl || undefined} />
{/if}
<div class="flex items-center gap-1.5">
diff --git a/chat/src/SettingsModal.svelte b/chat/src/SettingsModal.svelte
index 9d1c79059..c519e8ce8 100644
--- a/chat/src/SettingsModal.svelte
+++ b/chat/src/SettingsModal.svelte
@@ -13,6 +13,7 @@
remoteServer,
syncServer,
toolSchema,
+ talkingHeadAvatarUrl,
} from './stores.js';
import Button from './Button.svelte';
import Modal from './Modal.svelte';
@@ -209,6 +210,17 @@
Consensus mode
</button>
</li>
+ <li>
+ <button
+ class="{activeTab === 'avatar'
+ ? '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 = 'avatar')}
+ >
+ <Icon icon={feStar} class="h-3 w-3 text-slate-700" />
+ Avatar
+ </button>
+ </li>
</ul>
</nav>
</div>
diff --git a/chat/src/convo.js b/chat/src/convo.js
index 653dbb1d8..7f329ca7f 100644
--- a/chat/src/convo.js
+++ b/chat/src/convo.js
@@ -159,110 +159,6 @@ export async function complete(convo, onupdate, onabort) {
}
}
-export async function completeConsensus(convo, onupdate, onabort) {
- controller.set(new AbortController());
- const param = get(params);
-
- // Query all models in parallel
- const modelResults = await Promise.all(
- convo.models.map(async (model) => {
- const openAICompatibleFormat =
- model.provider === 'OpenAI' ||
- model.provider === 'OpenRouter' ||
- model.provider === 'Groq' ||
- model.provider === 'Mistral';
-
- let messages = convo.messages.map(
- openAICompatibleFormat ? messageToOpenAIFormat : messageToAnthropicFormat
- );
-
- if (param.messagesContextLimit > 0) {
- messages = limitMessagesContext(messages, param.messagesContextLimit);
- }
-
- const provider = providers.find((p) => p.name === model.provider);
-
- const response = await fetch(`${provider.url}${provider.completionUrl}`, {
- method: 'POST',
- headers: {
- ...(model.provider === 'OpenRouter' ||
- model.provider === 'OpenAI' ||
- model.provider === 'Groq' ||
- model.provider === 'Mistral'
- ? { Authorization: `Bearer ${provider.apiKeyFn()}` }
- : model.provider === 'Anthropic'
- ? {
- 'x-api-key': provider.apiKeyFn(),
- 'anthropic-version': '2023-06-01',
- }
- : {}),
- 'Content-Type': 'application/json',
- },
- signal: get(controller).signal,
- body: JSON.stringify({
- stream: false,
- model: model.id,
- temperature: param.temperature,
- messages,
- }),
- });
-
- 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,
- };
- })
- );
-
- // Prepare consensus query
- const consensusProvider = providers.find((p) => p.name === 'OpenRouter');
- const consensusModel = 'anthropic/claude-3.5-sonnet';
- const consensusMessages = [
- {
- role: 'system',
- content:
- 'You are a helpful assistant that analyzes multiple model responses and determines if there is a consensus.',
- },
- {
- role: 'user',
- content: `Here are responses from different models to the same user query:\n\nUser query:\n${convo.messages[convo.messages.length - 2].content}\n\n${modelResults
- .map((r) => `${r.model}: ${r.response}`)
- .join(
- '\n\n'
- )}\n\nIf there is a clear consensus across all responses, answer the user's query with a summary of the consensus and do not write anything else specifically mentioning the consensus. If no, explain the key differences across responses.`,
- },
- ];
-
- const consensusResponse = await fetch(
- `${consensusProvider.url}${consensusProvider.completionUrl}`,
- {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${consensusProvider.apiKeyFn()}`,
- 'Content-Type': 'application/json',
- },
- signal: get(controller).signal,
- body: JSON.stringify({
- stream: false,
- model: consensusModel,
- temperature: param.temperature,
- messages: consensusMessages,
- }),
- }
- );
-
- const consensusResult = await consensusResponse.json();
- onupdate({
- choices: [{ delta: { content: consensusResult.choices[0].message.content } }],
- });
-}
function toolSchemaToAnthropicFormat(schema) {
return {
diff --git a/chat/src/stores.js b/chat/src/stores.js
index 6f1ed6764..d6d6158ad 100644
--- a/chat/src/stores.js
+++ b/chat/src/stores.js
@@ -65,6 +65,7 @@ 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 talkingHeadAvatarUrl = persisted('talkingHeadAvatarUrl', '');
export const route = writable(
typeof window !== 'undefined' ? (window.location.hash.slice(1) || 'chat') : 'chat'
diff --git a/package-lock.json b/package-lock.json
index e05d8fe17..7063870a3 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -43,6 +43,7 @@
"ethers": "^6.16.0",
"gltf-validator": "^2.0.0-dev.3.10",
"jose": "^5.9.6",
+ "livekit-client": "^2.18.8",
"query-string": "^8.1.0",
"resend": "^6.12.2",
"sas-lib": "^1.0.10",
@@ -3330,6 +3331,12 @@
"specificity": "bin/cli.js"
}
},
+ "node_modules/@bufbuild/protobuf": {
+ "version": "1.10.1",
+ "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-1.10.1.tgz",
+ "integrity": "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==",
+ "license": "(Apache-2.0 AND BSD-3-Clause)"
+ },
"node_modules/@chenglou/pretext": {
"version": "0.0.5",
"resolved": "https://registry.npmjs.org/@chenglou/pretext/-/pretext-0.0.5.tgz",
@@ -4678,6 +4685,21 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
+ "node_modules/@livekit/mutex": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@livekit/mutex/-/mutex-1.1.1.tgz",
+ "integrity": "sha512-EsshAucklmpuUAfkABPxJNhzj9v2sG7JuzFDL4ML1oJQSV14sqrpTYnsaOudMAw9yOaW53NU3QQTlUQoRs4czw==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@livekit/protocol": {
+ "version": "1.45.3",
+ "resolved": "https://registry.npmjs.org/@livekit/protocol/-/protocol-1.45.3.tgz",
+ "integrity": "sha512-WmMxBTsy4dRBqcrswFwUUlgq3Z0nnhOqKR6tX749Rb/PcB1yBMUtrHxZvcsS6qi3/5+86zHeVG+exmu1sZqfJg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@bufbuild/protobuf": "^1.10.0"
+ }
+ },
"node_modules/@metaplex-foundation/mpl-core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@metaplex-foundation/mpl-core/-/mpl-core-1.10.0.tgz",
@@ -13386,6 +13408,15 @@
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
"license": "MIT"
},
+ "node_modules/events": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
+ "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8.x"
+ }
+ },
"node_modules/events-universal": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz",
@@ -15211,6 +15242,35 @@
"integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
"license": "MIT"
},
+ "node_modules/livekit-client": {
+ "version": "2.18.8",
+ "resolved": "https://registry.npmjs.org/livekit-client/-/livekit-client-2.18.8.tgz",
+ "integrity": "sha512-E+bSpnBVng/1xG4RfL1Q51dHUpBwL14Wix4sR5bS0djEzKMEtrxcUyhWLltdwQ0USf1t0PaxW6WL4oVb2s4Fsw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@livekit/mutex": "1.1.1",
+ "@livekit/protocol": "1.45.3",
+ "events": "^3.3.0",
+ "jose": "^6.1.0",
+ "loglevel": "^1.9.2",
+ "sdp-transform": "^2.15.0",
+ "tslib": "2.8.1",
+ "typed-emitter": "^2.1.0",
+ "webrtc-adapter": "9.0.5"
+ },
+ "peerDependencies": {
+ "@types/dom-mediacapture-record": "^1"
+ }
+ },
+ "node_modules/livekit-client/node_modules/jose": {
+ "version": "6.2.3",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz",
+ "integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
"node_modules/locate-character": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz",
@@ -15239,6 +15299,19 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/loglevel": {
+ "version": "1.9.2",
+ "resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.9.2.tgz",
+ "integrity": "sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6.0"
+ },
+ "funding": {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/loglevel"
+ }
+ },
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
@@ -17085,6 +17158,16 @@
"queue-microtask": "^1.2.2"
}
},
+ "node_modules/rxjs": {
+ "version": "7.8.2",
+ "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
+ "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.1.0"
+ }
+ },
"node_modules/safe-array-concat": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.3.tgz",
@@ -18140,6 +18223,21 @@
"node": ">=v12.22.7"
}
},
+ "node_modules/sdp": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/sdp/-/sdp-3.2.2.tgz",
+ "integrity": "sha512-xZocWwfyp4hkbN4hLWxMjmv2Q8aNa9MhmOZ7L9aCZPT+dZsgRr6wZRrSYE3HTdyk/2pZKPSgqI7ns7Een1xMSA==",
+ "license": "MIT"
+ },
+ "node_modules/sdp-transform": {
+ "version": "2.15.0",
+ "resolved": "https://registry.npmjs.org/sdp-transform/-/sdp-transform-2.15.0.tgz",
+ "integrity": "sha512-KrOH82c/W+GYQ0LHqtr3caRpM3ITglq3ljGUIb8LTki7ByacJZ9z+piSGiwZDsRyhQbYBOBJgr2k6X4BZXi3Kw==",
+ "license": "MIT",
+ "bin": {
+ "sdp-verify": "checker.js"
+ }
+ },
"node_modules/semver": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
@@ -19372,6 +19470,15 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/typed-emitter": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/typed-emitter/-/typed-emitter-2.1.0.tgz",
+ "integrity": "sha512-g/KzbYKbH5C2vPkaXGu8DJlHrGKHLsM25Zg9WuC9pMGfuvT+X25tZQWo5fK1BjBm8+UrVE9LDCvaY0CQk+fXDA==",
+ "license": "MIT",
+ "optionalDependencies": {
+ "rxjs": "*"
+ }
+ },
"node_modules/typed-query-selector": {
"version": "2.12.2",
"resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.2.tgz",
@@ -19955,6 +20062,19 @@
"dev": true,
"license": "BSD-2-Clause"
},
+ "node_modules/webrtc-adapter": {
+ "version": "9.0.5",
+ "resolved": "https://registry.npmjs.org/webrtc-adapter/-/webrtc-adapter-9.0.5.tgz",
+ "integrity": "sha512-U9vjByy/sK2OMXu5mmfuZFKTMIUQe34c0JXRO+oDrxJTsntdYT2iIFwYMOV7HhMTuktcZLGf2W1N/OcSf9ssWg==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "sdp": "^3.2.0"
+ },
+ "engines": {
+ "node": ">=6.0.0",
+ "npm": ">=3.10.0"
+ }
+ },
"node_modules/whatwg-mimetype": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",
diff --git a/package.json b/package.json
index 1ada4ea7d..078342810 100644
--- a/package.json
+++ b/package.json
@@ -22,7 +22,9 @@
"drag-and-drop",
"3d-agent"
],
- "workspaces": ["chat"],
+ "workspaces": [
+ "chat"
+ ],
"main": "src/app.js",
"browserslist": [
">1%",
@@ -93,6 +95,7 @@
"ethers": "^6.16.0",
"gltf-validator": "^2.0.0-dev.3.10",
"jose": "^5.9.6",
+ "livekit-client": "^2.18.8",
"query-string": "^8.1.0",
"resend": "^6.12.2",
"sas-lib": "^1.0.10",
diff --git a/public/chat/index.html b/public/chat/index.html
index 7e8c39048..45a956354 100644
--- a/public/chat/index.html
+++ b/public/chat/index.html
@@ -43,8 +43,8 @@
}
}
</script>
- <script type="module" crossorigin src="/chat/assets/index-BQNPWbBp.js"></script>
- <link rel="stylesheet" crossorigin href="/chat/assets/index-BcxH7WFG.css">
+ <script type="module" crossorigin src="/chat/assets/index-CNGGMqFP.js"></script>
+ <link rel="stylesheet" crossorigin href="/chat/assets/index-BeH6JEv0.css">
</head>
<body>
<div id="app"></div>
diff --git a/sdk/types/erc8004/abi.d.ts b/sdk/types/erc8004/abi.d.ts
new file mode 100644
index 000000000..2ad23ea2b
--- /dev/null
+++ b/sdk/types/erc8004/abi.d.ts
@@ -0,0 +1,12 @@
+export interface RegistryAddresses {
+ identityRegistry?: string;
+ reputationRegistry?: string;
+ validationRegistry?: string;
+}
+
+export declare const IDENTITY_REGISTRY_ABI: readonly string[];
+export declare const REPUTATION_REGISTRY_ABI: readonly string[];
+export declare const VALIDATION_REGISTRY_ABI: readonly string[];
+export declare const REGISTRY_DEPLOYMENTS: Record<number, RegistryAddresses>;
+
+export declare function agentRegistryId(chainId: number, registryAddress: string): string;
diff --git a/sdk/types/manifests.d.ts b/sdk/types/manifests.d.ts
new file mode 100644
index 000000000..3867b9b26
--- /dev/null
+++ b/sdk/types/manifests.d.ts
@@ -0,0 +1,29 @@
+export interface AgentRegistrationOptions {
+ name: string;
+ description: string;
+ endpoint: string;
+ image?: string;
+ services?: unknown[];
+ registrations?: unknown[];
+}
+export declare function agentRegistration(opts: AgentRegistrationOptions): object;
+
+export interface AgentCardOptions {
+ name: string;
+ description: string;
+ url: string;
+ version?: string;
+ org?: string;
+ skills?: unknown[];
+}
+export declare function agentCard(opts: AgentCardOptions): object;
+
+export interface AiPluginOptions {
+ name: string;
+ description: string;
+ openapiUrl: string;
+ logoUrl?: string;
+ contactEmail?: string;
+ legalUrl?: string;
+}
+export declare function aiPlugin(opts: AiPluginOptions): object;
diff --git a/sdk/types/panel.d.ts b/sdk/types/panel.d.ts
new file mode 100644
index 000000000..4a9a6ff3d
--- /dev/null
+++ b/sdk/types/panel.d.ts
@@ -0,0 +1,16 @@
+export interface AgentPanelOptions {
+ title?: string;
+ welcome?: string;
+ placeholder?: string;
+ onMessage?: (text: string) => string | Promise<string>;
+ voice?: boolean;
+}
+
+export declare class AgentPanel {
+ constructor(opts?: AgentPanelOptions);
+ mount(container: HTMLElement): this;
+ open(): void;
+ close(): void;
+ addMessage(role: string, text: string): void;
+ dispose(): void;
+}
diff --git a/sdk/types/permissions.d.ts b/sdk/types/permissions.d.ts
new file mode 100644
index 000000000..0b31f7b93
--- /dev/null
+++ b/sdk/types/permissions.d.ts
@@ -0,0 +1,56 @@
+export declare class PermissionError extends Error {
+ code: string;
+ name: 'PermissionError';
+ constructor(code: string, message: string);
+}
+
+export interface DelegationPublic {
+ id: string;
+ delegationHash: string;
+ agentId: string;
+ delegator: string;
+ delegate: string;
+ status: string;
+ chainId: number;
+ [key: string]: unknown;
+}
+
+export interface ScopePreset {
+ token: string;
+ maxAmount: string;
+ period: string;
+ targets: string[];
+ expiryDays: number;
+}
+
+export interface PermissionsClientOptions {
+ baseUrl?: string;
+ bearer?: string;
+}
+
+export declare class PermissionsClient {
+ constructor(opts?: PermissionsClientOptions);
+ listDelegations(params?: {
+ agentId?: string;
+ delegator?: string;
+ status?: string;
+ }): Promise<DelegationPublic[]>;
+ getMetadata(agentId: string): Promise<{ spec: string; delegations: DelegationPublic[] }>;
+ grant(params: {
+ agentId: string;
+ chainId: number;
+ preset: ScopePreset;
+ delegate: string;
+ signer: unknown;
+ }): Promise<{ id: string; delegationHash: string }>;
+ redeem(params: {
+ id: string;
+ calls: Array<{ to: string; value?: string; data: string }>;
+ }): Promise<{ txHash: string }>;
+ revoke(params: {
+ id: string;
+ delegationHash: string;
+ signer: unknown;
+ }): Promise<{ status: 'revoked'; txHash: string }>;
+ verify(hash: string, chainId: number): Promise<{ valid: boolean; reason?: string }>;
+}
diff --git a/sdk/types/solana-attestations.d.ts b/sdk/types/solana-attestations.d.ts
new file mode 100644
index 000000000..4810ff593
--- /dev/null
+++ b/sdk/types/solana-attestations.d.ts
@@ -0,0 +1,86 @@
+export interface AttestationResult {
+ signature: string;
+ memo: object;
+}
+
+export interface AttestFeedbackOptions {
+ agentAsset: string;
+ score: number;
+ taskId?: string;
+ uri?: string;
+ network?: 'mainnet' | 'devnet';
+ preferred?: string | null;
+}
+export declare function attestFeedback(opts?: AttestFeedbackOptions): Promise<AttestationResult>;
+
+export interface AttestValidationOptions {
+ agentAsset: string;
+ taskHash: string;
+ passed: boolean;
+ uri?: string;
+ network?: 'mainnet' | 'devnet';
+ preferred?: string | null;
+}
+export declare function attestValidation(opts?: AttestValidationOptions): Promise<AttestationResult>;
+
+export interface CreateTaskOptions {
+ agentAsset: string;
+ taskId: string;
+ scopeHash: string;
+ uri?: string;
+ network?: 'mainnet' | 'devnet';
+ preferred?: string | null;
+}
+export declare function createTask(opts?: CreateTaskOptions): Promise<AttestationResult>;
+
+export interface AcceptTaskOptions {
+ agentAsset: string;
+ taskId: string;
+ network?: 'mainnet' | 'devnet';
+ preferred?: string | null;
+}
+export declare function acceptTask(opts?: AcceptTaskOptions): Promise<AttestationResult>;
+
+export interface AttestRevokeOptions {
+ agentAsset: string;
+ targetSignature: string;
+ reason?: string;
+ network?: 'mainnet' | 'devnet';
+ preferred?: string | null;
+}
+export declare function attestRevoke(opts?: AttestRevokeOptions): Promise<AttestationResult>;
+
+export interface AttestDisputeOptions {
+ agentAsset: string;
+ targetSignature: string;
+ reason?: string;
+ uri?: string;
+ network?: 'mainnet' | 'devnet';
+ preferred?: string | null;
+}
+export declare function attestDispute(opts?: AttestDisputeOptions): Promise<AttestationResult>;
+
+export interface ListAttestationsOptions {
+ agentAsset: string;
+ kind?: 'feedback' | 'validation' | 'all';
+ limit?: number;
+ network?: 'mainnet' | 'devnet';
+}
+export declare function listAttestations(opts?: ListAttestationsOptions): Promise<
+ Array<{ signature: string; slot: number; attester: string; memo: object }>
+>;
+
+export interface FetchAttestationsOptions {
+ agentAsset: string;
+ kind?: string;
+ network?: 'mainnet' | 'devnet';
+ apiOrigin?: string;
+}
+export declare function fetchAttestations(opts?: FetchAttestationsOptions): Promise<unknown>;
+
+export interface FetchReputationOptions {
+ agentAsset: string;
+ network?: 'mainnet' | 'devnet';
+ apiOrigin?: string;
+}
+export declare function fetchReputation(opts?: FetchReputationOptions): Promise<unknown>;
diff --git a/sdk/types/solana.d.ts b/sdk/types/solana.d.ts
new file mode 100644
index 000000000..7205ddfa6
--- /dev/null
+++ b/sdk/types/solana.d.ts
@@ -0,0 +1,45 @@
+export declare function detectSolanaProvider(preferred?: string | null): unknown | null;
+
+export interface SignInWithSolanaOptions {
+ preferred?: string | null;
+ nonceUrl?: string;
+ verifyUrl?: string;
+ chainId?: string;
+}
+export declare function signInWithSolana(opts?: SignInWithSolanaOptions): Promise<{ user: object; wallet: object }>;
+
+export interface RegisterSolanaAgentOptions {
+ name: string;
+ description?: string;
+ avatarId?: string;
+ network?: 'mainnet' | 'devnet';
+ preferred?: string | null;
+ onStatus?: (msg: string) => void;
+}
+export declare function registerSolanaAgent(opts?: RegisterSolanaAgentOptions): Promise<{
+ agent: object;
+ sol_mint_address: string;
+ tx_signature: string;
+}>;
+
+export interface StartSolanaCheckoutOptions {
+ plan: 'pro' | 'team' | 'enterprise';
+ network?: 'mainnet' | 'devnet';
+}
+export declare function startSolanaCheckout(opts?: StartSolanaCheckoutOptions): Promise<{
+ solana_pay_url: string;
+ intent_id: string;
+ amount_usdc: number;
+ nonce: string;
+}>;
+
+export interface ConfirmSolanaPaymentOptions {
+ intentId: string;
+ txSignature: string;
+ network?: 'mainnet' | 'devnet';
+}
+export declare function confirmSolanaPayment(opts?: ConfirmSolanaPaymentOptions): Promise<{
+ ok: boolean;
+ plan: string;
+ active_until: string;
+}>;
diff --git a/src/kol/wallets.js b/src/kol/wallets.js
index 19e9ad8da..f491fb80c 100644
--- a/src/kol/wallets.js
+++ b/src/kol/wallets.js
@@ -2,7 +2,7 @@
//
// Minimum P&L threshold rule: wallets here must have realised ≥$10 000
// cumulative profit on Solana meme-token trades.
-// TODO: replace stub with a dynamic source (on-chain P&L indexer, Dune, Birdeye)
+// Live P&L is fetched from /api/kol/wallets (Birdeye proxy) via getKolWalletsPnl().
export const KOL_WALLETS = [
{ address: 'Hxk8X7rXhWoJfhbJL8C6kA3mZVJH6P2n5hpwJzE9K1s', label: 'kol-alpha', tags: ['kol'] },
@@ -19,3 +19,24 @@ export function isSmartMoney(address) {
export function getWalletMeta(address) {
return _index.get(address) || null;
}
+
+/**
+ * Fetch live P&L for all KOL_WALLETS from the Birdeye proxy endpoint.
+ * Each entry is merged with its label/tags from the static list.
+ *
+ * @param {{ baseUrl?: string }} opts
+ * @returns {Promise<Array<{ address, label, tags, realizedPnl, unrealizedPnl, winRate, totalTrades, topToken }>>}
+ */
+export async function getKolWalletsPnl({ baseUrl = '' } = {}) {
+ const addresses = KOL_WALLETS.map((w) => w.address).join(',');
+ const res = await fetch(`${baseUrl}/api/kol/wallets?addresses=${encodeURIComponent(addresses)}`);
+ if (!res.ok) {
+ const j = await res.json().catch(() => ({}));
+ throw Object.assign(new Error(j.error_description ?? `kol/wallets ${res.status}`), { status: res.status, code: j.error });
+ }
+ const { data } = await res.json();
+ return data.map((entry) => {
+ const meta = _index.get(entry.address) ?? {};
+ return { label: meta.label ?? null, tags: meta.tags ?? [], ...entry };
+ });
+}
diff --git a/src/runtime/livekit-voice.js b/src/runtime/livekit-voice.js
new file mode 100644
index 000000000..127e13f7f
--- /dev/null
+++ b/src/runtime/livekit-voice.js
@@ -0,0 +1,105 @@
+// LiveKit realtime voice — bidirectional audio via a LiveKit room.
+// The agent server joins the same room, handles VAD/STT/TTS, and sends
+// data-channel messages with transcript payloads.
+
+import { Room, RoomEvent, Track } from 'livekit-client';
+
+export class LiveKitVoice {
+ /**
+ * @param {object} opts
+ * @param {string} opts.serverUrl LiveKit server WebSocket URL (wss://…)
+ * @param {string} opts.token Room access JWT
+ * @param {import('../agent-protocol.js').AgentProtocol} opts.protocol
+ */
+ constructor({ serverUrl, token, protocol }) {
+ this._serverUrl = serverUrl;
+ this._token = token;
+ this._protocol = protocol;
+ this._room = null;
+ this._audioEls = []; // { track, el }[]
+ this._userSpeaking = false;
+ }
+
+ async connect() {
+ const room = new Room();
+ this._room = room;
+
+ // Agent TTS audio — attach <audio> element when track arrives
+ room.on(RoomEvent.TrackSubscribed, (track, _pub, _participant) => {
+ if (track.kind !== Track.Kind.Audio) return;
+ const el = track.attach();
+ document.body.appendChild(el);
+ this._audioEls.push({ track, el });
+ });
+
+ room.on(RoomEvent.TrackUnsubscribed, (track) => {
+ const idx = this._audioEls.findIndex((e) => e.track === track);
+ if (idx === -1) return;
+ const { el } = this._audioEls.splice(idx, 1)[0];
+ try { track.detach(el); } catch {}
+ el.remove();
+ });
+
+ // Data messages from the agent server
+ room.on(RoomEvent.DataReceived, (data, _participant) => {
+ let msg;
+ try {
+ msg = JSON.parse(new TextDecoder().decode(data));
+ } catch {
+ return;
+ }
+ // Agent speaking — drive avatar lipsync + chat bubble
+ if (msg.type === 'transcript' && msg.text) {
+ this._protocol.emit({
+ type: 'speak',
+ payload: { text: msg.text, sentiment: 0 },
+ });
+ }
+ // User speech boundaries (VAD from agent server)
+ if (msg.type === 'speech_started') {
+ this._userSpeaking = true;
+ this._protocol.emit({ type: 'listen-start', payload: {} });
+ }
+ if (msg.type === 'speech_ended') {
+ this._userSpeaking = false;
+ this._protocol.emit({
+ type: 'listen-end',
+ payload: { text: msg.transcript || '' },
+ });
+ }
+ });
+
+ // Fallback: use LiveKit active-speaker VAD when agent doesn't send speech events
+ room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
+ const localId = room.localParticipant?.identity;
+ const active = speakers.some((p) => p.identity === localId);
+ if (active && !this._userSpeaking) {
+ this._userSpeaking = true;
+ this._protocol.emit({ type: 'listen-start', payload: {} });
+ } else if (!active && this._userSpeaking) {
+ this._userSpeaking = false;
+ this._protocol.emit({ type: 'listen-end', payload: { text: '' } });
+ }
+ });
+
+ await room.connect(this._serverUrl, this._token);
+ await room.localParticipant.setMicrophoneEnabled(true);
+ }
+
+ async disconnect() {
+ for (const { track, el } of this._audioEls) {
+ try { track.detach(el); } catch {}
+ try { el.remove(); } catch {}
+ }
+ this._audioEls = [];
+ if (this._room) {
+ try { await this._room.disconnect(); } catch {}
+ this._room = null;
+ }
+ this._userSpeaking = false;
+ }
+
+ get connected() {
+ return this._room?.state === 'connected';
+ }
+}
diff --git a/src/runtime/speech.js b/src/runtime/speech.js
index 42bb7b07a..50422cd76 100644
--- a/src/runtime/speech.js
+++ b/src/runtime/speech.js
@@ -1,5 +1,7 @@
// Speech I/O — TTS and STT. Browser-native by default; provider-swappable.
+export { LiveKitVoice } from './livekit-voice.js';
+
export class BrowserTTS {
constructor({ voiceId = 'default', rate = 1, pitch = 1, lang = 'en-US' } = {}) {
this.voiceId = voiceId;