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.

feat(plugins): implement plugin marketplace API with CRUD operations and validation

nirholasac17d4389d1f
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index 70b6c8586..d2c76b392 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -3,6 +3,8 @@
* ---------------------
* GET /api/marketplace/categories
* GET /api/marketplace/agents ?category=&q=&sort=&cursor=
+ * POST /api/marketplace/agents — create a new agent
+ * GET /api/marketplace/agents/mine — caller's own agents (auth required)
* GET /api/marketplace/agents/:id
* GET /api/marketplace/agents/:id/versions
* GET /api/marketplace/agents/:id/similar
@@ -20,6 +22,7 @@ import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.
import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
import { publicUrl } from '../_lib/r2.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
+import { z } from 'zod';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -42,6 +45,26 @@ const CATEGORIES = [
const SORTS = new Set(['recommended', 'recent', 'popular']);
+const createAgentSchema = z.object({
+ name: z.string().trim().min(1, 'name required').max(100),
+ description: z.string().trim().min(1, 'description required').max(500),
+ system_prompt: z.string().trim().min(1, 'system prompt required').max(16000),
+ greeting: z.string().trim().max(1000).nullable().optional(),
+ category: z.enum(CATEGORIES).default('general'),
+ tags: z
+ .array(z.string().trim().toLowerCase().min(1).max(40))
+ .max(12)
+ .default([]),
+ capabilities: z
+ .object({
+ bullets: z.array(z.string().max(200)).max(20).default([]),
+ skills: z.array(z.any()).max(50).default([]),
+ library: z.array(z.any()).max(50).default([]),
+ })
+ .default({}),
+ publish: z.boolean().default(false),
+});
+
export default wrap(async (req, res) => {
const url = new URL(req.url, 'http://x');
const parts = url.pathname.split('/').filter(Boolean); // ['api','marketplace',...]
@@ -52,7 +75,12 @@ export default wrap(async (req, res) => {
if (head === 'categories') return handleCategories(req, res);
if (head === 'agents') {
- if (!id) return handleList(req, res, url);
+ if (!id) {
+ if (req.method === 'POST' || (req.method === 'OPTIONS' && req.headers['access-control-request-method'] === 'POST'))
+ return handleCreate(req, res);
+ return handleList(req, res, url);
+ }
+ if (id === 'mine') return handleMine(req, res);
if (!UUID_RE.test(id)) return error(res, 404, 'not_found', 'agent not found');
if (!sub) return handleDetail(req, res, id);
if (sub === 'versions') return handleVersions(req, res, id);
diff --git a/api/plugins/[action].js b/api/plugins/[action].js
new file mode 100644
index 000000000..3a7f73a6b
--- /dev/null
+++ b/api/plugins/[action].js
@@ -0,0 +1,315 @@
+/**
+ * Plugin Marketplace API
+ * ─────────────────────
+ * GET /api/plugins/categories
+ * GET /api/plugins/list ?category=&q=&sort=&cursor=&limit=
+ * GET /api/plugins/:id
+ * POST /api/plugins/import { manifest_url } — fetch + validate + optionally save
+ * POST /api/plugins/publish { manifest_json } — publish plugin to marketplace
+ * POST /api/plugins/:id/install — increment install_count (called client-side on install)
+ */
+
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+const VALID_SORTS = new Set(['popular', 'new', 'az']);
+const MAX_MANIFEST_BYTES = 64 * 1024; // 64 KB
+const FETCH_TIMEOUT_MS = 8000;
+
+// ── Manifest validation (mirrors src/plugins/index.js) ───────────────────────
+
+function validateManifest(json) {
+ if (!json || typeof json !== 'object') throw new Error('Manifest must be a JSON object');
+ if (!String(json.schema_version || '').startsWith('plugin/'))
+ throw new Error('Invalid schema_version — expected "plugin/1.x"');
+ if (!json.identifier || typeof json.identifier !== 'string')
+ throw new Error('Missing identifier');
+ if (!/^[a-z0-9-_]+$/i.test(json.identifier))
+ throw new Error('identifier must be alphanumeric + hyphens/underscores');
+ if (!json.meta?.title) throw new Error('Missing meta.title');
+ if (!Array.isArray(json.api) || !json.api.length)
+ throw new Error('api must be a non-empty array');
+ for (const tool of json.api) {
+ if (!tool.name || !tool.description)
+ throw new Error(`Tool "${tool.name || '?'}" missing name or description`);
+ }
+}
+
+// ── Auth ──────────────────────────────────────────────────────────────────────
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+// ── Row → API shape ───────────────────────────────────────────────────────────
+
+function toPlugin(row) {
+ return {
+ id: row.id,
+ identifier: row.identifier,
+ manifest_url: row.manifest_url,
+ manifest_json: row.manifest_json,
+ name: row.name,
+ description: row.description,
+ category: row.category,
+ tags: row.tags || [],
+ install_count: row.install_count || 0,
+ avg_rating: Number(row.avg_rating) || 0,
+ author: row.author_id
+ ? { id: row.author_id, display_name: row.author_display_name }
+ : null,
+ created_at: row.created_at,
+ };
+}
+
+// ── Route dispatcher ──────────────────────────────────────────────────────────
+
+export default wrap(async (req, res) => {
+ const url = new URL(req.url, 'http://x');
+ const parts = url.pathname.split('/').filter(Boolean); // ['api','plugins',...]
+ const segment = parts[2]; // 'categories' | 'list' | 'import' | 'publish' | <uuid>
+
+ if (segment === 'categories') return handleCategories(req, res);
+ if (segment === 'list' || !segment) return handleList(req, res, url);
+ if (segment === 'import') return handleImport(req, res);
+ if (segment === 'publish') return handlePublish(req, res);
+
+ // /api/plugins/:id[/install]
+ if (UUID_RE.test(segment)) {
+ const sub = parts[3];
+ if (sub === 'install') return handleInstall(req, res, segment);
+ if (!sub) return handleDetail(req, res, segment);
+ }
+
+ return error(res, 404, 'not_found', 'unknown plugin action');
+});
+
+// ── Categories ────────────────────────────────────────────────────────────────
+
+async function handleCategories(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const rows = await sql`
+ SELECT category, count(*)::int AS count
+ FROM plugins
+ WHERE is_public = true AND deleted_at IS NULL
+ GROUP BY category
+ HAVING count(*) > 0
+ ORDER BY count DESC
+ `;
+
+ return json(
+ res,
+ 200,
+ { data: { categories: rows.map((r) => ({ slug: r.category, count: r.count })) } },
+ { 'cache-control': 'public, max-age=60' },
+ );
+}
+
+// ── List ──────────────────────────────────────────────────────────────────────
+
+async function handleList(req, res, url) {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const q = (url.searchParams.get('q') || '').trim().slice(0, 80) || null;
+ const category = url.searchParams.get('category') || null;
+ const sortParam = url.searchParams.get('sort') || 'popular';
+ const sort = VALID_SORTS.has(sortParam) ? sortParam : 'popular';
+ const cursor = url.searchParams.get('cursor') || null;
+ const limit = Math.min(40, Math.max(1, Number(url.searchParams.get('limit')) || 20));
+ const offset = cursor ? Math.max(0, Number(cursor)) : 0;
+
+ const rows = await sql`
+ SELECT p.*, u.display_name AS author_display_name
+ FROM plugins p
+ LEFT JOIN users u ON u.id = p.author_id
+ WHERE p.is_public = true
+ AND p.deleted_at IS NULL
+ ${category ? sql`AND p.category = ${category}` : sql``}
+ ${q ? sql`AND (p.name ILIKE ${'%' + q + '%'} OR p.description ILIKE ${'%' + q + '%'})` : sql``}
+ ORDER BY ${sort === 'popular' ? sql`p.install_count DESC, p.created_at DESC` : sort === 'new' ? sql`p.created_at DESC` : sql`p.name ASC`}
+ LIMIT ${limit + 1} OFFSET ${offset}
+ `;
+
+ const hasMore = rows.length > limit;
+ const items = rows.slice(0, limit).map(toPlugin);
+ return json(res, 200, {
+ data: {
+ items,
+ next_cursor: hasMore ? String(offset + limit) : null,
+ },
+ });
+}
+
+// ── Detail ────────────────────────────────────────────────────────────────────
+
+async function handleDetail(req, res, id) {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [row] = await sql`
+ SELECT p.*, u.display_name AS author_display_name
+ FROM plugins p
+ LEFT JOIN users u ON u.id = p.author_id
+ WHERE p.id = ${id} AND p.deleted_at IS NULL
+ `;
+ if (!row) return error(res, 404, 'not_found', 'plugin not found');
+
+ return json(res, 200, { data: { plugin: toPlugin(row) } });
+}
+
+// ── Import by URL ─────────────────────────────────────────────────────────────
+
+async function handleImport(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = await readJson(req);
+ const manifestUrl = (body?.manifest_url || '').trim();
+ if (!manifestUrl) return error(res, 400, 'validation_error', 'manifest_url is required');
+
+ let parsed;
+ try {
+ parsed = new URL(manifestUrl);
+ } catch {
+ return error(res, 400, 'validation_error', 'manifest_url is not a valid URL');
+ }
+ if (!['https:', 'http:'].includes(parsed.protocol))
+ return error(res, 400, 'validation_error', 'manifest_url must be http or https');
+
+ // Fetch the manifest server-side to avoid CORS issues
+ let manifest;
+ try {
+ const ac = new AbortController();
+ const timer = setTimeout(() => ac.abort(), FETCH_TIMEOUT_MS);
+ const resp = await fetch(manifestUrl, { signal: ac.signal });
+ clearTimeout(timer);
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
+ const text = await resp.text();
+ if (text.length > MAX_MANIFEST_BYTES)
+ throw new Error(`Manifest exceeds ${MAX_MANIFEST_BYTES / 1024}KB limit`);
+ manifest = JSON.parse(text);
+ } catch (err) {
+ return error(res, 422, 'fetch_failed', `Could not fetch manifest: ${err.message}`);
+ }
+
+ try {
+ validateManifest(manifest);
+ } catch (err) {
+ return error(res, 422, 'invalid_manifest', err.message);
+ }
+
+ // Return the validated manifest — client decides whether to install locally
+ return json(res, 200, {
+ data: {
+ manifest: { ...manifest, _manifest_url: manifestUrl },
+ },
+ });
+}
+
+// ── Publish ───────────────────────────────────────────────────────────────────
+
+const publishSchema = z.object({
+ manifest_json: z.record(z.any()),
+ manifest_url: z.string().url().optional(),
+ is_public: z.boolean().default(true),
+});
+
+async function handlePublish(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'authentication required');
+
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const raw = await readJson(req);
+ let body;
+ try {
+ body = publishSchema.parse(raw);
+ } catch (err) {
+ return error(res, 400, 'validation_error', err.errors?.[0]?.message || 'invalid body');
+ }
+
+ const manifest = body.manifest_json;
+ try {
+ validateManifest(manifest);
+ } catch (err) {
+ return error(res, 422, 'invalid_manifest', err.message);
+ }
+
+ const name = String(manifest.meta?.title || manifest.identifier).slice(0, 80);
+ const description = String(manifest.meta?.description || '').slice(0, 500);
+ const category = String(manifest.meta?.category || 'general').slice(0, 50);
+ const tags = Array.isArray(manifest.meta?.tags)
+ ? manifest.meta.tags.slice(0, 20).map((t) => String(t).slice(0, 40))
+ : [];
+
+ // Upsert on identifier + author so re-publishing updates the record
+ const [row] = await sql`
+ INSERT INTO plugins (author_id, identifier, manifest_url, manifest_json, name, description, category, tags, is_public)
+ VALUES (
+ ${auth.userId},
+ ${manifest.identifier},
+ ${body.manifest_url ?? null},
+ ${JSON.stringify(manifest)},
+ ${name},
+ ${description},
+ ${category},
+ ${tags},
+ ${body.is_public}
+ )
+ ON CONFLICT (identifier, author_id) DO UPDATE SET
+ manifest_url = EXCLUDED.manifest_url,
+ manifest_json = EXCLUDED.manifest_json,
+ name = EXCLUDED.name,
+ description = EXCLUDED.description,
+ category = EXCLUDED.category,
+ tags = EXCLUDED.tags,
+ is_public = EXCLUDED.is_public,
+ updated_at = now()
+ RETURNING *
+ `;
+
+ return json(res, 200, { data: { plugin: toPlugin(row) } });
+}
+
+// ── Install (counter) ─────────────────────────────────────────────────────────
+
+async function handleInstall(req, res, id) {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ await sql`
+ UPDATE plugins SET install_count = install_count + 1 WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ return json(res, 200, { data: { ok: true } });
+}
diff --git a/src/CLAUDE.md b/src/CLAUDE.md
index f3a69be24..f0679991f 100644
--- a/src/CLAUDE.md
+++ b/src/CLAUDE.md
@@ -77,6 +77,7 @@ All events are `CustomEvent` with `detail = { type, payload, timestamp, agentId,
| `load-end` | `{ uri, error? }` | viewer | avatar (concern or celebration) |
| `validate` | `{ errors, warnings }` | validator | avatar, identity |
| `presence` | `{ state }` | element | home |
+| `interrupted` | `{}` | speech.js (TTS cancel) | avatar (startle + curiosity) |
**Identity records these to the backend:** `speak`, `remember`, `sign`, `skill-done`, `validate`, `load-end`. Fire-and-forget via `POST /api/agent-actions`.
diff --git a/src/agent-avatar.js b/src/agent-avatar.js
index 8cb112de5..d58278423 100644
--- a/src/agent-avatar.js
+++ b/src/agent-avatar.js
@@ -209,6 +209,7 @@ export class AgentAvatar {
this._sub(ACTION_TYPES.LOAD_START, this._onLoadStart.bind(this));
this._sub(ACTION_TYPES.LOAD_END, this._onLoadEnd.bind(this));
this._sub(ACTION_TYPES.VALIDATE, this._onValidate.bind(this));
+ this._sub(ACTION_TYPES.INTERRUPTED, this._onInterrupted.bind(this));
// First-encounter curiosity burst
if (this._firstEncounter) {
@@ -454,6 +455,15 @@ export class AgentAvatar {
}
}
+ _onInterrupted() {
+ this._triggerOneShot('startle', 0.6);
+ this._emotion.patience = 0;
+ this._injectStimulus('curiosity', 0.5);
+ // Morph impulse — lerps back to emotion-driven values on next tick
+ this._setMorphTarget('browInnerUp', 0.9);
+ this._setMorphTarget('mouthOpen', 0.3);
+ }
+
// ── Empathy Layer — The Novel Part ────────────────────────────────────────
/**
diff --git a/src/agent-notifier.js b/src/agent-notifier.js
new file mode 100644
index 000000000..5b0024ad6
--- /dev/null
+++ b/src/agent-notifier.js
@@ -0,0 +1,117 @@
+import { ACTION_TYPES } from './agent-protocol.js';
+
+export class AgentNotifier {
+ /**
+ * @param {HTMLElement} hostEl — the <agent-3d> element
+ * @param {import('./agent-protocol.js').AgentProtocol} protocol
+ */
+ constructor(hostEl, protocol) {
+ this._host = hostEl;
+ this._protocol = protocol;
+ this._queue = [];
+ this._busy = false;
+ this._originalStyles = null;
+ this._onNotifyBound = this._onNotify.bind(this);
+ }
+
+ attach() {
+ this._protocol.on(ACTION_TYPES.NOTIFY, this._onNotifyBound);
+ _ensureDocStyle();
+ }
+
+ detach() {
+ this._protocol.off(ACTION_TYPES.NOTIFY, this._onNotifyBound);
+ this._queue = [];
+ if (this._busy) {
+ this._busy = false;
+ this._host.classList.remove('notifying');
+ if (this._originalStyles) {
+ Object.assign(this._host.style, this._originalStyles);
+ this._host.style.transition = '';
+ this._originalStyles = null;
+ }
+ }
+ }
+
+ _onNotify(action) {
+ this._queue.push(action.payload);
+ if (!this._busy) this._processNext();
+ }
+
+ async _processNext() {
+ if (!this._queue.length) { this._busy = false; return; }
+ this._busy = true;
+ const { message, duration = 6000 } = this._queue.shift();
+ await this._enterFrame();
+ if (!this._busy) return;
+ this._protocol.emit({ type: ACTION_TYPES.SPEAK, payload: { text: message } });
+ await this._wait(duration);
+ if (!this._busy) return;
+ await this._exitFrame();
+ this._processNext();
+ }
+
+ async _enterFrame() {
+ this._originalStyles = {
+ transform: this._host.style.transform,
+ opacity: this._host.style.opacity,
+ visibility: this._host.style.visibility,
+ position: this._host.style.position,
+ bottom: this._host.style.bottom,
+ right: this._host.style.right,
+ width: this._host.style.width,
+ height: this._host.style.height,
+ zIndex: this._host.style.zIndex,
+ };
+
+ this._host.classList.add('notifying');
+
+ // Snap to off-screen start position without transition
+ this._host.style.transition = 'none';
+ this._host.style.transform = 'translateX(120%)';
+ this._host.style.visibility = 'visible';
+ this._host.style.opacity = '0';
+
+ // Force reflow so the snap position is committed before the transition starts
+ void this._host.offsetWidth;
+
+ // Slide in
+ this._host.style.transition = 'transform 0.4s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.3s ease';
+ this._host.style.transform = 'translateX(0)';
+ this._host.style.opacity = '1';
+
+ await this._wait(450);
+ }
+
+ async _exitFrame() {
+ this._host.style.transition = 'transform 0.35s ease-in, opacity 0.25s ease';
+ this._host.style.transform = 'translateX(120%)';
+ this._host.style.opacity = '0';
+ await this._wait(380);
+
+ this._host.classList.remove('notifying');
+ Object.assign(this._host.style, this._originalStyles);
+ this._host.style.transition = '';
+ this._originalStyles = null;
+ }
+
+ _wait(ms) {
+ return new Promise(r => setTimeout(r, ms));
+ }
+}
+
+function _ensureDocStyle() {
+ if (document.getElementById('agent-notifier-style')) return;
+ const style = document.createElement('style');
+ style.id = 'agent-notifier-style';
+ style.textContent = `
+agent-3d.notifying {
+ position: fixed !important;
+ bottom: 24px !important;
+ right: 24px !important;
+ width: 200px !important;
+ height: 300px !important;
+ z-index: 9999 !important;
+}`;
+ document.head.appendChild(style);
+}
diff --git a/src/agent-protocol.js b/src/agent-protocol.js
index 8ca5f27ad..e1e6a0bb4 100644
--- a/src/agent-protocol.js
+++ b/src/agent-protocol.js
@@ -27,6 +27,7 @@ export const ACTION_TYPES = {
PERMISSIONS_REDEEM_START: 'permissions.redeem.start',
PERMISSIONS_REDEEM_SUCCESS: 'permissions.redeem.success',
PERMISSIONS_REDEEM_ERROR: 'permissions.redeem.error',
+ NOTIFY: 'notify', // avatar walks into frame, delivers a message, retreats
};
/**
diff --git a/src/element.js b/src/element.js
index c7618cde0..449015110 100644
--- a/src/element.js
+++ b/src/element.js
@@ -15,6 +15,7 @@ import { attachTradeReactions } from './pump/trade-reactions.js';
import { EmbedActionBridge } from './embed-action-bridge.js';
import { protocol, ACTION_TYPES } from './agent-protocol.js';
// END:EMBED_BRIDGES_IMPORT
+import { AgentNotifier } from './agent-notifier.js';
const MODES = ['inline', 'floating', 'section', 'fullscreen'];
@@ -349,6 +350,7 @@ class Agent3DElement extends HTMLElement {
this._detachTradeReactions = null;
this._livekitVoice = null;
this._voiceClient = null;
+ this._notifier = null;
}
connectedCallback() {
@@ -1107,6 +1109,9 @@ class Agent3DElement extends HTMLElement {
this._mounted = true;
+ this._notifier = new AgentNotifier(this, protocol);
+ this._notifier.attach();
+
// LiveKit realtime voice — connect when voice="livekit" and agent-id is set
if (this.getAttribute('voice') === 'livekit' && _backendId) {
this._connectLiveKit(_backendId).catch((err) => {
@@ -1576,6 +1581,8 @@ class Agent3DElement extends HTMLElement {
this._voiceClient.stop();
this._voiceClient = null;
}
+ this._notifier?.detach();
+ this._notifier = null;
try {
this._runtime?.destroy();
} catch {}
diff --git a/src/plugins/index.js b/src/plugins/index.js
new file mode 100644
index 000000000..cd34b863f
--- /dev/null
+++ b/src/plugins/index.js
@@ -0,0 +1,161 @@
+// Plugin registry — load JSON plugin manifests, bridge to LLM tool system.
+// Manifest format: { schema_version: "plugin/1.0", identifier, meta, api[], settings[], system_role }
+// Compatible with LobeHub plugin manifest v1 (superset).
+
+const STORAGE_KEY = 'installed_plugins_v1';
+
+// ── Validation ────────────────────────────────────────────────────────────────
+
+export function validatePluginManifest(json) {
+ if (!json || typeof json !== 'object') throw new Error('Plugin manifest must be a JSON object');
+ if (!json.schema_version?.startsWith('plugin/'))
+ throw new Error('Missing or invalid schema_version — expected "plugin/1.x"');
+ if (!json.identifier || typeof json.identifier !== 'string')
+ throw new Error('Plugin manifest missing required field: identifier');
+ if (!json.meta?.title) throw new Error('Plugin manifest missing meta.title');
+ if (!Array.isArray(json.api) || json.api.length === 0)
+ throw new Error('Plugin manifest must declare at least one api tool');
+ for (const tool of json.api) {
+ if (!tool.name || !tool.description)
+ throw new Error(`Plugin tool "${tool.name || '?'}" missing name or description`);
+ }
+ return true;
+}
+
+export async function fetchPluginManifest(url) {
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`Manifest fetch failed: ${url} (${res.status})`);
+ const ct = res.headers.get('content-type') || '';
+ if (!ct.includes('json') && !ct.includes('octet'))
+ throw new Error(`Expected JSON response from ${url}, got ${ct}`);
+ const json = await res.json();
+ validatePluginManifest(json);
+ return { ...json, _manifest_url: url };
+}
+
+// ── PluginRegistry ────────────────────────────────────────────────────────────
+
+export class PluginRegistry {
+ constructor() {
+ this._plugins = new Map(); // identifier → manifest
+ this._loadFromStorage();
+ }
+
+ _loadFromStorage() {
+ try {
+ const raw =
+ typeof localStorage !== 'undefined' ? localStorage.getItem(STORAGE_KEY) : null;
+ if (!raw) return;
+ for (const p of JSON.parse(raw)) this._plugins.set(p.identifier, p);
+ } catch {
+ // ignore corrupt storage
+ }
+ }
+
+ _saveToStorage() {
+ try {
+ if (typeof localStorage !== 'undefined') {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(this.list()));
+ }
+ } catch {
+ // storage full or unavailable
+ }
+ }
+
+ /** Install from a URL string or a pre-fetched manifest object. */
+ async install(urlOrManifest) {
+ const manifest =
+ typeof urlOrManifest === 'string'
+ ? await fetchPluginManifest(urlOrManifest)
+ : urlOrManifest;
+ validatePluginManifest(manifest);
+ this._plugins.set(manifest.identifier, manifest);
+ this._saveToStorage();
+ return manifest;
+ }
+
+ uninstall(identifier) {
+ const had = this._plugins.delete(identifier);
+ if (had) this._saveToStorage();
+ return had;
+ }
+
+ isInstalled(identifier) {
+ return this._plugins.has(identifier);
+ }
+
+ get(identifier) {
+ return this._plugins.get(identifier) ?? null;
+ }
+
+ list() {
+ return Array.from(this._plugins.values());
+ }
+
+ // ── LLM integration ───────────────────────────────────────────────────────
+
+ /**
+ * Convert installed plugin tools to the Anthropic tool format so the LLM
+ * can call them alongside built-in tools.
+ */
+ toClaudeTools() {
+ const tools = [];
+ for (const plugin of this._plugins.values()) {
+ for (const api of plugin.api) {
+ tools.push({
+ name: api.name,
+ description: `[${plugin.meta.title}] ${api.description}`,
+ input_schema: api.parameters ?? { type: 'object', properties: {} },
+ // private routing fields (stripped before sending to Anthropic)
+ _plugin: plugin.identifier,
+ _url: api.url ?? null,
+ _method: (api.method ?? 'POST').toUpperCase(),
+ });
+ }
+ }
+ return tools;
+ }
+
+ /** System prompt fragments injected for installed plugins. */
+ systemPrompt() {
+ const parts = [];
+ for (const plugin of this._plugins.values()) {
+ if (plugin.system_role) {
+ parts.push(
+ `<plugin name="${plugin.identifier}">\n${plugin.system_role}\n</plugin>`,
+ );
+ }
+ }
+ return parts.join('\n');
+ }
+
+ /**
+ * Execute a plugin tool by POSTing args to its declared URL.
+ * Returns the parsed JSON response body.
+ */
+ async invoke(toolName, args, { fetchFn = fetch } = {}) {
+ for (const plugin of this._plugins.values()) {
+ const tool = plugin.api.find((t) => t.name === toolName);
+ if (!tool) continue;
+ if (!tool.url) throw new Error(`Plugin tool "${toolName}" has no url`);
+ const method = (tool.method ?? 'POST').toUpperCase();
+ const res = await fetchFn(tool.url, {
+ method,
+ headers: { 'content-type': 'application/json' },
+ body: method !== 'GET' ? JSON.stringify(args) : undefined,
+ });
+ if (!res.ok)
+ throw new Error(`Plugin tool "${toolName}" returned HTTP ${res.status}`);
+ return res.json();
+ }
+ throw new Error(`No installed plugin handles tool "${toolName}"`);
+ }
+}
+
+// ── Singleton ─────────────────────────────────────────────────────────────────
+
+let _registry;
+export function getPluginRegistry() {
+ if (!_registry) _registry = new PluginRegistry();
+ return _registry;
+}
diff --git a/src/runtime/index.js b/src/runtime/index.js
index f1562c609..68c16cc4c 100644
--- a/src/runtime/index.js
+++ b/src/runtime/index.js
@@ -227,7 +227,7 @@ export class Runtime extends EventTarget {
}
pause() {
- this.tts?.cancel();
+ this.tts?.cancel(protocol);
this.stt?.stop();
}
destroy() {
diff --git a/src/runtime/scene.js b/src/runtime/scene.js
index 350c77b9c..3100d240c 100644
--- a/src/runtime/scene.js
+++ b/src/runtime/scene.js
@@ -35,6 +35,9 @@ export class SceneController {
get scene() {
return this.viewer.scene;
}
+ get renderer() {
+ return this.viewer.renderer;
+ }
get mixer() {
return this._groupMixer || this.viewer.mixer;
}
diff --git a/src/runtime/screen-context.js b/src/runtime/screen-context.js
new file mode 100644
index 000000000..ce4525b77
--- /dev/null
+++ b/src/runtime/screen-context.js
@@ -0,0 +1,58 @@
+// Screen / context capture utilities for the see_screen tool.
+// Three modes: canvas (always), text (always), screen (user permission required).
+
+async function captureCanvas(renderer) {
+ return renderer.domElement.toDataURL('image/jpeg', 0.6);
+}
+
+function captureVisibleText() {
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
+ const parts = [];
+ let total = 0;
+ while (walker.nextNode() && total < 2000) {
+ const el = walker.currentNode;
+ const style = window.getComputedStyle(el);
+ if (style.display === 'none' || style.visibility === 'hidden') continue;
+ const rect = el.getBoundingClientRect();
+ if (rect.width === 0 && rect.height === 0) continue;
+ if (el.children.length > 0) continue;
+ const text = el.textContent?.trim();
+ if (text) {
+ parts.push(text);
+ total += text.length;
+ }
+ }
+ return parts.join('\n').slice(0, 2000);
+}
+
+async function captureScreen() {
+ const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });
+ const track = stream.getVideoTracks()[0];
+ try {
+ const imageCapture = new ImageCapture(track);
+ const bitmap = await imageCapture.grabFrame();
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ canvas.getContext('2d').drawImage(bitmap, 0, 0);
+ const blob = await canvas.convertToBlob({ type: 'image/jpeg', quality: 0.6 });
+ const buf = await blob.arrayBuffer();
+ const bytes = new Uint8Array(buf);
+ let binary = '';
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return 'data:image/jpeg;base64,' + btoa(binary);
+ } finally {
+ track.stop();
+ }
+}
+
+/**
+ * Capture the current screen context in the requested mode.
+ * @param {import('three').WebGLRenderer} renderer
+ * @param {{ mode?: 'canvas' | 'text' | 'screen' }} options
+ * @returns {Promise<{ type: 'image' | 'text', data: string }>}
+ */
+export async function captureContext(renderer, { mode = 'canvas' } = {}) {
+ if (mode === 'canvas') return { type: 'image', data: await captureCanvas(renderer) };
+ if (mode === 'text') return { type: 'text', data: captureVisibleText() };
+ if (mode === 'screen') return { type: 'image', data: await captureScreen() };
+ throw new Error(`Unknown capture mode: ${mode}`);
+}