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

nirholas9448ec96ae12
diff --git a/chat/src/App.svelte b/chat/src/App.svelte
index 82e5c5f3a..0cb79f1a1 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, activeAgent, talkingHeadEnabled, route, mode, websiteCategory } from './stores.js';
+ import { controller, remoteServer, config, params, toolSchema, syncServer, brandConfig, ttsEnabled, localAgentId, activeAgent, talkingHeadEnabled, route, mode, websiteCategory, loadCurrentUser } from './stores.js';
import AuthPage from './manus/pages/AuthPage.svelte';
import Pricing from './manus/pages/Pricing.svelte';
import MarketingPage from './manus/pages/MarketingPage.svelte';
@@ -1065,6 +1065,9 @@
syncRouteFromHash();
window.addEventListener('hashchange', syncRouteFromHash);
+ // Populate auth state from session cookie
+ await loadCurrentUser();
+
// Fetch global brand config from server
try {
const res = await fetch('/api/chat/config');
@@ -1207,6 +1210,8 @@
let talkingHead;
let talkingHeadReady = false;
let pendingSpeak = null;
+ let agentReady = false;
+ let agentPendingSpeak = null;
let agentVisible = true;
let agentScriptLoaded = false;
let agentPickerOpen = false;
@@ -1224,6 +1229,21 @@
// Expose to client tools
$: if (agentEl) window.__threewsAgent = agentEl;
+ $: if (agentEl && !agentReady) {
+ agentEl.addEventListener('agent:ready', () => {
+ agentReady = true;
+ if (agentPendingSpeak) {
+ agentEl.speak(agentPendingSpeak);
+ agentPendingSpeak = null;
+ }
+ }, { once: true });
+ }
+
+ $: if (effectiveAgentId) {
+ agentReady = false;
+ agentPendingSpeak = null;
+ }
+
// Inject 3D agent tools into schema when an agent is active
$: if (effectiveAgentId) {
const hasGroup = $toolSchema.some(g => g.name === '3D Agent');
@@ -1232,12 +1252,27 @@
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;
+ const scores = { concern: 0, celebration: 0, curiosity: 0, empathy: 0, patience: 0 };
+
+ 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;
+
+ 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;
+
+ if (/\b(interesting|fascinating|curious|wonder|surprising|actually|notably|worth knowing)\b/.test(t)) scores.curiosity += 2;
+ if (/\?/.test(text)) scores.curiosity += 1;
+
+ 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;
+
+ if (/\b(let me|one moment|working on|processing|calculating|give me a|just a)\b/.test(t)) scores.patience += 2;
+
+ 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;
}
$: if ($mode !== 'website') websiteCategory.set(null);
@@ -1247,12 +1282,18 @@
if (!last?.content) return;
if (agentEl && effectiveAgentId) {
- agentEl.speak(last.content);
- const emotion = detectEmotion(last.content);
- if (emotion) setTimeout(() => agentEl?.expressEmotion(emotion), 600);
+ if (agentReady) {
+ agentEl.speak(last.content);
+ const emotion = detectEmotion(last.content);
+ if (emotion) setTimeout(() => agentEl?.expressEmotion(emotion), 600);
+ } else {
+ agentPendingSpeak = last.content;
+ }
} else if ($talkingHeadEnabled && agentVisible) {
if (talkingHeadReady) {
- talkingHead.speak({ text: last.content });
+ const mood = detectEmotion(last.content);
+ if (mood) talkingHead.setMood(mood);
+ talkingHead.speak({ text: last.content, mood: mood || 'neutral' });
} else {
pendingSpeak = last.content;
}
diff --git a/chat/src/TalkingHead.svelte b/chat/src/TalkingHead.svelte
index 8fbc72b6c..997b32332 100644
--- a/chat/src/TalkingHead.svelte
+++ b/chat/src/TalkingHead.svelte
@@ -22,17 +22,38 @@
export let ttsApikey = '';
export let lipsyncModules = ['en'];
+ const CDN_URL =
+ 'https://cdn.jsdelivr.net/gh/met4citizen/[email protected]/modules/talkinghead.mjs';
+
const dispatch = createEventDispatcher();
let container;
let head = null;
let loadError = null;
- onMount(async () => {
+ function importWithTimeout(url, ms) {
+ return Promise.race([
+ import(/* @vite-ignore */ url),
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error('CDN load timed out')), ms)
+ ),
+ ]);
+ }
+
+ async function loadAvatar() {
+ loadError = null;
+ if (head?.stop) head.stop();
+ head = null;
+
try {
- const mod = await import(
- /* @vite-ignore */ 'https://cdn.jsdelivr.net/gh/met4citizen/[email protected]/modules/talkinghead.mjs'
- );
+ let mod;
+ try {
+ mod = await importWithTimeout(CDN_URL, 15000);
+ } catch {
+ await new Promise((r) => setTimeout(r, 2000));
+ mod = await importWithTimeout(CDN_URL, 15000);
+ }
+
const { TalkingHead } = mod;
head = new TalkingHead(container, {
ttsEndpoint,
@@ -40,17 +61,32 @@
lipsyncModules,
cameraView: 'upper',
});
- await head.showAvatar({
- url: avatarUrl,
- body: avatarBody,
- avatarMood: 'neutral',
- lipsyncLang: 'en',
- });
+
+ 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)
+ ),
+ ]);
+
dispatch('ready');
} catch (err) {
loadError = err?.message || String(err);
console.warn('[TalkingHead] failed to load', err);
}
+ }
+
+ export function retry() {
+ loadAvatar();
+ }
+
+ onMount(() => {
+ loadAvatar();
});
onDestroy(() => {
@@ -74,7 +110,11 @@
<div class="talking-head" bind:this={container}>
{#if loadError}
- <div class="error">avatar failed to load: {loadError}</div>
+ <div class="error">
+ <p>Avatar failed to load</p>
+ <p class="detail">{loadError}</p>
+ <button on:click={retry}>Retry</button>
+ </div>
{/if}
</div>
@@ -90,11 +130,30 @@
.error {
position: absolute;
inset: 0;
- display: grid;
- place-items: center;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ padding: 16px;
+ }
+ .error p {
color: #f88;
- font: 12px/1.4 system-ui, sans-serif;
- padding: 12px;
+ font-size: 12px;
text-align: center;
+ margin: 0;
+ }
+ .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;
}
</style>
diff --git a/chat/src/manus/TopNav.svelte b/chat/src/manus/TopNav.svelte
index 92e5bf755..ffb78b27b 100644
--- a/chat/src/manus/TopNav.svelte
+++ b/chat/src/manus/TopNav.svelte
@@ -2,6 +2,7 @@
import { route } from '../stores.js';
import Icon from '../Icon.svelte';
import { feMenu, feX } from '../feather.js';
+ import WalletConnect from '../WalletConnect.svelte';
import FeaturesDropdown from './dropdowns/FeaturesDropdown.svelte';
import SolutionsDropdown from './dropdowns/SolutionsDropdown.svelte';
import ResourcesDropdown from './dropdowns/ResourcesDropdown.svelte';
@@ -154,14 +155,7 @@
<!-- 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>
+ <WalletConnect />
</div>
<button
class="rounded p-2 text-ink hover:bg-paper-deep md:hidden"
@@ -183,14 +177,7 @@
>{label}</button>
{/each}
<div class="flex gap-2 px-6 py-4">
- <button
- class="h-9 flex-1 rounded-full bg-black text-sm font-medium text-white"
- on:click={() => { route.set('signin'); mobileOpen = false; }}
- >Sign in</button>
- <button
- class="h-9 flex-1 rounded-full border border-rule bg-white text-sm font-medium text-ink"
- on:click={() => { route.set('signup'); mobileOpen = false; }}
- >Sign up</button>
+ <WalletConnect />
</div>
</div>
{/if}
diff --git a/chat/src/manus/pages/AuthPage.svelte b/chat/src/manus/pages/AuthPage.svelte
index 03c130c8d..8ecbbbecf 100644
--- a/chat/src/manus/pages/AuthPage.svelte
+++ b/chat/src/manus/pages/AuthPage.svelte
@@ -1,13 +1,45 @@
<script>
- import { route } from '../../stores.js';
+ import { route, 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() {
- console.log(kind, { email, password, name });
+ // Email/password auth not yet implemented
route.set('chat');
}
</script>
@@ -24,14 +56,23 @@
</p>
<div class="mt-6 space-y-3">
- <button 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">
- <span class="w-4 h-4 inline-block bg-[url('https://www.google.com/favicon.ico')] bg-cover" />
- Continue with Google
+ <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 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">
- <span class="w-4 h-4 inline-block bg-[url('https://github.com/favicon.ico')] bg-cover" />
- Continue with GitHub
+ <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>
<div class="flex items-center gap-3 text-xs text-[#9C9A93] my-4">
diff --git a/public/chat/index.html b/public/chat/index.html
index 4bc6dd1a7..a54d77bb3 100644
--- a/public/chat/index.html
+++ b/public/chat/index.html
@@ -43,8 +43,8 @@
}
}
</script>
- <script type="module" crossorigin src="/chat/assets/index-fqASZrpU.js"></script>
- <link rel="stylesheet" crossorigin href="/chat/assets/index-BUeeFXPP.css">
+ <script type="module" crossorigin src="/chat/assets/index-CyOvkWX9.js"></script>
+ <link rel="stylesheet" crossorigin href="/chat/assets/index-CJygAP8J.css">
</head>
<body>
<div id="app"></div>
diff --git a/src/agent-protocol.js b/src/agent-protocol.js
index f4f28a207..7f780dfc2 100644
--- a/src/agent-protocol.js
+++ b/src/agent-protocol.js
@@ -22,6 +22,7 @@ export const ACTION_TYPES = {
LOAD_END: 'load-end', // model/asset loading finished
VALIDATE: 'validate', // validation result (errors, warnings, hints)
PRESENCE: 'presence', // agent came online / went idle
+ PROTOCOL_ERROR: 'protocol-error', // emitted by the rate limiter on cascade detection
PERMISSIONS_REDEEM_START: 'permissions.redeem.start',
PERMISSIONS_REDEEM_SUCCESS: 'permissions.redeem.success',
PERMISSIONS_REDEEM_ERROR: 'permissions.redeem.error',
@@ -41,6 +42,21 @@ export class AgentProtocol extends EventTarget {
super();
this._history = [];
this._maxHistory = 200;
+
+ // Rate limiter state
+ this._counters = new Map(); // eventType → { count, windowStart }
+ this._throttled = new Set(); // event types currently rate-limited
+ this._limits = {
+ 'perform-skill': 10,
+ 'emote': 20,
+ 'speak': 5,
+ '*': 100,
+ };
+ this._windowMs = 100;
+ this._cooldownMs = 1000;
+
+ /** Set to true at runtime to log all emits instead of rate-limiting. */
+ this.debug = false;
}
/**
@@ -48,6 +64,13 @@ export class AgentProtocol extends EventTarget {
* @param {Omit<ActionPayload, 'timestamp'>} action
*/
emit(action) {
+ if (this.debug) {
+ console.log(`[agent-protocol] ${Date.now()} ${action.type}`, action.payload);
+ } else if (this._isThrottled(action.type)) {
+ console.warn(`[agent-protocol] rate-limited: ${action.type} — too many events`);
+ return;
+ }
+
const full = {
type: action.type,
payload: action.payload || {},
@@ -67,6 +90,60 @@ export class AgentProtocol extends EventTarget {
this.dispatchEvent(new CustomEvent('*', { detail: full }));
}
+ _isThrottled(type) {
+ if (this._throttled.has(type)) return true;
+
+ const now = Date.now();
+ const counter = this._counters.get(type) || { count: 0, windowStart: now };
+
+ if (now - counter.windowStart > this._windowMs) {
+ counter.count = 1;
+ counter.windowStart = now;
+ this._counters.set(type, counter);
+ return false;
+ }
+
+ counter.count++;
+ this._counters.set(type, counter);
+
+ const limit = this._limits[type] ?? this._limits['*'];
+ if (counter.count > limit) {
+ this._throttle(type);
+ return true;
+ }
+ return false;
+ }
+
+ _throttle(type) {
+ this._throttled.add(type);
+ 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);
+ }
+
+ // Bypasses the rate limiter — only for internal protocol-error emission.
+ _dispatchDirect(type, payload) {
+ const full = {
+ type,
+ payload,
+ timestamp: Date.now(),
+ agentId: 'protocol',
+ sourceSkill: null,
+ };
+ this._history.push(full);
+ if (this._history.length > this._maxHistory) this._history.shift();
+ this.dispatchEvent(new CustomEvent(type, { detail: full }));
+ this.dispatchEvent(new CustomEvent('*', { detail: full }));
+ }
+
/**
* Subscribe to a specific action type (or '*' for all).
* @param {string} type