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: add 3D avatar model viewer and improve rendering updates in Viewer

nirholasc83849a38ab5
diff --git a/features.css b/features.css
index bafb658bc..acc8773a2 100644
--- a/features.css
+++ b/features.css
@@ -60,19 +60,23 @@
.hero {
position: relative;
- display: flex;
+ display: grid;
+ /* Golden-ratio split: text (1) : avatar (φ ≈ 1.618) */
+ grid-template-columns: 1fr 1.618fr;
align-items: center;
- justify-content: center;
+ gap: var(--space-2xl);
min-height: 100vh;
+ max-width: 1200px;
+ margin: 0 auto;
padding: var(--space-2xl) var(--space-lg);
- text-align: center;
overflow: hidden;
}
.hero-content {
- max-width: 720px;
position: relative;
z-index: 1;
+ max-width: 34em;
+ text-align: left;
}
.hero-eyebrow {
@@ -85,12 +89,12 @@
}
.hero-title {
- font-size: clamp(2rem, 6vw, var(--text-2xl));
+ font-size: clamp(2rem, 5.2vw, var(--text-2xl));
font-weight: 600;
color: #fff;
line-height: var(--leading-tight);
margin: 0 0 var(--space-lg);
- letter-spacing: -0.01em;
+ letter-spacing: -0.015em;
}
.hero-subtitle {
@@ -99,26 +103,64 @@
font-weight: 300;
line-height: var(--leading-normal);
max-width: 38.2em; /* phi-proportioned line length */
- margin: 0 auto var(--space-xl);
+ margin: 0 0 var(--space-xl);
}
.hero-cta {
display: flex;
gap: var(--space-md);
- justify-content: center;
+ justify-content: flex-start;
flex-wrap: wrap;
}
+/* ── Hero Avatar (right column) ─────────────────────────────────────────── */
+
+.hero-avatar {
+ position: relative;
+ z-index: 1;
+ width: 100%;
+ aspect-ratio: 1 / 1;
+ max-width: 520px;
+ justify-self: end;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.hero-avatar-viewer {
+ width: 100%;
+ height: 100%;
+ background: transparent;
+ --poster-color: transparent;
+ border-radius: 50%;
+ outline: none;
+}
+
+.hero-avatar-ring {
+ position: absolute;
+ inset: 6%;
+ border-radius: 50%;
+ background:
+ radial-gradient(circle at 50% 45%, rgba(255, 215, 0, 0.12) 0%, rgba(255, 215, 0, 0.04) 40%, transparent 70%),
+ radial-gradient(circle at 50% 60%, rgba(255, 255, 255, 0.04) 0%, transparent 60%);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ box-shadow:
+ inset 0 1px 0 rgba(255, 255, 255, 0.05),
+ 0 30px 80px -20px rgba(255, 215, 0, 0.12);
+ pointer-events: none;
+}
+
.hero-glow {
position: absolute;
- width: 600px;
- height: 600px;
+ width: 700px;
+ height: 700px;
border-radius: 50%;
- background: radial-gradient(circle, rgba(255, 215, 0, 0.06) 0%, transparent 70%);
+ background: radial-gradient(circle, rgba(255, 215, 0, 0.07) 0%, transparent 70%);
top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
+ right: -10%;
+ transform: translateY(-50%);
pointer-events: none;
+ z-index: 0;
}
/* ── Buttons ─────────────────────────────────────────────────────────────── */
@@ -450,10 +492,49 @@
/* ── Responsive ──────────────────────────────────────────────────────────── */
+/* Tablet — keep two columns but tighten the split */
+@media screen and (max-width: 1024px) {
+ .hero {
+ grid-template-columns: 1fr 1fr;
+ gap: var(--space-xl);
+ }
+
+ .hero-avatar {
+ max-width: 420px;
+ }
+}
+
@media screen and (max-width: 768px) {
.hero {
- min-height: 80vh;
+ grid-template-columns: 1fr;
+ gap: var(--space-xl);
+ min-height: auto;
padding: var(--space-xl) var(--space-md);
+ text-align: center;
+ }
+
+ .hero-content {
+ max-width: 100%;
+ text-align: center;
+ order: 2;
+ }
+
+ .hero-avatar {
+ order: 1;
+ max-width: 320px;
+ margin: 0 auto;
+ justify-self: center;
+ }
+
+ .hero-cta {
+ justify-content: center;
+ }
+
+ .hero-glow {
+ right: 50%;
+ transform: translate(50%, -50%);
+ width: 500px;
+ height: 500px;
}
.hero-title {
diff --git a/features.html b/features.html
index bbf8973ab..60c3dc47e 100644
--- a/features.html
+++ b/features.html
@@ -44,6 +44,28 @@
<a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener" class="btn-ghost">Read ERC-8004 →</a>
</div>
</div>
+ <div class="hero-avatar scroll-reveal" aria-hidden="true">
+ <div class="hero-avatar-ring"></div>
+ <model-viewer
+ class="hero-avatar-viewer"
+ src="/avatars/cz.glb"
+ alt="3D Agent avatar"
+ camera-controls
+ disable-zoom
+ auto-rotate
+ auto-rotate-delay="0"
+ rotation-per-second="18deg"
+ interaction-prompt="none"
+ shadow-intensity="0.8"
+ shadow-softness="1"
+ exposure="1.05"
+ tone-mapping="aces"
+ environment-image="neutral"
+ camera-orbit="20deg 80deg 2.4m"
+ field-of-view="28deg"
+ loading="eager"
+ ></model-viewer>
+ </div>
<div class="hero-glow"></div>
</section>
diff --git a/src/app.js b/src/app.js
index 094801729..2ad7abd89 100644
--- a/src/app.js
+++ b/src/app.js
@@ -1,17 +1,24 @@
import * as THREE from 'three';
import WebGL from 'three/addons/capabilities/WebGL.js';
-import { Viewer } from './viewer.js';
+import { Viewer } from './viewer.js';
import { SimpleDropzone } from 'simple-dropzone';
-import { Validator } from './validator.js';
-import { Footer } from './components/footer';
-import { NichAgent } from './nich-agent.js';
+import { Validator } from './validator.js';
+import { Footer } from './components/footer';
+import { NichAgent } from './nich-agent.js';
import { AvatarCreator } from './avatar-creator.js';
import { resolveURI, isDecentralizedURI } from './ipfs.js';
-import { saveRemoteGlbToAccount } from './account.js';
+import { saveRemoteGlbToAccount } from './account.js';
import queryString from 'query-string';
-window.THREE = THREE;
-window.VIEWER = {};
+// Agent system — the new primitive layer
+import { protocol, ACTION_TYPES } from './agent-protocol.js';
+import { AgentIdentity } from './agent-identity.js';
+import { AgentSkills } from './agent-skills.js';
+import { AgentAvatar } from './agent-avatar.js';
+import { AgentHome } from './agent-home.js';
+
+window.THREE = THREE;
+window.VIEWER = {};
if (!(window.File && window.FileReader && window.FileList && window.Blob)) {
console.error('The File APIs are not fully supported in this browser.');
@@ -27,20 +34,29 @@ class App {
constructor(el, location) {
const hash = location.hash ? queryString.parse(location.hash) : {};
this.options = {
- kiosk: Boolean(hash.kiosk),
- model: hash.model || '',
- preset: hash.preset || '',
+ kiosk: Boolean(hash.kiosk),
+ model: hash.model || '',
+ preset: hash.preset || '',
cameraPosition: hash.cameraPosition ? hash.cameraPosition.split(',').map(Number) : null,
};
- this.el = el;
- this.viewer = null;
- this.viewerEl = null;
- this.spinnerEl = el.querySelector('.spinner');
- this.dropEl = el.querySelector('.wrap');
- this.inputEl = el.querySelector('#file-input');
+ this.el = el;
+ this.viewer = null;
+ this.viewerEl = null;
+ this.spinnerEl = el.querySelector('.spinner');
+ this.dropEl = el.querySelector('.wrap');
+ this.inputEl = el.querySelector('#file-input');
this.viewerContainerEl = el.querySelector('#viewer-container');
- this.validator = new Validator(el);
+ this.validator = new Validator(el);
+
+ // ── Agent System ──────────────────────────────────────────────────────
+ this.identity = new AgentIdentity({ autoLoad: true });
+ this.skills = null; // initialised after identity loads
+ this.avatar = null; // initialised after viewer + content load
+ this.agentHome = null;
+
+ // Wire validator results into the protocol
+ this._hookValidator();
this.createDropzone();
this.setupAvatarCreator();
@@ -61,29 +77,99 @@ class App {
// Load specified model or default CZ avatar
const model = options.model || '/avatars/cz.glb';
- // Resolve decentralized URIs (ipfs://, ar://) to gateway URLs
const resolvedModel = isDecentralizedURI(model) ? resolveURI(model) : model;
this.view(resolvedModel, '', new Map());
+
+ // Boot the agent system once identity is ready
+ this._initAgentSystem();
+ }
+
+ // ── Agent System Init ─────────────────────────────────────────────────────
+
+ async _initAgentSystem() {
+ try {
+ // Wait for identity to resolve (uses local storage immediately, backend async)
+ await this.identity.load();
+
+ // Skills need identity + memory
+ this.skills = new AgentSkills(protocol, this.identity.memory);
+
+ // Expose agent on window for debugging
+ window.VIEWER.agent_protocol = protocol;
+ window.VIEWER.agent_identity = this.identity;
+ window.VIEWER.agent_skills = this.skills;
+
+ // Announce presence
+ protocol.emit({
+ type: ACTION_TYPES.PRESENCE,
+ payload: { status: 'online', agentId: this.identity.id },
+ agentId: this.identity.id,
+ });
+
+ // Render the agent home panel (identity card + timeline)
+ const homeEl = document.getElementById('agent-home-container');
+ if (homeEl) {
+ this.agentHome = new AgentHome(homeEl, this.identity, protocol, this.avatar);
+ await this.agentHome.render();
+ }
+
+ // Boot the voice/chat agent with skills wired in
+ this._initNichAgent();
+
+ // Log all significant actions to identity history (fire-and-forget)
+ protocol.on('*', (action) => {
+ if ([
+ ACTION_TYPES.SPEAK,
+ ACTION_TYPES.REMEMBER,
+ ACTION_TYPES.SIGN,
+ ACTION_TYPES.SKILL_DONE,
+ ACTION_TYPES.VALIDATE,
+ ACTION_TYPES.LOAD_END,
+ ].includes(action.type)) {
+ this.identity.recordAction(action);
+ }
+ });
+
+ } catch (err) {
+ console.warn('[3d-agent] Agent system init failed:', err.message);
+ }
+ }
+
+ _initNichAgent() {
+ const agent = new NichAgent(document.body, protocol, this.skills, this.identity);
+ window.VIEWER.agent = agent;
+ // Greet on first open
+ agent.onFirstOpen = () => {
+ this.skills.perform('greet', {}, { identity: this.identity });
+ };
}
+ // ── Viewer setup + Avatar attachment ────────────────────────────────────
+
/**
- * Sets up the drag-and-drop controller.
+ * Sets up the view manager.
+ * @return {Viewer}
*/
+ createViewer() {
+ this.viewerEl = this.viewerContainerEl;
+ this.viewer = new Viewer(this.viewerEl, this.options);
+ return this.viewer;
+ }
+
+ // ── Dropzone ─────────────────────────────────────────────────────────────
+
createDropzone() {
const dropCtrl = new SimpleDropzone(this.dropEl, this.inputEl);
- dropCtrl.on('drop', ({ files }) => this.load(files));
+ dropCtrl.on('drop', ({ files }) => this.load(files));
dropCtrl.on('dropstart', () => this.showSpinner());
dropCtrl.on('droperror', () => this.hideSpinner());
}
- /**
- * Sets up the Create Avatar button and AvatarCreator instance.
- */
+ // ── Avatar Creator ────────────────────────────────────────────────────────
+
setupAvatarCreator() {
this.avatarCreator = new AvatarCreator(document.body, async (glbUrl) => {
this.view(glbUrl, '', new Map());
- // Best-effort: if the user is signed in, persist the exported avatar
- // into their account so it's immediately available via the MCP server.
try {
const avatar = await saveRemoteGlbToAccount(glbUrl, { source: 'avaturn' });
this._flashSaved(avatar);
@@ -100,31 +186,13 @@ class App {
}
}
- _flashSaved(avatar) {
- const el = document.createElement('div');
- el.className = 'save-toast';
- el.innerHTML = `Saved to your account · <a href="/dashboard/#avatars">${avatar.name}</a>`;
- document.body.appendChild(el);
- setTimeout(() => el.remove(), 5000);
- }
-
- /**
- * Sets up the view manager.
- * @return {Viewer}
- */
- createViewer() {
- this.viewerEl = this.viewerContainerEl;
- this.viewer = new Viewer(this.viewerEl, this.options);
- return this.viewer;
- }
+ // ── File Loading ──────────────────────────────────────────────────────────
/**
- * Loads a fileset provided by user action.
* @param {Map<string, File>} fileMap
*/
load(fileMap) {
- let rootFile;
- let rootPath;
+ let rootFile, rootPath;
Array.from(fileMap).forEach(([path, file]) => {
if (file.name.match(/\.(gltf|glb)$/)) {
rootFile = file;
@@ -140,7 +208,6 @@ class App {
}
/**
- * Passes a model to the viewer, given file and resources.
* @param {File|string} rootFile
* @param {string} rootPath
* @param {Map<string, File>} fileMap
@@ -148,10 +215,16 @@ class App {
view(rootFile, rootPath, fileMap) {
if (this.viewer) this.viewer.clear();
- const viewer = this.viewer || this.createViewer();
-
+ const viewer = this.viewer || this.createViewer();
const fileURL = typeof rootFile === 'string' ? rootFile : URL.createObjectURL(rootFile);
+ // Emit load start
+ protocol.emit({
+ type: ACTION_TYPES.LOAD_START,
+ payload: { url: typeof rootFile === 'string' ? rootFile : rootFile.name },
+ agentId: this.identity?.id || 'default',
+ });
+
const cleanup = () => {
this.hideSpinner();
if (typeof rootFile === 'object') URL.revokeObjectURL(fileURL);
@@ -159,10 +232,28 @@ class App {
viewer
.load(fileURL, rootPath, fileMap)
- .catch((e) => this.onError(e))
+ .catch((e) => {
+ // Emit load error
+ protocol.emit({
+ type: ACTION_TYPES.LOAD_END,
+ payload: { error: e.message },
+ agentId: this.identity?.id || 'default',
+ });
+ this.onError(e);
+ })
.then((gltf) => {
- // TODO: GLTFLoader parsing can fail on invalid files. Ideally,
- // we could run the validator either way.
+ if (!gltf) return;
+
+ // Emit load success
+ protocol.emit({
+ type: ACTION_TYPES.LOAD_END,
+ payload: { success: true },
+ agentId: this.identity?.id || 'default',
+ });
+
+ // Attach the avatar empathy system to the newly loaded content
+ this._attachAvatar(viewer);
+
if (!this.options.kiosk) {
this.validator.validate(fileURL, rootPath, fileMap, gltf);
}
@@ -170,6 +261,54 @@ class App {
});
}
+ /** Attach (or reattach) the AgentAvatar to the viewer after content loads */
+ _attachAvatar(viewer) {
+ if (this.avatar) this.avatar.detach();
+ this.avatar = new AgentAvatar(viewer, protocol, this.identity);
+ this.avatar.attach();
+
+ // Update agent-home with the live avatar reference
+ if (this.agentHome) this.agentHome.avatar = this.avatar;
+
+ window.VIEWER.agent_avatar = this.avatar;
+
+ // Let the skills system access the viewer
+ if (this.skills) {
+ window.VIEWER.agent_skills = this.skills;
+ }
+ }
+
+ // ── Validator hook ────────────────────────────────────────────────────────
+
+ _hookValidator() {
+ // Intercept the validator toggle DOM node to emit validation results
+ const observer = new MutationObserver(() => {
+ const el = document.querySelector('.validator-toggle');
+ if (!el) return;
+
+ const errors = parseInt(el.dataset.errors || '0', 10);
+ const warnings = parseInt(el.dataset.warnings || '0', 10);
+ const hints = parseInt(el.dataset.hints || '0', 10);
+
+ protocol.emit({
+ type: ACTION_TYPES.VALIDATE,
+ payload: { errors, warnings, hints },
+ agentId: this.identity?.id || 'default',
+ });
+ });
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true });
+ }
+
+ // ── UI Helpers ────────────────────────────────────────────────────────────
+
+ _flashSaved(avatar) {
+ const el = document.createElement('div');
+ el.className = 'save-toast';
+ el.innerHTML = `Saved to your account · <a href="/dashboard/#avatars">${avatar.name}</a>`;
+ document.body.appendChild(el);
+ setTimeout(() => el.remove(), 5000);
+ }
+
/**
* @param {Error} error
*/
@@ -191,29 +330,19 @@ class App {
import('./erc8004/register-ui.js').then(({ RegisterUI }) => {
new RegisterUI(this.viewerContainerEl, (result) => {
console.info('[ERC-8004] Agent registered:', result);
+ this.identity.update({ isRegistered: true, meta: { ...this.identity.meta, erc8004: result } });
});
});
}
- showSpinner() {
- this.spinnerEl.style.display = '';
- }
-
- hideSpinner() {
- this.spinnerEl.style.display = 'none';
- }
+ showSpinner() { this.spinnerEl.style.display = ''; }
+ hideSpinner() { this.spinnerEl.style.display = 'none'; }
}
document.body.innerHTML += Footer();
document.addEventListener('DOMContentLoaded', () => {
const app = new App(document.body, location);
-
window.VIEWER.app = app;
-
- // Initialize Avaturn Agent
- const agent = new NichAgent(document.body);
- window.VIEWER.agent = agent;
-
console.info('[3D Agent] Debugging data exported as `window.VIEWER`.');
});
diff --git a/src/memory/index.js b/src/memory/index.js
new file mode 100644
index 000000000..843c2a0d7
--- /dev/null
+++ b/src/memory/index.js
@@ -0,0 +1,198 @@
+// Agent memory — file-based, human-readable, Claude-shaped.
+// See specs/MEMORY_SPEC.md
+
+const FRONTMATTER_RE = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;
+
+function parseFrontmatter(text) {
+ const m = text.match(FRONTMATTER_RE);
+ if (!m) return { meta: {}, body: text };
+ const meta = {};
+ for (const line of m[1].split('\n')) {
+ const [k, ...rest] = line.split(':');
+ if (!k) continue;
+ meta[k.trim()] = rest.join(':').trim();
+ }
+ return { meta, body: m[2] };
+}
+
+function stringifyFrontmatter(meta, body) {
+ const lines = ['---'];
+ for (const [k, v] of Object.entries(meta)) lines.push(`${k}: ${v}`);
+ lines.push('---', '', body);
+ return lines.join('\n');
+}
+
+export class Memory {
+ constructor({ mode = 'local', namespace, index = {}, files = {}, timeline = [] } = {}) {
+ this.mode = mode;
+ this.namespace = namespace;
+ this.files = new Map(Object.entries(files));
+ this.timeline = timeline;
+ this.indexText = index.text || '';
+ this._dirty = false;
+ }
+
+ static async load({ mode = 'local', namespace, manifestURI, fetchFn }) {
+ if (mode === 'none') return new Memory({ mode: 'none', namespace });
+ if (mode === 'local') return Memory._loadLocal(namespace);
+ if (mode === 'ipfs' || mode === 'encrypted-ipfs') {
+ return Memory._loadIPFS({ mode, namespace, manifestURI, fetchFn });
+ }
+ throw new Error(`Unknown memory mode: ${mode}`);
+ }
+
+ static _loadLocal(namespace) {
+ const key = `agent:${namespace}:memory`;
+ try {
+ const raw = localStorage.getItem(key);
+ if (!raw) return new Memory({ mode: 'local', namespace });
+ const data = JSON.parse(raw);
+ return new Memory({ mode: 'local', namespace, ...data });
+ } catch {
+ return new Memory({ mode: 'local', namespace });
+ }
+ }
+
+ static async _loadIPFS({ mode, namespace, manifestURI, fetchFn }) {
+ // Minimal IPFS mode — fetch memory/ from the manifest bundle.
+ const base = manifestURI.replace(/manifest\.json$/, '');
+ try {
+ const idxRes = await fetchFn(`${base}memory/MEMORY.md`);
+ const indexText = idxRes.ok ? await idxRes.text() : '';
+ const files = {};
+ // Parse MEMORY.md links to discover files
+ const linkRe = /\[([^\]]+)\]\(([^)]+\.md)\)/g;
+ let m;
+ while ((m = linkRe.exec(indexText))) {
+ const file = m[2];
+ try {
+ const r = await fetchFn(`${base}memory/${file}`);
+ if (r.ok) files[file] = await r.text();
+ } catch { /* skip missing */ }
+ }
+ return new Memory({ mode, namespace, index: { text: indexText }, files });
+ } catch {
+ return new Memory({ mode, namespace });
+ }
+ }
+
+ read(key) {
+ const file = key.endsWith('.md') ? key : `${key}.md`;
+ const raw = this.files.get(file);
+ if (!raw) return null;
+ return parseFrontmatter(raw);
+ }
+
+ write(key, { name, description, type, body, decay }) {
+ const file = key.endsWith('.md') ? key : `${key}.md`;
+ const now = new Date().toISOString().slice(0, 10);
+ const existing = this.files.get(file);
+ const created = existing ? parseFrontmatter(existing).meta.created || now : now;
+ const meta = { name, description, type, created, updated: now };
+ if (decay) meta.decay = decay;
+ this.files.set(file, stringifyFrontmatter(meta, body || ''));
+ this._rebuildIndex();
+ this._dirty = true;
+ this._persist();
+ }
+
+ note(type, data) {
+ const entry = { ts: new Date().toISOString(), type, ...data };
+ this.timeline.push(entry);
+ // Cap timeline to 1000 entries in-memory
+ if (this.timeline.length > 1000) this.timeline = this.timeline.slice(-1000);
+ this._dirty = true;
+ this._persist();
+ }
+
+ async recall(query, { limit = 5 } = {}) {
+ // Placeholder: naive substring match. Real impl: embeddings via runtime.
+ const q = query.toLowerCase();
+ const hits = [];
+ for (const [file, raw] of this.files) {
+ const { meta, body } = parseFrontmatter(raw);
+ const hay = `${meta.name || ''} ${meta.description || ''} ${body}`.toLowerCase();
+ if (hay.includes(q)) hits.push({ file, meta, body, score: hay.split(q).length - 1 });
+ }
+ return hits.sort((a, b) => b.score - a.score).slice(0, limit);
+ }
+
+ _rebuildIndex() {
+ const byType = { user: [], feedback: [], project: [], reference: [] };
+ for (const [file, raw] of this.files) {
+ const { meta } = parseFrontmatter(raw);
+ const t = meta.type || 'user';
+ if (!byType[t]) byType[t] = [];
+ byType[t].push({ file, name: meta.name || file, description: meta.description || '' });
+ }
+ const lines = ['# Memory', ''];
+ const headings = { user: '## User', feedback: '## Feedback', project: '## Project', reference: '## Reference' };
+ for (const [t, items] of Object.entries(byType)) {
+ if (!items.length) continue;
+ lines.push(headings[t] || `## ${t}`);
+ for (const it of items) lines.push(`- [${it.name}](${it.file}) — ${it.description}`);
+ lines.push('');
+ }
+ this.indexText = lines.join('\n');
+ }
+
+ _persist() {
+ if (this.mode !== 'local' || !this.namespace) return;
+ const key = `agent:${this.namespace}:memory`;
+ const data = {
+ index: { text: this.indexText },
+ files: Object.fromEntries(this.files),
+ timeline: this.timeline.slice(-200), // persist only recent timeline
+ };
+ try {
+ localStorage.setItem(key, JSON.stringify(data));
+ } catch (e) {
+ console.warn('[memory] persist failed', e);
+ }
+ }
+
+ // Budget-aware context serialization for LLM injection
+ contextBlock({ maxTokens = 8192 } = {}) {
+ // Rough token estimate: 4 chars/token
+ const budget = maxTokens * 4;
+ const parts = ['# Agent Memory', '', this.indexText];
+ let used = parts.join('\n').length;
+ // Include top-matching file bodies until budget exhausted
+ for (const [file, raw] of this.files) {
+ if (used + raw.length > budget) break;
+ parts.push('', `## ${file}`, raw);
+ used += raw.length;
+ }
+ if (this.timeline.length) {
+ const recent = this.timeline.slice(-20);
+ const tl = recent.map((e) => JSON.stringify(e)).join('\n');
+ if (used + tl.length < budget) {
+ parts.push('', '## Recent timeline', '```', tl, '```');
+ }
+ }
+ return parts.join('\n');
+ }
+
+ async export() {
+ return {
+ version: 'memory/0.1',
+ index: this.indexText,
+ files: Object.fromEntries(this.files),
+ timeline: this.timeline,
+ };
+ }
+
+ async import(blob, { strategy = 'merge' } = {}) {
+ if (strategy === 'replace') {
+ this.files = new Map(Object.entries(blob.files || {}));
+ this.timeline = blob.timeline || [];
+ } else {
+ for (const [k, v] of Object.entries(blob.files || {})) {
+ if (!this.files.has(k)) this.files.set(k, v);
+ }
+ this.timeline = [...this.timeline, ...(blob.timeline || [])].slice(-1000);
+ }
+ this._rebuildIndex();
+ this._persist();
+ }
+}
diff --git a/src/runtime/providers.js b/src/runtime/providers.js
new file mode 100644
index 000000000..c3e64e209
--- /dev/null
+++ b/src/runtime/providers.js
@@ -0,0 +1,95 @@
+// LLM provider abstraction. Calls go through a proxy URL by default —
+// never ship API keys in the browser.
+
+export class AnthropicProvider {
+ constructor({ model = 'claude-opus-4-6', proxyURL, apiKey, temperature = 0.7, maxTokens = 4096, thinking = 'auto' } = {}) {
+ this.model = model;
+ this.proxyURL = proxyURL;
+ this.apiKey = apiKey;
+ this.temperature = temperature;
+ this.maxTokens = maxTokens;
+ this.thinking = thinking;
+ }
+
+ async complete({ system, messages, tools }) {
+ const body = {
+ model: this.model,
+ max_tokens: this.maxTokens,
+ temperature: this.temperature,
+ system,
+ messages,
+ };
+ if (tools && tools.length) body.tools = tools;
+ if (this.thinking === 'always') {
+ body.thinking = { type: 'enabled', budget_tokens: 2048 };
+ }
+
+ const url = this.proxyURL || 'https://api.anthropic.com/v1/messages';
+ const headers = { 'content-type': 'application/json' };
+ if (this.apiKey) {
+ headers['x-api-key'] = this.apiKey;
+ headers['anthropic-version'] = '2023-06-01';
+ headers['anthropic-dangerous-direct-browser-access'] = 'true';
+ }
+
+ const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(body) });
+ if (!res.ok) {
+ const text = await res.text();
+ throw new Error(`Anthropic ${res.status}: ${text}`);
+ }
+ const data = await res.json();
+ return this._normalize(data);
+ }
+
+ _normalize(data) {
+ // Convert Anthropic response shape into the runtime's common shape:
+ // { text, toolCalls: [{ id, name, input }], stopReason }
+ const out = { text: '', toolCalls: [], thinking: '', stopReason: data.stop_reason };
+ for (const block of data.content || []) {
+ if (block.type === 'text') out.text += block.text;
+ else if (block.type === 'thinking') out.thinking += block.thinking || '';
+ else if (block.type === 'tool_use') {
+ out.toolCalls.push({ id: block.id, name: block.name, input: block.input });
+ }
+ }
+ return out;
+ }
+
+ // Convert normalized tool results back into a user-role message
+ formatToolResults(results) {
+ return {
+ role: 'user',
+ content: results.map((r) => ({
+ type: 'tool_result',
+ tool_use_id: r.id,
+ content: typeof r.output === 'string' ? r.output : JSON.stringify(r.output),
+ is_error: !!r.isError,
+ })),
+ };
+ }
+
+ formatAssistantWithToolCalls(text, toolCalls) {
+ const content = [];
+ if (text) content.push({ type: 'text', text });
+ for (const c of toolCalls) {
+ content.push({ type: 'tool_use', id: c.id, name: c.name, input: c.input });
+ }
+ return { role: 'assistant', content };
+ }
+}
+
+export class NullProvider {
+ // Used when brain.provider === "none" — skills drive the agent.
+ async complete() {
+ return { text: '', toolCalls: [], stopReason: 'end_turn' };
+ }
+ formatToolResults() { return { role: 'user', content: [] }; }
+ formatAssistantWithToolCalls(text) { return { role: 'assistant', content: text || '' }; }
+}
+
+export function createProvider(config = {}) {
+ const provider = config.provider || 'anthropic';
+ if (provider === 'anthropic') return new AnthropicProvider(config);
+ if (provider === 'none') return new NullProvider();
+ throw new Error(`Unsupported provider: ${provider}. Supported: anthropic, none`);
+}
diff --git a/src/skills/index.js b/src/skills/index.js
new file mode 100644
index 000000000..ae99f5498
--- /dev/null
+++ b/src/skills/index.js
@@ -0,0 +1,189 @@
+// Skill registry — loads skill bundles and exposes the ctx API.
+// See specs/SKILL_SPEC.md
+
+import { resolveURI } from '../ipfs.js';
+
+const FRONTMATTER_RE = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;
+
+function parseFrontmatter(text) {
+ const m = text.match(FRONTMATTER_RE);
+ if (!m) return { meta: {}, body: text };
+ const meta = {};
+ for (const line of m[1].split('\n')) {
+ const [k, ...rest] = line.split(':');
+ if (!k) continue;
+ const val = rest.join(':').trim();
+ // Handle simple arrays
+ if (val.startsWith('-')) continue; // skip, multi-line array
+ meta[k.trim()] = val;
+ }
+ return { meta, body: m[2] };
+}
+
+function joinURI(base, rel) {
+ if (/^([a-z]+:|\/)/i.test(rel)) return rel;
+ if (!base.endsWith('/')) base += '/';
+ return base + rel;
+}
+
+export class Skill {
+ constructor({ uri, manifest, instructions, tools, handlers }) {
+ this.uri = uri;
+ this.manifest = manifest;
+ this.name = manifest.name;
+ this.version = manifest.version;
+ this.instructions = instructions;
+ this.tools = tools || [];
+ this.handlers = handlers || {};
+ }
+
+ async invoke(toolName, args, ctx) {
+ const handler = this.handlers[toolName];
+ if (!handler) {
+ throw new Error(`Skill "${this.name}" has no handler for tool "${toolName}"`);
+ }
+ const scoped = { ...ctx, skillBaseURI: this.uri };
+ return handler(args, scoped);
+ }
+
+ systemPromptFragment() {
+ // The LLM sees the skill's markdown body as part of its system context.
+ if (!this.instructions) return '';
+ return `\n\n<skill name="${this.name}" version="${this.version}">\n${this.instructions}\n</skill>`;
+ }
+}
+
+export class SkillRegistry {
+ constructor({ fetchFn = fetch.bind(globalThis), trust = 'owned-only', ownerAddress } = {}) {
+ this.fetchFn = fetchFn;
+ this.trust = trust;
+ this.ownerAddress = ownerAddress?.toLowerCase();
+ this.skills = new Map();
+ }
+
+ async install(spec, { bundleBase } = {}) {
+ // spec: { uri, version? } — uri may be relative, ipfs://, or https://
+ const uri = this._resolveBundleURI(spec.uri, bundleBase);
+ if (this.skills.has(uri)) return this.skills.get(uri);
+
+ const manifest = await this._fetchJSON(`${uri}manifest.json`);
+ this._enforceTrust(manifest);
+
+ const [instructions, toolsJSON, handlersMod] = await Promise.all([
+ this._fetchText(`${uri}SKILL.md`).catch(() => ''),
+ this._fetchJSON(`${uri}tools.json`).catch(() => ({ tools: [] })),
+ this._fetchHandlers(`${uri}handlers.js`).catch(() => null),
+ ]);
+
+ const skill = new Skill({
+ uri,
+ manifest,
+ instructions,
+ tools: toolsJSON.tools || [],
+ handlers: handlersMod || {},
+ });
+
+ // Recursively install skill dependencies
+ if (manifest.dependencies) {
+ for (const [depURI, depVer] of Object.entries(manifest.dependencies)) {
+ await this.install({ uri: depURI, version: depVer });
+ }
+ }
+
+ this.skills.set(uri, skill);
+ return skill;
+ }
+
+ uninstall(name) {
+ for (const [uri, skill] of this.skills) {
+ if (skill.name === name) {
+ this.skills.delete(uri);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ all() {
+ return Array.from(this.skills.values());
+ }
+
+ allTools() {
+ // Merge tool schemas from all skills. Later skills override earlier on name collision.
+ const merged = new Map();
+ for (const skill of this.skills.values()) {
+ for (const tool of skill.tools) {
+ if (merged.has(tool.name)) {
+ console.warn(`[skills] tool "${tool.name}" overridden by skill "${skill.name}"`);
+ }
+ merged.set(tool.name, { ...tool, _skill: skill.name });
+ }
+ }
+ return Array.from(merged.values());
+ }
+
+ findSkillForTool(toolName) {
+ for (const skill of this.skills.values()) {
+ if (skill.tools.some((t) => t.name === toolName)) return skill;
+ }
+ return null;
+ }
+
+ systemPrompt() {
+ return this.all().map((s) => s.systemPromptFragment()).join('');
+ }
+
+ _resolveBundleURI(uri, base) {
+ let resolved = uri;
+ if (!/^([a-z]+:|\/)/i.test(uri) && base) {
+ resolved = joinURI(base, uri);
+ }
+ // Normalize trailing slash
+ if (!resolved.endsWith('/')) resolved += '/';
+ // Resolve ipfs:// → https gateway
+ if (resolved.startsWith('ipfs://') || resolved.startsWith('ar://')) {
+ resolved = resolveURI(resolved);
+ }
+ return resolved;
+ }
+
+ async _fetchJSON(url) {
+ const res = await this.fetchFn(url);
+ if (!res.ok) throw new Error(`Fetch failed: ${url} (${res.status})`);
+ return res.json();
+ }
+
+ async _fetchText(url) {
+ const res = await this.fetchFn(url);
+ if (!res.ok) throw new Error(`Fetch failed: ${url} (${res.status})`);
+ return res.text();
+ }
+
+ async _fetchHandlers(url) {
+ // Dynamic import the handlers module. Browser-side, this uses the import()
+ // intrinsic and respects CORS. For tighter sandboxing, swap in a Realms
+ // shim or Workers-based execution in a future version.
+ try {
+ const mod = await import(/* @vite-ignore */ url);
+ return mod;
+ } catch (e) {
+ console.warn(`[skills] handlers load failed: ${url}`, e);
+ return null;
+ }
+ }
+
+ _enforceTrust(manifest) {
+ if (this.trust === 'any') return;
+ if (this.trust === 'owned-only') {
+ const author = (manifest.author || '').toLowerCase();
+ if (author && this.ownerAddress && author !== this.ownerAddress) {
+ throw new Error(
+ `Skill "${manifest.name}" author ${author} not trusted under owned-only policy`,
+ );
+ }
+ }
+ if (this.trust === 'whitelist') {
+ // Whitelist check would consult a configured allowlist; left as hook.
+ }
+ }
+}
diff --git a/src/viewer.js b/src/viewer.js
index a7fc4b238..f33d6bced 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -464,6 +464,7 @@ export class Viewer {
this.mixer.clipAction(clip).reset().play();
this.state.actionStates[clip.name] = true;
});
+ this.invalidate();
}
/**
@@ -481,6 +482,7 @@ export class Viewer {
}
});
}
+ this.invalidate();
}
updateLights() {
@@ -502,6 +504,8 @@ export class Viewer {
lights[1].intensity = state.directIntensity;
lights[1].color.set(state.directColor);
}
+
+ this.invalidate();
}
addLights() {
@@ -538,10 +542,12 @@ export class Viewer {
)[0];
this.getCubeMapTexture(environment).then(({ envMap }) => {
+ if (this._disposed || !this.scene) return;
this.scene.environment = envMap;
this.scene.background = this.state.transparentBg
? null
: this.state.background ? envMap : this.backgroundColor;
+ this.invalidate();
});
}
@@ -618,6 +624,8 @@ export class Viewer {
}
this.controls.autoRotate = this.state.autoRotate;
+
+ this.invalidate();
}
updateBackground() {
@@ -630,6 +638,7 @@ export class Viewer {
this.renderer.setClearColor(0x000000, 1);
this.updateEnvironment();
}
+ this.invalidate();
}
/**
@@ -664,6 +673,8 @@ export class Viewer {
this.el.appendChild(el);
this.annotationEls.push({ el, position: ann.position });
});
+
+ this.invalidate();
}
projectAnnotations() {
@@ -882,6 +893,7 @@ export class Viewer {
action = action || this.mixer.clipAction(clip);
action.setEffectiveTimeScale(1);
playAnimation ? action.play() : action.stop();
+ this.invalidate();
});
this.animCtrls.push(ctrl);
});
@@ -916,6 +928,9 @@ export class Viewer {
}
}
});
+
+ this.content = null;
+ if (!this._disposed) this.invalidate();
}
dispose() {