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.

fix(embed): send every API call to three.ws, never the host page, and add a chat composer

nirholasfb067d0f279a
diff --git a/api/agents/_id/_sub.js b/api/agents/_id/_sub.js
index fbde93cec..6b479412b 100644
--- a/api/agents/_id/_sub.js
+++ b/api/agents/_id/_sub.js
@@ -374,7 +374,7 @@ export const handleManifest = wrap(async (req, res, id) => {
return error(res, 400, 'invalid_request', 'agent id required');
const [row] =
- await sql`select a.id, a.name, a.description, a.avatar_id, a.skills, a.meta, a.chain_id, a.erc8004_agent_id, a.erc8004_registry, a.registration_cid, a.created_at, a.voice_provider, a.voice_id, a.persona_prompt_hash, a.persona_tone_tags, a.persona_extracted_at, a.persona_traits, av.id as avatar_db_id, av.storage_key, av.content_type from agent_identities a left join avatars av on av.id = a.avatar_id and av.deleted_at is null where a.id = ${id} and a.deleted_at is null limit 1`;
+ await sql`select a.id, a.name, a.description, a.avatar_id, a.skills, a.meta, a.chain_id, a.erc8004_agent_id, a.erc8004_registry, a.registration_cid, a.created_at, a.voice_provider, a.voice_id, a.voice_model, a.voice_settings, a.persona_prompt_hash, a.persona_tone_tags, a.persona_extracted_at, a.persona_traits, av.id as avatar_db_id, av.storage_key, av.content_type from agent_identities a left join avatars av on av.id = a.avatar_id and av.deleted_at is null where a.id = ${id} and a.deleted_at is null limit 1`;
if (!row) return error(res, 404, 'not_found', 'agent not found');
// Live signal: whether the agent has claimed its activation grant (funded +
@@ -449,8 +449,18 @@ export const handleManifest = wrap(async (req, res, id) => {
},
]
: [],
+ // The model and delivery settings ride along with the voice id so an
+ // <agent-3d> embed, which resolves agents from this document, speaks with
+ // the delivery the owner tuned and not just the right timbre.
voice: row.voice_id
- ? { provider: row.voice_provider || 'elevenlabs', voice_id: row.voice_id }
+ ? {
+ provider: row.voice_provider || 'elevenlabs',
+ voice_id: row.voice_id,
+ ...(row.voice_model ? { model: row.voice_model } : {}),
+ ...(row.voice_settings && typeof row.voice_settings === 'object'
+ ? { settings: row.voice_settings }
+ : {}),
+ }
: { provider: 'browser' },
persona: {
has_persona: Boolean(row.persona_prompt_hash),
diff --git a/api/agents/pumpfun.js b/api/agents/pumpfun.js
index 47c23a5c7..ff0fe58da 100644
--- a/api/agents/pumpfun.js
+++ b/api/agents/pumpfun.js
@@ -17,7 +17,7 @@
*/
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
-import { cors, json, method, error, wrap, rateLimited } from '../_lib/http.js';
+import { cors, embedReadCors, json, method, error, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';
@@ -98,7 +98,9 @@ import { connectPumpFunFeed, recentBuffered } from '../_lib/pumpfun-ws-feed.js';
const TIER_RANK = { notable: 1, influencer: 2, mega: 3 };
async function handleFeed(req, res) {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ // Public market data with no session in it. `<agent-3d tracked-mint>` opens
+ // this stream from the embedding site, so an anonymous read answers any origin.
+ if (embedReadCors(req, res)) return;
if (!method(req, res, ['GET'])) return;
const rl = await limits.mcpIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl, 'too many feed connections');
diff --git a/api/avatars/[id].js b/api/avatars/[id].js
index 4d40b0217..ba6cc7594 100644
--- a/api/avatars/[id].js
+++ b/api/avatars/[id].js
@@ -13,7 +13,7 @@ import {
} from '../_lib/avatars.js';
import { sql } from '../_lib/db.js';
import { logAudit } from '../_lib/audit.js';
-import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
+import { cors, embedReadCors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { headObject } from '../_lib/r2.js';
import { limits } from '../_lib/rate-limit.js';
@@ -61,7 +61,10 @@ export default wrap(async (req, res) => {
return mod.dispatch(id, req, res);
}
- if (cors(req, res, { methods: 'GET,PATCH,DELETE,OPTIONS', credentials: true })) return;
+ // `<agent-3d avatar-id>` reads this from whatever site embeds it. An anonymous
+ // GET only ever sees a public avatar, so it is open to any origin; a request
+ // carrying a session, and every write, keeps the credentialed allowlist.
+ if (embedReadCors(req, res, { authedMethods: 'GET,PATCH,DELETE,OPTIONS' })) return;
if (!method(req, res, ['GET', 'PATCH', 'DELETE'])) return;
// Guard the DB call: an id that isn't a uuid would otherwise hit Postgres as
diff --git a/src/agent-memory.js b/src/agent-memory.js
index 228c874b4..60d3fcbd9 100644
--- a/src/agent-memory.js
+++ b/src/agent-memory.js
@@ -50,11 +50,15 @@ export class AgentMemory {
/**
* @param {string} agentId
* @param {{ backendSync?: boolean,
+ * apiOrigin?: string,
* embedFn?: (text: string) => Promise<number[] | { vector: number[], model?: string|null }> }} [opts]
+ * `apiOrigin` is the three.ws origin the sync calls go to; '' keeps them
+ * relative, which is right on three.ws's own pages.
*/
- constructor(agentId, { backendSync = false, embedFn = null } = {}) {
+ constructor(agentId, { backendSync = false, apiOrigin = '', embedFn = null } = {}) {
this.agentId = agentId;
this.backendSync = backendSync;
+ this.apiOrigin = apiOrigin;
this.embedFn = embedFn;
this._entries = [];
this._dirty = false;
@@ -201,7 +205,7 @@ export class AgentMemory {
if (!q) return null;
const params = new URLSearchParams({ agentId: this.agentId, q, topK: String(limit) });
if (type) params.set('type', type);
- const resp = await fetch(`/api/memory/search?${params}`, { credentials: 'include' });
+ const resp = await fetch(`${this.apiOrigin}/api/memory/search?${params}`, { credentials: 'include' });
if (!resp.ok) return null;
const { results } = await resp.json();
if (!Array.isArray(results)) return null;
@@ -304,7 +308,7 @@ export class AgentMemory {
_scheduleSync(entry) {
this._persist();
if (!this.backendSync || !this.agentId) return;
- fetch(`/api/agents/${this.agentId}/memories`, {
+ fetch(`${this.apiOrigin}/api/agents/${this.agentId}/memories`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
credentials: 'include',
@@ -332,7 +336,7 @@ export class AgentMemory {
const headers = {};
if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
const resp = await fetch(
- `/api/agent-memory?agentId=${encodeURIComponent(agentId)}`,
+ `${this.apiOrigin}/api/agent-memory?agentId=${encodeURIComponent(agentId)}`,
{ credentials: 'include', headers },
);
if (!resp.ok) return;
@@ -383,7 +387,7 @@ export class AgentMemory {
async _syncForget(id) {
try {
- await fetch(`/api/agents/${this.agentId}/memories/${id}`, {
+ await fetch(`${this.apiOrigin}/api/agents/${this.agentId}/memories/${id}`, {
method: 'DELETE',
credentials: 'include',
});
@@ -392,7 +396,7 @@ export class AgentMemory {
async _hydrateFromBackend() {
try {
- const resp = await fetch(`/api/agents/${this.agentId}/memories`, {
+ const resp = await fetch(`${this.apiOrigin}/api/agents/${this.agentId}/memories`, {
credentials: 'include',
});
if (!resp.ok) return;
diff --git a/src/agent-resolver.js b/src/agent-resolver.js
index 72ebf229a..d39c5e4c4 100644
--- a/src/agent-resolver.js
+++ b/src/agent-resolver.js
@@ -12,61 +12,68 @@ export class AgentResolveError extends Error {
}
}
-async function fetchJSON(url, { fetchFn }) {
- let res;
- try {
- res = await fetchFn(url, { credentials: 'include' });
- } catch (err) {
- throw new AgentResolveError(
- 'network',
- `network error fetching ${url}: ${err.message || err}`,
- );
- }
- if (res.status === 401 || res.status === 403) {
- throw new AgentResolveError(
- 'unauthorized',
- `unauthorized fetching ${url} (${res.status})`,
- { status: res.status },
- );
- }
- if (res.status === 404) {
- throw new AgentResolveError('not_found', `resource not found: ${url}`, { status: 404 });
- }
- if (!res.ok) {
- throw new AgentResolveError('network', `request failed: ${url} (${res.status})`, {
- status: res.status,
- });
- }
- try {
- return await res.json();
- } catch (err) {
- throw new AgentResolveError('network', `invalid JSON from ${url}: ${err.message || err}`);
- }
+// Map a stored ElevenLabs voice_settings object (snake_case, as persisted by
+// PUT /api/agents/:id/voice) to the camelCase options ElevenLabsTTS accepts.
+// Omits absent fields so the TTS client falls back to its own defaults.
+function voiceSettingsToConfig(vs) {
+ if (!vs || typeof vs !== 'object') return {};
+ const out = {};
+ if (vs.stability != null) out.stability = vs.stability;
+ if (vs.similarity_boost != null) out.similarityBoost = vs.similarity_boost;
+ if (vs.style != null) out.style = vs.style;
+ if (vs.use_speaker_boost != null) out.useSpeakerBoost = vs.use_speaker_boost;
+ return out;
}
-const _resolveCache = new Map();
-const _CACHE_MAX = 100;
+function ttsConfigFromManifestVoice(voice, { origin, agentId }) {
+ const provider = voice?.provider || 'browser';
+ if (provider !== 'elevenlabs' || !voice?.voice_id) return { provider: 'browser' };
+ return {
+ provider: 'elevenlabs',
+ voiceId: voice.voice_id,
+ proxyURL: `${origin}/api/tts/eleven`,
+ // Lets the proxy serve this clip on the owner's own ElevenLabs key, so an
+ // embed speaks for visitors too.
+ agentId,
+ ...(voice.model ? { modelId: voice.model } : {}),
+ ...voiceSettingsToConfig(voice.settings),
+ };
+}
/**
- * Resolve an agent ID to its manifest URL via GET /api/agents/:id.
- * Returns null if the agent record has no manifestUrl (caller may fall back to resolveAgentById).
- * Throws AgentResolveError('not_found') on 404.
+ * Resolve a hosted agent id to the in-memory manifest the element boots from.
+ *
+ * Reads the agent's public manifest, GET {origin}/api/agents/:id/manifest. That
+ * document is the embed contract: anonymous, CDN-cacheable, and served with
+ * `access-control-allow-origin: *`, so the same request works from three.ws and
+ * from any third-party page. It also carries the owner's gesture slots and
+ * routines, which the element applies at boot.
+ *
+ * `origin` must be the three.ws API base the element was loaded from, never the
+ * host page's origin: on example.com a site-absolute path asks example.com for
+ * the agent, 404s, and the embed falls back to a default body named "Agent".
*
* @param {string} agentId
- * @param {AbortSignal} [signal]
- * @returns {Promise<string|null>}
+ * @param {{ origin?: string, fetchFn?: typeof fetch, signal?: AbortSignal }} [opts]
*/
-export async function resolveByAgentId(agentId, signal) {
+export async function resolveAgentById(
+ agentId,
+ {
+ origin = typeof location !== 'undefined' ? location.origin : '',
+ fetchFn = fetch,
+ signal,
+ } = {},
+) {
if (!agentId) throw new AgentResolveError('not_found', 'agentId required');
- if (_resolveCache.has(agentId)) return _resolveCache.get(agentId);
-
- const origin = typeof location !== 'undefined' ? location.origin : '';
- const endpoint = `${origin}/api/agents/${encodeURIComponent(agentId)}`;
+ const boundFetch = fetchFn.bind(typeof globalThis !== 'undefined' ? globalThis : undefined);
+ const endpoint = `${origin}/api/agents/${encodeURIComponent(agentId)}/manifest`;
let res;
try {
- res = await fetch(endpoint, { credentials: 'include', signal });
+ // Public document: no cookies, so the wildcard CORS answer is usable
+ // from any origin and shared caches can serve it.
+ res = await boundFetch(endpoint, { credentials: 'omit', signal });
} catch (err) {
if (err?.name === 'AbortError') throw err;
throw new AgentResolveError(
@@ -74,118 +81,53 @@ export async function resolveByAgentId(agentId, signal) {
`network error fetching ${endpoint}: ${err.message || err}`,
);
}
-
- if (res.status === 404)
- throw new AgentResolveError('not_found', `agent ${agentId} not found`, { status: 404 });
- if (res.status === 401 || res.status === 403)
- throw new AgentResolveError('unauthorized', `unauthorized (${res.status})`, {
+ // 400 is the API's answer to an id that is not a uuid: no such agent.
+ if (res.status === 404 || res.status === 400)
+ throw new AgentResolveError('not_found', `agent ${agentId} not found`, {
status: res.status,
});
if (!res.ok)
- throw new AgentResolveError('network', `request failed (${res.status})`, {
+ throw new AgentResolveError('network', `request failed: ${endpoint} (${res.status})`, {
status: res.status,
});
- let data;
+ let doc;
try {
- data = await res.json();
+ doc = await res.json();
} catch (err) {
- throw new AgentResolveError('network', `invalid JSON from ${endpoint}`);
- }
-
- const raw = data?.agent?.manifestUrl ?? null;
- let resolved = null;
- if (raw) {
- try {
- resolved = new URL(raw, origin).href;
- } catch {
- resolved = raw;
- }
- }
-
- if (_resolveCache.size >= _CACHE_MAX) _resolveCache.delete(_resolveCache.keys().next().value);
- _resolveCache.set(agentId, resolved);
-
- return resolved;
-}
-
-// Map a stored ElevenLabs voice_settings object (snake_case, as persisted by
-// PUT /api/agents/:id/voice) to the camelCase options ElevenLabsTTS accepts.
-// Omits absent fields so the TTS client falls back to its own defaults.
-function voiceSettingsToConfig(vs) {
- if (!vs || typeof vs !== 'object') return {};
- const out = {};
- if (vs.stability != null) out.stability = vs.stability;
- if (vs.similarity_boost != null) out.similarityBoost = vs.similarity_boost;
- if (vs.style != null) out.style = vs.style;
- if (vs.use_speaker_boost != null) out.useSpeakerBoost = vs.use_speaker_boost;
- return out;
-}
-
-export async function resolveAgentById(
- agentId,
- { origin = typeof location !== 'undefined' ? location.origin : '', fetchFn = fetch } = {},
-) {
- if (!agentId) throw new AgentResolveError('not_found', 'agentId required');
-
- const boundFetch = fetchFn.bind(typeof globalThis !== 'undefined' ? globalThis : undefined);
-
- const agentRes = await fetchJSON(`${origin}/api/agents/${encodeURIComponent(agentId)}`, {
- fetchFn: boundFetch,
- });
- const agent = agentRes?.agent;
- if (!agent) throw new AgentResolveError('not_found', `agent ${agentId} not found`);
-
- if (!agent.avatar_id) {
- throw new AgentResolveError('no_avatar', `agent ${agentId} has no avatar bound`);
+ throw new AgentResolveError('network', `invalid JSON from ${endpoint}: ${err.message || err}`);
}
- const avatarRes = await fetchJSON(
- `${origin}/api/avatars/${encodeURIComponent(agent.avatar_id)}`,
- { fetchFn: boundFetch },
- );
- const avatar = avatarRes?.avatar;
- if (!avatar || !avatar.url) {
- throw new AgentResolveError('no_avatar', `avatar ${agent.avatar_id} has no url`);
- }
+ const id = doc?.id || agentId;
+ const bodyUri = doc?.body?.uri;
+ if (!bodyUri) throw new AgentResolveError('no_avatar', `agent ${agentId} has no avatar bound`);
- const skills = Array.isArray(agent.skills)
- ? agent.skills.map((s) => (typeof s === 'string' ? { name: s } : s)).filter(Boolean)
+ const skills = Array.isArray(doc.skills)
+ ? doc.skills.map((s) => (typeof s === 'string' ? { name: s } : s)).filter(Boolean)
: [];
+ const registration = Array.isArray(doc.registrations) ? doc.registrations[0] : null;
+ const chainId = registration?.agentRegistry
+ ? Number(String(registration.agentRegistry).split(':')[1]) || undefined
+ : undefined;
return {
spec: 'agent-manifest/0.1',
- name: agent.name || 'Agent',
- description: agent.description || '',
- id: {
- agentId: agent.id,
- owner: agent.wallet_address,
- chainId: agent.chain_id,
- walletAddress: agent.wallet_address,
- },
- body: { uri: avatar.url, format: 'gltf-binary' },
+ name: doc.name || 'Agent',
+ description: doc.description || '',
+ id: { agentId: id, ...(chainId ? { chainId } : {}) },
+ body: { uri: bodyUri, format: 'gltf-binary' },
brain: {},
voice: {
- tts:
- agent.voice_id && agent.voice_provider === 'elevenlabs'
- ? {
- provider: 'elevenlabs',
- voiceId: agent.voice_id,
- proxyURL: `${origin}/api/tts/eleven`,
- // Lets the proxy serve this clip on the owner's own
- // ElevenLabs key, so an embed speaks for visitors too.
- agentId: agent.id,
- ...(agent.voice_model ? { modelId: agent.voice_model } : {}),
- ...voiceSettingsToConfig(agent.voice_settings),
- }
- : { provider: 'browser' },
+ tts: ttsConfigFromManifestVoice(doc.voice, { origin, agentId: id }),
stt: { provider: 'browser' },
},
skills,
- memory: { mode: 'local', namespace: agent.id },
+ memory: { mode: 'local', namespace: id },
tools: ['wave', 'lookAt', 'play_clip', 'setExpression', 'speak', 'remember'],
+ ...(doc.animationSlots ? { animationSlots: doc.animationSlots } : {}),
+ ...(Array.isArray(doc.choreographies) ? { choreographies: doc.choreographies } : {}),
version: '0.1.0',
- _baseURI: `${origin}/agent/${agent.id}/`,
+ _baseURI: `${origin}/agent/${id}/`,
_source: 'agent-id',
};
}
diff --git a/src/element.js b/src/element.js
index 0154fc274..f63ffb08c 100644
--- a/src/element.js
+++ b/src/element.js
@@ -12,7 +12,6 @@ import { loadManifest, fetchRelative } from './manifest.js';
import { uriCandidates } from './ipfs.js';
import {
resolveAgentById,
- resolveByAgentId,
resolveByAvatarId,
AgentResolveError,
} from './agent-resolver.js';
@@ -25,6 +24,12 @@ import { AgentAvatar } from './agent-avatar.js';
// END:EMBED_BRIDGES_IMPORT
import { AgentNotifier } from './agent-notifier.js';
import { log } from './shared/log.js';
+import {
+ apiOriginFromScriptURL,
+ resolveApiBase,
+ credentialsFor,
+ isPageOrigin,
+} from './shared/embed-api-origin.js';
const MODES = ['inline', 'floating', 'section', 'fullscreen'];
@@ -113,14 +118,10 @@ function _parsePx(val) {
return n > 0 && typeof val === 'string' && val.trim().endsWith('px') ? n : 0;
}
-// Derive the origin of the script itself so cross-origin embeds hit the right API.
-const _scriptOrigin = (() => {
- try {
- return new URL(import.meta.url).origin;
- } catch {
- return '';
- }
-})();
+// The three.ws origin this script was served from. Cross-origin embeds send
+// every API call here, never to the host page; see shared/embed-api-origin.js.
+const _scriptOrigin = apiOriginFromScriptURL(import.meta.url);
+const _pageOrigin = () => (typeof location !== 'undefined' ? location.origin : '');
function originAllowed(originUrl, policy, firstParty = []) {
if (!originUrl) return false;
@@ -376,6 +377,68 @@ const BASE_STYLE = `
@keyframes blink-cursor { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
/* Suggestion chips when the conversation is empty */
.suggest-row { display: flex; flex-wrap: wrap; gap: 6px; padding: 8px 0 0; }
+ /* Composer: where a visitor types to the agent. Enter or the send button
+ submits; the mic appears only where speech input can actually work. */
+ .input-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-top: 8px;
+ background: var(--agent-surface);
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 999px;
+ padding: 4px 4px 4px 14px;
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+ flex: 0 0 auto;
+ transition: border-color 0.15s, box-shadow 0.15s, opacity 0.15s;
+ }
+ .input-row:hover { border-color: rgba(255, 255, 255, 0.22); }
+ .input-row:focus-within {
+ border-color: var(--agent-accent);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--agent-accent) 30%, transparent);
+ }
+ .input-row[data-busy="true"] { opacity: 0.75; }
+ .input-row input {
+ flex: 1;
+ min-width: 0;
+ background: transparent;
+ border: 0;
+ color: var(--agent-on-surface);
+ font: 14px var(--agent-chat-font);
+ outline: none;
+ padding: 6px 0;
+ }
+ .input-row input::placeholder { color: color-mix(in srgb, var(--agent-on-surface) 55%, transparent); }
+ .input-row input:disabled { cursor: progress; }
+ .input-row input[data-state="thinking"] { opacity: 0.6; }
+ button.icon {
+ flex: 0 0 auto;
+ width: 36px;
+ height: 36px;
+ border-radius: 50%;
+ border: 0;
+ background: var(--agent-accent);
+ color: #fff;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ transition: transform 0.12s, filter 0.12s, box-shadow 0.15s, opacity 0.15s;
+ }
+ button.icon svg { width: 18px; height: 18px; }
+ button.icon:hover:not(:disabled) { filter: brightness(1.12); }
+ button.icon:active:not(:disabled) { transform: scale(0.94); }
+ button.icon:focus-visible { outline: 2px solid var(--agent-on-surface); outline-offset: 2px; }
+ button.icon:disabled { opacity: 0.45; cursor: default; }
+ button.icon.mic { background: rgba(255, 255, 255, 0.12); }
+ button.icon.mic[data-listening="true"] { box-shadow: 0 0 0 4px var(--agent-mic-glow); }
+ button.icon.mic[data-voice-state="listening"] { box-shadow: 0 0 0 4px #22c55e; }
+ button.icon.mic[data-voice-state="thinking"] { box-shadow: 0 0 0 4px #eab308; }
+ button.icon.mic[data-voice-state="speaking"] { box-shadow: 0 0 0 4px #3b82f6; }
+ @media (prefers-reduced-motion: reduce) {
+ .input-row, button.icon { transition: none; }
+ }
/* A chip carries its own ground. It used to be a 6% white wash, which is only
legible over something dark: on a host page with a light background the
near-white label disappeared. */
@@ -490,6 +553,10 @@ const BASE_STYLE = `
}
.name-plate:empty,
:host([name-plate="off"]) .name-plate { display: none; }
+ /* Chat mode: the composer owns the bottom edge, so the plate reads as a
+ header instead, and the conversation starts below it. */
+ :host(:not([data-bare])) .name-plate { top: 14px; bottom: auto; left: 16px; }
+ :host(:not([data-bare]):not([name-plate="off"])) .chat { padding-top: 26px; }
/* Background variants — set on :host so the canvas composites over them. */
:host([background="transparent"]) { background: transparent; }
:host([background="transparent"]) .thought-bubble {
@@ -607,6 +674,7 @@ const BASE_STYLE = `
gap: 8px;
}
:host([avatar-chat="off"]) .chat { flex: 1; max-height: 40%; }
+ :host([avatar-chat="off"]) .input-row { flex: 0 0 auto; }
:host([avatar-chat="off"]) .avatar-anchor { display: none; }
/* Floating mode layout fixes */
:host([mode="floating"]) .chrome {
@@ -620,6 +688,9 @@ const BASE_STYLE = `
:host([mode="section"]) .chat {
max-width: 600px;
}
+ :host([mode="section"]) .input-row {
+ max-width: 600px;
+ }
/* Fullscreen mode — centre the chrome column on large monitors */
:host([mode="fullscreen"]) .chrome {
max-width: 800px;
@@ -680,8 +751,6 @@ class Agent3DElement extends HTMLElement {
this._mqNarrowHandler = null;
this._ro = null;
this._outsideTapHandler = null;
- this._autoResolvedManifest = false;
- this._suppressAttrChange = false;
this._detachTradeReactions = null;
this._livekitVoice = null;
this._voiceClient = null;
@@ -760,6 +829,28 @@ class Agent3DElement extends HTMLElement {
return /^agent:\/\//i.test(this.getAttribute('src') || '');
}
+ // The base every API request of this element is built on: the `api-base`
+ // attribute when set, else the three.ws origin this script came from. Never
+ // the host page's origin unless the page IS that origin. See
+ // shared/embed-api-origin.js for the full resolution order.
+ _apiBase() {
+ return resolveApiBase({
+ attr: this.getAttribute('api-base'),
+ scriptOrigin: _scriptOrigin,
+ pageOrigin: _pageOrigin(),
+ });
+ }
+
+ // True when this element's API base is the page's own origin, i.e. the
+ // visitor's three.ws session cookie belongs to its requests.
+ _apiIsPageOrigin() {
+ return isPageOrigin(this._apiBase(), _pageOrigin());
+ }
+
+ _apiCredentials() {
+ return credentialsFor(this._apiBase(), _pageOrigin());
+ }
+
// Reflect the resolved chrome mode onto the host as a read-only `data-bare`
// marker. CSS keys the debug-GUI/axes hiding off it, so the default bare
// avatar shows no controls even though it carries no `kiosk`/`viewer` attr.
@@ -767,6 +858,22 @@ class Agent3DElement extends HTMLElement {
this.toggleAttribute('data-bare', !this._isChatMode());
}
+ // The memory mode for this boot. `remote` and `encrypted-ipfs` store through
+ // the owner's three.ws session; on another site that session cannot ride
+ // along, so they would read nothing and fail every write. Keep the
+ // conversation's memory in this browser instead, and say why once.
+ _memoryMode(manifest) {
+ const requested = this.getAttribute('memory') || manifest.memory?.mode || 'local';
+ if ((requested === 'remote' || requested === 'encrypted-ipfs') && !this._apiIsPageOrigin()) {
+ log.warn(
+ `[agent-3d] memory="${requested}" needs the owner's three.ws session, which is not ` +
+ 'available on this site; using memory="local" for this embed.',
+ );
+ return 'local';
+ }
+ return requested;
+ }
+
// Tear down and rebuild the entire shadow shell, then reboot. Used when the
// chat↔bare mode flips at runtime, since the two modes render different
// chrome and _renderShell is otherwise idempotent.
@@ -841,7 +948,6 @@ class Agent3DElement extends HTMLElement {
}
attributeChangedCallback(name, oldVal, newVal) {
- if (this._suppressAttrChange) return;
// Source attribute set on a not-yet-booted (eager but no source) element
// — boot now instead of rebooting.
if (
@@ -862,7 +968,7 @@ class Agent3DElement extends HTMLElement {
if (name === 'tracked-mint') {
this._detachTradeReactions?.();
this._detachTradeReactions = newVal
- ? attachTradeReactions(this, { mint: newVal })
+ ? attachTradeReactions(this, { mint: newVal, origin: this._apiBase() })
: null;
}
if (name === 'avatar-walk' && newVal === 'off') {
@@ -1007,6 +1113,7 @@ class Agent3DElement extends HTMLElement {
chat.appendChild(avatarAnchor);
chrome.appendChild(chat);
+ chrome.appendChild(this._buildComposer());
this.shadowRoot.appendChild(chrome);
this._chatEl = chat;
this._avatarAnchorEl = avatarAnchor;
@@ -1121,7 +1228,7 @@ class Agent3DElement extends HTMLElement {
this._walletHostEl = host;
this._walletAgentId = agentId;
- const origin = this.getAttribute('api-base') || _scriptOrigin || window.location.origin;
+ const origin = this._apiBase();
const mode = (this.getAttribute('wallet') || '').trim().toLowerCase();
import('./shared/portable-wallet.js')
.then(({ mountPortableWallet }) => {
@@ -1139,6 +1246,77 @@ class Agent3DElement extends HTMLElement {
});
}
+ // The chat composer: a text field, a send button, and (where the browser can
+ // hear) a push-to-talk mic. Without it chat mode had no way to type to the
+ // agent at all; the only inputs were the canned suggestion chips.
+ _buildComposer() {
+ const row = document.createElement('form');
+ row.className = 'input-row';
+ row.part = 'input-row';
+ row.setAttribute('aria-label', 'Message the agent');
+
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.placeholder = 'Say something...';
+ input.autocomplete = 'off';
+ input.enterKeyHint = 'send';
+ input.maxLength = 2000;
+ input.setAttribute('aria-label', 'Message to agent');
+ input.part = 'input';
+
+ const send = document.createElement('button');
+ send.type = 'submit';
+ send.className = 'icon send';
+ send.title = 'Send';
+ send.setAttribute('aria-label', 'Send message');
+ send.innerHTML =
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
+ '<path d="M5 12h14"></path><path d="M13 6l6 6-6 6"></path></svg>';
+
+ row.addEventListener('submit', (e) => {
+ e.preventDefault();
+ const text = input.value.trim();
+ if (!text || input.disabled) return;
+ input.value = '';
+ this._onStreamChunk(); // immediate visual feedback before the LLM responds
+ this.say(text);
+ });
+
+ row.appendChild(input);
+ if (this._speechInputAvailable()) {
+ const mic = document.createElement('button');
+ mic.type = 'button';
+ mic.className = 'icon mic';
+ mic.title = 'Push to talk';
+ mic.setAttribute('aria-label', 'Push to talk');
+ mic.innerHTML =
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
+ '<rect x="9" y="3" width="6" height="11" rx="3"></rect>' +
+ '<path d="M5 11a7 7 0 0 0 14 0"></path><path d="M12 18v3"></path></svg>';
+ mic.addEventListener('click', () => this._toggleMic());
+ row.appendChild(mic);
+ this._micEl = mic;
+ }
+ row.appendChild(send);
+ this._inputEl = input;
+ return row;
+ }
+
+ // Names the agent once it is known, so the field reads as a conversation
+ // with someone rather than a generic text box.
+ _composerPlaceholder() {
+ const name = (this._manifest?.name || '').trim();
+ return name && name !== 'Agent' ? `Message ${name}…` : 'Say something...';
+ }
+
+ // Push-to-talk works through a voice server or the browser's own speech
+ // recognition. Where neither exists the mic would be a dead button.
+ _speechInputAvailable() {
+ if (this.getAttribute('voice-server')) return true;
+ if (typeof window === 'undefined') return false;
+ return Boolean(window.SpeechRecognition || window.webkitSpeechRecognition);
+ }
+
_renderSuggestions() {
if (!this._chatEl) return;
const existing = this._chatEl.querySelector('.suggest-row');
@@ -1595,7 +1773,7 @@ class Agent3DElement extends HTMLElement {
this._mountWalletAffordance();
if (_backendId) {
try {
- const _policyBase = _scriptOrigin || window.location.origin;
+ const _policyBase = this._apiBase();
const _pr = await fetch(
`${_policyBase}/api/agents/${_backendId}/embed-policy`,
{ credentials: 'omit' },
@@ -1638,6 +1816,9 @@ class Agent3DElement extends HTMLElement {
// _startInitialPlayback.
this._stageEl.classList.add('is-settling');
const viewer = new Viewer(this._stageEl, {
+ // Never mount the editor's debug GUI or clip panel inside the
+ // element: their styles live in the site stylesheet, not here.
+ embed: true,
kiosk: !this._isChatMode(),
framing: this.getAttribute('framing') === 'portrait' ? 'portrait' : 'full',
});
@@ -1649,10 +1830,11 @@ class Agent3DElement extends HTMLElement {
// A bare avatar carries no name-plate unless the embedder asks for one.
this._applyBackground();
this._setNamePlateText(this._isChatMode() ? manifest.name || '' : '');
+ if (this._inputEl) this._inputEl.placeholder = this._composerPlaceholder();
this._applyNamePlate();
// Fetch animation defs before viewer.load so _setupAnimationPanel
// can preload idle+walk during the model load.
- const _animBase = _scriptOrigin || window.location.origin;
+ const _animBase = this._apiBase();
try {
const _animRes = await fetch(`${_animBase}/animations/manifest.json`);
if (_animRes.ok) {
@@ -1708,11 +1890,14 @@ class Agent3DElement extends HTMLElement {
await Promise.allSettled([_am.ensureLoaded('idle'), _am.ensureLoaded('walk')]);
}
// After the reveal tween completes, shift the orbital target upward
- // so the avatar's upper body fills the avatar-anchor window rather
- // than the full canvas height. Skipped under `framing="portrait"`,
- // where setContent already places the head-to-mid-thigh crop and an
- // extra nudge would fight it.
- if (this.getAttribute('framing') !== 'portrait') {
+ // so the avatar's upper body fills the chat shell's avatar-anchor
+ // window rather than the full canvas height. Chat mode only: a bare
+ // avatar has no anchor window, and the nudge tilted its camera up by
+ // 12% of the body height, which in any frame wider than 3:4 (where
+ // the height fit is tight) pushed the feet out of the bottom edge.
+ // Also skipped under `framing="portrait"`, where setContent already
+ // places the head-to-mid-thigh crop and an extra nudge would fight it.
+ if (this._isChatMode() && this.getAttribute('framing') !== 'portrait') {
const _v = viewer;
const _nudge = () => {
if (_v._cameraTweenRaf) {
@@ -1747,17 +1932,24 @@ class Agent3DElement extends HTMLElement {
const memoryNamespace =
manifest.id?.agentId || this.getAttribute('memory-key') || manifest.name || 'anon';
this._memory = await Memory.load({
- mode: this.getAttribute('memory') || manifest.memory?.mode || 'local',
+ mode: this._memoryMode(manifest),
namespace: memoryNamespace,
manifestURI: manifest._baseURI + 'manifest.json',
fetchFn: fetch.bind(globalThis),
+ apiOrigin: this._apiBase(),
});
// Pull backend memories into the shared AgentMemory localStorage store
// before the first LLM turn so cross-device memory is present on init.
- if (_backendId) {
+ // Those memories are owner-only and read through the visitor's three.ws
+ // session, which only exists on three.ws itself: from any other site
+ // the request could only ever come back empty, so it is not made.
+ if (_backendId && this._apiIsPageOrigin()) {
const { AgentMemory } = await import('./agent-memory.js');
- const syncMem = new AgentMemory(_backendId, { backendSync: true });
+ const syncMem = new AgentMemory(_backendId, {
+ backendSync: true,
+ apiOrigin: this._apiBase(),
+ });
await syncMem.pull(_backendId).catch(() => {});
}
@@ -1788,7 +1980,7 @@ class Agent3DElement extends HTMLElement {
apiKey: this.getAttribute('api-key') || undefined,
proxyURL: this.getAttribute('key-proxy') || undefined,
agentId: _backendId || undefined,
- apiOrigin: _scriptOrigin || window.location.origin,
+ apiOrigin: this._apiBase(),
};
// Fetch skill prices + purchased state so the runtime can gate paid skills.
@@ -1796,11 +1988,10 @@ class Agent3DElement extends HTMLElement {
let _skillAccess;
if (_backendId) {
try {
- const detailBase = _scriptOrigin || window.location.origin;
// On somebody else's site our cookies are third-party and the public
// answer is all an embed can use, so only send them on our own origin.
- const r = await fetch(`${detailBase}/api/agents/${_backendId}/skill-access`, {
- credentials: detailBase === window.location.origin ? 'include' : 'omit',
+ const r = await fetch(`${this._apiBase()}/api/agents/${_backendId}/skill-access`, {
+ credentials: this._apiCredentials(),
});
if (r.ok) {
const a = (await r.json())?.data;
@@ -2010,8 +2201,9 @@ class Agent3DElement extends HTMLElement {
// the agent protocol. Falls back to the full modal when there is no
// chat thread (e.g. avatar-only embed with avatar-chat="off").
if (_backendId && this.shadowRoot) {
- this._paymentModal = new SkillPaymentModal(this.shadowRoot, _backendId);
- this._paymentChip = new PaymentChip(_backendId);
+ const _payOpts = { apiOrigin: this._apiBase() };
+ this._paymentModal = new SkillPaymentModal(this.shadowRoot, _backendId, _payOpts);
+ this._paymentChip = new PaymentChip(_backendId, _payOpts);
let _paymentInFlight = false;
this._runtime.addEventListener('skill:payment-required', async (e) => {
@@ -2049,10 +2241,10 @@ class Agent3DElement extends HTMLElement {
});
// Refresh skillAccess so next call goes through without re-prompting.
try {
- const base = _scriptOrigin || window.location.origin;
- const r = await fetch(`${base}/api/agents/${_backendId}/skill-access`, {
- credentials: base === window.location.origin ? 'include' : 'omit',
- });
+ const r = await fetch(
+ `${this._apiBase()}/api/agents/${_backendId}/skill-access`,
+ { credentials: this._apiCredentials() },
+ );
if (r.ok) {
const a = (await r.json())?.data;
if (a) {
@@ -2101,7 +2293,10 @@ class Agent3DElement extends HTMLElement {
const _trackedMint = this.getAttribute('tracked-mint');
if (_trackedMint) {
- this._detachTradeReactions = attachTradeReactions(this, { mint: _trackedMint });
+ this._detachTradeReactions = attachTradeReactions(this, {
+ mint: _trackedMint,
+ origin: this._apiBase(),
+ });
}
// BEGIN:EMBED_BRIDGES
if (window !== window.parent) {
@@ -2175,7 +2370,7 @@ class Agent3DElement extends HTMLElement {
const agentIdAttr = this.getAttribute('agent-id');
const avatarIdAttr = this.getAttribute('avatar-id');
const chainIdAttr = this.getAttribute('chain-id');
- const apiBase = this.getAttribute('api-base') || _scriptOrigin || window.location.origin;
+ const apiBase = this._apiBase();
if (avatarIdAttr && !src && !manifestAttr && !body && !agentIdAttr) {
try {
return await resolveByAvatarId(avatarIdAttr, { origin: apiBase });
@@ -2222,22 +2417,16 @@ class Agent3DElement extends HTMLElement {
: agentIdAttr;
const ref = parseAgentRef(caipInput);
if (ref) {
- const resolved = await resolveOnchainAgent(ref);
+ const resolved = await resolveOnchainAgent(ref, { origin: apiBase });
if (resolved.error && !resolved.glbUrl)
throw new Error(`On-chain resolve failed: ${resolved.error}`);
return toManifest(resolved);
}
// Explicit manifest= wins over backend UUID resolution.
if (manifestAttr) return loadManifest(manifestAttr);
- // Resolve agent-id → manifestUrl via backend, then load that manifest.
- const manifestUrl = await resolveByAgentId(agentIdAttr);
- if (manifestUrl) {
- this._autoResolvedManifest = true;
- this.setAttribute('manifest', manifestUrl);
- return loadManifest(manifestUrl);
- }
- // No manifestUrl on agent record — build inline manifest from avatar data.
- return await resolveAgentById(agentIdAttr);
+ // The agent's public manifest, read from the API origin this script
+ // came from (never the host page's origin).
+ return await resolveAgentById(agentIdAttr, { origin: apiBase });
} catch (err) {
// Never let avatar rendering error out — fall back to default avatar.
log.warn('[agent-3d] agent resolve failed, using default avatar:', err);
@@ -2454,7 +2643,7 @@ class Agent3DElement extends HTMLElement {
this._inputEl.dataset.state = busy ? 'thinking' : '';
const row = this._inputEl.closest('.input-row');
if (row) row.dataset.busy = busy ? 'true' : 'false';
- this._inputEl.placeholder = busy ? 'Thinking…' : 'Say something...';
+ this._inputEl.placeholder = busy ? 'Thinking…' : this._composerPlaceholder();
if (!busy && this.shadowRoot?.activeElement == null) {
this._inputEl.focus();
}
@@ -2771,9 +2960,7 @@ class Agent3DElement extends HTMLElement {
}
async _toggleMic() {
- // The mic button lives in the (now removed) input row, so this is only
- // reachable if a future voice flow calls it directly. Bail safely when
- // there is no mic element to reflect listening state onto.
+ // The mic only exists in chat mode, and only where speech input works.
if (!this._micEl) return;
const voiceServer = this.getAttribute('voice-server');
if (voiceServer) {
@@ -2814,9 +3001,8 @@ class Agent3DElement extends HTMLElement {
}
async _connectLiveKit(agentId) {
- const base = _scriptOrigin || window.location.origin;
- const resp = await fetch(`${base}/api/agents/${agentId}/livekit-token`, {
- credentials: 'include',
+ const resp = await fetch(`${this._apiBase()}/api/agents/${agentId}/livekit-token`, {
+ credentials: this._apiCredentials(),
});
if (!resp.ok) {
const body = await resp.json().catch(() => ({}));
@@ -2831,17 +3017,6 @@ class Agent3DElement extends HTMLElement {
}
_teardown() {
- // Clear manifest that was auto-resolved from agent-id so the next boot resolves fresh.
- // Suppress attributeChangedCallback to avoid a reboot loop.
- if (this._autoResolvedManifest) {
- this._suppressAttrChange = true;
- try {
- this.removeAttribute('manifest');
- } finally {
- this._suppressAttrChange = false;
- }
- this._autoResolvedManifest = false;
- }
// A torn-down element must not leave a microphone open or a tone playing.
this.stopSonar();
_untrackLiveViewer(this);
diff --git a/src/erc8004/queries.js b/src/erc8004/queries.js
index b2600021d..3c89c1a1e 100644
--- a/src/erc8004/queries.js
+++ b/src/erc8004/queries.js
@@ -207,10 +207,15 @@ export { findAvatar3D } from './avatar-meta.js';
* back to the direct fetch if our proxy is the one that fails. Same-origin URIs
* skip the proxy entirely: there is nothing to work around.
*
+ * `apiOrigin` names the three.ws origin that hosts the proxy. An <agent-3d>
+ * embed on another site passes it; left empty, the proxy path stays relative,
+ * which is right on three.ws's own pages.
+ *
* @param {string} uri
+ * @param {{ apiOrigin?: string }} [opts]
* @returns {Promise<{ ok: boolean, data?: any, error?: string, resolvedUrl?: string, viaProxy?: boolean }>}
*/
-export async function fetchAgentMetadata(uri) {
+export async function fetchAgentMetadata(uri, { apiOrigin = '' } = {}) {
if (!uri) return { ok: false, error: 'empty uri' };
// data:application/json;base64,... (inline)
@@ -231,7 +236,7 @@ export async function fetchAgentMetadata(uri) {
if (isSameOrigin(url)) return fetchAgentMetadataDirect(url);
- const viaProxy = await fetchAgentMetadataViaProxy(uri, url);
+ const viaProxy = await fetchAgentMetadataViaProxy(uri, url, apiOrigin);
if (viaProxy.ok) return viaProxy;
const direct = await fetchAgentMetadataDirect(url);
@@ -260,9 +265,9 @@ async function fetchAgentMetadataDirect(url) {
}
}
-async function fetchAgentMetadataViaProxy(uri, url) {
+async function fetchAgentMetadataViaProxy(uri, url, apiOrigin = '') {
try {
- const res = await fetch(`/api/erc8004/metadata?uri=${encodeURIComponent(uri)}`);
+ const res = await fetch(`${apiOrigin}/api/erc8004/metadata?uri=${encodeURIComponent(uri)}`);
const body = await res.json().catch(() => null);
if (!res.ok) {
return {
diff --git a/src/erc8004/resolver.js b/src/erc8004/resolver.js
index cc5bfc259..93b517e44 100644
--- a/src/erc8004/resolver.js
+++ b/src/erc8004/resolver.js
@@ -176,7 +176,7 @@ function cacheKey(ref) {
* error?: string,
* }>}
*/
-export async function resolveOnchainAgent(input, { ethProvider, fresh = false } = {}) {
+export async function resolveOnchainAgent(input, { ethProvider, fresh = false, origin } = {}) {
const parsed = parseAgentRef(input);
if (!parsed) throw new Error(`Unrecognised agent reference: ${input}`);
@@ -194,8 +194,12 @@ export async function resolveOnchainAgent(input, { ethProvider, fresh = false }
const base = {
ref,
caip: toCAIP10(ref),
+ // `origin` is the three.ws API base when an embed on another site calls
+ // this; the page's own origin would link the visitor to that site.
publicUrl:
- typeof location !== 'undefined' ? toPublicUrl(ref) : `/a/${ref.chainId}/${ref.agentId}`,
+ origin || typeof location !== 'undefined'
+ ? toPublicUrl(ref, { origin })
+ : `/a/${ref.chainId}/${ref.agentId}`,
chain: chainMeta
? { name: chainMeta.name, testnet: !!chainMeta.testnet, explorer: chainMeta.explorer }
: null,
@@ -223,7 +227,7 @@ export async function resolveOnchainAgent(input, { ethProvider, fresh = false }
return base;
}
- const metaRes = await fetchAgentMetadata(uri);
+ const metaRes = await fetchAgentMetadata(uri, { apiOrigin: origin });
if (!metaRes.ok) {
base.error = metaRes.error;
base.metadataUrl = metaRes.resolvedUrl || null;
diff --git a/src/memory/index.js b/src/memory/index.js
index 2ad35daae..874668498 100644
--- a/src/memory/index.js
+++ b/src/memory/index.js
@@ -73,6 +73,8 @@ export class Memory {
// null for built-in modes. Drives _persist / recall / save delegation.
this._backend = backend;
this._dirty = false;
+ // Set by Memory.load; '' keeps API calls relative to the page.
+ this.apiOrigin = '';
}
/**
@@ -123,10 +125,19 @@ export class Memory {
* @returns {Promise<Memory>}
*/
static async load(opts = {}) {
+ const mem = await Memory._loadForMode(opts);
+ // Remote and pinned modes call the three.ws API after boot. An embed on
+ // another site passes the API origin here so those calls leave the host
+ // page's origin alone; three.ws's own pages leave it empty (relative).
+ mem.apiOrigin = opts.apiOrigin || '';
+ return mem;
+ }
+
+ static async _loadForMode(opts) {
const { mode = 'local', namespace, manifestURI, fetchFn, deriveKey } = opts;
if (mode === 'none') return new Memory({ mode: 'none', namespace });
if (mode === 'local') return Memory._loadLocal(namespace);
- if (mode === 'remote') return Memory._loadRemote({ namespace, fetchFn });
+ if (mode === 'remote') return Memory._loadRemote({ namespace, fetchFn, apiOrigin: opts.apiOrigin });
if (mode === 'ipfs' || mode === 'encrypted-ipfs') {
if (mode === 'encrypted-ipfs' && !deriveKey)
throw new Error('encrypted-ipfs mode requires a deriveKey function');
@@ -159,11 +170,11 @@ export class Memory {
return mem;
}
- static async _loadRemote({ namespace, fetchFn }) {
+ static async _loadRemote({ namespace, fetchFn, apiOrigin = '' }) {
const f = fetchFn || fetch.bind(globalThis);
if (!namespace) return new Memory({ mode: 'remote', namespace });
try {
- const resp = await f(`/api/agent-memory?agentId=${encodeURIComponent(namespace)}&limit=500`, {
+ const resp = await f(`${apiOrigin}/api/agent-memory?agentId=${encodeURIComponent(namespace)}&limit=500`, {
credentials: 'include',
});
if (!resp.ok) return new Memory({ mode: 'remote', namespace });
@@ -397,7 +408,7 @@ export class Memory {
try {
// allowAnonymous: this background sync swallows failures silently; a 401
// must stay a silent no-op, not a login redirect.
- const resp = await apiFetch('/api/agent-memory', {
+ const resp = await apiFetch(`${this.apiOrigin}/api/agent-memory`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
@@ -442,7 +453,7 @@ export class Memory {
const plainBytes = new TextEncoder().encode(content);
const { nonce, ciphertext } = await encryptBlob(plainBytes, this.cryptoKey);
const data = bytesToBase64(pack({ nonce, ciphertext }));
- const resp = await fetch(`/api/agents/${this.namespace}/memory/pin`, {
+ const resp = await fetch(`${this.apiOrigin}/api/agents/${this.namespace}/memory/pin`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
@@ -457,7 +468,7 @@ export class Memory {
// Pin the updated MEMORY.md index (plaintext — it only lists filenames and CIDs).
const indexData = bytesToBase64(new TextEncoder().encode(this.indexText));
- const indexResp = await fetch(`/api/agents/${this.namespace}/memory/pin`, {
+ const indexResp = await fetch(`${this.apiOrigin}/api/agents/${this.namespace}/memory/pin`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
diff --git a/src/payment-modal.js b/src/payment-modal.js
index 816bf8da3..e8fcb96d3 100644
--- a/src/payment-modal.js
+++ b/src/payment-modal.js
@@ -15,6 +15,7 @@ import { showAddFunds } from './shared/add-funds.js';
import { ensureRiskAck } from './shared/risk-ack.js';
import { resolveTokenProgramId } from './shared/spl-token-program.js';
import { apiFetch } from './api.js';
+import { isPageOrigin } from './shared/embed-api-origin.js';
import { log } from './shared/log.js';
const USDC_DECIMALS = 6;
@@ -60,6 +61,8 @@ const STYLE = `
transition: opacity .15s; letter-spacing: .02em;
}
.pay-chip-btn:hover:not(:disabled) { opacity: .85; }
+a.pay-chip-btn { display: inline-flex; align-items: center; justify-content: center; text-decoration: none; }
+.pay-chip-btn:active:not(:disabled) { transform: translateY(1px); }
.pay-chip-btn:disabled { opacity: .4; cursor: default; }
.pay-chip-btn-pay { background: linear-gradient(135deg, #059669, #047857); border: none; }
.pay-chip-btn-cancel { flex: 0 0 auto; background: rgba(255,255,255,.08); color: rgba(255,255,255,.45); }
@@ -199,6 +202,13 @@ const STYLE = `
font-size: 12px; color: rgba(255,255,255,.4); text-decoration: none;
}
.skill-pay-open-link:hover { color: rgba(255,255,255,.7); text-decoration: underline; }
+.skill-pay-open-link.is-primary {
+ padding: 11px 14px; border-radius: 10px; font-size: 14px; font-weight: 600;
+ color: #fff; background: linear-gradient(135deg, #059669, #047857);
+ transition: opacity .15s, transform .15s;
+}
+.skill-pay-open-link.is-primary:hover { color: #fff; text-decoration: none; opacity: .9; }
+.skill-pay-open-link.is-primary:active { transform: translateY(1px); }
.skill-pay-add-funds, .pay-chip-add-funds {
margin-left: 6px; padding: 3px 9px; border-radius: 7px; cursor: pointer;
font: inherit; font-size: 12px; font-weight: 600;
@@ -226,14 +236,29 @@ const STYLE = `
}
`;
+// An <agent-3d> on another site cannot buy in place: the purchase endpoints are
+// bound to the visitor's three.ws session, whose cookie is third-party there,
+// and a 401 would send the HOST page to its own /login. Off three.ws the card
+// hands the visitor to the agent's checkout on three.ws instead.
+function checkoutContext(apiOrigin, agentId, skill) {
+ const pageOrigin = typeof location !== 'undefined' ? location.origin : '';
+ return {
+ offsite: !isPageOrigin(apiOrigin, pageOrigin),
+ checkoutURL: `${apiOrigin || ''}/marketplace/agents/${encodeURIComponent(agentId)}?buy=${encodeURIComponent(skill)}`,
+ };
+}
+
export class SkillPaymentModal {
/**
* @param {ShadowRoot|Document} root where to inject the modal element
* @param {string} agentId the seller agent's UUID
+ * @param {{ apiOrigin?: string }} [opts] three.ws origin for API calls and
+ * the checkout link; '' keeps them relative (three.ws's own pages)
*/
- constructor(root, agentId) {
+ constructor(root, agentId, { apiOrigin = '' } = {}) {
this._root = root;
this._agentId = agentId;
+ this._apiOrigin = apiOrigin;
this._resolve = null;
this._wallet = null;
this._connection = null;
@@ -373,8 +398,17 @@ export class SkillPaymentModal {
if (eq) { usdEqEl.textContent = eq; usdEqEl.hidden = false; }
else { usdEqEl.hidden = true; }
});
- this._el.querySelector('.skill-pay-open-link').href =
- `/marketplace/agents/${this._agentId}?buy=${encodeURIComponent(skill)}`;
+ const { offsite, checkoutURL } = checkoutContext(this._apiOrigin, this._agentId, skill);
+ const openLink = this._el.querySelector('.skill-pay-open-link');
+ openLink.href = checkoutURL;
+ openLink.textContent = offsite ? 'Unlock on three.ws →' : 'Open in marketplace →';
+ openLink.classList.toggle('is-primary', offsite);
+ for (const sel of ['.skill-pay-steps', '.skill-pay-wallet-area', '.skill-pay-confirm']) {
+ this._el.querySelector(sel).hidden = offsite;
+ }
+ this._el.querySelector('.skill-pay-desc').textContent = offsite
+ ? 'This skill requires a one-time payment. Unlock it on three.ws, then come back and ask again.'
+ : 'This skill requires a one-time payment to unlock.';
// Proof-phase promo: ask the server what the quote will actually charge.
// When a first-N rule is live, show the real price (list struck through)
@@ -384,7 +418,7 @@ export class SkillPaymentModal {
const promoEl = this._el.querySelector('.skill-pay-promo');
listEl.hidden = true;
promoEl.hidden = true;
- fetch(`/api/marketplace/skill-promo?agent_id=${encodeURIComponent(this._agentId)}&skill=${encodeURIComponent(skill)}`)
+ fetch(`${this._apiOrigin}/api/marketplace/skill-promo?agent_id=${encodeURIComponent(this._agentId)}&skill=${encodeURIComponent(skill)}`)
.then((r) => (r.ok ? r.json() : null))
.then((j) => {
const state = j?.data;
@@ -602,7 +636,7 @@ export class SkillPaymentModal {
this._setStatus('Creating purchase…');
let purchase;
try {
- const r = await apiFetch('/api/marketplace/purchase', {
+ const r = await apiFetch(`${this._apiOrigin}/api/marketplace/purchase`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
credentials: 'include',
@@ -750,7 +784,7 @@ export class SkillPaymentModal {
async _pollConfirm(reference, maxMs = 60_000) {
const deadline = Date.now() + maxMs;
while (Date.now() < deadline) {
- const r = await apiFetch(`/api/marketplace/purchase/${reference}/confirm`, {
+ const r = await apiFetch(`${this._apiOrigin}/api/marketplace/purchase/${reference}/confirm`, {
method: 'POST',
credentials: 'include',
});
@@ -781,9 +815,13 @@ export class SkillPaymentModal {
* The agent narrates before/after; the chip handles wallet connection + SPL transfer.
*/
export class PaymentChip {
- /** @param {string} agentId seller agent UUID */
- constructor(agentId) {
+ /**
+ * @param {string} agentId seller agent UUID
+ * @param {{ apiOrigin?: string }} [opts] see SkillPaymentModal
+ */
+ constructor(agentId, { apiOrigin = '' } = {}) {
this._agentId = agentId;
+ this._apiOrigin = apiOrigin;
this._wallet = null;
this._connection = null;
}
@@ -833,8 +871,19 @@ export class PaymentChip {
resolve(result);
};
+ const { offsite, checkoutURL } = checkoutContext(this._apiOrigin, this._agentId, skill);
+
const updateActions = () => {
const actions = wrapper.querySelector('.pay-chip-actions');
+ if (offsite) {
+ actions.innerHTML = `
+ <a class="pay-chip-btn pay-chip-btn-pay" href="${escHtml(checkoutURL)}" target="_blank" rel="noopener">Unlock on three.ws</a>
+ <button class="pay-chip-btn pay-chip-btn-cancel">Dismiss</button>
+ `;
+ setStatus('Unlock it on three.ws, then ask again.');
+ actions.querySelector('.pay-chip-btn-cancel').addEventListener('click', () => dismiss(false));
+ return;
+ }
const connected = this._wallet?.isConnected || window.solana?.isConnected;
if (connected) {
actions.innerHTML = `
@@ -885,7 +934,7 @@ export class PaymentChip {
setStatus('Creating purchase…');
let purch;
try {
- const r = await apiFetch('/api/marketplace/purchase', {
+ const r = await apiFetch(`${this._apiOrigin}/api/marketplace/purchase`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
credentials: 'include',
@@ -1054,7 +1103,7 @@ export class PaymentChip {
async _pollConfirm(reference, maxMs = 60_000) {
const deadline = Date.now() + maxMs;
while (Date.now() < deadline) {
- const r = await apiFetch(`/api/marketplace/purchase/${reference}/confirm`, {
+ const r = await apiFetch(`${this._apiOrigin}/api/marketplace/purchase/${reference}/confirm`, {
method: 'POST',
credentials: 'include',
});
diff --git a/src/pump/trade-reactions.js b/src/pump/trade-reactions.js
index b0cef72e2..5d8b97f73 100644
--- a/src/pump/trade-reactions.js
+++ b/src/pump/trade-reactions.js
@@ -23,10 +23,17 @@ function p90(amounts) {
/**
* @param {object} agent — Agent3DElement with a playEmote(name, intensity) method
- * @param {{ mint: string, intensity?: number, _EventSource?: typeof EventSource }} opts
+ * `origin` is the three.ws origin serving the feed. An embed on another site
+ * must pass it: a bare path would open the stream on the host page's origin.
+ * The feed is public market data, so a cross-origin stream carries no cookies.
+ *
+ * @param {{ mint: string, intensity?: number, origin?: string, _EventSource?: typeof EventSource }} opts
* @returns {() => void} detach
*/
-export function attachTradeReactions(agent, { mint, intensity = 1, _EventSource = globalThis.EventSource } = {}) {
+export function attachTradeReactions(
+ agent,
+ { mint, intensity = 1, origin = '', _EventSource = globalThis.EventSource } = {},
+) {
if (!mint || !_EventSource) return () => {};
// Rolling buffer of { amount: number, ts: number }
@@ -64,7 +71,9 @@ export function attachTradeReactions(agent, { mint, intensity = 1, _EventSource
}
const params = new URLSearchParams({ kind: 'trades', mint });
- const es = new _EventSource(`${FEED_PATH}?${params}`, { withCredentials: true });
+ const pageOrigin = typeof location !== 'undefined' ? location.origin : '';
+ const sameOrigin = !origin || origin === pageOrigin;
+ const es = new _EventSource(`${origin}${FEED_PATH}?${params}`, { withCredentials: sameOrigin });
es.addEventListener('trade', onTrade);
es.addEventListener('graduation', onGraduation);
diff --git a/src/runtime/index.js b/src/runtime/index.js
index ad336e9f5..af0a561a4 100644
--- a/src/runtime/index.js
+++ b/src/runtime/index.js
@@ -35,6 +35,9 @@ export class Runtime extends EventTarget {
this.skills = skills;
this.stage = stage;
this.agentId = agentId;
+ // The three.ws origin skills call back to (an embed on another site
+ // passes it in providerConfig); '' keeps calls relative.
+ this.apiOrigin = providerConfig?.apiOrigin || '';
this.skillAccess = skillAccess || alwaysAllow();
this.provider = createProvider({
@@ -289,6 +292,7 @@ export class Runtime extends EventTarget {
call: async (toolName, args) => this._dispatchTool({ name: toolName, input: args }),
stage: this.stage,
agentId: this.agentId,
+ apiOrigin: this.apiOrigin,
};
}
diff --git a/src/shared/embed-api-origin.js b/src/shared/embed-api-origin.js
new file mode 100644
index 000000000..068f460e0
--- /dev/null
+++ b/src/shared/embed-api-origin.js
@@ -0,0 +1,105 @@
+// Where an <agent-3d> embed sends its API calls.
+//
+// The element runs on pages we do not own. A site-absolute path like
+// `/api/agents/:id` resolves against the HOST page's origin, so on example.com it
+// asks example.com for an agent, gets a 404, and the embed silently falls back to
+// a default body named "Agent". Every request the element makes must instead go
+// to the three.ws origin it was loaded from, which this module derives once from
+// the script's own URL and hands to every caller.
+//
+// Resolution order (first match wins):
+// 1. the `api-base` attribute, for self-hosted backends and local development;
+// 2. the origin serving the element's script (three.ws for the CDN embed);
+// 3. https://three.ws when that script came from a public npm CDN (unpkg,
+// jsDelivr, ...), which serves files but none of the API;
+// 4. the page's own origin, which is only right when the page IS three.ws.
+
+export const DEFAULT_API_ORIGIN = 'https://three.ws';
+
+// Package CDNs that mirror the npm build. They serve the bundle, never /api/*.
+const PACKAGE_CDN_HOSTS = new Set([
+ 'unpkg.com',
+ 'cdn.jsdelivr.net',
+ 'fastly.jsdelivr.net',
+ 'gcore.jsdelivr.net',
+ 'esm.sh',
+ 'esm.run',
+ 'cdn.skypack.dev',
+ 'ga.jspm.io',
+ 'jspm.dev',
+]);
+
+function parseURL(value, base) {
+ try {
+ return base ? new URL(value, base) : new URL(value);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The API origin implied by the URL the element's script was loaded from.
+ * Returns '' when the URL carries no usable http(s) origin (blob:, data:, a
+ * bundler's virtual module), so the caller falls through to the page origin.
+ *
+ * @param {string} scriptUrl usually `import.meta.url`
+ * @returns {string}
+ */
+export function apiOriginFromScriptURL(scriptUrl) {
+ const url = parseURL(String(scriptUrl || ''));
+ if (!url || !/^https?:$/.test(url.protocol)) return '';
+ if (PACKAGE_CDN_HOSTS.has(url.hostname.toLowerCase())) return DEFAULT_API_ORIGIN;
+ return url.origin;
+}
+
+/**
+ * Resolve the base URL every API request of one element is built on, without a
+ * trailing slash, so callers can write `${base}/api/...`.
+ *
+ * @param {{ attr?: string|null, scriptOrigin?: string, pageOrigin?: string }} opts
+ * @returns {string}
+ */
+export function resolveApiBase({ attr, scriptOrigin = '', pageOrigin = '' } = {}) {
+ const raw = typeof attr === 'string' ? attr.trim() : '';
+ if (raw) {
+ const url = parseURL(raw, pageOrigin || undefined);
+ if (url && /^https?:$/.test(url.protocol)) {
+ return (url.origin + url.pathname).replace(/\/+$/, '');
+ }
+ }
+ return scriptOrigin || pageOrigin || '';
+}
+
+/**
+ * True when `base` is the page's own origin, i.e. three.ws embedding itself.
+ * Only then do the visitor's three.ws cookies belong to the request; anywhere
+ * else they are third-party and a credentialed request would also be refused by
+ * every public endpoint, which answers anonymous reads with a wildcard origin.
+ *
+ * @param {string} base
+ * @param {string} pageOrigin
+ */
+export function isPageOrigin(base, pageOrigin) {
+ if (!base) return true; // relative URLs resolve against the page
+ const url = parseURL(base, pageOrigin || undefined);
+ return !!url && url.origin === pageOrigin;
+}
+
+/**
+ * The fetch `credentials` mode for a request to `base` from `pageOrigin`.
+ * @returns {'include'|'omit'}
+ */
+export function credentialsFor(base, pageOrigin) {
+ return isPageOrigin(base, pageOrigin) ? 'include' : 'omit';
+}
+
+/**
+ * Join an API base and a site-absolute path. An empty base keeps the path
+ * relative, which is the same-origin behaviour three.ws's own pages rely on.
+ *
+ * @param {string} base
+ * @param {string} path must start with '/'
+ */
+export function apiURL(base, path) {
+ return `${base || ''}${path}`;
+}
diff --git a/src/skills/index.js b/src/skills/index.js
index f37c697bd..78ea88742 100644
--- a/src/skills/index.js
+++ b/src/skills/index.js
@@ -5,6 +5,7 @@ import { resolveURI } from '../ipfs.js';
import { getHost } from './sandbox-host.js';
import { startDataReactive } from '../runtime/data-reactive.js';
import { log } from '../shared/log.js';
+import { credentialsFor } from '../shared/embed-api-origin.js';
/** Injected into every skill handler ctx as ctx.dataReactive */
const dataReactive = { start: startDataReactive };
@@ -46,7 +47,9 @@ export class Skill {
}
async invoke(toolName, args, ctx) {
- const paymentProof = ctx?.agentId ? await checkPaymentGate(toolName, ctx.agentId) : null;
+ const paymentProof = ctx?.agentId
+ ? await checkPaymentGate(toolName, ctx.agentId, ctx.apiOrigin || '')
+ : null;
const scoped = {
...ctx,
skillBaseURI: this.uri,
@@ -237,10 +240,16 @@ function mintSymbol(mint) {
return KNOWN_MINT_SYMBOLS[mint] || `${String(mint).slice(0, 4)}…${String(mint).slice(-4)}`;
}
-async function fetchAgentSnippet(agentId) {
+// `apiOrigin` is the three.ws origin an <agent-3d> embed was loaded from; ''
+// keeps these reads relative on three.ws's own pages.
+function apiCredentials(apiOrigin) {
+ return credentialsFor(apiOrigin, typeof location !== 'undefined' ? location.origin : '');
+}
+
+async function fetchAgentSnippet(agentId, apiOrigin = '') {
try {
- const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}`, {
- credentials: 'include',
+ const r = await fetch(`${apiOrigin}/api/agents/${encodeURIComponent(agentId)}`, {
+ credentials: apiCredentials(apiOrigin),
});
if (!r.ok) return {};
const data = await r.json();
@@ -255,14 +264,14 @@ async function fetchAgentSnippet(agentId) {
* Returns the intentId string if payment was collected, null if the skill is free.
* Throws (with code=PAYMENT_CANCELLED) if the user dismisses the modal.
*/
-async function checkPaymentGate(toolName, agentId) {
+async function checkPaymentGate(toolName, agentId, apiOrigin = '') {
if (typeof document === 'undefined') return null;
let manifest;
try {
const r = await fetch(
- `/api/agents/x402/manifest?agent_id=${encodeURIComponent(agentId)}&skill=${encodeURIComponent(toolName)}`,
- { credentials: 'include' },
+ `${apiOrigin}/api/agents/x402/manifest?agent_id=${encodeURIComponent(agentId)}&skill=${encodeURIComponent(toolName)}`,
+ { credentials: apiCredentials(apiOrigin) },
);
if (r.status !== 200) return null;
manifest = await r.json();
@@ -298,7 +307,7 @@ async function checkPaymentGate(toolName, agentId) {
{ code: 'NO_PROVIDER' },
);
}
- const agentSnippet = await fetchAgentSnippet(agentId);
+ const agentSnippet = await fetchAgentSnippet(agentId, apiOrigin);
const adapter = getPaymentsAdapter('pumpfun');
const paid = await adapter.payAgent({
agent: { id: agentId, ...agentSnippet },
diff --git a/src/viewer.js b/src/viewer.js
index d7636f66f..7b4c0dcc3 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -412,7 +412,6 @@ export class Viewer {
this._tabVisible = !document.hidden;
this._disposed = false;
this._loadedEnvironment = null;
- this._guiWrap = null;
this._needsRender = true;
this._animating = false;
@@ -1974,8 +1973,13 @@ export class Viewer {
perfLi.classList.add('gui-stats');
perfFolder.__ul.appendChild(perfLi);
+ // `embed` (the <agent-3d> web component) keeps the GUI object, which the
+ // load path updates, but never mounts its DOM: its styles live in the
+ // site stylesheet, which a shadow root cannot see, so on a host page the
+ // panel spilled out below the element as thousands of unstyled controls.
+ const mountDebugUI = !this.options.embed;
const guiWrap = document.createElement('div');
- this.el.appendChild(guiWrap);
+ if (mountDebugUI) this.el.appendChild(guiWrap);
guiWrap.classList.add('gui-wrap');
guiWrap.classList.add('gui-wrap--hidden');
guiWrap.appendChild(gui.domElement);
@@ -2000,7 +2004,7 @@ export class Viewer {
const shown = guiWrap.classList.toggle('gui-wrap--hidden');
toggle.classList.toggle('gui-toggle--active', !shown);
});
- this.el.appendChild(toggle);
+ if (mountDebugUI) this.el.appendChild(toggle);
this._guiToggle = toggle;
// AR button — hidden until setARTarget() is called with a supported URL
@@ -2137,7 +2141,9 @@ export class Viewer {
this._animPanelEl = null;
}
- if (this.options.kiosk) return;
+ // The clip panel is editor chrome. Kiosk views and the <agent-3d> embed
+ // (whose host page carries none of its styles) play clips on demand.
+ if (this.options.kiosk || this.options.embed) return;
const defs = this.animationManager.getAnimationDefs();
if (defs.length === 0) return;
diff --git a/tests/api/agents-sub-resources.test.js b/tests/api/agents-sub-resources.test.js
index 7b99fc3fe..4121d48a0 100644
--- a/tests/api/agents-sub-resources.test.js
+++ b/tests/api/agents-sub-resources.test.js
@@ -151,6 +151,25 @@ describe('_sub.js handleManifest', () => {
expect(res.headers['cache-control']).toContain('max-age');
});
+ it('carries the voice model and delivery settings an embed needs to speak in the owner-tuned voice', async () => {
+ agentRow = ownedAgent({
+ voice_provider: 'elevenlabs',
+ voice_id: 'voice-abc',
+ voice_model: 'eleven_turbo_v2_5',
+ voice_settings: { stability: 0.4, similarity_boost: 0.8 },
+ });
+ const { res, json } = await run(sub.handleManifest, {
+ url: `/api/agents/${AGENT_ID}/manifest`,
+ });
+ expect(res.statusCode).toBe(200);
+ expect(json.voice).toEqual({
+ provider: 'elevenlabs',
+ voice_id: 'voice-abc',
+ model: 'eleven_turbo_v2_5',
+ settings: { stability: 0.4, similarity_boost: 0.8 },
+ });
+ });
+
it('404s for an agent that does not exist rather than emitting a hollow manifest', async () => {
agentRow = null;
const { res, json } = await run(sub.handleManifest, {
diff --git a/tests/api/embed-public-reads-cors.test.js b/tests/api/embed-public-reads-cors.test.js
new file mode 100644
index 000000000..660f41718
--- /dev/null
+++ b/tests/api/embed-public-reads-cors.test.js
@@ -0,0 +1,129 @@
+// The <agent-3d> element reads two public endpoints from whatever site embeds it:
+// GET /api/avatars/:id (the `avatar-id` attribute) and the pump.fun trade stream
+// (the `tracked-mint` attribute). Both used the credentialed allowlist, which
+// sends no `access-control-allow-origin` to a stranger, so the browser blocked
+// the read on every site but three.ws. An anonymous GET only ever sees public
+// data, so it answers any origin; a session-bearing read and every write keep
+// the allowlist.
+
+import { describe, it, expect, vi } from 'vitest';
+
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: async () => {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+
+const { sqlMock } = vi.hoisted(() => ({ sqlMock: vi.fn(async () => []) }));
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: sqlMock,
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: async () => null,
+ authenticateBearer: async () => null,
+ extractBearer: () => null,
+ hasScope: () => false,
+}));
+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: async () => true }));
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: async () => ({ success: true }), mcpIp: async () => ({ success: true }) },
+ clientIp: () => '127.0.0.1',
+}));
+vi.mock('../../api/_lib/usage.js', () => ({ recordEvent: () => {} }));
+vi.mock('../../api/_lib/avatars.js', () => ({
+ getAvatar: async () => ({ id: AVATAR_ID, visibility: 'public', name: 'Public body' }),
+ resolveAvatarUrl: async () => ({ url: 'https://cdn.test/body.glb' }),
+ stripOwnerFor: (a) => a,
+ deleteAvatar: async () => null,
+ updateAvatar: async () => null,
+}));
+vi.mock('../../api/_lib/r2.js', () => ({
+ r2: {},
+ headObject: async () => null,
+ publicUrl: (k) => `https://cdn.test/${k}`,
+ thumbnailUrl: (k) => `https://cdn.test/${k}`,
+}));
+
+const AVATAR_ID = '22222222-2222-4222-8222-222222222222';
+const STRANGER = 'https://bookshop.example';
+
+function makeReq({ method = 'GET', url, query = {}, headers = {} }) {
+ return {
+ method,
+ url,
+ query,
+ headers: { host: 'three.ws', origin: STRANGER, ...headers },
+ on() {},
+ };
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ setHeader(k, v) {
+ this._h[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this._h[k.toLowerCase()];
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body = chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+describe('GET /api/avatars/:id from another site', () => {
+ it('answers an anonymous read with a wildcard origin so avatar-id embeds load anywhere', async () => {
+ const { default: handler } = await import('../../api/avatars/[id].js');
+ const res = makeRes();
+ await handler(makeReq({ url: `/api/avatars/${AVATAR_ID}`, query: { id: AVATAR_ID } }), res);
+ expect(res.statusCode).toBe(200);
+ expect(res._h['access-control-allow-origin']).toBe('*');
+ expect(res._h['access-control-allow-credentials']).toBeUndefined();
+ });
+
+ it('gives a stranger no CORS grant for a read that carries a session cookie', async () => {
+ const { default: handler } = await import('../../api/avatars/[id].js');
+ const res = makeRes();
+ await handler(
+ makeReq({ url: `/api/avatars/${AVATAR_ID}`, query: { id: AVATAR_ID }, headers: { cookie: 'sid=1' } }),
+ res,
+ );
+ expect(res._h['access-control-allow-origin']).toBeUndefined();
+ });
+
+ it('refuses a stranger\'s preflight for a write', async () => {
+ const { default: handler } = await import('../../api/avatars/[id].js');
+ const res = makeRes();
+ await handler(
+ makeReq({
+ method: 'OPTIONS',
+ url: `/api/avatars/${AVATAR_ID}`,
+ query: { id: AVATAR_ID },
+ headers: { 'access-control-request-method': 'PATCH' },
+ }),
+ res,
+ );
+ expect(res.statusCode).toBe(204);
+ expect(res._h['access-control-allow-origin']).toBeUndefined();
+ });
+});
+
+describe('GET /api/agents/pumpfun-feed from another site', () => {
+ it('answers the anonymous preflight with a wildcard origin so tracked-mint embeds can stream trades', async () => {
+ const { default: handler } = await import('../../api/agents/pumpfun.js');
+ const res = makeRes();
+ await handler(
+ makeReq({
+ method: 'OPTIONS',
+ url: '/api/agents/pumpfun-feed?kind=trades&mint=THREEsynthetic1111111111111111111111111111',
+ query: { _handler: 'feed' },
+ headers: { 'access-control-request-method': 'GET' },
+ }),
+ res,
+ );
+ expect(res.statusCode).toBe(204);
+ expect(res._h['access-control-allow-origin']).toBe('*');
+ });
+});
diff --git a/tests/src/agent-resolver.test.js b/tests/src/agent-resolver.test.js
new file mode 100644
index 000000000..b7c13306a
--- /dev/null
+++ b/tests/src/agent-resolver.test.js
@@ -0,0 +1,134 @@
+// @vitest-environment jsdom
+// src/agent-resolver.js turns an `agent-id` into the manifest <agent-3d> boots
+// from. It must read the agent from the three.ws origin it is handed, never the
+// host page's origin, and it reads the public manifest because that document is
+// the one served with an open CORS policy to any embedding site.
+import { describe, it, expect, vi } from 'vitest';
+import { resolveAgentById, resolveByAvatarId, AgentResolveError } from '../../src/agent-resolver.js';
+
+const AGENT_ID = '27a0f649-3b59-4552-bb0b-faf616ac448b';
+const API = 'https://three.ws';
+
+function jsonResponse(status, body) {
+ return { ok: status >= 200 && status < 300, status, json: async () => body };
+}
+
+function publicManifest(overrides = {}) {
+ return {
+ spec: 'agent-manifest/0.1',
+ id: AGENT_ID,
+ name: 'AxisXV',
+ description: 'Evidence-first Signal Cards.',
+ body: { uri: 'https://cdn.example/axis.glb', format: 'model/gltf-binary' },
+ skills: ['greet', 'remember'],
+ registrations: [],
+ voice: { provider: 'browser' },
+ ...overrides,
+ };
+}
+
+describe('resolveAgentById', () => {
+ it('reads the public manifest from the API origin, not the page origin, without cookies', async () => {
+ expect(location.origin).not.toBe(API); // jsdom page origin stands in for the host site
+ const fetchFn = vi.fn(async () => jsonResponse(200, publicManifest()));
+ await resolveAgentById(AGENT_ID, { origin: API, fetchFn });
+ expect(fetchFn).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchFn.mock.calls[0];
+ expect(url).toBe(`${API}/api/agents/${AGENT_ID}/manifest`);
+ expect(init.credentials).toBe('omit');
+ });
+
+ it('builds the boot manifest: real name, body, skills, and URLs rooted at the API origin', async () => {
+ const fetchFn = vi.fn(async () => jsonResponse(200, publicManifest()));
+ const m = await resolveAgentById(AGENT_ID, { origin: API, fetchFn });
+ expect(m.name).toBe('AxisXV');
+ expect(m.id.agentId).toBe(AGENT_ID);
+ expect(m.body).toEqual({ uri: 'https://cdn.example/axis.glb', format: 'gltf-binary' });
+ expect(m.skills).toEqual([{ name: 'greet' }, { name: 'remember' }]);
+ expect(m.memory).toEqual({ mode: 'local', namespace: AGENT_ID });
+ expect(m._baseURI).toBe(`${API}/agent/${AGENT_ID}/`);
+ expect(m._source).toBe('agent-id');
+ expect(m.voice.tts).toEqual({ provider: 'browser' });
+ });
+
+ it('routes an ElevenLabs voice through the API origin with the owner-tuned delivery', async () => {
+ const fetchFn = vi.fn(async () =>
+ jsonResponse(
+ 200,
+ publicManifest({
+ voice: {
+ provider: 'elevenlabs',
+ voice_id: 'voice-abc',
+ model: 'eleven_turbo_v2_5',
+ settings: { stability: 0.4, similarity_boost: 0.8, use_speaker_boost: true },
+ },
+ }),
+ ),
+ );
+ const m = await resolveAgentById(AGENT_ID, { origin: API, fetchFn });
+ expect(m.voice.tts).toEqual({
+ provider: 'elevenlabs',
+ voiceId: 'voice-abc',
+ proxyURL: `${API}/api/tts/eleven`,
+ agentId: AGENT_ID,
+ modelId: 'eleven_turbo_v2_5',
+ stability: 0.4,
+ similarityBoost: 0.8,
+ useSpeakerBoost: true,
+ });
+ });
+
+ it('carries the owner gesture slots and routines the element applies at boot', async () => {
+ const slots = { greet: 'wave' };
+ const routines = [{ name: 'welcome', steps: [] }];
+ const fetchFn = vi.fn(async () =>
+ jsonResponse(200, publicManifest({ animationSlots: slots, choreographies: routines })),
+ );
+ const m = await resolveAgentById(AGENT_ID, { origin: API, fetchFn });
+ expect(m.animationSlots).toEqual(slots);
+ expect(m.choreographies).toEqual(routines);
+ });
+
+ it('reports a missing agent as not_found (404, and the 400 a non-uuid id gets)', async () => {
+ for (const status of [404, 400]) {
+ const fetchFn = vi.fn(async () => jsonResponse(status, { error: 'x' }));
+ await expect(resolveAgentById(AGENT_ID, { origin: API, fetchFn })).rejects.toMatchObject({
+ name: 'AgentResolveError',
+ code: 'not_found',
+ status,
+ });
+ }
+ });
+
+ it('reports an agent with no body as no_avatar rather than booting an empty frame', async () => {
+ const fetchFn = vi.fn(async () => jsonResponse(200, publicManifest({ body: undefined })));
+ await expect(resolveAgentById(AGENT_ID, { origin: API, fetchFn })).rejects.toBeInstanceOf(
+ AgentResolveError,
+ );
+ await expect(resolveAgentById(AGENT_ID, { origin: API, fetchFn })).rejects.toMatchObject({
+ code: 'no_avatar',
+ });
+ });
+
+ it('turns a network failure into a typed error the element can fall back on', async () => {
+ const fetchFn = vi.fn(async () => {
+ throw new TypeError('Failed to fetch');
+ });
+ await expect(resolveAgentById(AGENT_ID, { origin: API, fetchFn })).rejects.toMatchObject({
+ code: 'network',
+ });
+ });
+});
+
+describe('resolveByAvatarId', () => {
+ it('reads the avatar from the API origin it is given, without cookies', async () => {
+ const fetchFn = vi.fn(async () =>
+ jsonResponse(200, { avatar: { name: 'Body', url: 'https://cdn.example/body.glb' } }),
+ );
+ const m = await resolveByAvatarId('22222222-2222-4222-8222-222222222222', { origin: API, fetchFn });
+ const [url, init] = fetchFn.mock.calls[0];
+ expect(url).toBe(`${API}/api/avatars/22222222-2222-4222-8222-222222222222`);
+ expect(init.credentials).toBe('omit');
+ expect(m.body.uri).toBe('https://cdn.example/body.glb');
+ });
+});
diff --git a/tests/src/element-api-origin.test.js b/tests/src/element-api-origin.test.js
new file mode 100644
index 000000000..696aaf122
--- /dev/null
+++ b/tests/src/element-api-origin.test.js
@@ -0,0 +1,198 @@
+// @vitest-environment jsdom
+// <agent-3d> on a site other than three.ws. Every API call must go to the
+// three.ws origin the element's script was loaded from (or an explicit
+// `api-base`), never to the host page's origin, and chat mode must give the
+// visitor somewhere to type.
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const SCRIPT_ORIGIN = 'https://three.ws';
+
+// The element derives its API origin from import.meta.url. Under vitest that is
+// a file:// URL, so stand in for "this script was served by three.ws".
+vi.mock('../../src/shared/embed-api-origin.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, apiOriginFromScriptURL: () => SCRIPT_ORIGIN };
+});
+
+vi.mock('../../src/viewer.js', () => ({
+ Viewer: class {
+ constructor(stage) {
+ this.stage = stage;
+ this.scene = { background: null };
+ this.renderer = { setClearAlpha() {} };
+ }
+ async load() {}
+ dispose() {}
+ },
+}));
+vi.mock('../../src/runtime/index.js', () => ({
+ Runtime: class extends EventTarget {
+ destroy() {}
+ },
+ skillAccessFromAgentDetail: () => null,
+}));
+vi.mock('../../src/runtime/scene.js', () => ({ SceneController: class {} }));
+vi.mock('../../src/skills/index.js', () => ({
+ SkillRegistry: class {
+ async install() {
+ return { name: 'x', uri: 'x' };
+ }
+ all() {
+ return [];
+ }
+ },
+}));
+vi.mock('../../src/memory/index.js', () => ({
+ Memory: {
+ async load() {
+ return { recall() {
+ return [];
+ } };
+ },
+ },
+}));
+vi.mock('../../src/manifest.js', () => ({
+ loadManifest: vi.fn(),
+ fetchRelative: vi.fn(async () => ''),
+}));
+vi.mock('../../src/ipfs.js', () => ({ resolveURI: (u) => u, uriCandidates: (u) => [u] }));
+vi.mock('../../src/agent-resolver.js', () => ({
+ resolveAgentById: vi.fn(async (id) => ({
+ spec: 'agent-manifest/0.1',
+ name: 'AxisXV',
+ id: { agentId: id },
+ body: { uri: 'https://cdn.example/axis.glb' },
+ brain: {},
+ voice: {},
+ skills: [],
+ _baseURI: '',
+ })),
+ resolveByAvatarId: vi.fn(async () => ({
+ spec: 'agent-manifest/0.1',
+ name: 'Body',
+ body: { uri: 'https://cdn.example/body.glb' },
+ brain: { provider: 'none' },
+ voice: {},
+ skills: [],
+ _baseURI: '',
+ })),
+ AgentResolveError: class extends Error {},
+}));
+vi.mock('../../src/erc8004/resolver.js', () => ({
+ parseAgentRef: () => null,
+ resolveOnchainAgent: vi.fn(),
+ toManifest: vi.fn(),
+}));
+vi.mock('../../src/pump/trade-reactions.js', () => ({ attachTradeReactions: () => () => {} }));
+vi.mock('../../src/embed-action-bridge.js', () => ({
+ EmbedActionBridge: class {
+ start() {}
+ stop() {}
+ },
+}));
+vi.mock('../../src/agent-protocol.js', () => ({
+ protocol: { emit() {}, on() {} },
+ ACTION_TYPES: {},
+}));
+
+globalThis.fetch = vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }));
+
+const AGENT_ID = '27a0f649-3b59-4552-bb0b-faf616ac448b';
+let resolver;
+
+beforeEach(async () => {
+ if (!customElements.get('agent-3d')) await import('../../src/element.js');
+ resolver = await import('../../src/agent-resolver.js');
+ resolver.resolveAgentById.mockClear();
+ resolver.resolveByAvatarId.mockClear();
+ document.body.innerHTML = '';
+});
+
+describe('<agent-3d> API origin on a third-party page', () => {
+ it('resolves agent-id against the script origin, not the host page origin', async () => {
+ expect(location.origin).not.toBe(SCRIPT_ORIGIN);
+ const el = document.createElement('agent-3d');
+ el.setAttribute('agent-id', AGENT_ID);
+ const manifest = await el._resolveManifest();
+ expect(manifest.name).toBe('AxisXV');
+ expect(resolver.resolveAgentById).toHaveBeenCalledWith(AGENT_ID, { origin: SCRIPT_ORIGIN });
+ });
+
+ it('resolves avatar-id against the script origin too', async () => {
+ const el = document.createElement('agent-3d');
+ el.setAttribute('avatar-id', '22222222-2222-4222-8222-222222222222');
+ await el._resolveManifest();
+ expect(resolver.resolveByAvatarId.mock.calls[0][1].origin).toBe(SCRIPT_ORIGIN);
+ });
+
+ it('lets the api-base attribute point the element at another backend', async () => {
+ const el = document.createElement('agent-3d');
+ el.setAttribute('agent-id', AGENT_ID);
+ el.setAttribute('api-base', 'https://agents.bookshop.example/');
+ await el._resolveManifest();
+ expect(resolver.resolveAgentById).toHaveBeenCalledWith(AGENT_ID, {
+ origin: 'https://agents.bookshop.example',
+ });
+ });
+
+ it('sends no cookies cross-origin and keeps owner-only memory modes local', () => {
+ const el = document.createElement('agent-3d');
+ expect(el._apiBase()).toBe(SCRIPT_ORIGIN);
+ expect(el._apiCredentials()).toBe('omit');
+ el.setAttribute('memory', 'remote');
+ expect(el._memoryMode({})).toBe('local');
+ el.setAttribute('memory', 'none');
+ expect(el._memoryMode({})).toBe('none');
+ });
+
+ it('treats an api-base on the page origin as first-party (cookies, remote memory)', () => {
+ const el = document.createElement('agent-3d');
+ el.setAttribute('api-base', location.origin);
+ expect(el._apiCredentials()).toBe('include');
+ el.setAttribute('memory', 'remote');
+ expect(el._memoryMode({})).toBe('remote');
+ });
+});
+
+describe('<agent-3d> chat composer', () => {
+ it('gives chat mode a text field and send button that talk to the agent', () => {
+ const el = document.createElement('agent-3d');
+ el.setAttribute('chat', '');
+ el.setAttribute('body', 'https://cdn.example/body.glb');
+ el._renderShell();
+ const form = el.shadowRoot.querySelector('form.input-row');
+ const input = form.querySelector('input');
+ expect(input.getAttribute('aria-label')).toBe('Message to agent');
+ expect(form.querySelector('button[type="submit"]').getAttribute('aria-label')).toBe('Send message');
+
+ el.say = vi.fn();
+ input.value = ' hello there ';
+ form.dispatchEvent(new Event('submit', { cancelable: true }));
+ expect(el.say).toHaveBeenCalledWith('hello there');
+ expect(input.value).toBe('');
+
+ el.say.mockClear();
+ form.dispatchEvent(new Event('submit', { cancelable: true }));
+ expect(el.say).not.toHaveBeenCalled(); // an empty field sends nothing
+ });
+
+ it('shows the mic only where speech input can work', () => {
+ const el = document.createElement('agent-3d');
+ el.setAttribute('chat', '');
+ el._renderShell();
+ expect(el.shadowRoot.querySelector('button.mic')).toBeNull(); // jsdom has no SpeechRecognition
+
+ const voiced = document.createElement('agent-3d');
+ voiced.setAttribute('chat', '');
+ voiced.setAttribute('voice-server', 'wss://voice.example');
+ voiced._renderShell();
+ expect(voiced.shadowRoot.querySelector('button.mic')).not.toBeNull();
+ });
+
+ it('builds no composer for a bare avatar', () => {
+ const el = document.createElement('agent-3d');
+ el.setAttribute('body', 'https://cdn.example/body.glb');
+ el._renderShell();
+ expect(el.shadowRoot.querySelector('.input-row')).toBeNull();
+ });
+});
diff --git a/tests/src/embed-api-origin.test.js b/tests/src/embed-api-origin.test.js
new file mode 100644
index 000000000..6a5e0dc0a
--- /dev/null
+++ b/tests/src/embed-api-origin.test.js
@@ -0,0 +1,79 @@
+// src/shared/embed-api-origin.js decides where every API request of an
+// <agent-3d> goes. The bug it exists to prevent: on example.com a site-absolute
+// path asked example.com for the agent, 404'd, and the embed fell back to a
+// default body named "Agent".
+import { describe, it, expect } from 'vitest';
+import {
+ DEFAULT_API_ORIGIN,
+ apiOriginFromScriptURL,
+ resolveApiBase,
+ isPageOrigin,
+ credentialsFor,
+ apiURL,
+} from '../../src/shared/embed-api-origin.js';
+
+describe('apiOriginFromScriptURL', () => {
+ it('is the origin that served the script', () => {
+ expect(apiOriginFromScriptURL('https://three.ws/agent-3d/1/agent-3d.js')).toBe('https://three.ws');
+ expect(apiOriginFromScriptURL('http://localhost:3000/src/element.js')).toBe('http://localhost:3000');
+ });
+
+ it('maps a public npm CDN to three.ws, since those hosts serve no API', () => {
+ expect(apiOriginFromScriptURL('https://unpkg.com/[email protected]/agent-3d.umd.cjs')).toBe(DEFAULT_API_ORIGIN);
+ expect(apiOriginFromScriptURL('https://cdn.jsdelivr.net/npm/three.ws/agent-3d.js')).toBe(DEFAULT_API_ORIGIN);
+ expect(apiOriginFromScriptURL('https://esm.sh/three.ws')).toBe(DEFAULT_API_ORIGIN);
+ });
+
+ it('yields nothing for a URL with no http(s) origin, so the caller falls through', () => {
+ expect(apiOriginFromScriptURL('blob:https://example.com/1234')).toBe('');
+ expect(apiOriginFromScriptURL('file:///repo/src/element.js')).toBe('');
+ expect(apiOriginFromScriptURL('')).toBe('');
+ expect(apiOriginFromScriptURL(undefined)).toBe('');
+ });
+});
+
+describe('resolveApiBase', () => {
+ const page = 'https://bookshop.example';
+
+ it('prefers the script origin over the host page origin', () => {
+ expect(resolveApiBase({ scriptOrigin: 'https://three.ws', pageOrigin: page })).toBe('https://three.ws');
+ });
+
+ it('lets an api-base attribute override both, without a trailing slash', () => {
+ expect(
+ resolveApiBase({ attr: 'https://agents.bookshop.example/', scriptOrigin: 'https://three.ws', pageOrigin: page }),
+ ).toBe('https://agents.bookshop.example');
+ expect(
+ resolveApiBase({ attr: ' https://edge.example/three/ ', scriptOrigin: 'https://three.ws', pageOrigin: page }),
+ ).toBe('https://edge.example/three');
+ });
+
+ it('resolves a relative api-base against the page', () => {
+ expect(resolveApiBase({ attr: '/backend', scriptOrigin: '', pageOrigin: page })).toBe(`${page}/backend`);
+ });
+
+ it('ignores an api-base that is not an http(s) URL', () => {
+ expect(
+ resolveApiBase({ attr: 'javascript:alert(1)', scriptOrigin: 'https://three.ws', pageOrigin: page }),
+ ).toBe('https://three.ws');
+ });
+
+ it('falls back to the page origin only when nothing else is known', () => {
+ expect(resolveApiBase({ scriptOrigin: '', pageOrigin: page })).toBe(page);
+ });
+});
+
+describe('credentials', () => {
+ it('sends cookies only to the page origin itself', () => {
+ expect(isPageOrigin('https://three.ws', 'https://three.ws')).toBe(true);
+ expect(credentialsFor('https://three.ws', 'https://three.ws')).toBe('include');
+ expect(isPageOrigin('https://three.ws', 'https://bookshop.example')).toBe(false);
+ expect(credentialsFor('https://three.ws', 'https://bookshop.example')).toBe('omit');
+ });
+
+ it('treats an empty base as relative, i.e. the page origin', () => {
+ expect(isPageOrigin('', 'https://three.ws')).toBe(true);
+ expect(apiURL('', '/api/x')).toBe('/api/x');
+ expect(apiURL('https://three.ws', '/api/x')).toBe('https://three.ws/api/x');
+ });
+});